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/org/pentaho/agilebi/pdi/wizard/ui/xul/steps/DataSourceAndQueryStep.java b/src/org/pentaho/agilebi/pdi/wizard/ui/xul/steps/DataSourceAndQueryStep.java
index 9ae06f0..8a98c12 100644
--- a/src/org/pentaho/agilebi/pdi/wizard/ui/xul/steps/DataSourceAndQueryStep.java
+++ b/src/org/pentaho/agilebi/pdi/wizard/ui/xul/steps/DataSourceAndQueryStep.java
@@ -1,461 +1,461 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2009 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.agilebi.pdi.wizard.ui.xul.steps;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.table.TableModel;
import org.pentaho.agilebi.pdi.modeler.ModelerException;
import org.pentaho.agilebi.pdi.modeler.ModelerWorkspace;
import org.pentaho.agilebi.pdi.modeler.ModelerWorkspaceUtil;
import org.pentaho.agilebi.pdi.wizard.EmbeddedWizard;
import org.pentaho.commons.metadata.mqleditor.MqlQuery;
import org.pentaho.commons.metadata.mqleditor.editor.MQLEditorService;
import org.pentaho.commons.metadata.mqleditor.editor.SwtMqlEditor;
import org.pentaho.commons.metadata.mqleditor.editor.service.MQLEditorServiceImpl;
import org.pentaho.commons.metadata.mqleditor.editor.service.util.MQLEditorServiceDelegate;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.metadata.query.model.util.QueryXmlHelper;
import org.pentaho.metadata.repository.IMetadataDomainRepository;
import org.pentaho.reporting.engine.classic.core.AbstractReportDefinition;
import org.pentaho.reporting.engine.classic.core.CompoundDataFactory;
import org.pentaho.reporting.engine.classic.core.MetaAttributeNames;
import org.pentaho.reporting.engine.classic.core.MetaTableModel;
import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException;
import org.pentaho.reporting.engine.classic.core.states.datarow.StaticDataRow;
import org.pentaho.reporting.engine.classic.core.wizard.DataAttributes;
import org.pentaho.reporting.engine.classic.core.wizard.DataSchema;
import org.pentaho.reporting.engine.classic.core.wizard.DataSchemaModel;
import org.pentaho.reporting.engine.classic.core.wizard.DefaultDataAttributeContext;
import org.pentaho.reporting.engine.classic.extensions.datasources.pmd.IPmdConnectionProvider;
import org.pentaho.reporting.engine.classic.extensions.datasources.pmd.PmdConnectionProvider;
import org.pentaho.reporting.engine.classic.extensions.datasources.pmd.PmdDataFactory;
import org.pentaho.reporting.engine.classic.wizard.ui.xul.WizardEditorModel;
import org.pentaho.reporting.engine.classic.wizard.ui.xul.components.AbstractWizardStep;
import org.pentaho.reporting.libraries.base.util.DebugLog;
import org.pentaho.reporting.libraries.base.util.StringUtils;
import org.pentaho.reporting.ui.datasources.pmd.PmdPreviewWorker;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulLoader;
import org.pentaho.ui.xul.XulServiceCallback;
import org.pentaho.ui.xul.components.XulButton;
import org.pentaho.ui.xul.components.XulLabel;
import org.pentaho.ui.xul.impl.AbstractXulEventHandler;
import org.pentaho.ui.xul.impl.DefaultXulOverlay;
import org.pentaho.ui.xul.swt.SwtXulLoader;
/**
* TODO: Document Me
*
* @author William Seyler
*/
public class DataSourceAndQueryStep extends AbstractWizardStep
{
private static final String DATASOURCE_AND_QUERY_STEP_OVERLAY = "org/pentaho/agilebi/pdi/wizard/ui/xul/res/datasource_and_query_step_Overlay.xul"; //$NON-NLS-1$
private static final String HANDLER_NAME = "datasource_and_query_step_handler"; //$NON-NLS-1$
private static final String CURRENT_QUERY_PROPERTY_NAME = "currentQuery"; //$NON-NLS-1$
private static final String DATA_SOURCE_NAME_LABEL_ID = "data_source_name_label"; //$NON-NLS-1$
private static final String AVAILABLE_COLUMNS_PROPERTY_NAME = "availableColumns"; //$NON-NLS-1$
private static final String ELEMENTS_PROPERTY_NAME = "elements"; //$NON-NLS-1$
private static final String QUERY_RESULT_LIST_ID = "query_result_list"; //$NON-NLS-1$
private static final String NEXT_BTN_ID = "next_btn"; //$NON-NLS-1$
private static final String DEFAULT = "default"; //$NON-NLS-1$
private PmdDataFactory df;
private ModelerWorkspace model;
private File modelFile;
private List<String> availableColumns;
/**
* @author wseyler
* DatasourceAndQueryStepHandler
* A concrete implementation of AbstractXulEventHandler that defines a name for
* itself and contains methods that correspond to onClick and onCommand markups
* in the corresponding *.xul file.
*/
protected class DatasourceAndQueryStepHandler extends AbstractXulEventHandler
{
public DatasourceAndQueryStepHandler()
{
}
public String getName()
{
return HANDLER_NAME;
}
private IMetadataDomainRepository getDomainRepo() throws ReportDataFactoryException {
IPmdConnectionProvider connectionProvider = ((PmdDataFactory) getEditorModel().getReportDefinition().getDataFactory()).getConnectionProvider();
IMetadataDomainRepository repo = connectionProvider.getMetadataDomainRepository(DEFAULT, getEditorModel().getReportDefinition().getResourceManager(), getEditorModel().getReportDefinition().getContentBase(), df.getXmiFile());
return repo;
}
private MQLEditorServiceDelegate getMqlServiceDelegate() throws ReportDataFactoryException{
MQLEditorServiceDelegate delegate = new MQLEditorServiceDelegate(getDomainRepo()) {
@Override
public String[][] getPreviewData(MqlQuery query, int page, int limit) {
org.pentaho.metadata.query.model.Query mqlQuery = convertQueryModel(query);
String mqlString = new QueryXmlHelper().toXML(mqlQuery);
PmdDataFactory df = (PmdDataFactory) getEditorModel().getReportDefinition().getDataFactory();
df.setQuery("default", mqlString);
PmdPreviewWorker worker = new PmdPreviewWorker(df, "default", 0, limit);
worker.run();
if(worker.getException() != null){
worker.getException().printStackTrace();
}
TableModel model = worker.getResultTableModel();
int colCount = model.getColumnCount();
int rowCount = model.getRowCount();
String[][] results = new String[rowCount][colCount];
for(int y = 0; y < rowCount; y++ ){
for(int x=0; x < colCount; x++){
results[y][x] = ""+model.getValueAt(y, x);
}
}
return results;
}
};
return delegate;
}
private MQLEditorService getMqlService(MQLEditorServiceDelegate delegate){
MQLEditorServiceImpl mqlService = new MQLEditorServiceImpl(delegate) {
@Override
public void getPreviewData(MqlQuery query, int page, int limit, XulServiceCallback<String[][]> callback) {
callback.success(delegate.getPreviewData(query, page, limit));
}
};
return mqlService;
}
/**
* doEditQuery()
* Updates (or creates) a query using the PME data source.
*/
public void doEditQuery() {
try {
IMetadataDomainRepository repo = getDomainRepo();
MQLEditorServiceDelegate delegate = getMqlServiceDelegate();
SwtMqlEditor editor = new SwtMqlEditor(repo, getMqlService(delegate), delegate){
@Override
protected XulLoader getLoader() {
SwtXulLoader loader;
try {
loader = new SwtXulLoader();
loader.registerClassLoader(getClass().getClassLoader());
return loader;
} catch (XulException e) {
e.printStackTrace();
}
return null;
}
};
String queryString = null;
if (df != null && df.getQuery(DEFAULT) != null) {
queryString = df.getQuery(DEFAULT);
editor.setQuery(queryString);
}
editor.addOverlay(new DefaultXulOverlay("org/pentaho/agilebi/pdi/wizard/ui/xul/res/mqleditor-overlay.xul"));
editor.show();
if (editor.getOkClicked()) {
queryString = editor.getQuery();
df.setQuery(DEFAULT, queryString);
setCurrentQuery(DEFAULT);
}
} catch (Exception e) {
getDesignTimeContext().userError(e);
}
}
}
public DataSourceAndQueryStep()
{
super();
}
/* (non-Javadoc)
* @see org.pentaho.reporting.engine.classic.wizard.ui.xul.components.AbstractWizardStep#stepActivating()
*
* stepActivating()
* When this step activates we check to see if we've already been here and if we haven't then we
* creates the model 'n'.xmi file from the model.
*
* If we're coming back in then we just get the current data source and manipulate that.
*/
public void stepActivating()
{
super.stepActivating();
if (model != null && df == null) {
// Populate a PmdDataFactoryClass for the report definition to use
File modelsDir = new File("models"); //$NON-NLS-1$
modelsDir.mkdirs();
int idx = 1;
boolean looking = true;
String fileName = ""; //$NON-NLS-1$
String modelName = ""; //$NON-NLS-1$
while( looking ) {
modelName = "Model "+idx; //$NON-NLS-1$
fileName = "models/"+modelName+".xmi"; //$NON-NLS-1$ //$NON-NLS-2$
modelFile = new File(fileName);
if( !modelFile.exists() ) {
looking = false;
}
idx++;
}
model.setFileName(fileName);
model.setModelName(modelName);
try {
ModelerWorkspaceUtil.autoModelFlat(model);
ModelerWorkspaceUtil.saveWorkspace( model, fileName);
} catch (ModelerException e1) {
getDesignTimeContext().userError(e1);
}
if (getEditorModel().getReportDefinition().getDataFactory() != null && getEditorModel().getReportDefinition().getDataFactory() instanceof CompoundDataFactory) {
CompoundDataFactory cdf = (CompoundDataFactory) getEditorModel().getReportDefinition().getDataFactory();
for (int i=0; i<cdf.size(); i++) {
cdf.remove(i);
}
}
df = new PmdDataFactory();
PmdConnectionProvider connectionProvider = new PmdConnectionProvider();
df.setConnectionProvider(connectionProvider);
try {
df.setXmiFile(modelFile.getCanonicalPath());
} catch (IOException e) {
getDesignTimeContext().userError(e);
}
- df.setDomainId(DEFAULT);
+ df.setDomainId(model.getDomain().getId());
getEditorModel().getReportDefinition().setDataFactory(df);
} else { // editing existing
try {
df = (PmdDataFactory) getEditorModel().getReportDefinition().getDataFactory();
} catch (ClassCastException e) {
df = (PmdDataFactory)((CompoundDataFactory)getEditorModel().getReportDefinition().getDataFactory()).getDataFactoryForQuery(DEFAULT);
}
}
updateGui();
setValid(validateStep());
}
/**
* updateGui()
*
* Updates the data source name label and populates the available columns list box.
*/
private void updateGui() {
// Set the data source name
XulLabel datasourceLabel = (XulLabel) getDocument().getElementById(DATA_SOURCE_NAME_LABEL_ID);
if(datasourceLabel != null && modelFile != null){
datasourceLabel.setValue(modelFile.getName().substring(0, modelFile.getName().lastIndexOf('.')));
}
createColumnsList();
}
/**
* createColumnsList()
*
* Get all the columns current defined by the query and creates a list of their friendly
* names for display in the available columns list box.
*
* Additionally it removes any names whose source is not the query and then it sorts the
* final list.
*/
private void createColumnsList() {
// Set the available query fields;
final DataSchemaModel dataSchemaModel = getEditorModel().getDataSchema();
final DataSchema dataSchema = dataSchemaModel.getDataSchema();
final String[] names = dataSchema.getNames();
Arrays.sort(names);
ArrayList<String> items = new ArrayList<String>();
if (names != null) {
final DefaultDataAttributeContext dataAttributeContext = new DefaultDataAttributeContext();
for ( String name : names ) {
final DataAttributes attributes = dataSchema.getAttributes(name);
final String source = (String) attributes.getMetaAttribute(MetaAttributeNames.Core.NAMESPACE, MetaAttributeNames.Core.SOURCE, String.class, dataAttributeContext);
if ( !source.equals("environment") && !source.equals("parameter") ) {
items.add((String) attributes.getMetaAttribute
(MetaAttributeNames.Formatting.NAMESPACE, MetaAttributeNames.Formatting.LABEL,
String.class, dataAttributeContext));
}
}
}
if (items.size() < 1) {
items.add(BaseMessages.getString(EmbeddedWizard.class,"DataSourceAndQueryStep.no_defined_fields")); //$NON-NLS-1$
}
setAvailableColumns(items);
}
/**
* @return true if the query can be executed.
*/
protected boolean validateStep()
{
// If we have no createdDataFactory and we don't have anything in the model then we can't continue
final AbstractReportDefinition reportDefinition = getEditorModel().getReportDefinition();
if (reportDefinition.getDataFactory() == null ||
StringUtils.isEmpty(reportDefinition.getQuery()))
{
DebugLog.log("Have no query or no datafactory " + //$NON-NLS-1$
reportDefinition.getDataFactory() + " " + reportDefinition.getQuery()); //$NON-NLS-1$
return false;
}
// if we have a DataFactory and a query make sure that they are contained in cdf.
final String queryName = reportDefinition.getQuery();
if (df == null || df.isQueryExecutable(queryName, new StaticDataRow()) == false)
{
return false;
}
try
{
final AbstractReportDefinition abstractReportDefinition =
(AbstractReportDefinition) reportDefinition.derive();
abstractReportDefinition.setDataFactory(df);
final DataSchemaModel schemaModel = WizardEditorModel.compileDataSchemaModel(abstractReportDefinition);
return schemaModel.isValid();
}
catch (Exception ee)
{
getDesignTimeContext().userError(ee);
return false;
}
}
/* (non-Javadoc)
* @see org.pentaho.reporting.engine.classic.wizard.ui.xul.components.AbstractWizardStep#createPresentationComponent(org.pentaho.ui.xul.XulDomContainer)
*
* Loads the overlay for this step and hooks up the event handler
*/
public void createPresentationComponent(XulDomContainer mainWizardContainer) throws XulException
{
super.createPresentationComponent(mainWizardContainer);
mainWizardContainer.loadOverlay(DATASOURCE_AND_QUERY_STEP_OVERLAY);
mainWizardContainer.addEventHandler(new DatasourceAndQueryStepHandler());
}
/**
* @return the currently defined query
*/
public String getCurrentQuery()
{
return getEditorModel().getReportDefinition().getQuery();
}
/**
* @param currentQuery set the current query to the argument 'currentQuery' and fires
* a property change event for objects that have registered.
*/
public void setCurrentQuery(String currentQuery)
{
String oldQuery = getCurrentQuery();
getEditorModel().updateQuery(df, DEFAULT);
this.firePropertyChange(CURRENT_QUERY_PROPERTY_NAME, oldQuery, currentQuery);
this.setValid(validateStep());
updateGui();
}
/**
* @param availableColumns the availableColumns to set once set it fires and property
* change event.
*/
public void setAvailableColumns(List<String> newValue) {
List<String> oldValue = this.availableColumns;
this.availableColumns = newValue;
this.firePropertyChange(AVAILABLE_COLUMNS_PROPERTY_NAME, oldValue, newValue);
}
/**
* @return the availableColumns
*/
public List<String> getAvailableColumns() {
return availableColumns;
}
/* (non-Javadoc)
* @see org.pentaho.reporting.engine.classic.wizard.ui.xul.components.AbstractWizardStep#setValid(boolean)
*
* sets the validity of this step. If this is set to true the 'next' and preview button will
* be available.
*/
protected void setValid(final boolean valid) {
XulButton nextButton = (XulButton) getDocument().getElementById(NEXT_BTN_ID);
nextButton.setDisabled(!valid);
}
/* (non-Javadoc)
* @see org.pentaho.reporting.engine.classic.wizard.ui.xul.components.WizardStep#getStepName()
*
* returns the internationalized step name that appears in the step list.
*/
public String getStepName()
{
return BaseMessages.getString(EmbeddedWizard.class,"DataSourceAndQueryStep.name"); //$NON-NLS-1$
}
public void setModel(ModelerWorkspace model) {
this.model = model;
}
/* (non-Javadoc)
* @see org.pentaho.reporting.engine.classic.wizard.ui.xul.components.WizardStep#setBindings()
*
* Binds the available columns property to the query result list.
*/
public void setBindings() {
getBindingFactory().createBinding(this, AVAILABLE_COLUMNS_PROPERTY_NAME, QUERY_RESULT_LIST_ID, ELEMENTS_PROPERTY_NAME);
}
}
| true | true | public void stepActivating()
{
super.stepActivating();
if (model != null && df == null) {
// Populate a PmdDataFactoryClass for the report definition to use
File modelsDir = new File("models"); //$NON-NLS-1$
modelsDir.mkdirs();
int idx = 1;
boolean looking = true;
String fileName = ""; //$NON-NLS-1$
String modelName = ""; //$NON-NLS-1$
while( looking ) {
modelName = "Model "+idx; //$NON-NLS-1$
fileName = "models/"+modelName+".xmi"; //$NON-NLS-1$ //$NON-NLS-2$
modelFile = new File(fileName);
if( !modelFile.exists() ) {
looking = false;
}
idx++;
}
model.setFileName(fileName);
model.setModelName(modelName);
try {
ModelerWorkspaceUtil.autoModelFlat(model);
ModelerWorkspaceUtil.saveWorkspace( model, fileName);
} catch (ModelerException e1) {
getDesignTimeContext().userError(e1);
}
if (getEditorModel().getReportDefinition().getDataFactory() != null && getEditorModel().getReportDefinition().getDataFactory() instanceof CompoundDataFactory) {
CompoundDataFactory cdf = (CompoundDataFactory) getEditorModel().getReportDefinition().getDataFactory();
for (int i=0; i<cdf.size(); i++) {
cdf.remove(i);
}
}
df = new PmdDataFactory();
PmdConnectionProvider connectionProvider = new PmdConnectionProvider();
df.setConnectionProvider(connectionProvider);
try {
df.setXmiFile(modelFile.getCanonicalPath());
} catch (IOException e) {
getDesignTimeContext().userError(e);
}
df.setDomainId(DEFAULT);
getEditorModel().getReportDefinition().setDataFactory(df);
} else { // editing existing
try {
df = (PmdDataFactory) getEditorModel().getReportDefinition().getDataFactory();
} catch (ClassCastException e) {
df = (PmdDataFactory)((CompoundDataFactory)getEditorModel().getReportDefinition().getDataFactory()).getDataFactoryForQuery(DEFAULT);
}
}
updateGui();
setValid(validateStep());
}
| public void stepActivating()
{
super.stepActivating();
if (model != null && df == null) {
// Populate a PmdDataFactoryClass for the report definition to use
File modelsDir = new File("models"); //$NON-NLS-1$
modelsDir.mkdirs();
int idx = 1;
boolean looking = true;
String fileName = ""; //$NON-NLS-1$
String modelName = ""; //$NON-NLS-1$
while( looking ) {
modelName = "Model "+idx; //$NON-NLS-1$
fileName = "models/"+modelName+".xmi"; //$NON-NLS-1$ //$NON-NLS-2$
modelFile = new File(fileName);
if( !modelFile.exists() ) {
looking = false;
}
idx++;
}
model.setFileName(fileName);
model.setModelName(modelName);
try {
ModelerWorkspaceUtil.autoModelFlat(model);
ModelerWorkspaceUtil.saveWorkspace( model, fileName);
} catch (ModelerException e1) {
getDesignTimeContext().userError(e1);
}
if (getEditorModel().getReportDefinition().getDataFactory() != null && getEditorModel().getReportDefinition().getDataFactory() instanceof CompoundDataFactory) {
CompoundDataFactory cdf = (CompoundDataFactory) getEditorModel().getReportDefinition().getDataFactory();
for (int i=0; i<cdf.size(); i++) {
cdf.remove(i);
}
}
df = new PmdDataFactory();
PmdConnectionProvider connectionProvider = new PmdConnectionProvider();
df.setConnectionProvider(connectionProvider);
try {
df.setXmiFile(modelFile.getCanonicalPath());
} catch (IOException e) {
getDesignTimeContext().userError(e);
}
df.setDomainId(model.getDomain().getId());
getEditorModel().getReportDefinition().setDataFactory(df);
} else { // editing existing
try {
df = (PmdDataFactory) getEditorModel().getReportDefinition().getDataFactory();
} catch (ClassCastException e) {
df = (PmdDataFactory)((CompoundDataFactory)getEditorModel().getReportDefinition().getDataFactory()).getDataFactoryForQuery(DEFAULT);
}
}
updateGui();
setValid(validateStep());
}
|
diff --git a/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java b/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
index 6e19971..1b12cf5 100644
--- a/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
+++ b/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
@@ -1,1188 +1,1191 @@
package org.agmip.translators.dssat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static org.agmip.translators.dssat.DssatCommonInput.copyItem;
import static org.agmip.util.MapUtil.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* DSSAT Experiment Data I/O API Class
*
* @author Meng Zhang
* @version 1.0
*/
public class DssatXFileOutput extends DssatCommonOutput {
private static final Logger LOG = LoggerFactory.getLogger(DssatXFileOutput.class);
public static final DssatCRIDHelper crHelper = new DssatCRIDHelper();
/**
* DSSAT Experiment Data Output method
*
* @param arg0 file output path
* @param result data holder object
*/
@Override
public void writeFile(String arg0, Map result) {
// Initial variables
HashMap expData = (HashMap) result;
ArrayList<HashMap> soilArr = readSWData(expData, "soil");
// ArrayList<HashMap> wthArr = readSWData(expData, "weather");
HashMap soilData;
// HashMap wthData;
BufferedWriter bwX; // output object
StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output
StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data
HashMap secData;
ArrayList subDataArr; // Arraylist for event data holder
HashMap subData;
ArrayList secDataArr; // Arraylist for section data holder
HashMap sqData;
ArrayList<HashMap> evtArr; // Arraylist for section data holder
HashMap evtData;
// int trmnNum; // total numbers of treatment in the data holder
int cuNum; // total numbers of cultivars in the data holder
int flNum; // total numbers of fields in the data holder
int saNum; // total numbers of soil analysis in the data holder
int icNum; // total numbers of initial conditions in the data holder
int mpNum; // total numbers of plaintings in the data holder
int miNum; // total numbers of irrigations in the data holder
int mfNum; // total numbers of fertilizers in the data holder
int mrNum; // total numbers of residues in the data holder
int mcNum; // total numbers of chemical in the data holder
int mtNum; // total numbers of tillage in the data holder
int meNum; // total numbers of enveronment modification in the data holder
int mhNum; // total numbers of harvest in the data holder
int smNum; // total numbers of simulation controll record
ArrayList<HashMap> sqArr; // array for treatment record
ArrayList cuArr = new ArrayList(); // array for cultivars record
ArrayList flArr = new ArrayList(); // array for fields record
ArrayList saArr = new ArrayList(); // array for soil analysis record
ArrayList icArr = new ArrayList(); // array for initial conditions record
ArrayList mpArr = new ArrayList(); // array for plaintings record
ArrayList miArr = new ArrayList(); // array for irrigations record
ArrayList mfArr = new ArrayList(); // array for fertilizers record
ArrayList mrArr = new ArrayList(); // array for residues record
ArrayList mcArr = new ArrayList(); // array for chemical record
ArrayList mtArr = new ArrayList(); // array for tillage record
ArrayList meArr = new ArrayList(); // array for enveronment modification record
ArrayList mhArr = new ArrayList(); // array for harvest record
ArrayList smArr = new ArrayList(); // array for simulation control record
- String exName;
+// String exName;
try {
// Set default value for missing data
if (expData == null || expData.isEmpty()) {
return;
}
// decompressData((HashMap) result);
setDefVal();
// Initial BufferedWriter
String fileName = getFileName(result, "X");
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwX = new BufferedWriter(new FileWriter(outputFile));
// Output XFile
// EXP.DETAILS Section
sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n",
getFileName(result, "").replaceAll("\\.", ""),
getObjectOr(expData, "local_name", defValBlank).toString()));
// GENERAL Section
sbGenData.append("*GENERAL\r\n");
// People
if (!getObjectOr(expData, "people", "").equals("")) {
sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "people", defValBlank).toString()));
}
// Address
if (getObjectOr(expData, "institution", "").equals("")) {
if (!getObjectOr(expData, "fl_loc_1", "").equals("")
&& getObjectOr(expData, "fl_loc_2", "").equals("")
&& getObjectOr(expData, "fl_loc_3", "").equals("")) {
sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n",
getObjectOr(expData, "fl_loc_1", defValBlank).toString(),
getObjectOr(expData, "fl_loc_2", defValBlank).toString(),
getObjectOr(expData, "fl_loc_3", defValBlank).toString()));
}
} else {
sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString()));
}
// Site
if (!getObjectOr(expData, "site", "").equals("")) {
sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site", defValBlank).toString()));
}
// Plot Info
if (isPlotInfoExist(expData)) {
sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n");
sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n",
formatNumStr(6, expData, "plta", defValR),
formatNumStr(5, expData, "pltr#", defValI),
formatNumStr(5, expData, "pltln", defValR),
formatNumStr(5, expData, "pldr", defValI),
formatNumStr(5, expData, "pltsp", defValI),
getObjectOr(expData, "plot_layout", defValC).toString(),
formatNumStr(5, expData, "pltha", defValR),
formatNumStr(5, expData, "plth#", defValI),
formatNumStr(5, expData, "plthl", defValR),
getObjectOr(expData, "plthm", defValC).toString()));
}
// Notes
if (!getObjectOr(expData, "tr_notes", "").equals("")) {
sbNotesData.append("@NOTES\r\n");
String notes = getObjectOr(expData, "tr_notes", defValC).toString();
notes = notes.replaceAll("\\\\r\\\\n", "\r\n");
// If notes contain newline code, then write directly
if (notes.indexOf("\r\n") >= 0) {
// sbData.append(String.format(" %1$s\r\n", notes));
sbNotesData.append(notes);
} // Otherwise, add newline for every 75-bits charactors
else {
while (notes.length() > 75) {
sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n");
notes = notes.substring(75);
}
sbNotesData.append(" ").append(notes).append("\r\n");
}
}
sbData.append("\r\n");
// TREATMENT Section
sqArr = getDataList(expData, "dssat_sequence", "data");
evtArr = getDataList(expData, "management", "events");
ArrayList<HashMap> rootArr = getObjectOr(expData, "dssat_root", new ArrayList());
ArrayList<HashMap> meOrgArr = getDataList(expData, "dssat_environment_modification", "data");
ArrayList<HashMap> smOrgArr = getDataList(expData, "dssat_simulation_control", "data");
String seqId;
String em;
String sm;
sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n");
sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n");
// if there is no sequence info, create dummy data
if (sqArr.isEmpty()) {
sqArr.add(new HashMap());
}
// Set sequence related block info
for (int i = 0; i < sqArr.size(); i++) {
sqData = sqArr.get(i);
seqId = getValueOr(sqData, "seqid", defValBlank);
em = getValueOr(sqData, "em", defValBlank);
sm = getValueOr(sqData, "sm", defValBlank);
if (i < soilArr.size()) {
soilData = soilArr.get(i);
} else if (soilArr.isEmpty()) {
soilData = new HashMap();
} else {
soilData = soilArr.get(0);
}
+ if (soilData == null) {
+ soilData = new HashMap();
+ }
// if (i < wthArr.size()) {
// wthData = wthArr.get(i);
// } else if (wthArr.isEmpty()) {
// wthData = new HashMap();
// } else {
// wthData = wthArr.get(0);
// }
HashMap cuData = new HashMap();
HashMap flData = new HashMap();
HashMap mpData = new HashMap();
ArrayList<HashMap> miSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> meSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>();
HashMap smData = new HashMap();
HashMap rootData;
// Set exp root info
if (i < rootArr.size()) {
rootData = rootArr.get(i);
} else {
rootData = expData;
}
// Set field info
copyItem(flData, rootData, "id_field");
flData.put("wst_id", getWthFileName(rootData));
// if (i < rootArr.size()) {
// // copyItem(flData, expData, "wst_id");
// flData.put("wst_id", getWthFileName(rootData));
// } else {
// flData.put("wst_id", getWthFileName(wthData));
// }
copyItem(flData, rootData, "flsl");
copyItem(flData, rootData, "flob");
copyItem(flData, rootData, "fl_drntype");
copyItem(flData, rootData, "fldrd");
copyItem(flData, rootData, "fldrs");
copyItem(flData, rootData, "flst");
if (soilData.get("sltx") != null) {
copyItem(flData, soilData, "sltx");
} else {
copyItem(flData, rootData, "sltx");
}
copyItem(flData, soilData, "sldp");
copyItem(flData, rootData, "soil_id");
copyItem(flData, rootData, "fl_name");
copyItem(flData, rootData, "fl_lat");
copyItem(flData, rootData, "fl_long");
copyItem(flData, rootData, "flele");
copyItem(flData, rootData, "farea");
copyItem(flData, rootData, "fllwr");
copyItem(flData, rootData, "flsla");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "flhst");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "fhdur");
// remove the "_trno" in the soil_id when soil analysis is available
String soilId = getValueOr(flData, "soil_id", "");
if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) {
flData.put("soil_id", soilId.replaceAll("_\\d+$", ""));
}
flNum = setSecDataArr(flData, flArr);
// Set initial condition info
icNum = setSecDataArr(getObjectOr(rootData, "initial_conditions", new HashMap()), icArr);
// Set environment modification info
for (int j = 0; j < meOrgArr.size(); j++) {
if (em.equals(meOrgArr.get(j).get("em"))) {
HashMap tmp = new HashMap();
tmp.putAll(meOrgArr.get(j));
tmp.remove("em");
meSubArr.add(tmp);
}
}
// Set soil analysis info
// ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer");
ArrayList<HashMap> soilLarys = getObjectOr(soilData, "soilLayer", new ArrayList());
// // If it is stored in the initial condition block
// if (isSoilAnalysisExist(icSubArr)) {
// HashMap saData = new HashMap();
// ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
// HashMap saSubData;
// for (int i = 0; i < icSubArr.size(); i++) {
// saSubData = new HashMap();
// copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false);
// copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false);
// saSubArr.add(saSubData);
// }
// copyItem(saData, soilData, "sadat");
// saData.put("soilLayer", saSubArr);
// saNum = setSecDataArr(saData, saArr);
// } else
// If it is stored in the soil block
if (isSoilAnalysisExist(soilLarys)) {
HashMap saData = new HashMap();
ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
HashMap saSubData;
for (int j = 0; j < soilLarys.size(); j++) {
saSubData = new HashMap();
copyItem(saSubData, soilLarys.get(j), "sabl", "sllb", false);
copyItem(saSubData, soilLarys.get(j), "sasc", "slsc", false);
saSubArr.add(saSubData);
}
copyItem(saData, soilData, "sadat");
saData.put("soilLayer", saSubArr);
saNum = setSecDataArr(saData, saArr);
} else {
saNum = 0;
}
// Set simulation control info
for (int j = 0; j < smOrgArr.size(); j++) {
if (sm.equals(smOrgArr.get(j).get("sm"))) {
smData.putAll(smOrgArr.get(j));
smData.remove("sm");
break;
}
}
// if (smData.isEmpty()) {
// smData.put("fertilizer", mfSubArr);
// smData.put("irrigation", miSubArr);
// smData.put("planting", mpData);
// }
copyItem(smData, rootData, "sdat");
// Loop all event data
for (int j = 0; j < evtArr.size(); j++) {
evtData = new HashMap();
evtData.putAll(evtArr.get(j));
// Check if it has same sequence number
if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) {
evtData.remove("seqid");
// Planting event
if (getValueOr(evtData, "event", defValBlank).equals("planting")) {
// Set cultivals info
copyItem(cuData, evtData, "cul_name");
copyItem(cuData, evtData, "crid");
copyItem(cuData, evtData, "cul_id");
copyItem(cuData, evtData, "dssat_cul_id");
copyItem(cuData, evtData, "rm");
copyItem(cuData, evtData, "cul_notes");
translateTo2BitCrid(cuData);
// Set planting info
mpData.putAll(evtData);
mpData.remove("cul_name");
} // irrigation event
else if (getValueOr(evtData, "event", "").equals("irrigation")) {
miSubArr.add(evtData);
} // fertilizer event
else if (getValueOr(evtData, "event", "").equals("fertilizer")) {
mfSubArr.add(evtData);
} // organic_matter event
else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again.
mrSubArr.add(evtData);
} // chemical event
else if (getValueOr(evtData, "event", "").equals("chemical")) {
mcSubArr.add(evtData);
} // tillage event
else if (getValueOr(evtData, "event", "").equals("tillage")) {
mtSubArr.add(evtData);
// } // environment_modification event
// else if (getValueOr(evtData, "event", "").equals("environment_modification")) {
// meSubArr.add(evtData);
} // harvest event
else if (getValueOr(evtData, "event", "").equals("harvest")) {
mhSubArr.add(evtData);
} else {
}
} else {
}
}
// If alternative fields are avaiable for fertilizer data
if (mfSubArr.isEmpty()) {
if (!getObjectOr(result, "fen_tot", "").equals("")
|| !getObjectOr(result, "fep_tot", "").equals("")
|| !getObjectOr(result, "fek_tot", "").equals("")) {
mfSubArr.add(new HashMap());
}
}
cuNum = setSecDataArr(cuData, cuArr);
mpNum = setSecDataArr(mpData, mpArr);
miNum = setSecDataArr(miSubArr, miArr);
mfNum = setSecDataArr(mfSubArr, mfArr);
mrNum = setSecDataArr(mrSubArr, mrArr);
mcNum = setSecDataArr(mcSubArr, mcArr);
mtNum = setSecDataArr(mtSubArr, mtArr);
meNum = setSecDataArr(meSubArr, meArr);
mhNum = setSecDataArr(mhSubArr, mhArr);
smNum = setSecDataArr(smData, smArr);
if (smNum == 0) {
smNum = 1;
}
sbData.append(String.format("%1$-3s%2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n",
String.format("%2s", getValueOr(sqData, "trno", "1")), // For 3-bit treatment number
getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf
getValueOr(sqData, "op", "1").toString(),
getValueOr(sqData, "co", "0").toString(),
formatStr(25, sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC))),
cuNum, //getObjectOr(data, "ge", defValI).toString(),
flNum, //getObjectOr(data, "fl", defValI).toString(),
saNum, //getObjectOr(data, "sa", defValI).toString(),
icNum, //getObjectOr(data, "ic", defValI).toString(),
mpNum, //getObjectOr(data, "pl", defValI).toString(),
miNum, //getObjectOr(data, "ir", defValI).toString(),
mfNum, //getObjectOr(data, "fe", defValI).toString(),
mrNum, //getObjectOr(data, "om", defValI).toString(),
mcNum, //getObjectOr(data, "ch", defValI).toString(),
mtNum, //getObjectOr(data, "ti", defValI).toString(),
meNum, //getObjectOr(data, "em", defValI).toString(),
mhNum, //getObjectOr(data, "ha", defValI).toString(),
smNum)); // 1
}
sbData.append("\r\n");
// CULTIVARS Section
if (!cuArr.isEmpty()) {
sbData.append("*CULTIVARS\r\n");
sbData.append("@C CR INGENO CNAME\r\n");
for (int idx = 0; idx < cuArr.size(); idx++) {
secData = (HashMap) cuArr.get(idx);
// String cul_id = defValC;
String crid = getObjectOr(secData, "crid", "");
// Checl if necessary data is missing
if (crid.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n");
// } else {
// // Set cultivar id a default value deponds on the crop id
// if (crid.equals("MZ")) {
// cul_id = "990002";
// } else {
// cul_id = "999999";
// }
// }
// if (getObjectOr(secData, "cul_id", "").equals("")) {
// sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n");
}
sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
formatStr(2, secData, "crid", defValBlank), // P.S. if missing, default value use blank string
formatStr(6, secData, "dssat_cul_id", getObjectOr(secData, "cul_id", defValC)), // P.S. Set default value which is deponds on crid(Cancelled)
getObjectOr(secData, "cul_name", defValC).toString()));
if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) {
if (sbNotesData.toString().equals("")) {
sbNotesData.append("@NOTES\r\n");
}
sbNotesData.append(" Cultivar Additional Info\r\n");
sbNotesData.append(" C RM CNAME CUL_NOTES\r\n");
sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "rm", defValC).toString(),
getObjectOr(secData, "cul_notes", defValC).toString()));
}
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no cultivar data in the experiment.\r\n");
}
// FIELDS Section
if (!flArr.isEmpty()) {
sbData.append("*FIELDS\r\n");
sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n");
eventPart2 = new StringBuilder();
eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n");
} else {
sbError.append("! Warning: There is no field data in the experiment.\r\n");
}
for (int idx = 0; idx < flArr.size(); idx++) {
secData = (HashMap) flArr.get(idx);
// Check if the necessary is missing
if (getObjectOr(secData, "wst_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n");
}
String soil_id = getSoilID(secData);
if (soil_id.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n");
} else if (soil_id.length() > 10) {
sbError.append("! Warning: Oversized data : [soil_id] ").append(soil_id).append("\r\n");
}
sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
getObjectOr(secData, "id_field", defValC).toString(),
getObjectOr(secData, "wst_id", defValC).toString(),
getObjectOr(secData, "flsl", defValC).toString(),
formatNumStr(5, secData, "flob", defValR),
getObjectOr(secData, "fl_drntype", defValC).toString(),
formatNumStr(5, secData, "fldrd", defValR),
formatNumStr(5, secData, "fldrs", defValR),
getObjectOr(secData, "flst", defValC).toString(),
getObjectOr(secData, "sltx", defValC).toString(),
formatNumStr(5, secData, "sldp", defValR),
soil_id,
getObjectOr(secData, "fl_name", defValC).toString()));
eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
formatNumStr(15, secData, "fl_long", defValR),
formatNumStr(15, secData, "fl_lat", defValR),
formatNumStr(9, secData, "flele", defValR),
formatNumStr(17, secData, "farea", defValR),
"-99", // P.S. SLEN keeps -99
formatNumStr(5, secData, "fllwr", defValR),
formatNumStr(5, secData, "flsla", defValR),
getObjectOr(secData, "flhst", defValC).toString(),
formatNumStr(5, secData, "fhdur", defValR)));
}
if (!flArr.isEmpty()) {
sbData.append(eventPart2.toString()).append("\r\n");
}
// SOIL ANALYSIS Section
if (!saArr.isEmpty()) {
sbData.append("*SOIL ANALYSIS\r\n");
for (int idx = 0; idx < saArr.size(); idx++) {
secData = (HashMap) saArr.get(idx);
sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n",
idx + 1, //getObjectOr(secData, "sa", defValI).toString(),
formatDateStr(getObjectOr(secData, "sadat", defValD).toString()),
getObjectOr(secData, "samhb", defValC).toString(),
getObjectOr(secData, "sampx", defValC).toString(),
getObjectOr(secData, "samke", defValC).toString(),
getObjectOr(secData, "sa_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(subData, "sa", defValI).toString(),
formatNumStr(5, subData, "sabl", defValR),
formatNumStr(5, subData, "sabdm", defValR),
formatNumStr(5, subData, "saoc", defValR),
formatNumStr(5, subData, "sani", defValR),
formatNumStr(5, subData, "saphw", defValR),
formatNumStr(5, subData, "saphb", defValR),
formatNumStr(5, subData, "sapx", defValR),
formatNumStr(5, subData, "sake", defValR),
formatNumStr(5, subData, "sasc", defValR)));
}
}
sbData.append("\r\n");
}
// INITIAL CONDITIONS Section
if (!icArr.isEmpty()) {
sbData.append("*INITIAL CONDITIONS\r\n");
for (int idx = 0; idx < icArr.size(); idx++) {
secData = (HashMap) icArr.get(idx);
translateTo2BitCrid(secData, "icpcr");
sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n",
idx + 1, //getObjectOr(secData, "ic", defValI).toString(),
getObjectOr(secData, "icpcr", defValC).toString(),
formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()),
formatNumStr(5, secData, "icrt", defValR),
formatNumStr(5, secData, "icnd", defValR),
formatNumStr(5, secData, "icrz#", defValR),
formatNumStr(5, secData, "icrze", defValR),
formatNumStr(5, secData, "icwt", defValR),
formatNumStr(5, secData, "icrag", defValR),
formatNumStr(5, secData, "icrn", defValR),
formatNumStr(5, secData, "icrp", defValR),
formatNumStr(5, secData, "icrip", defValR),
formatNumStr(5, secData, "icrdp", defValR),
getObjectOr(secData, "ic_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@C ICBL SH2O SNH4 SNO3\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n",
idx + 1, //getObjectOr(subData, "ic", defValI).toString(),
formatNumStr(5, subData, "icbl", defValR),
formatNumStr(5, subData, "ich2o", defValR),
formatNumStr(5, subData, "icnh4", defValR),
formatNumStr(5, subData, "icno3", defValR)));
}
}
sbData.append("\r\n");
}
// PLANTING DETAILS Section
if (!mpArr.isEmpty()) {
sbData.append("*PLANTING DETAILS\r\n");
sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n");
for (int idx = 0; idx < mpArr.size(); idx++) {
secData = (HashMap) mpArr.get(idx);
// Check if necessary data is missing
String pdate = getObjectOr(secData, "date", "");
if (pdate.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n");
} else if (formatDateStr(pdate).equals(defValD)) {
sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n");
}
if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n");
}
if (getObjectOr(secData, "plrs", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n");
}
// if (getObjectOr(secData, "plma", "").equals("")) {
// sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n");
// }
// if (getObjectOr(secData, "plds", "").equals("")) {
// sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n");
// }
// if (getObjectOr(secData, "pldp", "").equals("")) {
// sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n");
// }
// mm -> cm
String pldp = getObjectOr(secData, "pldp", "");
if (!pldp.equals("")) {
try {
BigDecimal pldpBD = new BigDecimal(pldp);
pldpBD = pldpBD.divide(new BigDecimal("10"));
secData.put("pldp", pldpBD.toString());
} catch (NumberFormatException e) {
}
}
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n",
idx + 1, //getObjectOr(data, "pl", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()),
formatDateStr(getObjectOr(secData, "pldae", defValD).toString()),
formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)),
formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)),
getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled)
getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled)
formatNumStr(5, secData, "plrs", defValR),
formatNumStr(5, secData, "plrd", defValR),
formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled)
formatNumStr(5, secData, "plmwt", defValR),
formatNumStr(5, secData, "page", defValR),
formatNumStr(5, secData, "penv", defValR),
formatNumStr(5, secData, "plph", defValR),
formatNumStr(5, secData, "plspl", defValR),
getObjectOr(secData, "pl_name", defValC).toString()));
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no plainting data in the experiment.\r\n");
}
// IRRIGATION AND WATER MANAGEMENT Section
if (!miArr.isEmpty()) {
sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n");
for (int idx = 0; idx < miArr.size(); idx++) {
// secData = (ArrayList) miArr.get(idx);
subDataArr = (ArrayList) miArr.get(idx);
if (!subDataArr.isEmpty()) {
subData = (HashMap) subDataArr.get(0);
} else {
subData = new HashMap();
}
sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n",
idx + 1, //getObjectOr(data, "ir", defValI).toString(),
formatNumStr(5, subData, "ireff", defValR),
formatNumStr(5, subData, "irmdp", defValR),
formatNumStr(5, subData, "irthr", defValR),
formatNumStr(5, subData, "irept", defValR),
getObjectOr(subData, "irstg", defValC).toString(),
getObjectOr(subData, "iame", defValC).toString(),
formatNumStr(5, subData, "iamt", defValR),
getObjectOr(subData, "ir_name", defValC).toString()));
if (!subDataArr.isEmpty()) {
sbData.append("@I IDATE IROP IRVAL\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n",
idx + 1, //getObjectOr(subData, "ir", defValI).toString(),
formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date
getObjectOr(subData, "irop", defValC).toString(),
formatNumStr(5, subData, "irval", defValR)));
}
}
sbData.append("\r\n");
}
// FERTILIZERS (INORGANIC) Section
if (!mfArr.isEmpty()) {
sbData.append("*FERTILIZERS (INORGANIC)\r\n");
sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n");
// String fen_tot = getObjectOr(result, "fen_tot", defValR);
// String fep_tot = getObjectOr(result, "fep_tot", defValR);
// String fek_tot = getObjectOr(result, "fek_tot", defValR);
// String pdate = getPdate(result);
// if (pdate.equals("")) {
// pdate = defValD;
// }
for (int idx = 0; idx < mfArr.size(); idx++) {
secDataArr = (ArrayList) mfArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
// if (getObjectOr(secData, "fdate", "").equals("")) {
// sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n");
// }
// if (getObjectOr(secData, "fecd", "").equals("")) {
// sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n");
// }
// if (getObjectOr(secData, "feacd", "").equals("")) {
// sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n");
// }
// if (getObjectOr(secData, "fedep", "").equals("")) {
// sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n");
// }
// if (getObjectOr(secData, "feamn", "").equals("")) {
// sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamp", "").equals("")) {
// sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamk", "").equals("")) {
// sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n",
idx + 1, //getObjectOr(data, "fe", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date
getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled)
getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled)
formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled)
formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamc", defValR),
formatNumStr(5, secData, "feamo", defValR),
getObjectOr(secData, "feocd", defValC).toString(),
getObjectOr(secData, "fe_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// RESIDUES AND ORGANIC FERTILIZER Section
if (!mrArr.isEmpty()) {
sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n");
sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n");
for (int idx = 0; idx < mrArr.size(); idx++) {
secDataArr = (ArrayList) mrArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n",
idx + 1, //getObjectOr(secData, "om", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date
getObjectOr(secData, "omcd", defValC).toString(),
formatNumStr(5, secData, "omamt", defValR),
formatNumStr(5, secData, "omn%", defValR),
formatNumStr(5, secData, "omp%", defValR),
formatNumStr(5, secData, "omk%", defValR),
formatNumStr(5, secData, "ominp", defValR),
formatNumStr(5, secData, "omdep", defValR),
formatNumStr(5, secData, "omacd", defValR),
getObjectOr(secData, "om_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// CHEMICAL APPLICATIONS Section
if (!mcArr.isEmpty()) {
sbData.append("*CHEMICAL APPLICATIONS\r\n");
sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n");
for (int idx = 0; idx < mcArr.size(); idx++) {
secDataArr = (ArrayList) mcArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ch", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date
getObjectOr(secData, "chcd", defValC).toString(),
formatNumStr(5, secData, "chamt", defValR),
getObjectOr(secData, "chacd", defValC).toString(),
getObjectOr(secData, "chdep", defValC).toString(),
getObjectOr(secData, "ch_targets", defValC).toString(),
getObjectOr(secData, "ch_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// TILLAGE Section
if (!mtArr.isEmpty()) {
sbData.append("*TILLAGE AND ROTATIONS\r\n");
sbData.append("@T TDATE TIMPL TDEP TNAME\r\n");
for (int idx = 0; idx < mtArr.size(); idx++) {
secDataArr = (ArrayList) mtArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n",
idx + 1, //getObjectOr(secData, "ti", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date
getObjectOr(secData, "tiimp", defValC).toString(),
formatNumStr(5, secData, "tidep", defValR),
getObjectOr(secData, "ti_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// ENVIRONMENT MODIFICATIONS Section
if (!meArr.isEmpty()) {
sbData.append("*ENVIRONMENT MODIFICATIONS\r\n");
sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n");
for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) {
secDataArr = (ArrayList) meArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s%2$s\r\n",
cnt,
secData.get("em_data")));
// sbData.append(String.format("%1$2s%2$s\r\n",
// idx + 1,
// (String) secDataArr.get(i)));
// sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n",
// idx + 1, //getObjectOr(secData, "em", defValI).toString(),
// formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date
// getObjectOr(secData, "ecdyl", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdyl", defValR),
// getObjectOr(secData, "ecrad", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrad", defValR),
// getObjectOr(secData, "ecmax", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmax", defValR),
// getObjectOr(secData, "ecmin", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmin", defValR),
// getObjectOr(secData, "ecrai", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrai", defValR),
// getObjectOr(secData, "ecco2", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emco2", defValR),
// getObjectOr(secData, "ecdew", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdew", defValR),
// getObjectOr(secData, "ecwnd", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emwnd", defValR),
// getObjectOr(secData, "em_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// HARVEST DETAILS Section
if (!mhArr.isEmpty()) {
sbData.append("*HARVEST DETAILS\r\n");
sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n");
for (int idx = 0; idx < mhArr.size(); idx++) {
secDataArr = (ArrayList) mhArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ha", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date
getObjectOr(secData, "hastg", defValC).toString(),
getObjectOr(secData, "hacom", defValC).toString(),
getObjectOr(secData, "hasiz", defValC).toString(),
formatNumStr(5, secData, "hapc", defValR),
formatNumStr(5, secData, "habpc", defValR),
getObjectOr(secData, "ha_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section
if (!smArr.isEmpty()) {
// Set Title list
ArrayList smTitles = new ArrayList();
smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n");
smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n");
smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
String[] keys = new String[10];
keys[0] = "sm_general";
keys[1] = "sm_options";
keys[2] = "sm_methods";
keys[3] = "sm_management";
keys[4] = "sm_outputs";
keys[5] = "sm_planting";
keys[6] = "sm_irrigation";
keys[7] = "sm_nitrogen";
keys[8] = "sm_residues";
keys[9] = "sm_harvests";
// Loop all the simulation control records
for (int idx = 0; idx < smArr.size(); idx++) {
secData = (HashMap) smArr.get(idx);
if (secData.containsKey("sm_general")) {
sbData.append("*SIMULATION CONTROLS\r\n");
secData.remove("sm");
// Object[] keys = secData.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
sbData.append(smTitles.get(i));
sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n");
if (i == 4) {
sbData.append("\r\n");
}
}
sbData.append("\r\n");
} else {
sbData.append(createSMMAStr(idx + 1, secData));
}
}
} else {
sbData.append(createSMMAStr(1, new HashMap()));
}
// Output finish
bwX.write(sbError.toString());
bwX.write(sbGenData.toString());
bwX.write(sbNotesData.toString());
bwX.write(sbData.toString());
bwX.close();
} catch (IOException e) {
LOG.error(DssatCommonOutput.getStackTrace(e));
}
}
/**
* Create string of Simulation Control and Automatic Management Section
*
* @param smid simulation index number
* @param trData date holder for one treatment data
* @return date string with format of "yyddd"
*/
private String createSMMAStr(int smid, HashMap trData) {
StringBuilder sb = new StringBuilder();
String nitro = "Y";
String water = "Y";
String sdate;
String sm = String.format("%2d", smid);
ArrayList<HashMap> dataArr;
HashMap subData;
// // Check if the meta data of fertilizer is not "N" ("Y" or null)
// if (!getValueOr(expData, "fertilizer", "").equals("N")) {
//
// // Check if necessary data is missing in all the event records
// // P.S. rule changed since all the necessary data has a default value for it
// dataArr = (ArrayList) getObjectOr(trData, "fertilizer", new ArrayList());
// if (dataArr.isEmpty()) {
// nitro = "N";
// }
//// for (int i = 0; i < dataArr.size(); i++) {
//// subData = dataArr.get(i);
//// if (getValueOr(subData, "date", "").equals("")
//// || getValueOr(subData, "fecd", "").equals("")
//// || getValueOr(subData, "feacd", "").equals("")
//// || getValueOr(subData, "feamn", "").equals("")) {
//// nitro = "N";
//// break;
//// }
//// }
// }
// // Check if the meta data of irrigation is not "N" ("Y" or null)
// if (!getValueOr(expData, "irrigation", "").equals("N")) {
//
// // Check if necessary data is missing in all the event records
// dataArr = (ArrayList) getObjectOr(trData, "irrigation", new ArrayList());
// for (int i = 0; i < dataArr.size(); i++) {
// subData = dataArr.get(i);
// if (getValueOr(subData, "date", "").equals("")
// || getValueOr(subData, "irval", "").equals("")) {
// water = "N";
// break;
// }
// }
// }
sdate = getValueOr(trData, "sdat", "").toString();
if (sdate.equals("")) {
subData = (HashMap) getObjectOr(trData, "planting", new HashMap());
sdate = getValueOr(subData, "date", defValD);
}
sdate = formatDateStr(sdate);
sb.append("*SIMULATION CONTROLS\r\n");
sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME....................\r\n");
sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTROL\r\n");
sb.append("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
sb.append(sm).append(" OP ").append(water).append(" ").append(nitro).append(" Y N N N N Y M\r\n");
sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P"
sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
sb.append(sm).append(" MA R R R R M\r\n");
sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n");
sb.append("@ AUTOMATIC MANAGEMENT\r\n");
sb.append("@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
sb.append(sm).append(" PL 82050 82064 40 100 30 40 10\r\n");
sb.append("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
sb.append(sm).append(" IR 30 50 100 GS000 IR001 10 1.00\r\n");
sb.append("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
sb.append(sm).append(" NI 30 50 25 FE001 GS000\r\n");
sb.append("@N RESIDUES RIPCN RTIME RIDEP\r\n");
sb.append(sm).append(" RE 100 1 20\r\n");
sb.append("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
sb.append(sm).append(" HA 0 83057 100 0\r\n\r\n");
return sb.toString();
}
/**
* Get index value of the record and set new id value in the array
*
* @param m sub data
* @param arr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(HashMap m, ArrayList arr) {
if (!m.isEmpty()) {
for (int j = 0; j < arr.size(); j++) {
if (arr.get(j).equals(m)) {
return j + 1;
}
}
arr.add(m);
return arr.size();
} else {
return 0;
}
}
/**
* Get index value of the record and set new id value in the array
*
* @param inArr sub array of data
* @param outArr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(ArrayList inArr, ArrayList outArr) {
if (!inArr.isEmpty()) {
for (int j = 0; j < outArr.size(); j++) {
if (outArr.get(j).equals(inArr)) {
return j + 1;
}
}
outArr.add(inArr);
return outArr.size();
} else {
return 0;
}
}
/**
* To check if there is plot info data existed in the experiment
*
* @param expData experiment data holder
* @return the boolean value for if plot info exists
*/
private boolean isPlotInfoExist(Map expData) {
String[] plotIds = {"plta", "pltr#", "pltln", "pldr", "pltsp", "plot_layout", "pltha", "plth#", "plthl", "plthm"};
for (int i = 0; i < plotIds.length; i++) {
if (!getValueOr(expData, plotIds[i], "").equals("")) {
return true;
}
}
return false;
}
/**
* To check if there is soil analysis info data existed in the experiment
*
* @param expData initial condition layer data array
* @return the boolean value for if soil analysis info exists
*/
private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) {
for (int i = 0; i < icSubArr.size(); i++) {
if (!getValueOr(icSubArr.get(i), "slsc", "").equals("")) {
return true;
}
}
return false;
}
/**
* Get sub data array from experiment data object
*
* @param expData experiment data holder
* @param blockName top level block name
* @param dataListName sub array name
* @return sub data array
*/
private ArrayList<HashMap> getDataList(Map expData, String blockName, String dataListName) {
HashMap dataBlock = getObjectOr(expData, blockName, new HashMap());
return getObjectOr(dataBlock, dataListName, new ArrayList<HashMap>());
}
/**
* Try to translate 3-bit crid to 2-bit version stored in the map
*
* @param cuData the cultivar data record
* @param id the field id for contain crop id info
*/
private void translateTo2BitCrid(HashMap cuData, String id) {
String crid = getObjectOr(cuData, id, "");
if (!crid.equals("")) {
DssatCRIDHelper crids = new DssatCRIDHelper();
cuData.put(id, crids.get2BitCrid(crid));
}
}
/**
* Try to translate 3-bit crid to 2-bit version stored in the map
*
* @param cuData the cultivar data record
*/
private void translateTo2BitCrid(HashMap cuData) {
translateTo2BitCrid(cuData, "crid");
}
/**
* Get soil/weather data from data holder
*
* @param expData The experiment data holder
* @param key The key name for soil/weather section
* @return
*/
private ArrayList readSWData(HashMap expData, String key) {
ArrayList ret;
Object soil = expData.get(key);
if (soil != null) {
if (soil instanceof ArrayList) {
ret = (ArrayList) soil;
} else {
ret = new ArrayList();
ret.add(soil);
}
} else {
ret = new ArrayList();
}
return ret;
}
}
| false | true | public void writeFile(String arg0, Map result) {
// Initial variables
HashMap expData = (HashMap) result;
ArrayList<HashMap> soilArr = readSWData(expData, "soil");
// ArrayList<HashMap> wthArr = readSWData(expData, "weather");
HashMap soilData;
// HashMap wthData;
BufferedWriter bwX; // output object
StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output
StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data
HashMap secData;
ArrayList subDataArr; // Arraylist for event data holder
HashMap subData;
ArrayList secDataArr; // Arraylist for section data holder
HashMap sqData;
ArrayList<HashMap> evtArr; // Arraylist for section data holder
HashMap evtData;
// int trmnNum; // total numbers of treatment in the data holder
int cuNum; // total numbers of cultivars in the data holder
int flNum; // total numbers of fields in the data holder
int saNum; // total numbers of soil analysis in the data holder
int icNum; // total numbers of initial conditions in the data holder
int mpNum; // total numbers of plaintings in the data holder
int miNum; // total numbers of irrigations in the data holder
int mfNum; // total numbers of fertilizers in the data holder
int mrNum; // total numbers of residues in the data holder
int mcNum; // total numbers of chemical in the data holder
int mtNum; // total numbers of tillage in the data holder
int meNum; // total numbers of enveronment modification in the data holder
int mhNum; // total numbers of harvest in the data holder
int smNum; // total numbers of simulation controll record
ArrayList<HashMap> sqArr; // array for treatment record
ArrayList cuArr = new ArrayList(); // array for cultivars record
ArrayList flArr = new ArrayList(); // array for fields record
ArrayList saArr = new ArrayList(); // array for soil analysis record
ArrayList icArr = new ArrayList(); // array for initial conditions record
ArrayList mpArr = new ArrayList(); // array for plaintings record
ArrayList miArr = new ArrayList(); // array for irrigations record
ArrayList mfArr = new ArrayList(); // array for fertilizers record
ArrayList mrArr = new ArrayList(); // array for residues record
ArrayList mcArr = new ArrayList(); // array for chemical record
ArrayList mtArr = new ArrayList(); // array for tillage record
ArrayList meArr = new ArrayList(); // array for enveronment modification record
ArrayList mhArr = new ArrayList(); // array for harvest record
ArrayList smArr = new ArrayList(); // array for simulation control record
String exName;
try {
// Set default value for missing data
if (expData == null || expData.isEmpty()) {
return;
}
// decompressData((HashMap) result);
setDefVal();
// Initial BufferedWriter
String fileName = getFileName(result, "X");
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwX = new BufferedWriter(new FileWriter(outputFile));
// Output XFile
// EXP.DETAILS Section
sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n",
getFileName(result, "").replaceAll("\\.", ""),
getObjectOr(expData, "local_name", defValBlank).toString()));
// GENERAL Section
sbGenData.append("*GENERAL\r\n");
// People
if (!getObjectOr(expData, "people", "").equals("")) {
sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "people", defValBlank).toString()));
}
// Address
if (getObjectOr(expData, "institution", "").equals("")) {
if (!getObjectOr(expData, "fl_loc_1", "").equals("")
&& getObjectOr(expData, "fl_loc_2", "").equals("")
&& getObjectOr(expData, "fl_loc_3", "").equals("")) {
sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n",
getObjectOr(expData, "fl_loc_1", defValBlank).toString(),
getObjectOr(expData, "fl_loc_2", defValBlank).toString(),
getObjectOr(expData, "fl_loc_3", defValBlank).toString()));
}
} else {
sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString()));
}
// Site
if (!getObjectOr(expData, "site", "").equals("")) {
sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site", defValBlank).toString()));
}
// Plot Info
if (isPlotInfoExist(expData)) {
sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n");
sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n",
formatNumStr(6, expData, "plta", defValR),
formatNumStr(5, expData, "pltr#", defValI),
formatNumStr(5, expData, "pltln", defValR),
formatNumStr(5, expData, "pldr", defValI),
formatNumStr(5, expData, "pltsp", defValI),
getObjectOr(expData, "plot_layout", defValC).toString(),
formatNumStr(5, expData, "pltha", defValR),
formatNumStr(5, expData, "plth#", defValI),
formatNumStr(5, expData, "plthl", defValR),
getObjectOr(expData, "plthm", defValC).toString()));
}
// Notes
if (!getObjectOr(expData, "tr_notes", "").equals("")) {
sbNotesData.append("@NOTES\r\n");
String notes = getObjectOr(expData, "tr_notes", defValC).toString();
notes = notes.replaceAll("\\\\r\\\\n", "\r\n");
// If notes contain newline code, then write directly
if (notes.indexOf("\r\n") >= 0) {
// sbData.append(String.format(" %1$s\r\n", notes));
sbNotesData.append(notes);
} // Otherwise, add newline for every 75-bits charactors
else {
while (notes.length() > 75) {
sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n");
notes = notes.substring(75);
}
sbNotesData.append(" ").append(notes).append("\r\n");
}
}
sbData.append("\r\n");
// TREATMENT Section
sqArr = getDataList(expData, "dssat_sequence", "data");
evtArr = getDataList(expData, "management", "events");
ArrayList<HashMap> rootArr = getObjectOr(expData, "dssat_root", new ArrayList());
ArrayList<HashMap> meOrgArr = getDataList(expData, "dssat_environment_modification", "data");
ArrayList<HashMap> smOrgArr = getDataList(expData, "dssat_simulation_control", "data");
String seqId;
String em;
String sm;
sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n");
sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n");
// if there is no sequence info, create dummy data
if (sqArr.isEmpty()) {
sqArr.add(new HashMap());
}
// Set sequence related block info
for (int i = 0; i < sqArr.size(); i++) {
sqData = sqArr.get(i);
seqId = getValueOr(sqData, "seqid", defValBlank);
em = getValueOr(sqData, "em", defValBlank);
sm = getValueOr(sqData, "sm", defValBlank);
if (i < soilArr.size()) {
soilData = soilArr.get(i);
} else if (soilArr.isEmpty()) {
soilData = new HashMap();
} else {
soilData = soilArr.get(0);
}
// if (i < wthArr.size()) {
// wthData = wthArr.get(i);
// } else if (wthArr.isEmpty()) {
// wthData = new HashMap();
// } else {
// wthData = wthArr.get(0);
// }
HashMap cuData = new HashMap();
HashMap flData = new HashMap();
HashMap mpData = new HashMap();
ArrayList<HashMap> miSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> meSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>();
HashMap smData = new HashMap();
HashMap rootData;
// Set exp root info
if (i < rootArr.size()) {
rootData = rootArr.get(i);
} else {
rootData = expData;
}
// Set field info
copyItem(flData, rootData, "id_field");
flData.put("wst_id", getWthFileName(rootData));
// if (i < rootArr.size()) {
// // copyItem(flData, expData, "wst_id");
// flData.put("wst_id", getWthFileName(rootData));
// } else {
// flData.put("wst_id", getWthFileName(wthData));
// }
copyItem(flData, rootData, "flsl");
copyItem(flData, rootData, "flob");
copyItem(flData, rootData, "fl_drntype");
copyItem(flData, rootData, "fldrd");
copyItem(flData, rootData, "fldrs");
copyItem(flData, rootData, "flst");
if (soilData.get("sltx") != null) {
copyItem(flData, soilData, "sltx");
} else {
copyItem(flData, rootData, "sltx");
}
copyItem(flData, soilData, "sldp");
copyItem(flData, rootData, "soil_id");
copyItem(flData, rootData, "fl_name");
copyItem(flData, rootData, "fl_lat");
copyItem(flData, rootData, "fl_long");
copyItem(flData, rootData, "flele");
copyItem(flData, rootData, "farea");
copyItem(flData, rootData, "fllwr");
copyItem(flData, rootData, "flsla");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "flhst");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "fhdur");
// remove the "_trno" in the soil_id when soil analysis is available
String soilId = getValueOr(flData, "soil_id", "");
if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) {
flData.put("soil_id", soilId.replaceAll("_\\d+$", ""));
}
flNum = setSecDataArr(flData, flArr);
// Set initial condition info
icNum = setSecDataArr(getObjectOr(rootData, "initial_conditions", new HashMap()), icArr);
// Set environment modification info
for (int j = 0; j < meOrgArr.size(); j++) {
if (em.equals(meOrgArr.get(j).get("em"))) {
HashMap tmp = new HashMap();
tmp.putAll(meOrgArr.get(j));
tmp.remove("em");
meSubArr.add(tmp);
}
}
// Set soil analysis info
// ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer");
ArrayList<HashMap> soilLarys = getObjectOr(soilData, "soilLayer", new ArrayList());
// // If it is stored in the initial condition block
// if (isSoilAnalysisExist(icSubArr)) {
// HashMap saData = new HashMap();
// ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
// HashMap saSubData;
// for (int i = 0; i < icSubArr.size(); i++) {
// saSubData = new HashMap();
// copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false);
// copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false);
// saSubArr.add(saSubData);
// }
// copyItem(saData, soilData, "sadat");
// saData.put("soilLayer", saSubArr);
// saNum = setSecDataArr(saData, saArr);
// } else
// If it is stored in the soil block
if (isSoilAnalysisExist(soilLarys)) {
HashMap saData = new HashMap();
ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
HashMap saSubData;
for (int j = 0; j < soilLarys.size(); j++) {
saSubData = new HashMap();
copyItem(saSubData, soilLarys.get(j), "sabl", "sllb", false);
copyItem(saSubData, soilLarys.get(j), "sasc", "slsc", false);
saSubArr.add(saSubData);
}
copyItem(saData, soilData, "sadat");
saData.put("soilLayer", saSubArr);
saNum = setSecDataArr(saData, saArr);
} else {
saNum = 0;
}
// Set simulation control info
for (int j = 0; j < smOrgArr.size(); j++) {
if (sm.equals(smOrgArr.get(j).get("sm"))) {
smData.putAll(smOrgArr.get(j));
smData.remove("sm");
break;
}
}
// if (smData.isEmpty()) {
// smData.put("fertilizer", mfSubArr);
// smData.put("irrigation", miSubArr);
// smData.put("planting", mpData);
// }
copyItem(smData, rootData, "sdat");
// Loop all event data
for (int j = 0; j < evtArr.size(); j++) {
evtData = new HashMap();
evtData.putAll(evtArr.get(j));
// Check if it has same sequence number
if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) {
evtData.remove("seqid");
// Planting event
if (getValueOr(evtData, "event", defValBlank).equals("planting")) {
// Set cultivals info
copyItem(cuData, evtData, "cul_name");
copyItem(cuData, evtData, "crid");
copyItem(cuData, evtData, "cul_id");
copyItem(cuData, evtData, "dssat_cul_id");
copyItem(cuData, evtData, "rm");
copyItem(cuData, evtData, "cul_notes");
translateTo2BitCrid(cuData);
// Set planting info
mpData.putAll(evtData);
mpData.remove("cul_name");
} // irrigation event
else if (getValueOr(evtData, "event", "").equals("irrigation")) {
miSubArr.add(evtData);
} // fertilizer event
else if (getValueOr(evtData, "event", "").equals("fertilizer")) {
mfSubArr.add(evtData);
} // organic_matter event
else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again.
mrSubArr.add(evtData);
} // chemical event
else if (getValueOr(evtData, "event", "").equals("chemical")) {
mcSubArr.add(evtData);
} // tillage event
else if (getValueOr(evtData, "event", "").equals("tillage")) {
mtSubArr.add(evtData);
// } // environment_modification event
// else if (getValueOr(evtData, "event", "").equals("environment_modification")) {
// meSubArr.add(evtData);
} // harvest event
else if (getValueOr(evtData, "event", "").equals("harvest")) {
mhSubArr.add(evtData);
} else {
}
} else {
}
}
// If alternative fields are avaiable for fertilizer data
if (mfSubArr.isEmpty()) {
if (!getObjectOr(result, "fen_tot", "").equals("")
|| !getObjectOr(result, "fep_tot", "").equals("")
|| !getObjectOr(result, "fek_tot", "").equals("")) {
mfSubArr.add(new HashMap());
}
}
cuNum = setSecDataArr(cuData, cuArr);
mpNum = setSecDataArr(mpData, mpArr);
miNum = setSecDataArr(miSubArr, miArr);
mfNum = setSecDataArr(mfSubArr, mfArr);
mrNum = setSecDataArr(mrSubArr, mrArr);
mcNum = setSecDataArr(mcSubArr, mcArr);
mtNum = setSecDataArr(mtSubArr, mtArr);
meNum = setSecDataArr(meSubArr, meArr);
mhNum = setSecDataArr(mhSubArr, mhArr);
smNum = setSecDataArr(smData, smArr);
if (smNum == 0) {
smNum = 1;
}
sbData.append(String.format("%1$-3s%2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n",
String.format("%2s", getValueOr(sqData, "trno", "1")), // For 3-bit treatment number
getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf
getValueOr(sqData, "op", "1").toString(),
getValueOr(sqData, "co", "0").toString(),
formatStr(25, sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC))),
cuNum, //getObjectOr(data, "ge", defValI).toString(),
flNum, //getObjectOr(data, "fl", defValI).toString(),
saNum, //getObjectOr(data, "sa", defValI).toString(),
icNum, //getObjectOr(data, "ic", defValI).toString(),
mpNum, //getObjectOr(data, "pl", defValI).toString(),
miNum, //getObjectOr(data, "ir", defValI).toString(),
mfNum, //getObjectOr(data, "fe", defValI).toString(),
mrNum, //getObjectOr(data, "om", defValI).toString(),
mcNum, //getObjectOr(data, "ch", defValI).toString(),
mtNum, //getObjectOr(data, "ti", defValI).toString(),
meNum, //getObjectOr(data, "em", defValI).toString(),
mhNum, //getObjectOr(data, "ha", defValI).toString(),
smNum)); // 1
}
sbData.append("\r\n");
// CULTIVARS Section
if (!cuArr.isEmpty()) {
sbData.append("*CULTIVARS\r\n");
sbData.append("@C CR INGENO CNAME\r\n");
for (int idx = 0; idx < cuArr.size(); idx++) {
secData = (HashMap) cuArr.get(idx);
// String cul_id = defValC;
String crid = getObjectOr(secData, "crid", "");
// Checl if necessary data is missing
if (crid.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n");
// } else {
// // Set cultivar id a default value deponds on the crop id
// if (crid.equals("MZ")) {
// cul_id = "990002";
// } else {
// cul_id = "999999";
// }
// }
// if (getObjectOr(secData, "cul_id", "").equals("")) {
// sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n");
}
sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
formatStr(2, secData, "crid", defValBlank), // P.S. if missing, default value use blank string
formatStr(6, secData, "dssat_cul_id", getObjectOr(secData, "cul_id", defValC)), // P.S. Set default value which is deponds on crid(Cancelled)
getObjectOr(secData, "cul_name", defValC).toString()));
if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) {
if (sbNotesData.toString().equals("")) {
sbNotesData.append("@NOTES\r\n");
}
sbNotesData.append(" Cultivar Additional Info\r\n");
sbNotesData.append(" C RM CNAME CUL_NOTES\r\n");
sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "rm", defValC).toString(),
getObjectOr(secData, "cul_notes", defValC).toString()));
}
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no cultivar data in the experiment.\r\n");
}
// FIELDS Section
if (!flArr.isEmpty()) {
sbData.append("*FIELDS\r\n");
sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n");
eventPart2 = new StringBuilder();
eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n");
} else {
sbError.append("! Warning: There is no field data in the experiment.\r\n");
}
for (int idx = 0; idx < flArr.size(); idx++) {
secData = (HashMap) flArr.get(idx);
// Check if the necessary is missing
if (getObjectOr(secData, "wst_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n");
}
String soil_id = getSoilID(secData);
if (soil_id.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n");
} else if (soil_id.length() > 10) {
sbError.append("! Warning: Oversized data : [soil_id] ").append(soil_id).append("\r\n");
}
sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
getObjectOr(secData, "id_field", defValC).toString(),
getObjectOr(secData, "wst_id", defValC).toString(),
getObjectOr(secData, "flsl", defValC).toString(),
formatNumStr(5, secData, "flob", defValR),
getObjectOr(secData, "fl_drntype", defValC).toString(),
formatNumStr(5, secData, "fldrd", defValR),
formatNumStr(5, secData, "fldrs", defValR),
getObjectOr(secData, "flst", defValC).toString(),
getObjectOr(secData, "sltx", defValC).toString(),
formatNumStr(5, secData, "sldp", defValR),
soil_id,
getObjectOr(secData, "fl_name", defValC).toString()));
eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
formatNumStr(15, secData, "fl_long", defValR),
formatNumStr(15, secData, "fl_lat", defValR),
formatNumStr(9, secData, "flele", defValR),
formatNumStr(17, secData, "farea", defValR),
"-99", // P.S. SLEN keeps -99
formatNumStr(5, secData, "fllwr", defValR),
formatNumStr(5, secData, "flsla", defValR),
getObjectOr(secData, "flhst", defValC).toString(),
formatNumStr(5, secData, "fhdur", defValR)));
}
if (!flArr.isEmpty()) {
sbData.append(eventPart2.toString()).append("\r\n");
}
// SOIL ANALYSIS Section
if (!saArr.isEmpty()) {
sbData.append("*SOIL ANALYSIS\r\n");
for (int idx = 0; idx < saArr.size(); idx++) {
secData = (HashMap) saArr.get(idx);
sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n",
idx + 1, //getObjectOr(secData, "sa", defValI).toString(),
formatDateStr(getObjectOr(secData, "sadat", defValD).toString()),
getObjectOr(secData, "samhb", defValC).toString(),
getObjectOr(secData, "sampx", defValC).toString(),
getObjectOr(secData, "samke", defValC).toString(),
getObjectOr(secData, "sa_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(subData, "sa", defValI).toString(),
formatNumStr(5, subData, "sabl", defValR),
formatNumStr(5, subData, "sabdm", defValR),
formatNumStr(5, subData, "saoc", defValR),
formatNumStr(5, subData, "sani", defValR),
formatNumStr(5, subData, "saphw", defValR),
formatNumStr(5, subData, "saphb", defValR),
formatNumStr(5, subData, "sapx", defValR),
formatNumStr(5, subData, "sake", defValR),
formatNumStr(5, subData, "sasc", defValR)));
}
}
sbData.append("\r\n");
}
// INITIAL CONDITIONS Section
if (!icArr.isEmpty()) {
sbData.append("*INITIAL CONDITIONS\r\n");
for (int idx = 0; idx < icArr.size(); idx++) {
secData = (HashMap) icArr.get(idx);
translateTo2BitCrid(secData, "icpcr");
sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n",
idx + 1, //getObjectOr(secData, "ic", defValI).toString(),
getObjectOr(secData, "icpcr", defValC).toString(),
formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()),
formatNumStr(5, secData, "icrt", defValR),
formatNumStr(5, secData, "icnd", defValR),
formatNumStr(5, secData, "icrz#", defValR),
formatNumStr(5, secData, "icrze", defValR),
formatNumStr(5, secData, "icwt", defValR),
formatNumStr(5, secData, "icrag", defValR),
formatNumStr(5, secData, "icrn", defValR),
formatNumStr(5, secData, "icrp", defValR),
formatNumStr(5, secData, "icrip", defValR),
formatNumStr(5, secData, "icrdp", defValR),
getObjectOr(secData, "ic_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@C ICBL SH2O SNH4 SNO3\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n",
idx + 1, //getObjectOr(subData, "ic", defValI).toString(),
formatNumStr(5, subData, "icbl", defValR),
formatNumStr(5, subData, "ich2o", defValR),
formatNumStr(5, subData, "icnh4", defValR),
formatNumStr(5, subData, "icno3", defValR)));
}
}
sbData.append("\r\n");
}
// PLANTING DETAILS Section
if (!mpArr.isEmpty()) {
sbData.append("*PLANTING DETAILS\r\n");
sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n");
for (int idx = 0; idx < mpArr.size(); idx++) {
secData = (HashMap) mpArr.get(idx);
// Check if necessary data is missing
String pdate = getObjectOr(secData, "date", "");
if (pdate.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n");
} else if (formatDateStr(pdate).equals(defValD)) {
sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n");
}
if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n");
}
if (getObjectOr(secData, "plrs", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n");
}
// if (getObjectOr(secData, "plma", "").equals("")) {
// sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n");
// }
// if (getObjectOr(secData, "plds", "").equals("")) {
// sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n");
// }
// if (getObjectOr(secData, "pldp", "").equals("")) {
// sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n");
// }
// mm -> cm
String pldp = getObjectOr(secData, "pldp", "");
if (!pldp.equals("")) {
try {
BigDecimal pldpBD = new BigDecimal(pldp);
pldpBD = pldpBD.divide(new BigDecimal("10"));
secData.put("pldp", pldpBD.toString());
} catch (NumberFormatException e) {
}
}
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n",
idx + 1, //getObjectOr(data, "pl", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()),
formatDateStr(getObjectOr(secData, "pldae", defValD).toString()),
formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)),
formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)),
getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled)
getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled)
formatNumStr(5, secData, "plrs", defValR),
formatNumStr(5, secData, "plrd", defValR),
formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled)
formatNumStr(5, secData, "plmwt", defValR),
formatNumStr(5, secData, "page", defValR),
formatNumStr(5, secData, "penv", defValR),
formatNumStr(5, secData, "plph", defValR),
formatNumStr(5, secData, "plspl", defValR),
getObjectOr(secData, "pl_name", defValC).toString()));
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no plainting data in the experiment.\r\n");
}
// IRRIGATION AND WATER MANAGEMENT Section
if (!miArr.isEmpty()) {
sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n");
for (int idx = 0; idx < miArr.size(); idx++) {
// secData = (ArrayList) miArr.get(idx);
subDataArr = (ArrayList) miArr.get(idx);
if (!subDataArr.isEmpty()) {
subData = (HashMap) subDataArr.get(0);
} else {
subData = new HashMap();
}
sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n",
idx + 1, //getObjectOr(data, "ir", defValI).toString(),
formatNumStr(5, subData, "ireff", defValR),
formatNumStr(5, subData, "irmdp", defValR),
formatNumStr(5, subData, "irthr", defValR),
formatNumStr(5, subData, "irept", defValR),
getObjectOr(subData, "irstg", defValC).toString(),
getObjectOr(subData, "iame", defValC).toString(),
formatNumStr(5, subData, "iamt", defValR),
getObjectOr(subData, "ir_name", defValC).toString()));
if (!subDataArr.isEmpty()) {
sbData.append("@I IDATE IROP IRVAL\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n",
idx + 1, //getObjectOr(subData, "ir", defValI).toString(),
formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date
getObjectOr(subData, "irop", defValC).toString(),
formatNumStr(5, subData, "irval", defValR)));
}
}
sbData.append("\r\n");
}
// FERTILIZERS (INORGANIC) Section
if (!mfArr.isEmpty()) {
sbData.append("*FERTILIZERS (INORGANIC)\r\n");
sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n");
// String fen_tot = getObjectOr(result, "fen_tot", defValR);
// String fep_tot = getObjectOr(result, "fep_tot", defValR);
// String fek_tot = getObjectOr(result, "fek_tot", defValR);
// String pdate = getPdate(result);
// if (pdate.equals("")) {
// pdate = defValD;
// }
for (int idx = 0; idx < mfArr.size(); idx++) {
secDataArr = (ArrayList) mfArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
// if (getObjectOr(secData, "fdate", "").equals("")) {
// sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n");
// }
// if (getObjectOr(secData, "fecd", "").equals("")) {
// sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n");
// }
// if (getObjectOr(secData, "feacd", "").equals("")) {
// sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n");
// }
// if (getObjectOr(secData, "fedep", "").equals("")) {
// sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n");
// }
// if (getObjectOr(secData, "feamn", "").equals("")) {
// sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamp", "").equals("")) {
// sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamk", "").equals("")) {
// sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n",
idx + 1, //getObjectOr(data, "fe", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date
getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled)
getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled)
formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled)
formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamc", defValR),
formatNumStr(5, secData, "feamo", defValR),
getObjectOr(secData, "feocd", defValC).toString(),
getObjectOr(secData, "fe_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// RESIDUES AND ORGANIC FERTILIZER Section
if (!mrArr.isEmpty()) {
sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n");
sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n");
for (int idx = 0; idx < mrArr.size(); idx++) {
secDataArr = (ArrayList) mrArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n",
idx + 1, //getObjectOr(secData, "om", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date
getObjectOr(secData, "omcd", defValC).toString(),
formatNumStr(5, secData, "omamt", defValR),
formatNumStr(5, secData, "omn%", defValR),
formatNumStr(5, secData, "omp%", defValR),
formatNumStr(5, secData, "omk%", defValR),
formatNumStr(5, secData, "ominp", defValR),
formatNumStr(5, secData, "omdep", defValR),
formatNumStr(5, secData, "omacd", defValR),
getObjectOr(secData, "om_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// CHEMICAL APPLICATIONS Section
if (!mcArr.isEmpty()) {
sbData.append("*CHEMICAL APPLICATIONS\r\n");
sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n");
for (int idx = 0; idx < mcArr.size(); idx++) {
secDataArr = (ArrayList) mcArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ch", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date
getObjectOr(secData, "chcd", defValC).toString(),
formatNumStr(5, secData, "chamt", defValR),
getObjectOr(secData, "chacd", defValC).toString(),
getObjectOr(secData, "chdep", defValC).toString(),
getObjectOr(secData, "ch_targets", defValC).toString(),
getObjectOr(secData, "ch_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// TILLAGE Section
if (!mtArr.isEmpty()) {
sbData.append("*TILLAGE AND ROTATIONS\r\n");
sbData.append("@T TDATE TIMPL TDEP TNAME\r\n");
for (int idx = 0; idx < mtArr.size(); idx++) {
secDataArr = (ArrayList) mtArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n",
idx + 1, //getObjectOr(secData, "ti", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date
getObjectOr(secData, "tiimp", defValC).toString(),
formatNumStr(5, secData, "tidep", defValR),
getObjectOr(secData, "ti_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// ENVIRONMENT MODIFICATIONS Section
if (!meArr.isEmpty()) {
sbData.append("*ENVIRONMENT MODIFICATIONS\r\n");
sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n");
for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) {
secDataArr = (ArrayList) meArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s%2$s\r\n",
cnt,
secData.get("em_data")));
// sbData.append(String.format("%1$2s%2$s\r\n",
// idx + 1,
// (String) secDataArr.get(i)));
// sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n",
// idx + 1, //getObjectOr(secData, "em", defValI).toString(),
// formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date
// getObjectOr(secData, "ecdyl", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdyl", defValR),
// getObjectOr(secData, "ecrad", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrad", defValR),
// getObjectOr(secData, "ecmax", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmax", defValR),
// getObjectOr(secData, "ecmin", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmin", defValR),
// getObjectOr(secData, "ecrai", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrai", defValR),
// getObjectOr(secData, "ecco2", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emco2", defValR),
// getObjectOr(secData, "ecdew", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdew", defValR),
// getObjectOr(secData, "ecwnd", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emwnd", defValR),
// getObjectOr(secData, "em_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// HARVEST DETAILS Section
if (!mhArr.isEmpty()) {
sbData.append("*HARVEST DETAILS\r\n");
sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n");
for (int idx = 0; idx < mhArr.size(); idx++) {
secDataArr = (ArrayList) mhArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ha", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date
getObjectOr(secData, "hastg", defValC).toString(),
getObjectOr(secData, "hacom", defValC).toString(),
getObjectOr(secData, "hasiz", defValC).toString(),
formatNumStr(5, secData, "hapc", defValR),
formatNumStr(5, secData, "habpc", defValR),
getObjectOr(secData, "ha_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section
if (!smArr.isEmpty()) {
// Set Title list
ArrayList smTitles = new ArrayList();
smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n");
smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n");
smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
String[] keys = new String[10];
keys[0] = "sm_general";
keys[1] = "sm_options";
keys[2] = "sm_methods";
keys[3] = "sm_management";
keys[4] = "sm_outputs";
keys[5] = "sm_planting";
keys[6] = "sm_irrigation";
keys[7] = "sm_nitrogen";
keys[8] = "sm_residues";
keys[9] = "sm_harvests";
// Loop all the simulation control records
for (int idx = 0; idx < smArr.size(); idx++) {
secData = (HashMap) smArr.get(idx);
if (secData.containsKey("sm_general")) {
sbData.append("*SIMULATION CONTROLS\r\n");
secData.remove("sm");
// Object[] keys = secData.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
sbData.append(smTitles.get(i));
sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n");
if (i == 4) {
sbData.append("\r\n");
}
}
sbData.append("\r\n");
} else {
sbData.append(createSMMAStr(idx + 1, secData));
}
}
} else {
sbData.append(createSMMAStr(1, new HashMap()));
}
// Output finish
bwX.write(sbError.toString());
bwX.write(sbGenData.toString());
bwX.write(sbNotesData.toString());
bwX.write(sbData.toString());
bwX.close();
} catch (IOException e) {
LOG.error(DssatCommonOutput.getStackTrace(e));
}
}
| public void writeFile(String arg0, Map result) {
// Initial variables
HashMap expData = (HashMap) result;
ArrayList<HashMap> soilArr = readSWData(expData, "soil");
// ArrayList<HashMap> wthArr = readSWData(expData, "weather");
HashMap soilData;
// HashMap wthData;
BufferedWriter bwX; // output object
StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output
StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data
HashMap secData;
ArrayList subDataArr; // Arraylist for event data holder
HashMap subData;
ArrayList secDataArr; // Arraylist for section data holder
HashMap sqData;
ArrayList<HashMap> evtArr; // Arraylist for section data holder
HashMap evtData;
// int trmnNum; // total numbers of treatment in the data holder
int cuNum; // total numbers of cultivars in the data holder
int flNum; // total numbers of fields in the data holder
int saNum; // total numbers of soil analysis in the data holder
int icNum; // total numbers of initial conditions in the data holder
int mpNum; // total numbers of plaintings in the data holder
int miNum; // total numbers of irrigations in the data holder
int mfNum; // total numbers of fertilizers in the data holder
int mrNum; // total numbers of residues in the data holder
int mcNum; // total numbers of chemical in the data holder
int mtNum; // total numbers of tillage in the data holder
int meNum; // total numbers of enveronment modification in the data holder
int mhNum; // total numbers of harvest in the data holder
int smNum; // total numbers of simulation controll record
ArrayList<HashMap> sqArr; // array for treatment record
ArrayList cuArr = new ArrayList(); // array for cultivars record
ArrayList flArr = new ArrayList(); // array for fields record
ArrayList saArr = new ArrayList(); // array for soil analysis record
ArrayList icArr = new ArrayList(); // array for initial conditions record
ArrayList mpArr = new ArrayList(); // array for plaintings record
ArrayList miArr = new ArrayList(); // array for irrigations record
ArrayList mfArr = new ArrayList(); // array for fertilizers record
ArrayList mrArr = new ArrayList(); // array for residues record
ArrayList mcArr = new ArrayList(); // array for chemical record
ArrayList mtArr = new ArrayList(); // array for tillage record
ArrayList meArr = new ArrayList(); // array for enveronment modification record
ArrayList mhArr = new ArrayList(); // array for harvest record
ArrayList smArr = new ArrayList(); // array for simulation control record
// String exName;
try {
// Set default value for missing data
if (expData == null || expData.isEmpty()) {
return;
}
// decompressData((HashMap) result);
setDefVal();
// Initial BufferedWriter
String fileName = getFileName(result, "X");
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwX = new BufferedWriter(new FileWriter(outputFile));
// Output XFile
// EXP.DETAILS Section
sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n",
getFileName(result, "").replaceAll("\\.", ""),
getObjectOr(expData, "local_name", defValBlank).toString()));
// GENERAL Section
sbGenData.append("*GENERAL\r\n");
// People
if (!getObjectOr(expData, "people", "").equals("")) {
sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "people", defValBlank).toString()));
}
// Address
if (getObjectOr(expData, "institution", "").equals("")) {
if (!getObjectOr(expData, "fl_loc_1", "").equals("")
&& getObjectOr(expData, "fl_loc_2", "").equals("")
&& getObjectOr(expData, "fl_loc_3", "").equals("")) {
sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n",
getObjectOr(expData, "fl_loc_1", defValBlank).toString(),
getObjectOr(expData, "fl_loc_2", defValBlank).toString(),
getObjectOr(expData, "fl_loc_3", defValBlank).toString()));
}
} else {
sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString()));
}
// Site
if (!getObjectOr(expData, "site", "").equals("")) {
sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site", defValBlank).toString()));
}
// Plot Info
if (isPlotInfoExist(expData)) {
sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n");
sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n",
formatNumStr(6, expData, "plta", defValR),
formatNumStr(5, expData, "pltr#", defValI),
formatNumStr(5, expData, "pltln", defValR),
formatNumStr(5, expData, "pldr", defValI),
formatNumStr(5, expData, "pltsp", defValI),
getObjectOr(expData, "plot_layout", defValC).toString(),
formatNumStr(5, expData, "pltha", defValR),
formatNumStr(5, expData, "plth#", defValI),
formatNumStr(5, expData, "plthl", defValR),
getObjectOr(expData, "plthm", defValC).toString()));
}
// Notes
if (!getObjectOr(expData, "tr_notes", "").equals("")) {
sbNotesData.append("@NOTES\r\n");
String notes = getObjectOr(expData, "tr_notes", defValC).toString();
notes = notes.replaceAll("\\\\r\\\\n", "\r\n");
// If notes contain newline code, then write directly
if (notes.indexOf("\r\n") >= 0) {
// sbData.append(String.format(" %1$s\r\n", notes));
sbNotesData.append(notes);
} // Otherwise, add newline for every 75-bits charactors
else {
while (notes.length() > 75) {
sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n");
notes = notes.substring(75);
}
sbNotesData.append(" ").append(notes).append("\r\n");
}
}
sbData.append("\r\n");
// TREATMENT Section
sqArr = getDataList(expData, "dssat_sequence", "data");
evtArr = getDataList(expData, "management", "events");
ArrayList<HashMap> rootArr = getObjectOr(expData, "dssat_root", new ArrayList());
ArrayList<HashMap> meOrgArr = getDataList(expData, "dssat_environment_modification", "data");
ArrayList<HashMap> smOrgArr = getDataList(expData, "dssat_simulation_control", "data");
String seqId;
String em;
String sm;
sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n");
sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n");
// if there is no sequence info, create dummy data
if (sqArr.isEmpty()) {
sqArr.add(new HashMap());
}
// Set sequence related block info
for (int i = 0; i < sqArr.size(); i++) {
sqData = sqArr.get(i);
seqId = getValueOr(sqData, "seqid", defValBlank);
em = getValueOr(sqData, "em", defValBlank);
sm = getValueOr(sqData, "sm", defValBlank);
if (i < soilArr.size()) {
soilData = soilArr.get(i);
} else if (soilArr.isEmpty()) {
soilData = new HashMap();
} else {
soilData = soilArr.get(0);
}
if (soilData == null) {
soilData = new HashMap();
}
// if (i < wthArr.size()) {
// wthData = wthArr.get(i);
// } else if (wthArr.isEmpty()) {
// wthData = new HashMap();
// } else {
// wthData = wthArr.get(0);
// }
HashMap cuData = new HashMap();
HashMap flData = new HashMap();
HashMap mpData = new HashMap();
ArrayList<HashMap> miSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> meSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>();
HashMap smData = new HashMap();
HashMap rootData;
// Set exp root info
if (i < rootArr.size()) {
rootData = rootArr.get(i);
} else {
rootData = expData;
}
// Set field info
copyItem(flData, rootData, "id_field");
flData.put("wst_id", getWthFileName(rootData));
// if (i < rootArr.size()) {
// // copyItem(flData, expData, "wst_id");
// flData.put("wst_id", getWthFileName(rootData));
// } else {
// flData.put("wst_id", getWthFileName(wthData));
// }
copyItem(flData, rootData, "flsl");
copyItem(flData, rootData, "flob");
copyItem(flData, rootData, "fl_drntype");
copyItem(flData, rootData, "fldrd");
copyItem(flData, rootData, "fldrs");
copyItem(flData, rootData, "flst");
if (soilData.get("sltx") != null) {
copyItem(flData, soilData, "sltx");
} else {
copyItem(flData, rootData, "sltx");
}
copyItem(flData, soilData, "sldp");
copyItem(flData, rootData, "soil_id");
copyItem(flData, rootData, "fl_name");
copyItem(flData, rootData, "fl_lat");
copyItem(flData, rootData, "fl_long");
copyItem(flData, rootData, "flele");
copyItem(flData, rootData, "farea");
copyItem(flData, rootData, "fllwr");
copyItem(flData, rootData, "flsla");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "flhst");
copyItem(flData, getObjectOr(rootData, "dssat_info", new HashMap()), "fhdur");
// remove the "_trno" in the soil_id when soil analysis is available
String soilId = getValueOr(flData, "soil_id", "");
if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) {
flData.put("soil_id", soilId.replaceAll("_\\d+$", ""));
}
flNum = setSecDataArr(flData, flArr);
// Set initial condition info
icNum = setSecDataArr(getObjectOr(rootData, "initial_conditions", new HashMap()), icArr);
// Set environment modification info
for (int j = 0; j < meOrgArr.size(); j++) {
if (em.equals(meOrgArr.get(j).get("em"))) {
HashMap tmp = new HashMap();
tmp.putAll(meOrgArr.get(j));
tmp.remove("em");
meSubArr.add(tmp);
}
}
// Set soil analysis info
// ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer");
ArrayList<HashMap> soilLarys = getObjectOr(soilData, "soilLayer", new ArrayList());
// // If it is stored in the initial condition block
// if (isSoilAnalysisExist(icSubArr)) {
// HashMap saData = new HashMap();
// ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
// HashMap saSubData;
// for (int i = 0; i < icSubArr.size(); i++) {
// saSubData = new HashMap();
// copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false);
// copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false);
// saSubArr.add(saSubData);
// }
// copyItem(saData, soilData, "sadat");
// saData.put("soilLayer", saSubArr);
// saNum = setSecDataArr(saData, saArr);
// } else
// If it is stored in the soil block
if (isSoilAnalysisExist(soilLarys)) {
HashMap saData = new HashMap();
ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
HashMap saSubData;
for (int j = 0; j < soilLarys.size(); j++) {
saSubData = new HashMap();
copyItem(saSubData, soilLarys.get(j), "sabl", "sllb", false);
copyItem(saSubData, soilLarys.get(j), "sasc", "slsc", false);
saSubArr.add(saSubData);
}
copyItem(saData, soilData, "sadat");
saData.put("soilLayer", saSubArr);
saNum = setSecDataArr(saData, saArr);
} else {
saNum = 0;
}
// Set simulation control info
for (int j = 0; j < smOrgArr.size(); j++) {
if (sm.equals(smOrgArr.get(j).get("sm"))) {
smData.putAll(smOrgArr.get(j));
smData.remove("sm");
break;
}
}
// if (smData.isEmpty()) {
// smData.put("fertilizer", mfSubArr);
// smData.put("irrigation", miSubArr);
// smData.put("planting", mpData);
// }
copyItem(smData, rootData, "sdat");
// Loop all event data
for (int j = 0; j < evtArr.size(); j++) {
evtData = new HashMap();
evtData.putAll(evtArr.get(j));
// Check if it has same sequence number
if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) {
evtData.remove("seqid");
// Planting event
if (getValueOr(evtData, "event", defValBlank).equals("planting")) {
// Set cultivals info
copyItem(cuData, evtData, "cul_name");
copyItem(cuData, evtData, "crid");
copyItem(cuData, evtData, "cul_id");
copyItem(cuData, evtData, "dssat_cul_id");
copyItem(cuData, evtData, "rm");
copyItem(cuData, evtData, "cul_notes");
translateTo2BitCrid(cuData);
// Set planting info
mpData.putAll(evtData);
mpData.remove("cul_name");
} // irrigation event
else if (getValueOr(evtData, "event", "").equals("irrigation")) {
miSubArr.add(evtData);
} // fertilizer event
else if (getValueOr(evtData, "event", "").equals("fertilizer")) {
mfSubArr.add(evtData);
} // organic_matter event
else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again.
mrSubArr.add(evtData);
} // chemical event
else if (getValueOr(evtData, "event", "").equals("chemical")) {
mcSubArr.add(evtData);
} // tillage event
else if (getValueOr(evtData, "event", "").equals("tillage")) {
mtSubArr.add(evtData);
// } // environment_modification event
// else if (getValueOr(evtData, "event", "").equals("environment_modification")) {
// meSubArr.add(evtData);
} // harvest event
else if (getValueOr(evtData, "event", "").equals("harvest")) {
mhSubArr.add(evtData);
} else {
}
} else {
}
}
// If alternative fields are avaiable for fertilizer data
if (mfSubArr.isEmpty()) {
if (!getObjectOr(result, "fen_tot", "").equals("")
|| !getObjectOr(result, "fep_tot", "").equals("")
|| !getObjectOr(result, "fek_tot", "").equals("")) {
mfSubArr.add(new HashMap());
}
}
cuNum = setSecDataArr(cuData, cuArr);
mpNum = setSecDataArr(mpData, mpArr);
miNum = setSecDataArr(miSubArr, miArr);
mfNum = setSecDataArr(mfSubArr, mfArr);
mrNum = setSecDataArr(mrSubArr, mrArr);
mcNum = setSecDataArr(mcSubArr, mcArr);
mtNum = setSecDataArr(mtSubArr, mtArr);
meNum = setSecDataArr(meSubArr, meArr);
mhNum = setSecDataArr(mhSubArr, mhArr);
smNum = setSecDataArr(smData, smArr);
if (smNum == 0) {
smNum = 1;
}
sbData.append(String.format("%1$-3s%2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n",
String.format("%2s", getValueOr(sqData, "trno", "1")), // For 3-bit treatment number
getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf
getValueOr(sqData, "op", "1").toString(),
getValueOr(sqData, "co", "0").toString(),
formatStr(25, sqData, "trt_name", getValueOr(rootData, "trt_name", getValueOr(rootData, "exname", defValC))),
cuNum, //getObjectOr(data, "ge", defValI).toString(),
flNum, //getObjectOr(data, "fl", defValI).toString(),
saNum, //getObjectOr(data, "sa", defValI).toString(),
icNum, //getObjectOr(data, "ic", defValI).toString(),
mpNum, //getObjectOr(data, "pl", defValI).toString(),
miNum, //getObjectOr(data, "ir", defValI).toString(),
mfNum, //getObjectOr(data, "fe", defValI).toString(),
mrNum, //getObjectOr(data, "om", defValI).toString(),
mcNum, //getObjectOr(data, "ch", defValI).toString(),
mtNum, //getObjectOr(data, "ti", defValI).toString(),
meNum, //getObjectOr(data, "em", defValI).toString(),
mhNum, //getObjectOr(data, "ha", defValI).toString(),
smNum)); // 1
}
sbData.append("\r\n");
// CULTIVARS Section
if (!cuArr.isEmpty()) {
sbData.append("*CULTIVARS\r\n");
sbData.append("@C CR INGENO CNAME\r\n");
for (int idx = 0; idx < cuArr.size(); idx++) {
secData = (HashMap) cuArr.get(idx);
// String cul_id = defValC;
String crid = getObjectOr(secData, "crid", "");
// Checl if necessary data is missing
if (crid.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n");
// } else {
// // Set cultivar id a default value deponds on the crop id
// if (crid.equals("MZ")) {
// cul_id = "990002";
// } else {
// cul_id = "999999";
// }
// }
// if (getObjectOr(secData, "cul_id", "").equals("")) {
// sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n");
}
sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
formatStr(2, secData, "crid", defValBlank), // P.S. if missing, default value use blank string
formatStr(6, secData, "dssat_cul_id", getObjectOr(secData, "cul_id", defValC)), // P.S. Set default value which is deponds on crid(Cancelled)
getObjectOr(secData, "cul_name", defValC).toString()));
if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) {
if (sbNotesData.toString().equals("")) {
sbNotesData.append("@NOTES\r\n");
}
sbNotesData.append(" Cultivar Additional Info\r\n");
sbNotesData.append(" C RM CNAME CUL_NOTES\r\n");
sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "rm", defValC).toString(),
getObjectOr(secData, "cul_notes", defValC).toString()));
}
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no cultivar data in the experiment.\r\n");
}
// FIELDS Section
if (!flArr.isEmpty()) {
sbData.append("*FIELDS\r\n");
sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n");
eventPart2 = new StringBuilder();
eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n");
} else {
sbError.append("! Warning: There is no field data in the experiment.\r\n");
}
for (int idx = 0; idx < flArr.size(); idx++) {
secData = (HashMap) flArr.get(idx);
// Check if the necessary is missing
if (getObjectOr(secData, "wst_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n");
}
String soil_id = getSoilID(secData);
if (soil_id.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n");
} else if (soil_id.length() > 10) {
sbError.append("! Warning: Oversized data : [soil_id] ").append(soil_id).append("\r\n");
}
sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
getObjectOr(secData, "id_field", defValC).toString(),
getObjectOr(secData, "wst_id", defValC).toString(),
getObjectOr(secData, "flsl", defValC).toString(),
formatNumStr(5, secData, "flob", defValR),
getObjectOr(secData, "fl_drntype", defValC).toString(),
formatNumStr(5, secData, "fldrd", defValR),
formatNumStr(5, secData, "fldrs", defValR),
getObjectOr(secData, "flst", defValC).toString(),
getObjectOr(secData, "sltx", defValC).toString(),
formatNumStr(5, secData, "sldp", defValR),
soil_id,
getObjectOr(secData, "fl_name", defValC).toString()));
eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
formatNumStr(15, secData, "fl_long", defValR),
formatNumStr(15, secData, "fl_lat", defValR),
formatNumStr(9, secData, "flele", defValR),
formatNumStr(17, secData, "farea", defValR),
"-99", // P.S. SLEN keeps -99
formatNumStr(5, secData, "fllwr", defValR),
formatNumStr(5, secData, "flsla", defValR),
getObjectOr(secData, "flhst", defValC).toString(),
formatNumStr(5, secData, "fhdur", defValR)));
}
if (!flArr.isEmpty()) {
sbData.append(eventPart2.toString()).append("\r\n");
}
// SOIL ANALYSIS Section
if (!saArr.isEmpty()) {
sbData.append("*SOIL ANALYSIS\r\n");
for (int idx = 0; idx < saArr.size(); idx++) {
secData = (HashMap) saArr.get(idx);
sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n",
idx + 1, //getObjectOr(secData, "sa", defValI).toString(),
formatDateStr(getObjectOr(secData, "sadat", defValD).toString()),
getObjectOr(secData, "samhb", defValC).toString(),
getObjectOr(secData, "sampx", defValC).toString(),
getObjectOr(secData, "samke", defValC).toString(),
getObjectOr(secData, "sa_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(subData, "sa", defValI).toString(),
formatNumStr(5, subData, "sabl", defValR),
formatNumStr(5, subData, "sabdm", defValR),
formatNumStr(5, subData, "saoc", defValR),
formatNumStr(5, subData, "sani", defValR),
formatNumStr(5, subData, "saphw", defValR),
formatNumStr(5, subData, "saphb", defValR),
formatNumStr(5, subData, "sapx", defValR),
formatNumStr(5, subData, "sake", defValR),
formatNumStr(5, subData, "sasc", defValR)));
}
}
sbData.append("\r\n");
}
// INITIAL CONDITIONS Section
if (!icArr.isEmpty()) {
sbData.append("*INITIAL CONDITIONS\r\n");
for (int idx = 0; idx < icArr.size(); idx++) {
secData = (HashMap) icArr.get(idx);
translateTo2BitCrid(secData, "icpcr");
sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n",
idx + 1, //getObjectOr(secData, "ic", defValI).toString(),
getObjectOr(secData, "icpcr", defValC).toString(),
formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()),
formatNumStr(5, secData, "icrt", defValR),
formatNumStr(5, secData, "icnd", defValR),
formatNumStr(5, secData, "icrz#", defValR),
formatNumStr(5, secData, "icrze", defValR),
formatNumStr(5, secData, "icwt", defValR),
formatNumStr(5, secData, "icrag", defValR),
formatNumStr(5, secData, "icrn", defValR),
formatNumStr(5, secData, "icrp", defValR),
formatNumStr(5, secData, "icrip", defValR),
formatNumStr(5, secData, "icrdp", defValR),
getObjectOr(secData, "ic_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@C ICBL SH2O SNH4 SNO3\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n",
idx + 1, //getObjectOr(subData, "ic", defValI).toString(),
formatNumStr(5, subData, "icbl", defValR),
formatNumStr(5, subData, "ich2o", defValR),
formatNumStr(5, subData, "icnh4", defValR),
formatNumStr(5, subData, "icno3", defValR)));
}
}
sbData.append("\r\n");
}
// PLANTING DETAILS Section
if (!mpArr.isEmpty()) {
sbData.append("*PLANTING DETAILS\r\n");
sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n");
for (int idx = 0; idx < mpArr.size(); idx++) {
secData = (HashMap) mpArr.get(idx);
// Check if necessary data is missing
String pdate = getObjectOr(secData, "date", "");
if (pdate.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n");
} else if (formatDateStr(pdate).equals(defValD)) {
sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n");
}
if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n");
}
if (getObjectOr(secData, "plrs", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n");
}
// if (getObjectOr(secData, "plma", "").equals("")) {
// sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n");
// }
// if (getObjectOr(secData, "plds", "").equals("")) {
// sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n");
// }
// if (getObjectOr(secData, "pldp", "").equals("")) {
// sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n");
// }
// mm -> cm
String pldp = getObjectOr(secData, "pldp", "");
if (!pldp.equals("")) {
try {
BigDecimal pldpBD = new BigDecimal(pldp);
pldpBD = pldpBD.divide(new BigDecimal("10"));
secData.put("pldp", pldpBD.toString());
} catch (NumberFormatException e) {
}
}
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n",
idx + 1, //getObjectOr(data, "pl", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()),
formatDateStr(getObjectOr(secData, "pldae", defValD).toString()),
formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)),
formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)),
getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled)
getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled)
formatNumStr(5, secData, "plrs", defValR),
formatNumStr(5, secData, "plrd", defValR),
formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled)
formatNumStr(5, secData, "plmwt", defValR),
formatNumStr(5, secData, "page", defValR),
formatNumStr(5, secData, "penv", defValR),
formatNumStr(5, secData, "plph", defValR),
formatNumStr(5, secData, "plspl", defValR),
getObjectOr(secData, "pl_name", defValC).toString()));
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no plainting data in the experiment.\r\n");
}
// IRRIGATION AND WATER MANAGEMENT Section
if (!miArr.isEmpty()) {
sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n");
for (int idx = 0; idx < miArr.size(); idx++) {
// secData = (ArrayList) miArr.get(idx);
subDataArr = (ArrayList) miArr.get(idx);
if (!subDataArr.isEmpty()) {
subData = (HashMap) subDataArr.get(0);
} else {
subData = new HashMap();
}
sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n",
idx + 1, //getObjectOr(data, "ir", defValI).toString(),
formatNumStr(5, subData, "ireff", defValR),
formatNumStr(5, subData, "irmdp", defValR),
formatNumStr(5, subData, "irthr", defValR),
formatNumStr(5, subData, "irept", defValR),
getObjectOr(subData, "irstg", defValC).toString(),
getObjectOr(subData, "iame", defValC).toString(),
formatNumStr(5, subData, "iamt", defValR),
getObjectOr(subData, "ir_name", defValC).toString()));
if (!subDataArr.isEmpty()) {
sbData.append("@I IDATE IROP IRVAL\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n",
idx + 1, //getObjectOr(subData, "ir", defValI).toString(),
formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date
getObjectOr(subData, "irop", defValC).toString(),
formatNumStr(5, subData, "irval", defValR)));
}
}
sbData.append("\r\n");
}
// FERTILIZERS (INORGANIC) Section
if (!mfArr.isEmpty()) {
sbData.append("*FERTILIZERS (INORGANIC)\r\n");
sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n");
// String fen_tot = getObjectOr(result, "fen_tot", defValR);
// String fep_tot = getObjectOr(result, "fep_tot", defValR);
// String fek_tot = getObjectOr(result, "fek_tot", defValR);
// String pdate = getPdate(result);
// if (pdate.equals("")) {
// pdate = defValD;
// }
for (int idx = 0; idx < mfArr.size(); idx++) {
secDataArr = (ArrayList) mfArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
// if (getObjectOr(secData, "fdate", "").equals("")) {
// sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n");
// }
// if (getObjectOr(secData, "fecd", "").equals("")) {
// sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n");
// }
// if (getObjectOr(secData, "feacd", "").equals("")) {
// sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n");
// }
// if (getObjectOr(secData, "fedep", "").equals("")) {
// sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n");
// }
// if (getObjectOr(secData, "feamn", "").equals("")) {
// sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamp", "").equals("")) {
// sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamk", "").equals("")) {
// sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n",
idx + 1, //getObjectOr(data, "fe", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date
getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled)
getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled)
formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled)
formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamc", defValR),
formatNumStr(5, secData, "feamo", defValR),
getObjectOr(secData, "feocd", defValC).toString(),
getObjectOr(secData, "fe_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// RESIDUES AND ORGANIC FERTILIZER Section
if (!mrArr.isEmpty()) {
sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n");
sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n");
for (int idx = 0; idx < mrArr.size(); idx++) {
secDataArr = (ArrayList) mrArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n",
idx + 1, //getObjectOr(secData, "om", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date
getObjectOr(secData, "omcd", defValC).toString(),
formatNumStr(5, secData, "omamt", defValR),
formatNumStr(5, secData, "omn%", defValR),
formatNumStr(5, secData, "omp%", defValR),
formatNumStr(5, secData, "omk%", defValR),
formatNumStr(5, secData, "ominp", defValR),
formatNumStr(5, secData, "omdep", defValR),
formatNumStr(5, secData, "omacd", defValR),
getObjectOr(secData, "om_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// CHEMICAL APPLICATIONS Section
if (!mcArr.isEmpty()) {
sbData.append("*CHEMICAL APPLICATIONS\r\n");
sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n");
for (int idx = 0; idx < mcArr.size(); idx++) {
secDataArr = (ArrayList) mcArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ch", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date
getObjectOr(secData, "chcd", defValC).toString(),
formatNumStr(5, secData, "chamt", defValR),
getObjectOr(secData, "chacd", defValC).toString(),
getObjectOr(secData, "chdep", defValC).toString(),
getObjectOr(secData, "ch_targets", defValC).toString(),
getObjectOr(secData, "ch_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// TILLAGE Section
if (!mtArr.isEmpty()) {
sbData.append("*TILLAGE AND ROTATIONS\r\n");
sbData.append("@T TDATE TIMPL TDEP TNAME\r\n");
for (int idx = 0; idx < mtArr.size(); idx++) {
secDataArr = (ArrayList) mtArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n",
idx + 1, //getObjectOr(secData, "ti", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date
getObjectOr(secData, "tiimp", defValC).toString(),
formatNumStr(5, secData, "tidep", defValR),
getObjectOr(secData, "ti_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// ENVIRONMENT MODIFICATIONS Section
if (!meArr.isEmpty()) {
sbData.append("*ENVIRONMENT MODIFICATIONS\r\n");
sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n");
for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) {
secDataArr = (ArrayList) meArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s%2$s\r\n",
cnt,
secData.get("em_data")));
// sbData.append(String.format("%1$2s%2$s\r\n",
// idx + 1,
// (String) secDataArr.get(i)));
// sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n",
// idx + 1, //getObjectOr(secData, "em", defValI).toString(),
// formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date
// getObjectOr(secData, "ecdyl", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdyl", defValR),
// getObjectOr(secData, "ecrad", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrad", defValR),
// getObjectOr(secData, "ecmax", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmax", defValR),
// getObjectOr(secData, "ecmin", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmin", defValR),
// getObjectOr(secData, "ecrai", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrai", defValR),
// getObjectOr(secData, "ecco2", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emco2", defValR),
// getObjectOr(secData, "ecdew", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdew", defValR),
// getObjectOr(secData, "ecwnd", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emwnd", defValR),
// getObjectOr(secData, "em_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// HARVEST DETAILS Section
if (!mhArr.isEmpty()) {
sbData.append("*HARVEST DETAILS\r\n");
sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n");
for (int idx = 0; idx < mhArr.size(); idx++) {
secDataArr = (ArrayList) mhArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ha", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date
getObjectOr(secData, "hastg", defValC).toString(),
getObjectOr(secData, "hacom", defValC).toString(),
getObjectOr(secData, "hasiz", defValC).toString(),
formatNumStr(5, secData, "hapc", defValR),
formatNumStr(5, secData, "habpc", defValR),
getObjectOr(secData, "ha_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section
if (!smArr.isEmpty()) {
// Set Title list
ArrayList smTitles = new ArrayList();
smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n");
smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n");
smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
String[] keys = new String[10];
keys[0] = "sm_general";
keys[1] = "sm_options";
keys[2] = "sm_methods";
keys[3] = "sm_management";
keys[4] = "sm_outputs";
keys[5] = "sm_planting";
keys[6] = "sm_irrigation";
keys[7] = "sm_nitrogen";
keys[8] = "sm_residues";
keys[9] = "sm_harvests";
// Loop all the simulation control records
for (int idx = 0; idx < smArr.size(); idx++) {
secData = (HashMap) smArr.get(idx);
if (secData.containsKey("sm_general")) {
sbData.append("*SIMULATION CONTROLS\r\n");
secData.remove("sm");
// Object[] keys = secData.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
sbData.append(smTitles.get(i));
sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n");
if (i == 4) {
sbData.append("\r\n");
}
}
sbData.append("\r\n");
} else {
sbData.append(createSMMAStr(idx + 1, secData));
}
}
} else {
sbData.append(createSMMAStr(1, new HashMap()));
}
// Output finish
bwX.write(sbError.toString());
bwX.write(sbGenData.toString());
bwX.write(sbNotesData.toString());
bwX.write(sbData.toString());
bwX.close();
} catch (IOException e) {
LOG.error(DssatCommonOutput.getStackTrace(e));
}
}
|
diff --git a/web/modules/src/java/org/jdesktop/wonderland/modules/servlets/ModuleUploadServlet.java b/web/modules/src/java/org/jdesktop/wonderland/modules/servlets/ModuleUploadServlet.java
index 52e3b01c4..f7bd40a5d 100644
--- a/web/modules/src/java/org/jdesktop/wonderland/modules/servlets/ModuleUploadServlet.java
+++ b/web/modules/src/java/org/jdesktop/wonderland/modules/servlets/ModuleUploadServlet.java
@@ -1,162 +1,162 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.servlets;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jdesktop.wonderland.modules.Module;
import org.jdesktop.wonderland.modules.service.ModuleManager;
import org.jdesktop.wonderland.utils.RunUtil;
/**
*
* @author Jordan Slott <[email protected]>
*/
public class ModuleUploadServlet extends HttpServlet {
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
throw new ServletException("Upload servlet only handles post");
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Create a factory for disk-base file items to handle the request. Also
* place the file in add/.
*/
PrintWriter writer = response.getWriter();
ModuleManager manager = ModuleManager.getModuleManager();
Logger logger = ModuleManager.getLogger();
/* Check that we have a file upload request */
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart == false) {
logger.warning("[MODULE] UPLOAD Bad request");
writer.println("Unable to recognize upload request. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext() == true) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField() == false) {
/*
* The name given should have a .jar extension. Check this here. If
* not, return an error. If so, parse out just the module name.
*/
String moduleJar = item.getName();
if (moduleJar.endsWith(".jar") == false) {
/* Log an error to the log and write an error message back */
logger.warning("[MODULE] UPLOAD File is not a jar file " + moduleJar);
writer.println("The file " + moduleJar + " needs to be a jar file. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
String moduleName = moduleJar.substring(0, moduleJar.length() - 4);
logger.info("[MODULE] UPLOAD Install module " + moduleName + " with file name " + moduleJar);
/*
* Write the file a temporary file
*/
File tmpFile = null;
try {
- tmpFile = File.createTempFile(moduleName, ".jar");
+ tmpFile = File.createTempFile(moduleName+"_tmp", ".jar");
tmpFile.deleteOnExit();
RunUtil.writeToFile(stream, tmpFile);
logger.info("[MODULE] UPLOAD Wrote added module to " + tmpFile.getAbsolutePath());
} catch (java.lang.Exception excp) {
/* Log an error to the log and write an error message back */
logger.log(Level.WARNING, "[MODULE] UPLOAD Failed to save file", excp);
writer.println("Unable to save the file to the module directory. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
writer.println(excp.toString());
return;
}
/* Add the new module */
Collection<File> moduleFiles = new LinkedList<File>();
moduleFiles.add(tmpFile);
Collection<Module> result = manager.addToInstall(moduleFiles);
if (result.isEmpty() == true) {
/* Log an error to the log and write an error message back */
logger.warning("[MODULE] UPLOAD Failed to install module " + moduleName);
writer.println("Unable to install module for some reason. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
}
}
} catch (FileUploadException excp) {
/* Log an error to the log and write an error message back */
logger.log(Level.WARNING, "[MODULE] UPLOAD Failed", excp);
writer.println("Unable to install module for some reason. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
/* Install all of the modules that are possible */
manager.installAll();
/* If we have reached here, then post a simple message */
logger.info("[MODULE] UPLOAD Added module successfully");
writer.print("Module added successfully. Press the ");
writer.print("Back button on your browser and refresh the page to see the updates.<br><br>");
}
/**
* Returns a short description of the servlet.
*/
@Override
public String getServletInfo() {
return "Module Upload Servlet";
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Create a factory for disk-base file items to handle the request. Also
* place the file in add/.
*/
PrintWriter writer = response.getWriter();
ModuleManager manager = ModuleManager.getModuleManager();
Logger logger = ModuleManager.getLogger();
/* Check that we have a file upload request */
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart == false) {
logger.warning("[MODULE] UPLOAD Bad request");
writer.println("Unable to recognize upload request. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext() == true) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField() == false) {
/*
* The name given should have a .jar extension. Check this here. If
* not, return an error. If so, parse out just the module name.
*/
String moduleJar = item.getName();
if (moduleJar.endsWith(".jar") == false) {
/* Log an error to the log and write an error message back */
logger.warning("[MODULE] UPLOAD File is not a jar file " + moduleJar);
writer.println("The file " + moduleJar + " needs to be a jar file. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
String moduleName = moduleJar.substring(0, moduleJar.length() - 4);
logger.info("[MODULE] UPLOAD Install module " + moduleName + " with file name " + moduleJar);
/*
* Write the file a temporary file
*/
File tmpFile = null;
try {
tmpFile = File.createTempFile(moduleName, ".jar");
tmpFile.deleteOnExit();
RunUtil.writeToFile(stream, tmpFile);
logger.info("[MODULE] UPLOAD Wrote added module to " + tmpFile.getAbsolutePath());
} catch (java.lang.Exception excp) {
/* Log an error to the log and write an error message back */
logger.log(Level.WARNING, "[MODULE] UPLOAD Failed to save file", excp);
writer.println("Unable to save the file to the module directory. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
writer.println(excp.toString());
return;
}
/* Add the new module */
Collection<File> moduleFiles = new LinkedList<File>();
moduleFiles.add(tmpFile);
Collection<Module> result = manager.addToInstall(moduleFiles);
if (result.isEmpty() == true) {
/* Log an error to the log and write an error message back */
logger.warning("[MODULE] UPLOAD Failed to install module " + moduleName);
writer.println("Unable to install module for some reason. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
}
}
} catch (FileUploadException excp) {
/* Log an error to the log and write an error message back */
logger.log(Level.WARNING, "[MODULE] UPLOAD Failed", excp);
writer.println("Unable to install module for some reason. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
/* Install all of the modules that are possible */
manager.installAll();
/* If we have reached here, then post a simple message */
logger.info("[MODULE] UPLOAD Added module successfully");
writer.print("Module added successfully. Press the ");
writer.print("Back button on your browser and refresh the page to see the updates.<br><br>");
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Create a factory for disk-base file items to handle the request. Also
* place the file in add/.
*/
PrintWriter writer = response.getWriter();
ModuleManager manager = ModuleManager.getModuleManager();
Logger logger = ModuleManager.getLogger();
/* Check that we have a file upload request */
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart == false) {
logger.warning("[MODULE] UPLOAD Bad request");
writer.println("Unable to recognize upload request. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext() == true) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField() == false) {
/*
* The name given should have a .jar extension. Check this here. If
* not, return an error. If so, parse out just the module name.
*/
String moduleJar = item.getName();
if (moduleJar.endsWith(".jar") == false) {
/* Log an error to the log and write an error message back */
logger.warning("[MODULE] UPLOAD File is not a jar file " + moduleJar);
writer.println("The file " + moduleJar + " needs to be a jar file. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
String moduleName = moduleJar.substring(0, moduleJar.length() - 4);
logger.info("[MODULE] UPLOAD Install module " + moduleName + " with file name " + moduleJar);
/*
* Write the file a temporary file
*/
File tmpFile = null;
try {
tmpFile = File.createTempFile(moduleName+"_tmp", ".jar");
tmpFile.deleteOnExit();
RunUtil.writeToFile(stream, tmpFile);
logger.info("[MODULE] UPLOAD Wrote added module to " + tmpFile.getAbsolutePath());
} catch (java.lang.Exception excp) {
/* Log an error to the log and write an error message back */
logger.log(Level.WARNING, "[MODULE] UPLOAD Failed to save file", excp);
writer.println("Unable to save the file to the module directory. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
writer.println(excp.toString());
return;
}
/* Add the new module */
Collection<File> moduleFiles = new LinkedList<File>();
moduleFiles.add(tmpFile);
Collection<Module> result = manager.addToInstall(moduleFiles);
if (result.isEmpty() == true) {
/* Log an error to the log and write an error message back */
logger.warning("[MODULE] UPLOAD Failed to install module " + moduleName);
writer.println("Unable to install module for some reason. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
}
}
} catch (FileUploadException excp) {
/* Log an error to the log and write an error message back */
logger.log(Level.WARNING, "[MODULE] UPLOAD Failed", excp);
writer.println("Unable to install module for some reason. Press the ");
writer.println("Back button on your browser and try again.<br><br>");
return;
}
/* Install all of the modules that are possible */
manager.installAll();
/* If we have reached here, then post a simple message */
logger.info("[MODULE] UPLOAD Added module successfully");
writer.print("Module added successfully. Press the ");
writer.print("Back button on your browser and refresh the page to see the updates.<br><br>");
}
|
diff --git a/src/edu/sc/seis/sod/subsetter/waveformArm/PhaseRequest.java b/src/edu/sc/seis/sod/subsetter/waveformArm/PhaseRequest.java
index 9af2e88ed..ca024e4ea 100644
--- a/src/edu/sc/seis/sod/subsetter/waveformArm/PhaseRequest.java
+++ b/src/edu/sc/seis/sod/subsetter/waveformArm/PhaseRequest.java
@@ -1,230 +1,230 @@
package edu.sc.seis.sod.subsetter.waveFormArm;
import edu.sc.seis.sod.*;
import edu.sc.seis.TauP.*;
import edu.iris.Fissures.IfEvent.*;
import edu.iris.Fissures.event.*;
import edu.iris.Fissures.IfNetwork.*;
import edu.iris.Fissures.network.*;
import edu.iris.Fissures.Location;
import edu.iris.Fissures.model.*;
import edu.iris.Fissures.IfSeismogramDC.*;
import java.util.*;
import org.w3c.dom.*;
/**
* sample xml file
*<pre>
* <phaseRequest>
* <beginPhase>ttp</beginPhase>
* <beginOffset>
* <unit>SECOND</unit>
* <value>-120</value>
* </beginOffset>
* <endPhase>tts</endPhase>
* <endOffset>
* <unit>SECOND</unit>
* <value>600</value>
* </endOffset>
* </phaseRequest>
*</pre>
*/
public class PhaseRequest implements RequestGenerator{
/**
* Creates a new <code>PhaseRequest</code> instance.
*
* @param config an <code>Element</code> value
*/
public PhaseRequest (Element config) throws ConfigurationException{
NodeList childNodes = config.getChildNodes();
Node node;
for(int counter = 0; counter < childNodes.getLength(); counter++) {
node = childNodes.item(counter);
if(node instanceof Element) {
Element element = (Element)node;
if(element.getTagName().equals("beginPhase")) {
beginPhase = SodUtil.getNestedText(element);
} else if(element.getTagName().equals("beginOffset")) {
SodElement sodElement =
(SodElement) SodUtil.load(element,
waveformArmPackage);
beginOffset = (BeginOffset)sodElement;
} else if(element.getTagName().equals("endPhase")) {
endPhase = SodUtil.getNestedText(element);
} else if(element.getTagName().equals("endOffset")) {
SodElement sodElement =
(SodElement) SodUtil.load(element,
waveformArmPackage);
endOffset = (EndOffset)sodElement;
}
}
}
}
/**
* Describe <code>generateRequest</code> method here.
*
* @param event an <code>EventAccessOperations</code> value
* @param network a <code>NetworkAccess</code> value
* @param channel a <code>Channel</code> value
* @param cookies a <code>CookieJar</code> value
* @return a <code>RequestFilter[]</code> value
*/
public RequestFilter[] generateRequest(EventAccessOperations event,
NetworkAccess network,
Channel channel,
CookieJar cookies) throws Exception{
Origin origin = null;
double arrivalStartTime = -100.0;
double arrivalEndTime = -100.0;
origin = event.get_preferred_origin();
Properties props = Start.getProperties();
String tauPModel = new String();
try {
tauPModel = props.getProperty("edu.sc.seis.sod.TaupModel");
if(tauPModel == null) tauPModel = "prem";
} catch(Exception e) {
tauPModel = "prem";
}
String phaseNames= "";
if ( ! beginPhase.equals(ORIGIN)) {
phaseNames += " "+beginPhase;
} // end of if (beginPhase.equals("origin"))
if ( ! endPhase.equals(ORIGIN)) {
phaseNames += " "+endPhase;
} // end of if (beginPhase.equals("origin"))
Arrival[] arrivals = calculateArrivals(tauPModel,
phaseNames,
origin.my_location,
channel.my_site.my_location);
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(beginPhase.startsWith("tt")) {
if(beginPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalStartTime = arrivals[counter].getTime();
break;
} else if(beginPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
} else if(beginPhase.equals(arrivalName)) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
}
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(endPhase.startsWith("tt")) {
if(endPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalEndTime = arrivals[counter].getTime();
break;
} else if(endPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
} else if(endPhase.equals(arrivalName)) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
}
if (beginPhase.equals(ORIGIN)) {
arrivalStartTime = 0;
}
if (endPhase.equals(ORIGIN)) {
arrivalEndTime = 0;
}
if(arrivalStartTime == -100.0 || arrivalEndTime == -100.0) {
// no arrivals found, return zero length request filters
return new RequestFilter[0];
}
/*System.out.println("originDpeth "+originDepth);
System.out.println("distance "+SphericalCoords.distance(origin.my_location.latitude,
origin.my_location.longitude,
channel.my_site.my_station.my_location.latitude,
channel.my_site.my_station.my_location.longitude));
System.out.println("arrivalStartTime = "+arrivalStartTime);
System.out.println("arrivalEndTime = "+arrivalEndTime);*/
// round to milliseconds
arrivalStartTime = Math.rint(1000*arrivalStartTime)/1000;
arrivalEndTime = Math.rint(1000*arrivalEndTime)/1000;
edu.iris.Fissures.Time originTime = origin.origin_time;
MicroSecondDate originDate = new MicroSecondDate(originTime);
- TimeInterval bInterval =
- new TimeInterval(beginOffset.getValue()+arrivalStartTime,
- UnitImpl.SECOND);
- TimeInterval eInterval =
- new TimeInterval(endOffset.getValue()+arrivalEndTime,
- UnitImpl.SECOND);
+ TimeInterval bInterval = beginOffset.getTimeInterval();
+ bInterval = bInterval.add(new TimeInterval(arrivalStartTime,
+ UnitImpl.SECOND));
+ TimeInterval eInterval = endOffset.getTimeInterval();
+ eInterval = eInterval.add(new TimeInterval(arrivalEndTime,
+ UnitImpl.SECOND));
MicroSecondDate bDate = originDate.add(bInterval);
MicroSecondDate eDate = originDate.add(eInterval);
RequestFilter[] filters;
filters = new RequestFilter[1];
filters[0] =
new RequestFilter(channel.get_id(),
bDate.getFissuresTime(),
eDate.getFissuresTime()
);
return filters;
}
protected static TauP_Time tauPTime = new TauP_Time();
protected synchronized static Arrival[] calculateArrivals(
String tauPModelName,
String phases,
Location originLoc,
Location channelLoc)
throws java.io.IOException, TauModelException {
if (tauPTime.getTauModelName() != tauPModelName) {
tauPTime.loadTauModel(tauPModelName);
}
tauPTime.clearPhaseNames();
tauPTime.parsePhaseList(phases);
double originDepth =
((QuantityImpl)originLoc.depth).convertTo(UnitImpl.KILOMETER).value;
tauPTime.setSourceDepth(originDepth);
tauPTime.calculate(SphericalCoords.distance(originLoc.latitude,
originLoc.longitude,
channelLoc.latitude,
channelLoc.longitude));
return tauPTime.getArrivals();
}
private BeginOffset beginOffset;
private String beginPhase;
private EndOffset endOffset;
private String endPhase;
private static final String ORIGIN = "origin";
}// PhaseRequest
| true | true | public RequestFilter[] generateRequest(EventAccessOperations event,
NetworkAccess network,
Channel channel,
CookieJar cookies) throws Exception{
Origin origin = null;
double arrivalStartTime = -100.0;
double arrivalEndTime = -100.0;
origin = event.get_preferred_origin();
Properties props = Start.getProperties();
String tauPModel = new String();
try {
tauPModel = props.getProperty("edu.sc.seis.sod.TaupModel");
if(tauPModel == null) tauPModel = "prem";
} catch(Exception e) {
tauPModel = "prem";
}
String phaseNames= "";
if ( ! beginPhase.equals(ORIGIN)) {
phaseNames += " "+beginPhase;
} // end of if (beginPhase.equals("origin"))
if ( ! endPhase.equals(ORIGIN)) {
phaseNames += " "+endPhase;
} // end of if (beginPhase.equals("origin"))
Arrival[] arrivals = calculateArrivals(tauPModel,
phaseNames,
origin.my_location,
channel.my_site.my_location);
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(beginPhase.startsWith("tt")) {
if(beginPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalStartTime = arrivals[counter].getTime();
break;
} else if(beginPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
} else if(beginPhase.equals(arrivalName)) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
}
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(endPhase.startsWith("tt")) {
if(endPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalEndTime = arrivals[counter].getTime();
break;
} else if(endPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
} else if(endPhase.equals(arrivalName)) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
}
if (beginPhase.equals(ORIGIN)) {
arrivalStartTime = 0;
}
if (endPhase.equals(ORIGIN)) {
arrivalEndTime = 0;
}
if(arrivalStartTime == -100.0 || arrivalEndTime == -100.0) {
// no arrivals found, return zero length request filters
return new RequestFilter[0];
}
/*System.out.println("originDpeth "+originDepth);
System.out.println("distance "+SphericalCoords.distance(origin.my_location.latitude,
origin.my_location.longitude,
channel.my_site.my_station.my_location.latitude,
channel.my_site.my_station.my_location.longitude));
System.out.println("arrivalStartTime = "+arrivalStartTime);
System.out.println("arrivalEndTime = "+arrivalEndTime);*/
// round to milliseconds
arrivalStartTime = Math.rint(1000*arrivalStartTime)/1000;
arrivalEndTime = Math.rint(1000*arrivalEndTime)/1000;
edu.iris.Fissures.Time originTime = origin.origin_time;
MicroSecondDate originDate = new MicroSecondDate(originTime);
TimeInterval bInterval =
new TimeInterval(beginOffset.getValue()+arrivalStartTime,
UnitImpl.SECOND);
TimeInterval eInterval =
new TimeInterval(endOffset.getValue()+arrivalEndTime,
UnitImpl.SECOND);
MicroSecondDate bDate = originDate.add(bInterval);
MicroSecondDate eDate = originDate.add(eInterval);
RequestFilter[] filters;
filters = new RequestFilter[1];
filters[0] =
new RequestFilter(channel.get_id(),
bDate.getFissuresTime(),
eDate.getFissuresTime()
);
return filters;
}
| public RequestFilter[] generateRequest(EventAccessOperations event,
NetworkAccess network,
Channel channel,
CookieJar cookies) throws Exception{
Origin origin = null;
double arrivalStartTime = -100.0;
double arrivalEndTime = -100.0;
origin = event.get_preferred_origin();
Properties props = Start.getProperties();
String tauPModel = new String();
try {
tauPModel = props.getProperty("edu.sc.seis.sod.TaupModel");
if(tauPModel == null) tauPModel = "prem";
} catch(Exception e) {
tauPModel = "prem";
}
String phaseNames= "";
if ( ! beginPhase.equals(ORIGIN)) {
phaseNames += " "+beginPhase;
} // end of if (beginPhase.equals("origin"))
if ( ! endPhase.equals(ORIGIN)) {
phaseNames += " "+endPhase;
} // end of if (beginPhase.equals("origin"))
Arrival[] arrivals = calculateArrivals(tauPModel,
phaseNames,
origin.my_location,
channel.my_site.my_location);
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(beginPhase.startsWith("tt")) {
if(beginPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalStartTime = arrivals[counter].getTime();
break;
} else if(beginPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
} else if(beginPhase.equals(arrivalName)) {
arrivalStartTime = arrivals[counter].getTime();
break;
}
}
for(int counter = 0; counter < arrivals.length; counter++) {
String arrivalName = arrivals[counter].getName();
if(endPhase.startsWith("tt")) {
if(endPhase.equals("tts")
&& arrivalName.toUpperCase().startsWith("S")) {
arrivalEndTime = arrivals[counter].getTime();
break;
} else if(endPhase.equals("ttp")
&& arrivalName.toUpperCase().startsWith("P")) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
} else if(endPhase.equals(arrivalName)) {
arrivalEndTime = arrivals[counter].getTime();
break;
}
}
if (beginPhase.equals(ORIGIN)) {
arrivalStartTime = 0;
}
if (endPhase.equals(ORIGIN)) {
arrivalEndTime = 0;
}
if(arrivalStartTime == -100.0 || arrivalEndTime == -100.0) {
// no arrivals found, return zero length request filters
return new RequestFilter[0];
}
/*System.out.println("originDpeth "+originDepth);
System.out.println("distance "+SphericalCoords.distance(origin.my_location.latitude,
origin.my_location.longitude,
channel.my_site.my_station.my_location.latitude,
channel.my_site.my_station.my_location.longitude));
System.out.println("arrivalStartTime = "+arrivalStartTime);
System.out.println("arrivalEndTime = "+arrivalEndTime);*/
// round to milliseconds
arrivalStartTime = Math.rint(1000*arrivalStartTime)/1000;
arrivalEndTime = Math.rint(1000*arrivalEndTime)/1000;
edu.iris.Fissures.Time originTime = origin.origin_time;
MicroSecondDate originDate = new MicroSecondDate(originTime);
TimeInterval bInterval = beginOffset.getTimeInterval();
bInterval = bInterval.add(new TimeInterval(arrivalStartTime,
UnitImpl.SECOND));
TimeInterval eInterval = endOffset.getTimeInterval();
eInterval = eInterval.add(new TimeInterval(arrivalEndTime,
UnitImpl.SECOND));
MicroSecondDate bDate = originDate.add(bInterval);
MicroSecondDate eDate = originDate.add(eInterval);
RequestFilter[] filters;
filters = new RequestFilter[1];
filters[0] =
new RequestFilter(channel.get_id(),
bDate.getFissuresTime(),
eDate.getFissuresTime()
);
return filters;
}
|
diff --git a/libs/lint_checks/src/main/java/com/android/tools/lint/checks/FragmentDetector.java b/libs/lint_checks/src/main/java/com/android/tools/lint/checks/FragmentDetector.java
index 43d7e80..04e04c5 100644
--- a/libs/lint_checks/src/main/java/com/android/tools/lint/checks/FragmentDetector.java
+++ b/libs/lint_checks/src/main/java/com/android/tools/lint/checks/FragmentDetector.java
@@ -1,168 +1,159 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.lint.checks;
import static com.android.SdkConstants.CONSTRUCTOR_NAME;
import static com.android.SdkConstants.FRAGMENT;
import static com.android.SdkConstants.FRAGMENT_V4;
import com.android.annotations.NonNull;
import com.android.tools.lint.client.api.LintDriver;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.ClassContext;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Detector.ClassScanner;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.LintUtils;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.android.tools.lint.detector.api.Speed;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.List;
/**
* Checks that Fragment subclasses can be instantiated via
* {link {@link Class#newInstance()}}: the class is public, static, and has
* a public null constructor.
* <p>
* This helps track down issues like
* http://stackoverflow.com/questions/8058809/fragment-activity-crashes-on-screen-rotate
* (and countless duplicates)
*/
public class FragmentDetector extends Detector implements ClassScanner {
private static final String FRAGMENT_NAME_SUFFIX = "Fragment"; //$NON-NLS-1$
/** Are fragment subclasses instantiatable? */
public static final Issue ISSUE = Issue.create(
"ValidFragment", //$NON-NLS-1$
"Fragment not instantiatable",
"Ensures that `Fragment` subclasses can be instantiated",
"From the Fragment documentation:\n" +
"*Every* fragment must have an empty constructor, so it can be instantiated when " +
"restoring its activity's state. It is strongly recommended that subclasses do not " +
"have other constructors with parameters, since these constructors will not be " +
"called when the fragment is re-instantiated; instead, arguments can be supplied " +
"by the caller with `setArguments(Bundle)` and later retrieved by the Fragment " +
"with `getArguments()`.",
Category.CORRECTNESS,
6,
Severity.ERROR,
new Implementation(
FragmentDetector.class,
Scope.CLASS_FILE_SCOPE)
).addMoreInfo(
"http://developer.android.com/reference/android/app/Fragment.html#Fragment()"); //$NON-NLS-1$
/** Constructs a new {@link FragmentDetector} */
public FragmentDetector() {
}
@NonNull
@Override
public Speed getSpeed() {
return Speed.FAST;
}
// ---- Implements ClassScanner ----
@Override
public void checkClass(@NonNull ClassContext context, @NonNull ClassNode classNode) {
if ((classNode.access & Opcodes.ACC_ABSTRACT) != 0) {
// Ignore abstract classes since they are clearly (and by definition) not intended to
// be instantiated. We're looking for accidental non-static or missing constructor
// scenarios here.
return;
}
LintDriver driver = context.getDriver();
if (!(driver.isSubclassOf(classNode, FRAGMENT)
|| driver.isSubclassOf(classNode, FRAGMENT_V4))) {
- if (!context.getScope().contains(Scope.ALL_JAVA_FILES)) {
- // Single file checking: Just check that it looks like a fragment class
- // (since we don't have a full superclass map)
- if (!classNode.name.endsWith(FRAGMENT_NAME_SUFFIX) ||
- classNode.superName == null) {
- return;
- }
- } else {
- return;
- }
+ return;
}
if ((classNode.access & Opcodes.ACC_PUBLIC) == 0) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment class should be public (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
return;
}
if (classNode.name.indexOf('$') != -1 && !LintUtils.isStaticInnerClass(classNode)) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment inner class should be static (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
return;
}
boolean hasDefaultConstructor = false;
@SuppressWarnings("rawtypes") // ASM API
List methodList = classNode.methods;
for (Object m : methodList) {
MethodNode method = (MethodNode) m;
if (method.name.equals(CONSTRUCTOR_NAME)) {
if (method.desc.equals("()V")) { //$NON-NLS-1$
// The constructor must be public
if ((method.access & Opcodes.ACC_PUBLIC) != 0) {
hasDefaultConstructor = true;
} else {
context.report(ISSUE, context.getLocation(method, classNode),
"The default constructor must be public",
null);
// Also mark that we have a constructor so we don't complain again
// below since we've already emitted a more specific error related
// to the default constructor
hasDefaultConstructor = true;
}
} else if (!method.desc.contains("()")) { //$NON-NLS-1$
context.report(ISSUE, context.getLocation(method, classNode),
// TODO: Use separate issue for this which isn't an error
"Avoid non-default constructors in fragments: use a default constructor " +
"plus Fragment#setArguments(Bundle) instead",
null);
}
}
}
if (!hasDefaultConstructor) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment should provide a default constructor (a public " +
"constructor with no arguments) (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
}
}
}
| true | true | public void checkClass(@NonNull ClassContext context, @NonNull ClassNode classNode) {
if ((classNode.access & Opcodes.ACC_ABSTRACT) != 0) {
// Ignore abstract classes since they are clearly (and by definition) not intended to
// be instantiated. We're looking for accidental non-static or missing constructor
// scenarios here.
return;
}
LintDriver driver = context.getDriver();
if (!(driver.isSubclassOf(classNode, FRAGMENT)
|| driver.isSubclassOf(classNode, FRAGMENT_V4))) {
if (!context.getScope().contains(Scope.ALL_JAVA_FILES)) {
// Single file checking: Just check that it looks like a fragment class
// (since we don't have a full superclass map)
if (!classNode.name.endsWith(FRAGMENT_NAME_SUFFIX) ||
classNode.superName == null) {
return;
}
} else {
return;
}
}
if ((classNode.access & Opcodes.ACC_PUBLIC) == 0) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment class should be public (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
return;
}
if (classNode.name.indexOf('$') != -1 && !LintUtils.isStaticInnerClass(classNode)) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment inner class should be static (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
return;
}
boolean hasDefaultConstructor = false;
@SuppressWarnings("rawtypes") // ASM API
List methodList = classNode.methods;
for (Object m : methodList) {
MethodNode method = (MethodNode) m;
if (method.name.equals(CONSTRUCTOR_NAME)) {
if (method.desc.equals("()V")) { //$NON-NLS-1$
// The constructor must be public
if ((method.access & Opcodes.ACC_PUBLIC) != 0) {
hasDefaultConstructor = true;
} else {
context.report(ISSUE, context.getLocation(method, classNode),
"The default constructor must be public",
null);
// Also mark that we have a constructor so we don't complain again
// below since we've already emitted a more specific error related
// to the default constructor
hasDefaultConstructor = true;
}
} else if (!method.desc.contains("()")) { //$NON-NLS-1$
context.report(ISSUE, context.getLocation(method, classNode),
// TODO: Use separate issue for this which isn't an error
"Avoid non-default constructors in fragments: use a default constructor " +
"plus Fragment#setArguments(Bundle) instead",
null);
}
}
}
if (!hasDefaultConstructor) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment should provide a default constructor (a public " +
"constructor with no arguments) (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
}
}
| public void checkClass(@NonNull ClassContext context, @NonNull ClassNode classNode) {
if ((classNode.access & Opcodes.ACC_ABSTRACT) != 0) {
// Ignore abstract classes since they are clearly (and by definition) not intended to
// be instantiated. We're looking for accidental non-static or missing constructor
// scenarios here.
return;
}
LintDriver driver = context.getDriver();
if (!(driver.isSubclassOf(classNode, FRAGMENT)
|| driver.isSubclassOf(classNode, FRAGMENT_V4))) {
return;
}
if ((classNode.access & Opcodes.ACC_PUBLIC) == 0) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment class should be public (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
return;
}
if (classNode.name.indexOf('$') != -1 && !LintUtils.isStaticInnerClass(classNode)) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment inner class should be static (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
return;
}
boolean hasDefaultConstructor = false;
@SuppressWarnings("rawtypes") // ASM API
List methodList = classNode.methods;
for (Object m : methodList) {
MethodNode method = (MethodNode) m;
if (method.name.equals(CONSTRUCTOR_NAME)) {
if (method.desc.equals("()V")) { //$NON-NLS-1$
// The constructor must be public
if ((method.access & Opcodes.ACC_PUBLIC) != 0) {
hasDefaultConstructor = true;
} else {
context.report(ISSUE, context.getLocation(method, classNode),
"The default constructor must be public",
null);
// Also mark that we have a constructor so we don't complain again
// below since we've already emitted a more specific error related
// to the default constructor
hasDefaultConstructor = true;
}
} else if (!method.desc.contains("()")) { //$NON-NLS-1$
context.report(ISSUE, context.getLocation(method, classNode),
// TODO: Use separate issue for this which isn't an error
"Avoid non-default constructors in fragments: use a default constructor " +
"plus Fragment#setArguments(Bundle) instead",
null);
}
}
}
if (!hasDefaultConstructor) {
context.report(ISSUE, context.getLocation(classNode), String.format(
"This fragment should provide a default constructor (a public " +
"constructor with no arguments) (%1$s)",
ClassContext.createSignature(classNode.name, null, null)),
null);
}
}
|
diff --git a/classpath/java/io/BufferedInputStream.java b/classpath/java/io/BufferedInputStream.java
index b20309fd..67ac256a 100644
--- a/classpath/java/io/BufferedInputStream.java
+++ b/classpath/java/io/BufferedInputStream.java
@@ -1,88 +1,89 @@
/* Copyright (c) 2008-2010, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
package java.io;
public class BufferedInputStream extends InputStream {
private final InputStream in;
private final byte[] buffer;
private int position;
private int limit;
public BufferedInputStream(InputStream in, int size) {
this.in = in;
this.buffer = new byte[size];
}
public BufferedInputStream(InputStream in) {
this(in, 4096);
}
private void fill() throws IOException {
position = 0;
limit = in.read(buffer);
}
public int read() throws IOException {
if (position >= limit) {
fill();
if (limit == -1) {
return -1;
}
}
return buffer[position++] & 0xFF;
}
public int read(byte[] b, int offset, int length) throws IOException {
int count = 0;
if (position < limit) {
int remaining = limit - position;
if (remaining > length) {
remaining = length;
}
System.arraycopy(buffer, position, b, offset, remaining);
count += remaining;
position += remaining;
offset += remaining;
length -= remaining;
}
while (length > 0) {
int c = in.read(b, offset, length);
if (c == -1) {
if (count == 0) {
count = -1;
}
break;
} else {
+ offset += c;
count += c;
length -= c;
if (in.available() <= 0) {
break;
}
}
}
return count;
}
public int available() throws IOException {
return in.available() + (limit - position);
}
public void close() throws IOException {
in.close();
}
}
| true | true | public int read(byte[] b, int offset, int length) throws IOException {
int count = 0;
if (position < limit) {
int remaining = limit - position;
if (remaining > length) {
remaining = length;
}
System.arraycopy(buffer, position, b, offset, remaining);
count += remaining;
position += remaining;
offset += remaining;
length -= remaining;
}
while (length > 0) {
int c = in.read(b, offset, length);
if (c == -1) {
if (count == 0) {
count = -1;
}
break;
} else {
count += c;
length -= c;
if (in.available() <= 0) {
break;
}
}
}
return count;
}
| public int read(byte[] b, int offset, int length) throws IOException {
int count = 0;
if (position < limit) {
int remaining = limit - position;
if (remaining > length) {
remaining = length;
}
System.arraycopy(buffer, position, b, offset, remaining);
count += remaining;
position += remaining;
offset += remaining;
length -= remaining;
}
while (length > 0) {
int c = in.read(b, offset, length);
if (c == -1) {
if (count == 0) {
count = -1;
}
break;
} else {
offset += c;
count += c;
length -= c;
if (in.available() <= 0) {
break;
}
}
}
return count;
}
|
diff --git a/src/ua/in/leopard/androidCoocooAfisha/EditPreferences.java b/src/ua/in/leopard/androidCoocooAfisha/EditPreferences.java
index 6c02b75..157cfce 100644
--- a/src/ua/in/leopard/androidCoocooAfisha/EditPreferences.java
+++ b/src/ua/in/leopard/androidCoocooAfisha/EditPreferences.java
@@ -1,141 +1,146 @@
package ua.in.leopard.androidCoocooAfisha;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class EditPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
// Option names and default values
private static final String OPT_CITY = "city_current_name";
private static final String OPT_CITY_DEF = "Киев";
private static final String OPT_CITY_ID = "city_id";
private static final String OPT_CITY_ID_DEF = "1";
private static final String OPT_AUTO_UPD = "auto_update";
private static final Boolean OPT_AUTO_UPD_DEF = false;
private static final String OPT_AUTO_UPD_TIME = "auto_update_every_time";
private static final String OPT_AUTO_UPD_TIME_DEF = "1";
private static final String OPT_CACHED_POSTER = "cache_poster";
private static final Boolean OPT_CACHED_POSTER_DEF = false;
private static final String SECRET_TOKEN = SecretData.getSecretToken();
private static final String THEATERS_URL_KEY = "theaters_url";
private static final String THEATERS_URL = "http://coocoorooza.com/api/afisha_theaters/:city_id/:token.json";
private static final String CINEMAS_URL_KEY = "cinemas_url";
private static final String CINEMAS_URL = "http://coocoorooza.com/api/afisha_cinemas/:city_id/:token.json";
private ListPreference cities_lp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
cities_lp = (ListPreference)findPreference(OPT_CITY_ID);
ListPreference lp = (ListPreference)findPreference(OPT_AUTO_UPD_TIME);
if (getPreferenceScreen().getSharedPreferences().getBoolean(OPT_AUTO_UPD, OPT_AUTO_UPD_DEF)){
lp.setEnabled(true);
} else {
lp.setEnabled(false);
}
//In future
//DBClearDialogPreference db_clear_pref = (DBClearDialogPreference)findPreference(OPT_CLEAR_DB_DATABASE);
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public static String getCity(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(OPT_CITY, OPT_CITY_DEF);
}
public static Boolean isCachedPosters(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(OPT_CACHED_POSTER, OPT_CACHED_POSTER_DEF);
}
/** Get the current value of the cities option */
public static String getCityId(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(OPT_CITY_ID, OPT_CITY_ID_DEF);
}
public static String getTheaterUrl(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(THEATERS_URL_KEY, "");
}
public static String getCinemasUrl(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(CINEMAS_URL_KEY, "");
}
public static Boolean getAutoUpdate(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(OPT_AUTO_UPD, OPT_AUTO_UPD_DEF);
}
public static String getAutoUpdateTime(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(OPT_AUTO_UPD_TIME, OPT_AUTO_UPD_TIME_DEF);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(OPT_CITY_ID)) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(OPT_CITY, cities_lp.getEntry().toString());
editor.commit();
setDefUrls(sharedPreferences);
new DataProgressDialog(this).execute();
}
if (key.equals(OPT_AUTO_UPD)) {
ListPreference lp = (ListPreference)findPreference(OPT_AUTO_UPD_TIME);
stopService(new Intent(getApplicationContext(), DataUpdateService.class));
if (sharedPreferences.getBoolean(OPT_AUTO_UPD, OPT_AUTO_UPD_DEF)){
lp.setEnabled(true);
if (Integer.parseInt(sharedPreferences.getString(OPT_AUTO_UPD_TIME, OPT_AUTO_UPD_TIME_DEF)) != 0){
startService(new Intent(getApplicationContext(), DataUpdateService.class));
}
} else {
lp.setEnabled(false);
}
}
if (key.equals(OPT_AUTO_UPD_TIME)) {
stopService(new Intent(this, DataUpdateService.class));
if (Integer.parseInt(sharedPreferences.getString(OPT_AUTO_UPD_TIME, OPT_AUTO_UPD_TIME_DEF)) != 0){
startService(new Intent(getApplicationContext(), DataUpdateService.class));
}
}
+ if (key.equals(OPT_CACHED_POSTER)) {
+ if (sharedPreferences.getBoolean(OPT_CACHED_POSTER, OPT_CACHED_POSTER_DEF)){
+ new DataProgressDialog(this).execute();
+ }
+ }
}
private void setDefUrls(SharedPreferences sharedPreferences){
SharedPreferences.Editor editor = sharedPreferences.edit();
String theaters_url = THEATERS_URL;
theaters_url = theaters_url.replace(":city_id", cities_lp.getValue());
theaters_url = theaters_url.replace(":token", SECRET_TOKEN);
editor.putString(THEATERS_URL_KEY, theaters_url);
String cinemas_url = CINEMAS_URL;
cinemas_url = cinemas_url.replace(":city_id", cities_lp.getValue());
cinemas_url = cinemas_url.replace(":token", SECRET_TOKEN);
editor.putString(CINEMAS_URL_KEY, cinemas_url);
editor.commit();
}
}
| true | true | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(OPT_CITY_ID)) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(OPT_CITY, cities_lp.getEntry().toString());
editor.commit();
setDefUrls(sharedPreferences);
new DataProgressDialog(this).execute();
}
if (key.equals(OPT_AUTO_UPD)) {
ListPreference lp = (ListPreference)findPreference(OPT_AUTO_UPD_TIME);
stopService(new Intent(getApplicationContext(), DataUpdateService.class));
if (sharedPreferences.getBoolean(OPT_AUTO_UPD, OPT_AUTO_UPD_DEF)){
lp.setEnabled(true);
if (Integer.parseInt(sharedPreferences.getString(OPT_AUTO_UPD_TIME, OPT_AUTO_UPD_TIME_DEF)) != 0){
startService(new Intent(getApplicationContext(), DataUpdateService.class));
}
} else {
lp.setEnabled(false);
}
}
if (key.equals(OPT_AUTO_UPD_TIME)) {
stopService(new Intent(this, DataUpdateService.class));
if (Integer.parseInt(sharedPreferences.getString(OPT_AUTO_UPD_TIME, OPT_AUTO_UPD_TIME_DEF)) != 0){
startService(new Intent(getApplicationContext(), DataUpdateService.class));
}
}
}
| public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(OPT_CITY_ID)) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(OPT_CITY, cities_lp.getEntry().toString());
editor.commit();
setDefUrls(sharedPreferences);
new DataProgressDialog(this).execute();
}
if (key.equals(OPT_AUTO_UPD)) {
ListPreference lp = (ListPreference)findPreference(OPT_AUTO_UPD_TIME);
stopService(new Intent(getApplicationContext(), DataUpdateService.class));
if (sharedPreferences.getBoolean(OPT_AUTO_UPD, OPT_AUTO_UPD_DEF)){
lp.setEnabled(true);
if (Integer.parseInt(sharedPreferences.getString(OPT_AUTO_UPD_TIME, OPT_AUTO_UPD_TIME_DEF)) != 0){
startService(new Intent(getApplicationContext(), DataUpdateService.class));
}
} else {
lp.setEnabled(false);
}
}
if (key.equals(OPT_AUTO_UPD_TIME)) {
stopService(new Intent(this, DataUpdateService.class));
if (Integer.parseInt(sharedPreferences.getString(OPT_AUTO_UPD_TIME, OPT_AUTO_UPD_TIME_DEF)) != 0){
startService(new Intent(getApplicationContext(), DataUpdateService.class));
}
}
if (key.equals(OPT_CACHED_POSTER)) {
if (sharedPreferences.getBoolean(OPT_CACHED_POSTER, OPT_CACHED_POSTER_DEF)){
new DataProgressDialog(this).execute();
}
}
}
|
diff --git a/src/com/android/email/mail/transport/SmtpSender.java b/src/com/android/email/mail/transport/SmtpSender.java
index 71a86306..a9b13a66 100644
--- a/src/com/android/email/mail/transport/SmtpSender.java
+++ b/src/com/android/email/mail/transport/SmtpSender.java
@@ -1,334 +1,334 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.mail.transport;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import com.android.email.Email;
import com.android.email.mail.Sender;
import com.android.email.mail.Transport;
import com.android.emailcommon.Logging;
import com.android.emailcommon.internet.Rfc822Output;
import com.android.emailcommon.mail.Address;
import com.android.emailcommon.mail.AuthenticationFailedException;
import com.android.emailcommon.mail.CertificateValidationException;
import com.android.emailcommon.mail.MessagingException;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.provider.HostAuth;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import javax.net.ssl.SSLException;
/**
* This class handles all of the protocol-level aspects of sending messages via SMTP.
* TODO Remove dependence upon URI; there's no reason why we need it here
*/
public class SmtpSender extends Sender {
private final Context mContext;
private Transport mTransport;
private String mUsername;
private String mPassword;
/**
* Static named constructor.
*/
public static Sender newInstance(Account account, Context context) throws MessagingException {
return new SmtpSender(context, account);
}
/**
* Creates a new sender for the given account.
*/
private SmtpSender(Context context, Account account) throws MessagingException {
mContext = context;
HostAuth sendAuth = account.getOrCreateHostAuthSend(context);
if (sendAuth == null || !"smtp".equalsIgnoreCase(sendAuth.mProtocol)) {
throw new MessagingException("Unsupported protocol");
}
// defaults, which can be changed by security modifiers
int connectionSecurity = Transport.CONNECTION_SECURITY_NONE;
int defaultPort = 587;
// check for security flags and apply changes
if ((sendAuth.mFlags & HostAuth.FLAG_SSL) != 0) {
connectionSecurity = Transport.CONNECTION_SECURITY_SSL;
defaultPort = 465;
} else if ((sendAuth.mFlags & HostAuth.FLAG_TLS) != 0) {
connectionSecurity = Transport.CONNECTION_SECURITY_TLS;
}
boolean trustCertificates = ((sendAuth.mFlags & HostAuth.FLAG_TRUST_ALL) != 0);
int port = defaultPort;
if (sendAuth.mPort != HostAuth.PORT_UNKNOWN) {
port = sendAuth.mPort;
}
mTransport = new MailTransport("IMAP");
mTransport.setHost(sendAuth.mAddress);
mTransport.setPort(port);
mTransport.setSecurity(connectionSecurity, trustCertificates);
String[] userInfoParts = sendAuth.getLogin();
if (userInfoParts != null) {
mUsername = userInfoParts[0];
mPassword = userInfoParts[1];
}
}
/**
* For testing only. Injects a different transport. The transport should already be set
* up and ready to use. Do not use for real code.
* @param testTransport The Transport to inject and use for all future communication.
*/
/* package */ void setTransport(Transport testTransport) {
mTransport = testTransport;
}
@Override
public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
- if (result.contains("-STARTTLS")) {
+ if (result.contains("STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
@Override
public void sendMessage(long messageId) throws MessagingException {
close();
open();
Message message = Message.restoreMessageWithId(mContext, messageId);
if (message == null) {
throw new MessagingException("Trying to send non-existent message id="
+ Long.toString(messageId));
}
Address from = Address.unpackFirst(message.mFrom);
Address[] to = Address.unpack(message.mTo);
Address[] cc = Address.unpack(message.mCc);
Address[] bcc = Address.unpack(message.mBcc);
try {
executeSimpleCommand("MAIL FROM: " + "<" + from.getAddress() + ">");
for (Address address : to) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
for (Address address : cc) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
for (Address address : bcc) {
executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">");
}
executeSimpleCommand("DATA");
// TODO byte stuffing
Rfc822Output.writeTo(mContext, messageId,
new EOLConvertingOutputStream(mTransport.getOutputStream()),
false /* do not use smart reply */,
false /* do not send BCC */);
executeSimpleCommand("\r\n.");
} catch (IOException ioe) {
throw new MessagingException("Unable to send message", ioe);
}
}
/**
* Close the protocol (and the transport below it).
*
* MUST NOT return any exceptions.
*/
@Override
public void close() {
mTransport.close();
}
/**
* Send a single command and wait for a single response. Handles responses that continue
* onto multiple lines. Throws MessagingException if response code is 4xx or 5xx. All traffic
* is logged (if debug logging is enabled) so do not use this function for user ID or password.
*
* @param command The command string to send to the server.
* @return Returns the response string from the server.
*/
private String executeSimpleCommand(String command) throws IOException, MessagingException {
return executeSensitiveCommand(command, null);
}
/**
* Send a single command and wait for a single response. Handles responses that continue
* onto multiple lines. Throws MessagingException if response code is 4xx or 5xx.
*
* @param command The command string to send to the server.
* @param sensitiveReplacement If the command includes sensitive data (e.g. authentication)
* please pass a replacement string here (for logging).
* @return Returns the response string from the server.
*/
private String executeSensitiveCommand(String command, String sensitiveReplacement)
throws IOException, MessagingException {
if (command != null) {
mTransport.writeLine(command, sensitiveReplacement);
}
String line = mTransport.readLine();
String result = line;
while (line.length() >= 4 && line.charAt(3) == '-') {
line = mTransport.readLine();
result += line.substring(3);
}
if (result.length() > 0) {
char c = result.charAt(0);
if ((c == '4') || (c == '5')) {
throw new MessagingException(result);
}
}
return result;
}
// C: AUTH LOGIN
// S: 334 VXNlcm5hbWU6
// C: d2VsZG9u
// S: 334 UGFzc3dvcmQ6
// C: dzNsZDBu
// S: 235 2.0.0 OK Authenticated
//
// Lines 2-5 of the conversation contain base64-encoded information. The same conversation, with base64 strings decoded, reads:
//
//
// C: AUTH LOGIN
// S: 334 Username:
// C: weldon
// S: 334 Password:
// C: w3ld0n
// S: 235 2.0.0 OK Authenticated
private void saslAuthLogin(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
try {
executeSimpleCommand("AUTH LOGIN");
executeSensitiveCommand(
Base64.encodeToString(username.getBytes(), Base64.NO_WRAP),
"/username redacted/");
executeSensitiveCommand(
Base64.encodeToString(password.getBytes(), Base64.NO_WRAP),
"/password redacted/");
}
catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException(me.getMessage());
}
throw me;
}
}
private void saslAuthPlain(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
byte[] data = ("\000" + username + "\000" + password).getBytes();
data = Base64.encode(data, Base64.NO_WRAP);
try {
executeSensitiveCommand("AUTH PLAIN " + new String(data), "AUTH PLAIN /redacted/");
}
catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException(me.getMessage());
}
throw me;
}
}
}
| true | true | public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
if (result.contains("-STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
| public void open() throws MessagingException {
try {
mTransport.open();
// Eat the banner
executeSimpleCommand(null);
String localHost = "localhost";
// Try to get local address in the proper format.
InetAddress localAddress = mTransport.getLocalAddress();
if (localAddress != null) {
// Address Literal formatted in accordance to RFC2821 Sec. 4.1.3
StringBuilder sb = new StringBuilder();
sb.append('[');
if (localAddress instanceof Inet6Address) {
sb.append("IPv6:");
}
sb.append(localAddress.getHostAddress());
sb.append(']');
localHost = sb.toString();
}
String result = executeSimpleCommand("EHLO " + localHost);
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mTransport.canTryTlsSecurity()) {
if (result.contains("STARTTLS")) {
executeSimpleCommand("STARTTLS");
mTransport.reopenTls();
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
result = executeSimpleCommand("EHLO " + localHost);
} else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "TLS not supported but required");
}
throw new MessagingException(MessagingException.TLS_REQUIRED);
}
}
/*
* result contains the results of the EHLO in concatenated form
*/
boolean authLoginSupported = result.matches(".*AUTH.*LOGIN.*$");
boolean authPlainSupported = result.matches(".*AUTH.*PLAIN.*$");
if (mUsername != null && mUsername.length() > 0 && mPassword != null
&& mPassword.length() > 0) {
if (authPlainSupported) {
saslAuthPlain(mUsername, mPassword);
}
else if (authLoginSupported) {
saslAuthLogin(mUsername, mPassword);
}
else {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, "No valid authentication mechanism found.");
}
throw new MessagingException(MessagingException.AUTH_REQUIRED);
}
}
} catch (SSLException e) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, e.toString());
}
throw new CertificateValidationException(e.getMessage(), e);
} catch (IOException ioe) {
if (Email.DEBUG) {
Log.d(Logging.LOG_TAG, ioe.toString());
}
throw new MessagingException(MessagingException.IOERROR, ioe.toString());
}
}
|
diff --git a/tests/org.jboss.tools.jst.ui.bot.test/src/org/jboss/tools/ui/bot/test/JBTSWTBotTestCase.java b/tests/org.jboss.tools.jst.ui.bot.test/src/org/jboss/tools/ui/bot/test/JBTSWTBotTestCase.java
index 599ff051d..6954581b7 100644
--- a/tests/org.jboss.tools.jst.ui.bot.test/src/org/jboss/tools/ui/bot/test/JBTSWTBotTestCase.java
+++ b/tests/org.jboss.tools.jst.ui.bot.test/src/org/jboss/tools/ui/bot/test/JBTSWTBotTestCase.java
@@ -1,463 +1,477 @@
package org.jboss.tools.ui.bot.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.ILogListener;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException;
import org.eclipse.swtbot.swt.finder.utils.SWTBotPreferences;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.jboss.tools.ui.bot.ext.SWTBotExt;
import org.jboss.tools.ui.bot.ext.SWTTestExt;
import org.jboss.tools.ui.bot.ext.types.IDELabel;
import org.jboss.tools.ui.bot.ext.view.ProblemsView;
public abstract class JBTSWTBotTestCase extends SWTTestExt implements
ILogListener {
protected static final String BUILDING_WS = "Building workspace"; //$NON-NLS-1$
protected static final String VISUAL_UPDATE = "Visual Editor View Update"; //$NON-NLS-1$
protected static final String VISUAL_REFRESH = "Visual Editor Refresh"; //$NON-NLS-1$
protected static final String UPDATING_INDEXES = "Updating indexes"; //$NON-NLS-1$
private static Properties SWT_BOT_PROPERTIES;
private volatile Throwable exception;
public static final String PATH_TO_SWT_BOT_PROPERTIES = "SWTBot.properties"; //$NON-NLS-1$
protected SWTJBTBot bot = new SWTJBTBot();
private static int sleepTime = 1000;
private Logger log = Logger.getLogger(JBTSWTBotTestCase.class);
private HashSet<String> ignoredExceptionsFromEclipseLog = new HashSet<String>();
private boolean acceptExceptionsFromEclipseLog = false;
/*
* (non-Javadoc) This static block read properties from
* org.jboss.tools.ui.bot.test/resources/SWTBot.properties file and set up
* parameters for SWTBot tests. You may change a number of parameters in
* static block and their values in property file.
*/
static {
try {
InputStream inputStream = JBTSWTBotTestCase.class
.getResourceAsStream("/" + PATH_TO_SWT_BOT_PROPERTIES); //$NON-NLS-1$
SWT_BOT_PROPERTIES = new Properties();
SWT_BOT_PROPERTIES.load(inputStream);
SWTBotPreferences.PLAYBACK_DELAY = Long
.parseLong(SWT_BOT_PROPERTIES
.getProperty("SWTBotPreferences.PLAYBACK_DELAY")); //$NON-NLS-1$
SWTBotPreferences.TIMEOUT = Long.parseLong(SWT_BOT_PROPERTIES
.getProperty("SWTBotPreferences.TIMEOUT")); //$NON-NLS-1$
inputStream.close();
} catch (IOException e) {
IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,
"Can't load properties from " + PATH_TO_SWT_BOT_PROPERTIES //$NON-NLS-1$
+ " file", e); //$NON-NLS-1$
Activator.getDefault().getLog().log(status);
e.printStackTrace();
} catch (IllegalStateException e) {
IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,
"Property file " + PATH_TO_SWT_BOT_PROPERTIES //$NON-NLS-1$
+ " was not found", e); //$NON-NLS-1$
Activator.getDefault().getLog().log(status);
e.printStackTrace();
}
}
public void logging(IStatus status, String plugin) {
switch (status.getSeverity()) {
case IStatus.ERROR:
if (acceptExceptionsFromEclipseLog) {
Throwable throwable = status.getException();
if (throwable == null) {
if (!ignoredExceptionsFromEclipseLog.contains("null")) {
throwable = new Throwable(status.getMessage() + " in " //$NON-NLS-1$
+ status.getPlugin());
}
} else {
// Check if exception has to be ignored
if (ignoredExceptionsFromEclipseLog.contains(throwable
.getClass().getCanonicalName())) {
throwable = null;
}
}
setException(throwable);
}
break;
default:
break;
}
}
/**
* Getter method for exception that may be thrown during test execution.
* <p>
* You can call this method from any place of your methods and verify if any
* exception was thrown during test executing including Error Log.
*
* @return exception
* @see Throwable
*/
protected synchronized Throwable getException() {
return exception;
}
/**
* Setter method for exception. If param is not null test will fail and you
* will see stack trace in JUnit Error Log
*
* @param e
* - exception, that can be frown during test executing
* @see Throwable
*/
protected synchronized void setException(Throwable e) {
this.exception = e;
}
/**
* Delete .log file from junit-workspace .metadata, if it hadn't been
* deleted before
* <p>
* So we can catch exceptions and errors, which were thrown during current
* test.
*/
private void deleteLog() {
try {
Platform.getLogFileLocation().toFile().delete();
} catch (Exception e) {
}
}
/**
* Make a default preconditions before test launch
*
* @see #activePerspective()
* @see #openErrorLog()
* @see #openPackageExplorer()
* @see #setException(Throwable)
* @see #deleteLog()
* @see #delay()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
activePerspective();
try {
bot.viewByTitle(WidgetVariables.WELCOME).close();
} catch (WidgetNotFoundException e) {
}
try {
bot.editorByTitle(IDELabel.View.JBOSS_CENTRAL).close();
} catch (WidgetNotFoundException e) {
}
openErrorLog();
openPackageExplorer();
// openProgressStatus();
deleteLog();
setException(null);
Platform.addLogListener(this);
// delay();
}
/**
* Tears down the fixture. Verify Error Log.
*
* @see #getException()
*/
@Override
protected void tearDown() throws Exception {
Platform.removeLogListener(this);
deleteLog();
Throwable e = getException();
if (e != null) {
log.error(e.getMessage(),e);
if (e.getCause() != null){
log.error(e.getCause().getMessage(),e.getCause());
}
throw new Exception(e);
}
}
/**
* A little delay between test's steps. Use it where necessary.
*/
protected void delay() {
bot.sleep(sleepTime);
}
/**
* Defines which kind of perspective should be activated before tests' run.
*/
abstract protected void activePerspective();
/**
* Open and activate Error Log view if it hadn't been opened before
*/
protected void openErrorLog() {
try {
bot.viewByTitle(WidgetVariables.ERROR_LOG);
} catch (WidgetNotFoundException e) {
bot.menu("Window").menu("Show View").menu("Other...").click(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SWTBotTree viewTree = bot.tree();
delay();
viewTree.expandNode("General") //$NON-NLS-1$
.expandNode(WidgetVariables.ERROR_LOG).select();
bot.button("OK").click(); //$NON-NLS-1$
}
}
/**
* Open and activate Package Explorer view if it hadn't been opened before
*/
protected void openPackageExplorer() {
try {
bot.viewByTitle(WidgetVariables.PACKAGE_EXPLORER).setFocus();
} catch (WidgetNotFoundException e) {
bot.menu("Window").menu("Show View").menu("Other...").click(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SWTBotTree viewTree = bot.tree();
delay();
viewTree.expandNode("Java").expandNode( //$NON-NLS-1$
WidgetVariables.PACKAGE_EXPLORER).select();
bot.button("OK").click(); //$NON-NLS-1$
}
}
/**
* Open and activate Web Projects view if it hadn't been opened before
*/
protected void openWebProjects() {
try {
bot.viewByTitle(WidgetVariables.WEB_PROJECTS).setFocus();
} catch (WidgetNotFoundException e) {
bot.menu("Window").menu("Show View").menu("Other...").click(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SWTBotTree viewTree = bot.tree();
delay();
viewTree.expandNode("Java").expandNode( //$NON-NLS-1$
WidgetVariables.WEB_PROJECTS).select();
bot.button("OK").click(); //$NON-NLS-1$
}
}
/**
* Open and activate Server View if it hadn't been opened before
*/
protected void openServerView() {
try {
bot.viewByTitle(WidgetVariables.SERVERS).setFocus();
} catch (WidgetNotFoundException e) {
bot.menu("Window").menu("Show View").menu("Other...").click(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SWTBotTree viewTree = bot.tree();
delay();
viewTree.expandNode("Server").expandNode( //$NON-NLS-1$
WidgetVariables.SERVERS).select();
bot.button("OK").click(); //$NON-NLS-1$
}
}
/**
* Open and activate Properties View if it hadn't been opened before
*/
protected void openPropertiesView() {
try {
bot.viewByTitle(WidgetVariables.PROPERTIES).setFocus();
} catch (WidgetNotFoundException e) {
bot.menu("Window").menu("Show View").menu("Other...").click(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SWTBotTree viewTree = bot.tree();
delay();
viewTree.expandNode("General").expandNode( //$NON-NLS-1$
WidgetVariables.PROPERTIES).select();
bot.button("OK").click(); //$NON-NLS-1$
}
}
/**
* Open and activate Outline View if it hadn't been opened before
*/
protected void openOutlineView() {
try {
bot.viewByTitle(WidgetVariables.OUTLINE).setFocus();
} catch (WidgetNotFoundException e) {
bot.menu("Window").menu("Show View").menu("Other...").click(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SWTBotTree viewTree = bot.tree();
delay();
viewTree.expandNode("General").expandNode( //$NON-NLS-1$
WidgetVariables.OUTLINE).select();
bot.button("OK").click(); //$NON-NLS-1$
}
}
// protected void openProgressStatus() {
// try {
// bot.viewByTitle(WidgetVariables.PROGRESS_STATUS);
// } catch (WidgetNotFoundException e) {
// bot.menu("Window").menu("Show View").menu("Other...").click();
// SWTBotTree viewTree = bot.tree();
// delay();
// viewTree.expandNode("General").expandNode(WidgetVariables.PROGRESS_STATUS).select();
// bot.button("OK").click();
// }
// }
/**
* Use delay() method instead
*
* @see #delay()
*/
@Deprecated
protected final void waitForJobs() {
delay();
}
protected final void waitForBlockingJobsAcomplished(final long timeOut,
final String... jobNames) {
if (jobNames == null) {
return;
} else {
+ log.info("Entering waitForBlockingJobsAcomplished method");
Map<String, Boolean> runningProcessesMap = new HashMap<String, Boolean>();
for (int i = 0; i < jobNames.length; i++) {
runningProcessesMap.put(jobNames[i], false);
}
boolean isRequiredProcessesStarted = false;
long startTime = System.currentTimeMillis();
while (!isRequiredProcessesStarted) {
Job[] jobs = Job.getJobManager().find(null);
for (Job job : jobs) {
for (String jobName : jobNames) {
if (jobName.equalsIgnoreCase(job.getName())) {
if (!runningProcessesMap.get(jobName)) {
runningProcessesMap.remove(jobName);
runningProcessesMap.put(jobName, true);
}
}
}
}
isRequiredProcessesStarted = true;
for (String jobName : jobNames) {
isRequiredProcessesStarted = isRequiredProcessesStarted
& runningProcessesMap.get(jobName);
}
if (!isRequiredProcessesStarted) {
long endTime = System.currentTimeMillis();
if (endTime - startTime > timeOut) {
System.out.println("Next processes are already started or finished: "+ //$NON-NLS-1$
runningProcessesToString(jobNames)+" called in " + getName() + " class"); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
}
}
- while (isRequiredProcessesStarted) {
- isRequiredProcessesStarted = false;
+ boolean continueWaiting = isRequiredProcessesStarted;
+ while (continueWaiting) {
+ continueWaiting = false;
Job[] jobs = Job.getJobManager().find(null);
for (Job job : jobs) {
for (String jobName : jobNames) {
if (jobName.equalsIgnoreCase(job.getName())) {
- isRequiredProcessesStarted = true;
- delay();
+ log.info("Waiting for job " + job.getName() + " [job_state=" + job.getState() + "]");
+ if (job.getState() == Job.RUNNING){
+ continueWaiting = true;
+ // if job is sleeping after timeout do not wait anymore sometimes it gets stucked forever
+ } else if (job.getState() == Job.SLEEPING){
+ long timeLeftToWaitForSleepingJob = timeOut - (System.currentTimeMillis() - startTime);
+ if (timeLeftToWaitForSleepingJob > 0) {
+ log.info("Waiting for sleeping job for " + timeLeftToWaitForSleepingJob + " miliseconds");
+ continueWaiting = true;
+ }
+ }
+ if (continueWaiting){
+ delay();
+ }
}
}
}
}
}
}
protected final void waitForBlockingJobsAcomplished(String... jobNames) {
waitForBlockingJobsAcomplished(5 * 1000L, jobNames);
}
private String runningProcessesToString (String ... processes){
String process = ""; //$NON-NLS-1$
for (String processRunning : processes) {
process = process + processRunning + ", "; //$NON-NLS-1$
}
return process;
}
/**
* Asserts if Problems View has no errors
* @param botExt
*/
protected static void assertProbelmsViewNoErrors (SWTBotExt botExt){
SWTBotTreeItem[] errors = ProblemsView.getFilteredErrorsTreeItems(botExt, null, null, null, null);
boolean areThereNoErrors = ((errors == null) || (errors.length == 0));
assertTrue("There are errors in Problems view: " +
(areThereNoErrors ? "" : errors[0].getText()),
areThereNoErrors);
}
/**
* Asserts if Problems View has no errors for page pageName
*
* @param botExt
*/
protected static void assertProbelmsViewNoErrorsForPage(SWTBotExt botExt,
String pageName) {
SWTBotTreeItem[] errors = ProblemsView.getFilteredErrorsTreeItems(
botExt, null, null, pageName, null);
boolean areThereNoErrors = ((errors == null) || (errors.length == 0));
assertTrue("There are errors in Problems view for test page: "
+ (areThereNoErrors ? "" : errors[0].getText()),
areThereNoErrors);
}
/**
* Adds exceptionFullClassName to ignored exception from eclipse log
* exceptionFullClassName exception will not make test failing
* @param exceptionFullClassName
*/
protected void addIgnoredExceptionFromEclipseLog(String exceptionFullClassName){
ignoredExceptionsFromEclipseLog.add(exceptionFullClassName);
}
/**
* Removes exceptionFullClassName from ignored exception from eclipse log
* exceptionFullClassName exception will make test failing
* @param exceptionFullClassName
*/
protected void removeIgnoredExceptionFromEclipseLog(String exceptionFullClassName){
ignoredExceptionsFromEclipseLog.remove(exceptionFullClassName);
}
/**
* Removes all ignored exceptions
*/
protected void eraseIgnoredExceptionsFromEclipseLog(){
ignoredExceptionsFromEclipseLog.clear();
}
/**
* Disables catching exceptions from Eclipse log
*/
protected void ignoreAllExceptionsFromEclipseLog(){
acceptExceptionsFromEclipseLog = false;
}
/**
* Reenables catching exceptions from Eclipse log
*/
protected void catchExceptionsFromEclipseLog(){
acceptExceptionsFromEclipseLog = true;
}
/**
* Returns true when exceptions from Eclipse log are catched
* @return
*/
protected boolean isAcceptExceptionsFromEclipseLog(){
return acceptExceptionsFromEclipseLog;
}
}
| false | true | protected final void waitForBlockingJobsAcomplished(final long timeOut,
final String... jobNames) {
if (jobNames == null) {
return;
} else {
Map<String, Boolean> runningProcessesMap = new HashMap<String, Boolean>();
for (int i = 0; i < jobNames.length; i++) {
runningProcessesMap.put(jobNames[i], false);
}
boolean isRequiredProcessesStarted = false;
long startTime = System.currentTimeMillis();
while (!isRequiredProcessesStarted) {
Job[] jobs = Job.getJobManager().find(null);
for (Job job : jobs) {
for (String jobName : jobNames) {
if (jobName.equalsIgnoreCase(job.getName())) {
if (!runningProcessesMap.get(jobName)) {
runningProcessesMap.remove(jobName);
runningProcessesMap.put(jobName, true);
}
}
}
}
isRequiredProcessesStarted = true;
for (String jobName : jobNames) {
isRequiredProcessesStarted = isRequiredProcessesStarted
& runningProcessesMap.get(jobName);
}
if (!isRequiredProcessesStarted) {
long endTime = System.currentTimeMillis();
if (endTime - startTime > timeOut) {
System.out.println("Next processes are already started or finished: "+ //$NON-NLS-1$
runningProcessesToString(jobNames)+" called in " + getName() + " class"); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
}
}
while (isRequiredProcessesStarted) {
isRequiredProcessesStarted = false;
Job[] jobs = Job.getJobManager().find(null);
for (Job job : jobs) {
for (String jobName : jobNames) {
if (jobName.equalsIgnoreCase(job.getName())) {
isRequiredProcessesStarted = true;
delay();
}
}
}
}
}
}
| protected final void waitForBlockingJobsAcomplished(final long timeOut,
final String... jobNames) {
if (jobNames == null) {
return;
} else {
log.info("Entering waitForBlockingJobsAcomplished method");
Map<String, Boolean> runningProcessesMap = new HashMap<String, Boolean>();
for (int i = 0; i < jobNames.length; i++) {
runningProcessesMap.put(jobNames[i], false);
}
boolean isRequiredProcessesStarted = false;
long startTime = System.currentTimeMillis();
while (!isRequiredProcessesStarted) {
Job[] jobs = Job.getJobManager().find(null);
for (Job job : jobs) {
for (String jobName : jobNames) {
if (jobName.equalsIgnoreCase(job.getName())) {
if (!runningProcessesMap.get(jobName)) {
runningProcessesMap.remove(jobName);
runningProcessesMap.put(jobName, true);
}
}
}
}
isRequiredProcessesStarted = true;
for (String jobName : jobNames) {
isRequiredProcessesStarted = isRequiredProcessesStarted
& runningProcessesMap.get(jobName);
}
if (!isRequiredProcessesStarted) {
long endTime = System.currentTimeMillis();
if (endTime - startTime > timeOut) {
System.out.println("Next processes are already started or finished: "+ //$NON-NLS-1$
runningProcessesToString(jobNames)+" called in " + getName() + " class"); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
}
}
boolean continueWaiting = isRequiredProcessesStarted;
while (continueWaiting) {
continueWaiting = false;
Job[] jobs = Job.getJobManager().find(null);
for (Job job : jobs) {
for (String jobName : jobNames) {
if (jobName.equalsIgnoreCase(job.getName())) {
log.info("Waiting for job " + job.getName() + " [job_state=" + job.getState() + "]");
if (job.getState() == Job.RUNNING){
continueWaiting = true;
// if job is sleeping after timeout do not wait anymore sometimes it gets stucked forever
} else if (job.getState() == Job.SLEEPING){
long timeLeftToWaitForSleepingJob = timeOut - (System.currentTimeMillis() - startTime);
if (timeLeftToWaitForSleepingJob > 0) {
log.info("Waiting for sleeping job for " + timeLeftToWaitForSleepingJob + " miliseconds");
continueWaiting = true;
}
}
if (continueWaiting){
delay();
}
}
}
}
}
}
}
|
diff --git a/org.eclipse.jdt.debug/model/org/eclipse/jdt/debug/core/JDIDebugModel.java b/org.eclipse.jdt.debug/model/org/eclipse/jdt/debug/core/JDIDebugModel.java
index 5a315b752..68644297b 100644
--- a/org.eclipse.jdt.debug/model/org/eclipse/jdt/debug/core/JDIDebugModel.java
+++ b/org.eclipse.jdt.debug/model/org/eclipse/jdt/debug/core/JDIDebugModel.java
@@ -1,594 +1,594 @@
/*******************************************************************************
* 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.jdt.debug.core;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IBreakpointManager;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaExceptionBreakpoint;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaLineBreakpoint;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaMethodBreakpoint;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaMethodEntryBreakpoint;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaPatternBreakpoint;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaStratumLineBreakpoint;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaTargetPatternBreakpoint;
import org.eclipse.jdt.internal.debug.core.breakpoints.JavaWatchpoint;
import org.eclipse.jdt.internal.debug.core.model.JDIDebugTarget;
import com.sun.jdi.VirtualMachine;
/**
* Provides utility methods for creating debug targets and breakpoints specific
* to the JDI debug model.
* <p>
* To provide access to behavior and information specific to the JDI
* debug model, a set of interfaces are defined which extend the base
* set of debug element interfaces. For example, <code>IJavaStackFrame</code>
* is declared to extend <code>IStackFrame</code>, and provides methods
* specific to this debug model. The specialized interfaces are also
* available as adapters from the debug elements generated from this
* model.
* </p>
* <p>
* Clients are not intended to instantiate or subclass this class;
* this class provides static utility methods only.
* </p>
*/
public class JDIDebugModel {
/**
* Preference key for default JDI request timeout value.
*/
public static final String PREF_REQUEST_TIMEOUT = getPluginIdentifier() + ".PREF_REQUEST_TIMEOUT"; //$NON-NLS-1$
/**
* Preference key for specifying if hot code replace should be performed
* when a replacement class file contains compilation errors.
*/
public static final String PREF_HCR_WITH_COMPILATION_ERRORS= getPluginIdentifier() + ".PREF_HCR_WITH_COMPILATION_ERRORS"; //$NON-NLS-1$
/**
* The default JDI request timeout when no preference is set.
*/
public static final int DEF_REQUEST_TIMEOUT = 3000;
/**
* Not to be instantiated.
*/
private JDIDebugModel() {
super();
}
/**
* Creates and returns a debug target for the given VM, with
* the specified name, and associates the debug target with the
* given process for console I/O. The allow terminate flag specifies whether
* the debug target will support termination (<code>ITerminate</code>).
* The allow disconnect flag specifies whether the debug target will
* support disconnection (<code>IDisconnect</code>). Launching the actual
* VM is a client responsibility. By default, the target VM will be
* resumed on startup.
* The debug target is added to the given launch.
*
* @param launch the launch the new debug target will be contained in
* @param vm the VM to create a debug target for
* @param name the name to associate with the VM, which will be
* returned from <code>IDebugTarget.getName</code>. If <code>null</code>
* the name will be retrieved from the underlying VM.
* @param process the process to associate with the debug target,
* which will be returned from <code>IDebugTarget.getProcess</code>
* @param allowTerminate whether the target will support termianation
* @param allowDisconnect whether the target will support disconnection
* @return a debug target
* @see org.eclipse.debug.core.model.ITerminate
* @see org.eclipse.debug.core.model.IDisconnect
* @since 2.0
*/
public static IDebugTarget newDebugTarget(ILaunch launch, VirtualMachine vm, String name, IProcess process, boolean allowTerminate, boolean allowDisconnect) {
return newDebugTarget(launch, vm, name, process, allowTerminate, allowDisconnect, true);
}
/**
* Creates and returns a debug target for the given VM, with
* the specified name, and associates the debug target with the
* given process for console I/O. The allow terminate flag specifies whether
* the debug target will support termination (<code>ITerminate</code>).
* The allow disconnect flag specifies whether the debug target will
* support disconnection (<code>IDisconnect</code>). The resume
* flag specifies if the target VM should be resumed on startup (has
* no effect if the VM was already running when the connection to the
* VM was esatbished). Launching the actual VM is a client responsibility.
* The debug target is added to the given launch.
*
* @param launch the launch the new debug target will be contained in
* @param vm the VM to create a debug target for
* @param name the name to associate with the VM, which will be
* returned from <code>IDebugTarget.getName</code>. If <code>null</code>
* the name will be retrieved from the underlying VM.
* @param process the process to associate with the debug target,
* which will be returned from <code>IDebugTarget.getProcess</code>
* @param allowTerminate whether the target will support termianation
* @param allowDisconnect whether the target will support disconnection
* @param resume whether the target is to be resumed on startup. Has
* no effect if the target was already running when the connection
* to the VM was established.
* @return a debug target
* @see org.eclipse.debug.core.model.ITerminate
* @see org.eclipse.debug.core.model.IDisconnect
* @since 2.0
*/
public static IDebugTarget newDebugTarget(final ILaunch launch, final VirtualMachine vm, final String name, final IProcess process, final boolean allowTerminate, final boolean allowDisconnect, final boolean resume) {
final IJavaDebugTarget[] target = new IJavaDebugTarget[1];
IWorkspaceRunnable r = new IWorkspaceRunnable() {
public void run(IProgressMonitor m) {
target[0]= new JDIDebugTarget(launch, vm, name, allowTerminate, allowDisconnect, process, resume);
}
};
try {
ResourcesPlugin.getWorkspace().run(r, null, 0, null);
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
return target[0];
}
/**
* Returns the identifier for the JDI debug model plug-in
*
* @return plugin identifier
*/
public static String getPluginIdentifier() {
return JDIDebugPlugin.getUniqueIdentifier();
}
/**
* Registers the given listener for hot code replace notifications. Has no
* effect if an identical listener is already registered.
*
* @param listener hot code replace listener
* @see IJavaHotCodeReplaceListener
* @since 2.0
*/
public static void addHotCodeReplaceListener(IJavaHotCodeReplaceListener listener) {
JDIDebugPlugin.getDefault().addHotCodeReplaceListener(listener);
}
/**
* Deregisters the given listener for hot code replace notifications. Has no
* effect if an identical listener is not already registered.
*
* @param listener hot code replace listener
* @see IJavaHotCodeReplaceListener
* @since 2.0
*/
public static void removeHotCodeReplaceListener(IJavaHotCodeReplaceListener listener) {
JDIDebugPlugin.getDefault().removeHotCodeReplaceListener(listener);
}
/**
* Registers the given listener for breakpoint notifications. Has no
* effect if an identical listener is already registered.
*
* @param listener breakpoint listener
* @see IJavaBreakpointListener
* @since 2.0
*/
public static void addJavaBreakpointListener(IJavaBreakpointListener listener) {
JDIDebugPlugin.getDefault().addJavaBreakpointListener(listener);
}
/**
* Deregisters the given listener for breakpoint notifications. Has no
* effect if an identical listener is not already registered.
*
* @param listener breakpoint listener
* @see IJavaBreakpointListener
* @since 2.0
*/
public static void removeJavaBreakpointListener(IJavaBreakpointListener listener) {
JDIDebugPlugin.getDefault().removeJavaBreakpointListener(listener);
}
/**
* Creates and returns a line breakpoint in the type with the
* given name, at the given line number. The marker associated with the
* breakpoint will be created on the specified resource. If a character
* range within the line is known, it may be specified by charStart/charEnd.
* If hitCount is > 0, the breakpoint will suspend execution when it is
* "hit" the specified number of times.
*
* @param resource the resource on which to create the associated breakpoint
* marker
* @param typeName the fully qualified name of the type the breakpoint is
* to be installed in. If the breakpoint is to be installed in an inner type,
* it is sufficient to provide the name of the top level enclosing type.
* If an inner class name is specified, it should be formatted as the
* associated class file name (i.e. with <code>$</code>). For example,
* <code>example.SomeClass$InnerType</code>, could be specified, but
* <code>example.SomeClass</code> is sufficient.
* @param lineNumber the lineNumber on which the breakpoint is set - line
* numbers are 1 based, associated with the source file in which
* the breakpoint is set
* @param charStart the first character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param charEnd the last character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param hitCount the number of times the breakpoint will be hit before
* suspending execution - 0 if it should always suspend
* @param register whether to add this breakpoint to the breakpoint manager
* @param attributes a map of client defined attributes that should be assigned
* to the underlying breakpoint marker on creation, or <code>null</code> if none.
* @return a line breakpoint
* @exception CoreException If this method fails. Reasons include:<ul>
*<li>Failure creating underlying marker. The exception's status contains
* the underlying exception responsible for the failure.</li></ul>
* @since 2.0
*/
public static IJavaLineBreakpoint createLineBreakpoint(IResource resource, String typeName, int lineNumber, int charStart, int charEnd, int hitCount, boolean register, Map attributes) throws CoreException {
if (attributes == null) {
attributes = new HashMap(10);
}
return new JavaLineBreakpoint(resource, typeName, lineNumber, charStart, charEnd, hitCount, register, attributes);
}
/**
* Creates and returns a pattern breakpoint for the given resource at the
* given line number, which is installed in all classes whose fully
* qualified name matches the given pattern.
* If hitCount > 0, the breakpoint will suspend execution when it is
* "hit" the specified number of times.
*
* @param resource the resource on which to create the associated breakpoint
* marker
* @param sourceName the name of the source file in which the breakpoint is
* set, or <code>null</code>. When specified, the pattern breakpoint will
* install itself in classes that have a source file name debug attribute
* that matches this value, and satisfies the class name pattern.
* @param pattern the class name pattern in which the pattern breakpoint should
* be installed. The pattern breakpoint will install itself in every class which
* matches the pattern.
* @param lineNumber the lineNumber on which the breakpoint is set - line
* numbers are 1 based, associated with the source file in which
* the breakpoint is set
* @param charStart the first character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param charEnd the last character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param hitCount the number of times the breakpoint will be hit before
* suspending execution - 0 if it should always suspend
* @param register whether to add this breakpoint to the breakpoint manager
* @param attributes a map of client defined attributes that should be assigned
* to the underlying breakpoint marker on creation, or <code>null</code> if none.
* @return a pattern breakpoint
* @exception CoreException If this method fails. Reasons include:<ul>
*<li>Failure creating underlying marker. The exception's status contains
* the underlying exception responsible for the failure.</li></ul>
*/
public static IJavaPatternBreakpoint createPatternBreakpoint(IResource resource, String sourceName, String pattern, int lineNumber, int charStart, int charEnd, int hitCount, boolean register, Map attributes) throws CoreException {
if (attributes == null) {
attributes = new HashMap(10);
}
return new JavaPatternBreakpoint(resource, sourceName, pattern, lineNumber, charStart, charEnd, hitCount, register, attributes);
}
/**
* Creates and returns a line breakpoint associated with the given resource,
* at the given line number in the specified stratum (see JSR045). The breakpoint
* is installed in classes that have a matching stratum, source name, source path,
* and class name pattern.
*
* @param resource the resource on which to create the associated breakpoint
* marker
* @param stratum the stratum in which the source name, source path and line number
* are relative.
* @param sourceName the simple name of the source file in which the breakpoint is
* set. The breakpoint will install itself in classes that have a source
* file name debug attribute that matches this value in the specified stratum,
* and satisfies the class name pattern.
* @param sourcePath the path in the project of the source file in which the breakpoint is
* set, or <code>null</code>. When specified, the pattern breakpoint will
* install itself in classes that have a source file path in the specified stratum
* that matches this value, and satisfies the class name pattern.
* @param classNamePattern the class name pattern in which the pattern breakpoint should
* be installed. The pattern breakpoint will install itself in each class that
* matches this class name pattern, with a satisfying source name and source path.
* @param lineNumber the lineNumber on which the breakpoint is set - line
* numbers are 1 based, associated with the source file (stratum) in which
* the breakpoint is set
* @param charStart the first character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param charEnd the last character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param hitCount the number of times the breakpoint will be hit before
* suspending execution - 0 if it should always suspend
* @param register whether to add this breakpoint to the breakpoint manager
* @param attributes a map of client defined attributes that should be assigned
* to the underlying breakpoint marker on creation, or <code>null</code> if none.
* @return a stratum breakpoint
* @exception CoreException If this method fails. Reasons include:<ul>
*<li>Failure creating underlying marker. The exception's status contains
* the underlying exception responsible for the failure.</li></ul>
* @since 3.0
*/
public static IJavaStratumLineBreakpoint createStratumBreakpoint(IResource resource, String stratum, String sourceName, String sourcePath, String classNamePattern, int lineNumber, int charStart, int charEnd, int hitCount, boolean register, Map attributes) throws CoreException {
if (attributes == null) {
attributes = new HashMap(10);
}
return new JavaStratumLineBreakpoint(resource, stratum, sourceName, sourcePath, classNamePattern, lineNumber, charStart, charEnd, hitCount, register, attributes);
}
/**
* Creates and returns a target pattern breakpoint for the given resource at the
* given line number. Clients must set the class name pattern per target for
* this type of breakpoint.
* If hitCount > 0, the breakpoint will suspend execution when it is
* "hit" the specified number of times.
*
* @param resource the resource on which to create the associated breakpoint
* marker
* @param sourceName the name of the source file in which the breakpoint is
* set, or <code>null</code>. When specified, the pattern breakpoint will
* install itself in classes that have a source file name debug attribute
* that matches this value, and satisfies the class name pattern.
* @param lineNumber the lineNumber on which the breakpoint is set - line
* numbers are 1 based, associated with the source file in which
* the breakpoint is set
* @param charStart the first character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param charEnd the last character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param hitCount the number of times the breakpoint will be hit before
* suspending execution - 0 if it should always suspend
* @param register whether to add this breakpoint to the breakpoint manager
* @param attributes a map of client defined attributes that should be assigned
* to the underlying breakpoint marker on creation, or <code>null</code> if none.
* @return a target pattern breakpoint
* @exception CoreException If this method fails. Reasons include:<ul>
*<li>Failure creating underlying marker. The exception's status contains
* the underlying exception responsible for the failure.</li></ul>
*/
public static IJavaTargetPatternBreakpoint createTargetPatternBreakpoint(IResource resource, String sourceName, int lineNumber, int charStart, int charEnd, int hitCount, boolean register, Map attributes) throws CoreException {
if (attributes == null) {
attributes = new HashMap(10);
}
return new JavaTargetPatternBreakpoint(resource, sourceName, lineNumber, charStart, charEnd, hitCount, register, attributes);
}
/**
* Creates and returns an exception breakpoint for an exception with the given name.
* The marker associated with the breakpoint will be created on the specified resource.
* Caught and uncaught specify where the exception
* should cause thread suspensions - that is, in caught and/or uncaught locations.
* Checked indicates if the given exception is a checked exception.
*
* @param resource the resource on which to create the associated
* breakpoint marker
* @param exceptionName the fully qualified name of the exception for
* which to create the breakpoint
* @param caught whether to suspend in caught locations
* @param uncaught whether to suspend in uncaught locations
* @param checked whether the exception is a checked exception (i.e. complier
* detected)
* @param register whether to add this breakpoint to the breakpoint manager
* @param attributes a map of client defined attributes that should be assigned
* to the underlying breakpoint marker on creation or <code>null</code> if none.
* @return an exception breakpoint
* @exception CoreException If this method fails. Reasons include:<ul>
*<li>Failure creating underlying marker. The exception's status contains
* the underlying exception responsible for the failure.</li></ul>
* @since 2.0
*/
public static IJavaExceptionBreakpoint createExceptionBreakpoint(IResource resource, String exceptionName, boolean caught, boolean uncaught, boolean checked, boolean register, Map attributes) throws CoreException {
if (attributes == null) {
attributes = new HashMap(10);
}
return new JavaExceptionBreakpoint(resource, exceptionName, caught, uncaught, checked, register, attributes);
}
/**
* Creates and returns a watchpoint on a field with the given name
* in a type with the given name.
* The marker associated with the breakpoint will be created on the specified resource.
* If hitCount > 0, the breakpoint will suspend execution when it is
* "hit" the specified number of times.
*
* @param resource the resource on which to create the associated breakpoint
* marker
* @param typeName the fully qualified name of the type the breakpoint is
* to be installed in. If the breakpoint is to be installed in an inner type,
* it is sufficient to provide the name of the top level enclosing type.
* If an inner class name is specified, it should be formatted as the
* associated class file name (i.e. with <code>$</code>). For example,
* <code>example.SomeClass$InnerType</code>, could be specified, but
* <code>example.SomeClass</code> is sufficient.
* @param fieldName the name of the field on which to suspend (on access or modification)
* @param lineNumber the lineNumber on which the breakpoint is set - line
* numbers are 1 based, associated with the source file in which
* the breakpoint is set
* @param charStart the first character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param charEnd the last character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param hitCount the number of times the breakpoint will be hit before
* suspending execution - 0 if it should always suspend
* @param register whether to add this breakpoint to the breakpoint manager
* @param attributes a map of client defined attributes that should be assigned
* to the underlying breakpoint marker on creation, or <code>null</code> if none.
* @return a watchpoint
* @exception CoreException If this method fails. Reasons include:<ul>
*<li>Failure creating underlying marker. The CoreException's status contains
* the underlying exception responsible for the failure.</li></ul>
* @since 2.0
*/
public static IJavaWatchpoint createWatchpoint(IResource resource, String typeName, String fieldName, int lineNumber, int charStart, int charEnd, int hitCount, boolean register, Map attributes) throws CoreException {
if (attributes == null) {
attributes = new HashMap(10);
}
return new JavaWatchpoint(resource, typeName, fieldName, lineNumber, charStart, charEnd, hitCount, register, attributes);
}
/**
* Creates and returns a method breakpoint with the specified
* criteria.
*
* @param resource the resource on which to create the associated
* breakpoint marker
* @param typePattern the pattern specifying the fully qualified name of type(s)
* this breakpoint suspends execution in. Patterns are limited to exact
* matches and patterns that begin or end with '*'.
* @param methodName the name of the method(s) this breakpoint suspends
* execution in, or <code>null</code> if this breakpoint does
* not suspend execution based on method name
* @param methodSignature the signature of the method(s) this breakpoint suspends
* execution in, or <code>null</code> if this breakpoint does not
* suspend exectution based on method signature
* @param entry whether this breakpoint causes execution to suspend
* on entry of methods
* @param exit whether this breakpoint causes execution to suspend
* on exit of methods
* @param nativeOnly whether this breakpoint causes execution to suspend
* on entry/exit of native methods only
* @param lineNumber the lineNumber on which the breakpoint is set - line
* numbers are 1 based, associated with the source file in which
* the breakpoint is set
* @param charStart the first character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param charEnd the last character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param hitCount the number of times the breakpoint will be hit before
* suspending execution - 0 if it should always suspend
* @param register whether to add this breakpoint to the breakpoint manager
* @param attributes a map of client defined attributes that should be assigned
* to the underlying breakpoint marker on creation, or <code>null</code> if none.
* @return a method breakpoint
* @exception CoreException If this method fails. Reasons include:<ul>
*<li>Failure creating underlying marker. The exception's status contains
* the underlying exception responsible for the failure.</li></ul>
* @since 2.0
*/
public static IJavaMethodBreakpoint createMethodBreakpoint(IResource resource, String typePattern, String methodName, String methodSignature, boolean entry, boolean exit, boolean nativeOnly, int lineNumber, int charStart, int charEnd, int hitCount, boolean register, Map attributes) throws CoreException {
if (attributes == null) {
attributes = new HashMap(10);
}
return new JavaMethodBreakpoint(resource, typePattern, methodName, methodSignature, entry, exit, nativeOnly, lineNumber, charStart, charEnd, hitCount, register, attributes);
}
/**
* Creates and returns a method entry breakpoint with the specified
* criteria. A method entry breakpoint will only be installed for methods
* that have executable code (i.e. will not work for native methods).
*
* @param resource the resource on which to create the associated
* breakpoint marker
* @param typeName the fully qualified name of type
* this breakpoint suspends execution in.
* @param methodName the name of the method this breakpoint suspends
* execution in
* @param methodSignature the signature of the method this breakpoint suspends
* execution in
* @param lineNumber the lineNumber on which the breakpoint is set - line
* numbers are 1 based, associated with the source file in which
* the breakpoint is set
* @param charStart the first character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param charEnd the last character index associated with the breakpoint,
* or -1 if unspecified, in the source file in which the breakpoint is set
* @param hitCount the number of times the breakpoint will be hit before
* suspending execution - 0 if it should always suspend
* @param register whether to add this breakpoint to the breakpoint manager
* @param attributes a map of client defined attributes that should be assigned
* to the underlying breakpoint marker on creation, or <code>null</code> if none.
* @return a method entry breakpoint
* @exception CoreException If this method fails. Reasons include:<ul>
*<li>Failure creating underlying marker. The exception's status contains
* the underlying exception responsible for the failure.</li></ul>
* @since 2.0
*/
public static IJavaMethodEntryBreakpoint createMethodEntryBreakpoint(IResource resource, String typeName, String methodName, String methodSignature, int lineNumber, int charStart, int charEnd, int hitCount, boolean register, Map attributes) throws CoreException {
if (attributes == null) {
attributes = new HashMap(10);
}
return new JavaMethodEntryBreakpoint(resource, typeName, methodName, methodSignature, lineNumber, charStart, charEnd, hitCount, register, attributes);
}
/**
* Returns a Java line breakpoint that is already registered with the breakpoint
* manager for a type with the given name at the given line number.
*
* @param typeName fully qualified type name
* @param lineNumber line number
* @return a Java line breakpoint that is already registered with the breakpoint
* manager for a type with the given name at the given line number or <code>null</code>
* if no such breakpoint is registered
* @exception CoreException if unable to retrieve the associated marker
* attributes (line number).
*/
public static IJavaLineBreakpoint lineBreakpointExists(String typeName, int lineNumber) throws CoreException {
String modelId= getPluginIdentifier();
String markerType= JavaLineBreakpoint.getMarkerType();
IBreakpointManager manager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= manager.getBreakpoints(modelId);
for (int i = 0; i < breakpoints.length; i++) {
if (!(breakpoints[i] instanceof IJavaLineBreakpoint)) {
continue;
}
IJavaLineBreakpoint breakpoint = (IJavaLineBreakpoint) breakpoints[i];
if (breakpoint.getMarker().getType().equals(markerType)) {
String breakpointTypeName = breakpoint.getTypeName();
- if (breakpointTypeName.equals(typeName) || breakpointTypeName.startsWith(typeName + '$')) {
+ if (breakpointTypeName.equals(typeName) || typeName.startsWith(breakpointTypeName + '$')) {
if (breakpoint.getLineNumber() == lineNumber) {
return breakpoint;
}
}
}
}
return null;
}
/**
* Returns the preference store for this plug-in or <code>null</code>
* if the store is not available.
*
* @return the preference store for this plug-in
* @since 2.0
*/
public static Preferences getPreferences() {
JDIDebugPlugin deflt= JDIDebugPlugin.getDefault();
if (deflt != null) {
return deflt.getPluginPreferences();
}
return null;
}
/**
* Saves the preference store for this plug-in.
*
* @since 2.0
*/
public static void savePreferences() {
JDIDebugPlugin.getDefault().savePluginPreferences();
}
}
| true | true | public static IJavaLineBreakpoint lineBreakpointExists(String typeName, int lineNumber) throws CoreException {
String modelId= getPluginIdentifier();
String markerType= JavaLineBreakpoint.getMarkerType();
IBreakpointManager manager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= manager.getBreakpoints(modelId);
for (int i = 0; i < breakpoints.length; i++) {
if (!(breakpoints[i] instanceof IJavaLineBreakpoint)) {
continue;
}
IJavaLineBreakpoint breakpoint = (IJavaLineBreakpoint) breakpoints[i];
if (breakpoint.getMarker().getType().equals(markerType)) {
String breakpointTypeName = breakpoint.getTypeName();
if (breakpointTypeName.equals(typeName) || breakpointTypeName.startsWith(typeName + '$')) {
if (breakpoint.getLineNumber() == lineNumber) {
return breakpoint;
}
}
}
}
return null;
}
| public static IJavaLineBreakpoint lineBreakpointExists(String typeName, int lineNumber) throws CoreException {
String modelId= getPluginIdentifier();
String markerType= JavaLineBreakpoint.getMarkerType();
IBreakpointManager manager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= manager.getBreakpoints(modelId);
for (int i = 0; i < breakpoints.length; i++) {
if (!(breakpoints[i] instanceof IJavaLineBreakpoint)) {
continue;
}
IJavaLineBreakpoint breakpoint = (IJavaLineBreakpoint) breakpoints[i];
if (breakpoint.getMarker().getType().equals(markerType)) {
String breakpointTypeName = breakpoint.getTypeName();
if (breakpointTypeName.equals(typeName) || typeName.startsWith(breakpointTypeName + '$')) {
if (breakpoint.getLineNumber() == lineNumber) {
return breakpoint;
}
}
}
}
return null;
}
|
diff --git a/src/main/java/com/seitenbau/micgwaf/component/InputComponent.java b/src/main/java/com/seitenbau/micgwaf/component/InputComponent.java
index 4eeac74..3af39ca 100644
--- a/src/main/java/com/seitenbau/micgwaf/component/InputComponent.java
+++ b/src/main/java/com/seitenbau/micgwaf/component/InputComponent.java
@@ -1,47 +1,47 @@
package com.seitenbau.micgwaf.component;
import javax.servlet.http.HttpServletRequest;
public class InputComponent extends HtmlElementComponent
{
public boolean submitted;
public String value;
public InputComponent(Component parent)
{
super(parent);
}
public InputComponent(String elementName, String id, Component parent)
{
super(elementName, id, parent);
}
@Override
public Component processRequest(HttpServletRequest request)
{
System.out.println(request.getParameterMap());
String nameAttr = attributes.get("name");
- if (value != null)
+ if (nameAttr != null)
{
value = request.getParameter(nameAttr);
if (value != null)
{
submitted = true;
}
}
return super.processRequest(request);
}
public boolean isButton()
{
if ("button".equals(elementName)
|| ("input".equals(elementName)
&& "submit".equals(attributes.get("type"))))
{
return true;
}
return false;
}
}
| true | true | public Component processRequest(HttpServletRequest request)
{
System.out.println(request.getParameterMap());
String nameAttr = attributes.get("name");
if (value != null)
{
value = request.getParameter(nameAttr);
if (value != null)
{
submitted = true;
}
}
return super.processRequest(request);
}
| public Component processRequest(HttpServletRequest request)
{
System.out.println(request.getParameterMap());
String nameAttr = attributes.get("name");
if (nameAttr != null)
{
value = request.getParameter(nameAttr);
if (value != null)
{
submitted = true;
}
}
return super.processRequest(request);
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java b/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
index 5a74c3035..88eaaf937 100644
--- a/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
+++ b/modules/cpr/src/main/java/org/atmosphere/websocket/DefaultWebSocketProcessor.java
@@ -1,627 +1,627 @@
/*
* Copyright 2013 Jeanfrancois Arcand
*
* 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.atmosphere.websocket;
import org.atmosphere.cpr.Action;
import org.atmosphere.cpr.AsynchronousProcessor;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereFramework;
import org.atmosphere.cpr.AtmosphereMappingException;
import org.atmosphere.cpr.AtmosphereRequest;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEventImpl;
import org.atmosphere.cpr.AtmosphereResourceEventListener;
import org.atmosphere.cpr.AtmosphereResourceFactory;
import org.atmosphere.cpr.AtmosphereResourceImpl;
import org.atmosphere.cpr.AtmosphereResponse;
import org.atmosphere.cpr.HeaderConfig;
import org.atmosphere.util.DefaultEndpointMapper;
import org.atmosphere.util.EndpointMapper;
import org.atmosphere.util.ExecutorsFactory;
import org.atmosphere.util.VoidExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.atmosphere.cpr.ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE;
import static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;
import static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL_EXECUTION;
import static org.atmosphere.cpr.FrameworkConfig.ASYNCHRONOUS_HOOK;
import static org.atmosphere.cpr.FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CLOSE;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CONNECT;
import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.MESSAGE;
/**
* Like the {@link org.atmosphere.cpr.AsynchronousProcessor} class, this class is responsible for dispatching WebSocket request to the
* proper {@link org.atmosphere.websocket.WebSocket} implementation. This class can be extended in order to support any protocol
* running on top websocket.
*
* @author Jeanfrancois Arcand
*/
public class DefaultWebSocketProcessor implements WebSocketProcessor, Serializable {
private static final Logger logger = LoggerFactory.getLogger(DefaultWebSocketProcessor.class);
private final AtmosphereFramework framework;
private final WebSocketProtocol webSocketProtocol;
private final AtomicBoolean loggedMsg = new AtomicBoolean(false);
private final boolean destroyable;
private final boolean executeAsync;
private ExecutorService asyncExecutor;
private ScheduledExecutorService scheduler;
private final Map<String, WebSocketHandler> handlers = new HashMap<String, WebSocketHandler>();
private final EndpointMapper<WebSocketHandler> mapper = new DefaultEndpointMapper<WebSocketHandler>();
// 2MB - like maxPostSize
private int byteBufferMaxSize = 2097152;
private int charBufferMaxSize = 2097152;
private ByteBuffer bb = ByteBuffer.allocate(8192);
private CharBuffer cb = CharBuffer.allocate(8192);
private boolean shared = false;
public DefaultWebSocketProcessor(AtmosphereFramework framework) {
this.framework = framework;
this.webSocketProtocol = framework.getWebSocketProtocol();
String s = framework.getAtmosphereConfig().getInitParameter(RECYCLE_ATMOSPHERE_REQUEST_RESPONSE);
if (s != null && Boolean.valueOf(s)) {
destroyable = true;
} else {
destroyable = false;
}
s = framework.getAtmosphereConfig().getInitParameter(WEBSOCKET_PROTOCOL_EXECUTION);
if (s != null && Boolean.valueOf(s)) {
executeAsync = true;
} else {
executeAsync = false;
}
AtmosphereConfig config = framework.getAtmosphereConfig();
if (executeAsync) {
asyncExecutor = ExecutorsFactory.getAsyncOperationExecutor(config, "WebSocket");
} else {
asyncExecutor = VoidExecutorService.VOID;
}
scheduler = ExecutorsFactory.getScheduler(config);
}
@Override
public WebSocketProcessor registerWebSocketHandler(String path, WebSocketHandler webSockethandler) {
handlers.put(path, webSockethandler);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public final void open(final WebSocket webSocket, final AtmosphereRequest request, final AtmosphereResponse response) throws IOException {
if (!loggedMsg.getAndSet(true)) {
logger.debug("Atmosphere detected WebSocket: {}", webSocket.getClass().getName());
}
request.headers(configureHeader(request)).setAttribute(WebSocket.WEBSOCKET_SUSPEND, true);
AtmosphereResource r = AtmosphereResourceFactory.getDefault().create(framework.getAtmosphereConfig(),
response,
framework.getAsyncSupport());
request.setAttribute(INJECTED_ATMOSPHERE_RESOURCE, r);
request.setAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID, r.uuid());
webSocket.resource(r);
webSocketProtocol.onOpen(webSocket);
// No WebSocketHandler defined.
if (handlers.size() == 0) {
dispatch(webSocket, request, response);
} else {
WebSocketHandler handler = mapper.map(request, handlers);
if (handler == null) {
logger.debug("No WebSocketHandler maps request for {} with mapping {}", request.getRequestURI(), handlers);
throw new AtmosphereMappingException("No AtmosphereHandler maps request for " + request.getRequestURI());
}
handler.onOpen(webSocket);
// Force suspend.
webSocket.webSocketHandler(handler).resource().suspend(-1);
}
request.removeAttribute(INJECTED_ATMOSPHERE_RESOURCE);
if (webSocket.resource() != null) {
final AsynchronousProcessor.AsynchronousProcessorHook hook =
new AsynchronousProcessor.AsynchronousProcessorHook((AtmosphereResourceImpl) webSocket.resource());
request.setAttribute(ASYNCHRONOUS_HOOK, hook);
final Action action = ((AtmosphereResourceImpl) webSocket.resource()).action();
if (action.timeout() != -1 && !framework.getAsyncSupport().getContainerName().contains("Netty")) {
final AtomicReference<Future<?>> f = new AtomicReference();
f.set(scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (WebSocket.class.isAssignableFrom(webSocket.getClass())
&& System.currentTimeMillis() - WebSocket.class.cast(webSocket).lastWriteTimeStampInMilliseconds() > action.timeout()) {
hook.timedOut();
f.get().cancel(true);
}
}
}, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
}
} else {
logger.warn("AtmosphereResource was null");
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent("", CONNECT, webSocket));
}
private void dispatch(final WebSocket webSocket, List<AtmosphereRequest> list) {
if (list == null) return;
for (final AtmosphereRequest r : list) {
if (r != null) {
boolean b = r.dispatchRequestAsynchronously();
asyncExecutor.execute(new Runnable() {
@Override
public void run() {
AtmosphereResponse w = new AtmosphereResponse(webSocket, r, destroyable);
try {
dispatch(webSocket, r, w);
} finally {
r.destroy();
w.destroy();
}
}
});
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void invokeWebSocketProtocol(final WebSocket webSocket, String webSocketMessage) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
if (webSocketHandler == null) {
if (!WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = webSocketProtocol.onMessage(webSocket, webSocketMessage);
dispatch(webSocket, list);
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new StringReader(webSocketMessage));
return;
}
} else {
if (!WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
try {
webSocketHandler.onTextMessage(webSocket, webSocketMessage);
} catch (Exception ex) {
webSocketHandler.onError(webSocket, new WebSocketException(ex,
new AtmosphereResponse.Builder()
.request(webSocket.resource().getRequest())
.status(500)
.statusMessage("Server Error").build()));
}
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new StringReader(webSocketMessage));
return;
}
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent(webSocketMessage, MESSAGE, webSocket));
}
/**
* {@inheritDoc}
*/
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, byte[] data, int offset, int length) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
if (webSocketHandler == null) {
if (!WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = webSocketProtocol.onMessage(webSocket, data, offset, length);
dispatch(webSocket, list);
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new ByteArrayInputStream(data, offset, length));
return;
}
} else {
if (!WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
try {
webSocketHandler.onByteMessage(webSocket, data, offset, length);
} catch (Exception ex) {
webSocketHandler.onError(webSocket, new WebSocketException(ex,
new AtmosphereResponse.Builder()
.request(webSocket.resource().getRequest())
.status(500)
.statusMessage("Server Error").build()));
}
} else {
logger.debug("The WebServer doesn't support streaming. Wrapping the message as stream.");
invokeWebSocketProtocol(webSocket, new ByteArrayInputStream(data, offset, length));
return;
}
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<byte[]>(data, MESSAGE, webSocket));
}
/**
* {@inheritDoc}
*/
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, InputStream stream) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
try {
if (webSocketHandler == null) {
if (!WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = WebSocketProtocolStream.class.cast(webSocketProtocol).onBinaryStream(webSocket, stream);
dispatch(webSocket, list);
} else {
dispatchStream(webSocket, stream);
return;
}
} else {
if (WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
WebSocketStreamingHandler.class.cast(webSocketHandler).onBinaryStream(webSocket, stream);
} else {
dispatchStream(webSocket, stream);
return;
}
}
} catch (Exception ex) {
webSocketHandler.onError(webSocket, new WebSocketException(ex,
new AtmosphereResponse.Builder()
.request(webSocket.resource().getRequest())
.status(500)
.statusMessage("Server Error").build()));
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<InputStream>(stream, MESSAGE, webSocket));
}
/**
* {@inheritDoc}
*/
@Override
public void invokeWebSocketProtocol(WebSocket webSocket, Reader reader) {
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
try {
if (webSocketHandler == null) {
if (WebSocketProtocolStream.class.isAssignableFrom(webSocketProtocol.getClass())) {
List<AtmosphereRequest> list = WebSocketProtocolStream.class.cast(webSocketProtocol).onTextStream(webSocket, reader);
dispatch(webSocket, list);
} else {
dispatchReader(webSocket, reader);
return;
}
} else {
if (WebSocketStreamingHandler.class.isAssignableFrom(webSocketHandler.getClass())) {
WebSocketStreamingHandler.class.cast(webSocketHandler).onTextStream(webSocket, reader);
} else {
dispatchReader(webSocket, reader);
return;
}
}
} catch (Exception ex) {
webSocketHandler.onError(webSocket, new WebSocketException(ex,
new AtmosphereResponse.Builder()
.request(webSocket.resource().getRequest())
.status(500)
.statusMessage("Server Error").build()));
}
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent<Reader>(reader, MESSAGE, webSocket));
}
/**
* Dispatch to request/response to the {@link org.atmosphere.cpr.AsyncSupport} implementation as it was a normal HTTP request.
*
* @param request a {@link AtmosphereRequest}
* @param r a {@link AtmosphereResponse}
*/
public final void dispatch(WebSocket webSocket, final AtmosphereRequest request, final AtmosphereResponse r) {
if (request == null) return;
try {
framework.doCometSupport(request, r);
} catch (Throwable e) {
logger.warn("Failed invoking AtmosphereFramework.doCometSupport()", e);
webSocketProtocol.onError(webSocket, new WebSocketException(e,
new AtmosphereResponse.Builder()
.request(request)
.status(500)
.statusMessage("Server Error").build()));
return;
}
if (r.getStatus() >= 400) {
webSocketProtocol.onError(webSocket, new WebSocketException("Status code higher or equal than 400", r));
}
}
/**
* {@inheritDoc}
*/
@Override
public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent("", CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.warn("Unable to retrieve AtmosphereResource for {}", webSocket);
} else {
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
AsynchronousProcessor.AsynchronousProcessorHook h = (AsynchronousProcessor.AsynchronousProcessorHook)
r.getAttribute(ASYNCHRONOUS_HOOK);
if (!resource.isCancelled()) {
if (h != null) {
// Tomcat and Jetty differ, same with browser
if (closeCode == 1002) {
h.timedOut();
} else {
h.closed();
}
} else if (webSocketHandler == null) {
logger.warn("AsynchronousProcessor.AsynchronousProcessorHook was null");
}
}
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
// We must always destroy the root resource (the one created when the websocket was opened
// to prevent memory leaks.
resource.setIsInScope(false);
try {
resource.cancel();
} catch (IOException e) {
logger.trace("", e);
}
- AtmosphereResourceImpl.class.cast(r)._destroy();
+ AtmosphereResourceImpl.class.cast(resource)._destroy();
}
} finally {
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
if (webSocket != null) {
webSocket.resource(null);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() {
boolean shared = framework.isShareExecutorServices();
if (asyncExecutor != null && !shared) {
asyncExecutor.shutdown();
}
if (scheduler != null && !shared) {
scheduler.shutdown();
}
}
/**
* {@inheritDoc}
*/
@Override
public void notifyListener(WebSocket webSocket, WebSocketEventListener.WebSocketEvent event) {
AtmosphereResource resource = webSocket.resource();
if (resource == null) return;
AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(resource);
for (AtmosphereResourceEventListener l : r.atmosphereResourceEventListener()) {
if (WebSocketEventListener.class.isAssignableFrom(l.getClass())) {
try {
switch (event.type()) {
case CONNECT:
WebSocketEventListener.class.cast(l).onConnect(event);
break;
case DISCONNECT:
WebSocketEventListener.class.cast(l).onDisconnect(event);
break;
case CONTROL:
WebSocketEventListener.class.cast(l).onControl(event);
break;
case MESSAGE:
WebSocketEventListener.class.cast(l).onMessage(event);
break;
case HANDSHAKE:
WebSocketEventListener.class.cast(l).onHandshake(event);
break;
case CLOSE:
WebSocketEventListener.class.cast(l).onDisconnect(event);
WebSocketEventListener.class.cast(l).onClose(event);
break;
}
} catch (Throwable t) {
logger.debug("Listener error {}", t);
try {
WebSocketEventListener.class.cast(l).onThrowable(new AtmosphereResourceEventImpl(r, false, false, t));
} catch (Throwable t2) {
logger.warn("Listener error {}", t2);
}
}
}
}
}
public static final Map<String, String> configureHeader(AtmosphereRequest request) {
Map<String, String> headers = new HashMap<String, String>();
Enumeration<String> e = request.getParameterNames();
String s;
while (e.hasMoreElements()) {
s = e.nextElement();
headers.put(s, request.getParameter(s));
}
headers.put(HeaderConfig.X_ATMOSPHERE_TRANSPORT, HeaderConfig.WEBSOCKET_TRANSPORT);
return headers;
}
protected void dispatchStream(WebSocket webSocket, InputStream is) throws IOException {
int read = 0;
while (read > -1) {
bb.position(bb.position() + read);
if (bb.remaining() == 0) {
resizeByteBuffer();
}
read = is.read(bb.array(), bb.position(), bb.remaining());
}
bb.flip();
try {
invokeWebSocketProtocol(webSocket, bb.array(), 0, bb.limit());
} finally {
bb.clear();
}
}
protected void dispatchReader(WebSocket webSocket,Reader r) throws IOException {
int read = 0;
while (read > -1) {
cb.position(cb.position() + read);
if (cb.remaining() == 0) {
resizeCharBuffer();
}
read = r.read(cb.array(), cb.position(), cb.remaining());
}
cb.flip();
try {
invokeWebSocketProtocol(webSocket, cb.toString());
} finally {
cb.clear();
}
}
private void resizeByteBuffer() throws IOException {
int maxSize = getByteBufferMaxSize();
if (bb.limit() >= maxSize) {
throw new IOException("Message Buffer too small");
}
long newSize = bb.limit() * 2;
if (newSize > maxSize) {
newSize = maxSize;
}
// Cast is safe. newSize < maxSize and maxSize is an int
ByteBuffer newBuffer = ByteBuffer.allocate((int) newSize);
bb.rewind();
newBuffer.put(bb);
bb = newBuffer;
}
private void resizeCharBuffer() throws IOException {
int maxSize = getCharBufferMaxSize();
if (cb.limit() >= maxSize) {
throw new IOException("Message Buffer too small");
}
long newSize = cb.limit() * 2;
if (newSize > maxSize) {
newSize = maxSize;
}
// Cast is safe. newSize < maxSize and maxSize is an int
CharBuffer newBuffer = CharBuffer.allocate((int) newSize);
cb.rewind();
newBuffer.put(cb);
cb = newBuffer;
}
/**
* Obtain the current maximum size (in bytes) of the buffer used for binary
* messages.
*/
public final int getByteBufferMaxSize() {
return byteBufferMaxSize;
}
/**
* Set the maximum size (in bytes) of the buffer used for binary messages.
*/
public final void setByteBufferMaxSize(int byteBufferMaxSize) {
this.byteBufferMaxSize = byteBufferMaxSize;
}
/**
* Obtain the current maximum size (in characters) of the buffer used for
* binary messages.
*/
public final int getCharBufferMaxSize() {
return charBufferMaxSize;
}
/**
* Set the maximum size (in characters) of the buffer used for textual
* messages.
*/
public final void setCharBufferMaxSize(int charBufferMaxSize) {
this.charBufferMaxSize = charBufferMaxSize;
}
}
| true | true | public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent("", CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.warn("Unable to retrieve AtmosphereResource for {}", webSocket);
} else {
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
AsynchronousProcessor.AsynchronousProcessorHook h = (AsynchronousProcessor.AsynchronousProcessorHook)
r.getAttribute(ASYNCHRONOUS_HOOK);
if (!resource.isCancelled()) {
if (h != null) {
// Tomcat and Jetty differ, same with browser
if (closeCode == 1002) {
h.timedOut();
} else {
h.closed();
}
} else if (webSocketHandler == null) {
logger.warn("AsynchronousProcessor.AsynchronousProcessorHook was null");
}
}
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
// We must always destroy the root resource (the one created when the websocket was opened
// to prevent memory leaks.
resource.setIsInScope(false);
try {
resource.cancel();
} catch (IOException e) {
logger.trace("", e);
}
AtmosphereResourceImpl.class.cast(r)._destroy();
}
} finally {
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
if (webSocket != null) {
webSocket.resource(null);
}
}
}
}
| public void close(WebSocket webSocket, int closeCode) {
logger.trace("WebSocket closed with {}", closeCode);
WebSocketHandler webSocketHandler = webSocket.webSocketHandler();
// A message might be in the process of being processed and the websocket gets closed. In that corner
// case the webSocket.resource will be set to false and that might cause NPE in some WebSocketProcol implementation
// We could potentially synchronize on webSocket but since it is a rare case, it is better to not synchronize.
// synchronized (webSocket) {
notifyListener(webSocket, new WebSocketEventListener.WebSocketEvent("", CLOSE, webSocket));
AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
if (resource == null) {
logger.warn("Unable to retrieve AtmosphereResource for {}", webSocket);
} else {
AtmosphereRequest r = resource.getRequest(false);
AtmosphereResponse s = resource.getResponse(false);
try {
webSocketProtocol.onClose(webSocket);
if (resource != null && resource.isInScope()) {
AsynchronousProcessor.AsynchronousProcessorHook h = (AsynchronousProcessor.AsynchronousProcessorHook)
r.getAttribute(ASYNCHRONOUS_HOOK);
if (!resource.isCancelled()) {
if (h != null) {
// Tomcat and Jetty differ, same with browser
if (closeCode == 1002) {
h.timedOut();
} else {
h.closed();
}
} else if (webSocketHandler == null) {
logger.warn("AsynchronousProcessor.AsynchronousProcessorHook was null");
}
}
if (webSocketHandler != null) {
webSocketHandler.onClose(webSocket);
}
// We must always destroy the root resource (the one created when the websocket was opened
// to prevent memory leaks.
resource.setIsInScope(false);
try {
resource.cancel();
} catch (IOException e) {
logger.trace("", e);
}
AtmosphereResourceImpl.class.cast(resource)._destroy();
}
} finally {
if (r != null) {
r.destroy(true);
}
if (s != null) {
s.destroy(true);
}
if (webSocket != null) {
webSocket.resource(null);
}
}
}
}
|
diff --git a/src/main/java/com/github/fge/msgsimple/provider/LoadingMessageSourceProvider.java b/src/main/java/com/github/fge/msgsimple/provider/LoadingMessageSourceProvider.java
index d8384d6..81efc45 100644
--- a/src/main/java/com/github/fge/msgsimple/provider/LoadingMessageSourceProvider.java
+++ b/src/main/java/com/github/fge/msgsimple/provider/LoadingMessageSourceProvider.java
@@ -1,406 +1,406 @@
/*
* Copyright (c) 2013, Francis Galiegue <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.fge.msgsimple.provider;
import com.github.fge.msgsimple.InternalBundle;
import com.github.fge.msgsimple.source.MessageSource;
import javax.annotation.concurrent.ThreadSafe;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A caching, on-demand loading message source provider with configurable expiry
*
* <p>This class uses a {@link MessageSourceLoader} internally to look up
* message sources. As is the case for {@link StaticMessageSourceProvider}, you
* can also set a default source if the loader fails to grab a source.</p>
*
* <p>Apart from the loader, you can customize two aspects of the provider:</p>
*
* <ul>
* <li>its load timeout (5 seconds by default);</li>
* <li>its expiry time (10 minutes by default).</li>
* </ul>
*
* <p>Note that the expiry time is periodic only, and not per source. The
* loading result (success or failure) is recorded permanently until the expiry
* time kicks in, <b>except</b> when the timeout kicks in; in this case, loading
* will be retried.</p>
*
* <p>You can also configure a loader so that it never expires.</p>
*
* <p>You cannot instantiate that class directly; use {@link #newBuilder()} to
* obtain a builder class and set up your provider.</p>
*
* @see Builder
*/
@ThreadSafe
public final class LoadingMessageSourceProvider
implements MessageSourceProvider
{
/*
* Use daemon threads. We don't give control to the user about the
* ExecutorService, and we don't have a reliable way to shut it down (a JVM
* shutdown hook does not get involved on a webapp shutdown, so we cannot
* use that...).
*/
private static final ThreadFactory THREAD_FACTORY = new ThreadFactory()
{
private final ThreadFactory factory = Executors.defaultThreadFactory();
@Override
public Thread newThread(final Runnable r)
{
final Thread ret = factory.newThread(r);
ret.setDaemon(true);
return ret;
}
};
private static final InternalBundle BUNDLE
= InternalBundle.getInstance();
private static final int NTHREADS = 3;
/*
* Executor service for loading tasks
*/
private final ExecutorService service
= Executors.newFixedThreadPool(NTHREADS, THREAD_FACTORY);
/*
* Loader and default source
*/
private final MessageSourceLoader loader;
private final MessageSource defaultSource;
/*
* Timeout
*/
private final long timeoutDuration;
private final TimeUnit timeoutUnit;
/*
* Expiry
*
* Note that expiry is set up, if necessary, in the first call to
* .getMessage().
*/
private final AtomicBoolean expiryEnabled;
private final long expiryDuration;
private final TimeUnit expiryUnit;
/*
* List of sources
*/
private final Map<Locale, FutureTask<MessageSource>> sources
= new HashMap<Locale, FutureTask<MessageSource>>();
private LoadingMessageSourceProvider(final Builder builder)
{
loader = builder.loader;
defaultSource = builder.defaultSource;
timeoutDuration = builder.timeoutDuration;
timeoutUnit = builder.timeoutUnit;
expiryDuration = builder.expiryDuration;
expiryUnit = builder.expiryUnit;
/*
* Mimic an already enabled expiry if, in fact, there is none
*/
expiryEnabled = new AtomicBoolean(expiryDuration == 0L);
}
/**
* Create a new builder
*
* @return an empty builder
*/
public static Builder newBuilder()
{
return new Builder();
}
@Override
public MessageSource getMessageSource(final Locale locale)
{
/*
* Set up expiry, if necessary
*/
if (!expiryEnabled.getAndSet(true))
setupExpiry(expiryDuration, expiryUnit);
FutureTask<MessageSource> task;
/*
* The algorithm is as follows:
*
* - access the sources map in a synchronous manner (the expiry task
* also does this);
* - grab the FutureTask matching the required locale:
* - if no task exists, create it;
* - if it exists but has been cancelled (in the event of a timeout,
* see below), create a new task;
* - always within the synchronized access to sources, submit the task
* for immediate execution to our ExecutorService;
* - to be followed...
*/
synchronized (sources) {
task = sources.get(locale);
if (task == null || task.isCancelled()) {
task = loadingTask(locale);
sources.put(locale, task);
service.execute(task);
}
}
/*
* - try and get the result of the task, with a timeout;
* - if we get a result in time, return it, or the default source (if
* any) if the result is null;
* - in the event of an error, return the default source; in addition,
* if this is a timeout, cancel the task.
*/
try {
final MessageSource source = task.get(timeoutDuration, timeoutUnit);
return source == null ? defaultSource : source;
} catch (InterruptedException ignored) {
/*
- * Restore interrup state. We will not throw the exception here,
+ * Restore interrupt state. We will not throw the exception here,
* since static providers exist, which do not throw it -- and how
* would a message provider API sound to you if you had to catch
* InterruptedException each time you try and fetch a message?
*
* Let the caller deal with that.
*/
Thread.currentThread().interrupt();
return defaultSource;
} catch (ExecutionException ignored) {
return defaultSource;
} catch (TimeoutException ignored) {
task.cancel(true);
return defaultSource;
}
}
private FutureTask<MessageSource> loadingTask(final Locale locale)
{
return new FutureTask<MessageSource>(new Callable<MessageSource>()
{
@Override
public MessageSource call()
throws IOException
{
return loader.load(locale);
}
});
}
private void setupExpiry(final long duration, final TimeUnit unit)
{
final Runnable runnable = new Runnable()
{
@Override
public void run()
{
/*
* We remove all tasks for which Future's .isDone() returns
* true. This method returns true either if the task has
* completed one way or another, or has been cancelled.
*/
final Set<Locale> set = new HashSet<Locale>();
synchronized (sources) {
set.addAll(sources.keySet());
for (final Locale locale: set)
if (sources.get(locale).isDone())
sources.remove(locale);
}
}
};
// Overkill?
final ScheduledExecutorService scheduled
= Executors.newScheduledThreadPool(1, THREAD_FACTORY);
final long initialDelay = unit.toMillis(duration);
scheduled.scheduleAtFixedRate(runnable, initialDelay, duration, unit);
}
/**
* Builder class for a {@link LoadingMessageSourceProvider}
*/
public static final class Builder
{
/*
* NOTE: apart from requiring them to be positive, we do no checks at
* all on what the user submits as timeout/expiry values; it could
* want a 1 ns expiry that we woudln't prevent it.
*/
private MessageSourceLoader loader;
private MessageSource defaultSource;
private long timeoutDuration = 5L;
private TimeUnit timeoutUnit = TimeUnit.SECONDS;
private long expiryDuration = 10L;
private TimeUnit expiryUnit = TimeUnit.MINUTES;
private Builder()
{
}
/**
* Set the message source loader
*
* @param loader the loader
* @throws NullPointerException loader is null
* @return this
*/
public Builder setLoader(final MessageSourceLoader loader)
{
BUNDLE.checkNotNull(loader, "cfg.nullLoader");
this.loader = loader;
return this;
}
/**
* Set the default message source if the loader fails to load
*
* @param defaultSource the default source
* @throws NullPointerException source is null
* @return this
*/
public Builder setDefaultSource(final MessageSource defaultSource)
{
BUNDLE.checkNotNull(defaultSource, "cfg.nullDefaultSource");
this.defaultSource = defaultSource;
return this;
}
/**
* Set the load timeout
*
* @param duration number of units
* @param unit the time unit
* @throws IllegalArgumentException {@code duration} is negative or zero
* @throws NullPointerException {@code unit} is null
* @return this
*
* @deprecated use {@link #setLoadTimeout(long, TimeUnit)} instead.
* Will be removed in 0.6.
*/
@Deprecated
public Builder setTimeout(final long duration, final TimeUnit unit)
{
BUNDLE.checkArgument(duration > 0L, "cfg.nonPositiveDuration");
BUNDLE.checkNotNull(unit, "cfg.nullTimeUnit");
timeoutDuration = duration;
timeoutUnit = unit;
return this;
}
/**
* Set the load timeout (5 seconds by default)
*
* <p>If the loader passed as an argument fails to load a message
* source after the specified timeout is elapsed, then the default
* messagesource will be returned (if any).</p>
*
* @param duration number of units
* @param unit the time unit
* @throws IllegalArgumentException {@code duration} is negative or zero
* @throws NullPointerException {@code unit} is null
* @return this
*
* @see #setLoader(MessageSourceLoader)
* @see #setDefaultSource(MessageSource)
*/
public Builder setLoadTimeout(final long duration, final TimeUnit unit)
{
BUNDLE.checkArgument(duration > 0L, "cfg.nonPositiveDuration");
BUNDLE.checkNotNull(unit, "cfg.nullTimeUnit");
timeoutDuration = duration;
timeoutUnit = unit;
return this;
}
/**
* Set the source expiry time (10 minutes by default)
*
* <p>Do <b>not</b> use this method if you want no expiry at all; use
* {@link #neverExpires()} instead.</p>
*
* @since 0.5
*
* @param duration number of units
* @param unit the time unit
* @throws IllegalArgumentException {@code duration} is negative or zero
* @throws NullPointerException {@code unit} is null
* @return this
*/
public Builder setExpiryTime(final long duration, final TimeUnit unit)
{
BUNDLE.checkArgument(duration > 0L, "cfg.nonPositiveDuration");
BUNDLE.checkNotNull(unit, "cfg.nullTimeUnit");
expiryDuration = duration;
expiryUnit = unit;
return this;
}
/**
* Set this loading provider so that entries never expire
*
* <p>Note that, as noted in the description, apart from loading
* timeouts, successes and failures are recorded permanently (see
* {@link FutureTask}).</p>
*
* @since 0.5
*
* @return this
*/
public Builder neverExpires()
{
expiryDuration = 0L;
return this;
}
/**
* Build the provider
*
* @return a {@link LoadingMessageSourceProvider}
* @throws IllegalArgumentException no loader has been provided
*/
public MessageSourceProvider build()
{
BUNDLE.checkArgument(loader != null, "cfg.noLoader");
return new LoadingMessageSourceProvider(this);
}
}
}
| true | true | public MessageSource getMessageSource(final Locale locale)
{
/*
* Set up expiry, if necessary
*/
if (!expiryEnabled.getAndSet(true))
setupExpiry(expiryDuration, expiryUnit);
FutureTask<MessageSource> task;
/*
* The algorithm is as follows:
*
* - access the sources map in a synchronous manner (the expiry task
* also does this);
* - grab the FutureTask matching the required locale:
* - if no task exists, create it;
* - if it exists but has been cancelled (in the event of a timeout,
* see below), create a new task;
* - always within the synchronized access to sources, submit the task
* for immediate execution to our ExecutorService;
* - to be followed...
*/
synchronized (sources) {
task = sources.get(locale);
if (task == null || task.isCancelled()) {
task = loadingTask(locale);
sources.put(locale, task);
service.execute(task);
}
}
/*
* - try and get the result of the task, with a timeout;
* - if we get a result in time, return it, or the default source (if
* any) if the result is null;
* - in the event of an error, return the default source; in addition,
* if this is a timeout, cancel the task.
*/
try {
final MessageSource source = task.get(timeoutDuration, timeoutUnit);
return source == null ? defaultSource : source;
} catch (InterruptedException ignored) {
/*
* Restore interrup state. We will not throw the exception here,
* since static providers exist, which do not throw it -- and how
* would a message provider API sound to you if you had to catch
* InterruptedException each time you try and fetch a message?
*
* Let the caller deal with that.
*/
Thread.currentThread().interrupt();
return defaultSource;
} catch (ExecutionException ignored) {
return defaultSource;
} catch (TimeoutException ignored) {
task.cancel(true);
return defaultSource;
}
}
| public MessageSource getMessageSource(final Locale locale)
{
/*
* Set up expiry, if necessary
*/
if (!expiryEnabled.getAndSet(true))
setupExpiry(expiryDuration, expiryUnit);
FutureTask<MessageSource> task;
/*
* The algorithm is as follows:
*
* - access the sources map in a synchronous manner (the expiry task
* also does this);
* - grab the FutureTask matching the required locale:
* - if no task exists, create it;
* - if it exists but has been cancelled (in the event of a timeout,
* see below), create a new task;
* - always within the synchronized access to sources, submit the task
* for immediate execution to our ExecutorService;
* - to be followed...
*/
synchronized (sources) {
task = sources.get(locale);
if (task == null || task.isCancelled()) {
task = loadingTask(locale);
sources.put(locale, task);
service.execute(task);
}
}
/*
* - try and get the result of the task, with a timeout;
* - if we get a result in time, return it, or the default source (if
* any) if the result is null;
* - in the event of an error, return the default source; in addition,
* if this is a timeout, cancel the task.
*/
try {
final MessageSource source = task.get(timeoutDuration, timeoutUnit);
return source == null ? defaultSource : source;
} catch (InterruptedException ignored) {
/*
* Restore interrupt state. We will not throw the exception here,
* since static providers exist, which do not throw it -- and how
* would a message provider API sound to you if you had to catch
* InterruptedException each time you try and fetch a message?
*
* Let the caller deal with that.
*/
Thread.currentThread().interrupt();
return defaultSource;
} catch (ExecutionException ignored) {
return defaultSource;
} catch (TimeoutException ignored) {
task.cancel(true);
return defaultSource;
}
}
|
diff --git a/r/src/main/java/edu/dfci/cccb/mev/r/mock/cli/CliRScriptEngine.java b/r/src/main/java/edu/dfci/cccb/mev/r/mock/cli/CliRScriptEngine.java
index dc35de8c..c8284620 100644
--- a/r/src/main/java/edu/dfci/cccb/mev/r/mock/cli/CliRScriptEngine.java
+++ b/r/src/main/java/edu/dfci/cccb/mev/r/mock/cli/CliRScriptEngine.java
@@ -1,124 +1,125 @@
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.dfci.cccb.mev.r.mock.cli;
import static java.io.File.createTempFile;
import static java.lang.Runtime.getRuntime;
import static java.lang.System.getProperty;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
/**
* @author levk
*
*/
@Log4j
public class CliRScriptEngine extends AbstractScriptEngine {
private @Getter @Setter String rScriptExecutable = getProperty (CliRScriptEngine.class.getName ()
+ ".rScriptExecutable", "RScript");
private @Getter @Setter String rScriptLaunchingOptions = getProperty (CliRScriptEngine.class.getName ()
+ ".rScriptLaunchingOptions", "");
/* (non-Javadoc)
* @see javax.script.ScriptEngine#eval(java.lang.String,
* javax.script.ScriptContext) */
@Override
public Object eval (String script, ScriptContext context) throws ScriptException {
return eval (new StringReader (script), context);
}
/* (non-Javadoc)
* @see javax.script.ScriptEngine#eval(java.io.Reader,
* javax.script.ScriptContext) */
@Override
public Object eval (Reader reader, ScriptContext context) throws ScriptException {
try {
File script = createTempFile ("mev-r-", ".R");
try {
script.createNewFile ();
try (Writer writer = new BufferedWriter (new FileWriter (script))) {
for (int c; (c = reader.read ()) >= 0; writer.write (c));
writer.flush ();
log.debug ("Launching R script " + script);
- Process r = getRuntime ().exec ("Rscript " + rScriptLaunchingOptions + script.getAbsolutePath ());
+ Process r = getRuntime ().exec (rScriptExecutable + " "
+ + rScriptLaunchingOptions + script.getAbsolutePath ());
int result = r.waitFor ();
if (log.isDebugEnabled ())
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream ();
Writer debug = new BufferedWriter (new OutputStreamWriter (buffer));
Reader output = new BufferedReader (new InputStreamReader (r.getInputStream ()));
Reader error = new BufferedReader (new InputStreamReader (r.getErrorStream ()));
Reader code = new BufferedReader (new InputStreamReader (new FileInputStream (script)))) {
debug.write ("R process " + script + " exited with code " + result);
if (result != 0) {
debug.write ("\nOriginal script:\n");
for (int c; (c = code.read ()) >= 0; debug.write (c));
debug.write ("\nStandard output:\n");
for (int c; (c = output.read ()) >= 0; debug.write (c));
debug.write ("\nStandard error:\n");
for (int c; (c = error.read ()) >= 0; debug.write (c));
}
debug.flush ();
log.debug (buffer.toString ());
} catch (Exception e) {
log.warn ("Unable to dump debug output for R process " + script, e);
}
if (result == 0)
return result;
else
throw new RuntimeException ("Exited with abnormal return code " + result);
}
} finally {
script.delete ();
}
} catch (Exception e) {
throw new ScriptException (e);
}
}
/* (non-Javadoc)
* @see javax.script.ScriptEngine#createBindings() */
@Override
public Bindings createBindings () {
throw new UnsupportedOperationException ("nyi");
}
/* (non-Javadoc)
* @see javax.script.ScriptEngine#getFactory() */
@Override
public ScriptEngineFactory getFactory () {
return CliRScriptEngineFactory.getInstance ();
}
}
| true | true | public Object eval (Reader reader, ScriptContext context) throws ScriptException {
try {
File script = createTempFile ("mev-r-", ".R");
try {
script.createNewFile ();
try (Writer writer = new BufferedWriter (new FileWriter (script))) {
for (int c; (c = reader.read ()) >= 0; writer.write (c));
writer.flush ();
log.debug ("Launching R script " + script);
Process r = getRuntime ().exec ("Rscript " + rScriptLaunchingOptions + script.getAbsolutePath ());
int result = r.waitFor ();
if (log.isDebugEnabled ())
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream ();
Writer debug = new BufferedWriter (new OutputStreamWriter (buffer));
Reader output = new BufferedReader (new InputStreamReader (r.getInputStream ()));
Reader error = new BufferedReader (new InputStreamReader (r.getErrorStream ()));
Reader code = new BufferedReader (new InputStreamReader (new FileInputStream (script)))) {
debug.write ("R process " + script + " exited with code " + result);
if (result != 0) {
debug.write ("\nOriginal script:\n");
for (int c; (c = code.read ()) >= 0; debug.write (c));
debug.write ("\nStandard output:\n");
for (int c; (c = output.read ()) >= 0; debug.write (c));
debug.write ("\nStandard error:\n");
for (int c; (c = error.read ()) >= 0; debug.write (c));
}
debug.flush ();
log.debug (buffer.toString ());
} catch (Exception e) {
log.warn ("Unable to dump debug output for R process " + script, e);
}
if (result == 0)
return result;
else
throw new RuntimeException ("Exited with abnormal return code " + result);
}
} finally {
script.delete ();
}
} catch (Exception e) {
throw new ScriptException (e);
}
}
| public Object eval (Reader reader, ScriptContext context) throws ScriptException {
try {
File script = createTempFile ("mev-r-", ".R");
try {
script.createNewFile ();
try (Writer writer = new BufferedWriter (new FileWriter (script))) {
for (int c; (c = reader.read ()) >= 0; writer.write (c));
writer.flush ();
log.debug ("Launching R script " + script);
Process r = getRuntime ().exec (rScriptExecutable + " "
+ rScriptLaunchingOptions + script.getAbsolutePath ());
int result = r.waitFor ();
if (log.isDebugEnabled ())
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream ();
Writer debug = new BufferedWriter (new OutputStreamWriter (buffer));
Reader output = new BufferedReader (new InputStreamReader (r.getInputStream ()));
Reader error = new BufferedReader (new InputStreamReader (r.getErrorStream ()));
Reader code = new BufferedReader (new InputStreamReader (new FileInputStream (script)))) {
debug.write ("R process " + script + " exited with code " + result);
if (result != 0) {
debug.write ("\nOriginal script:\n");
for (int c; (c = code.read ()) >= 0; debug.write (c));
debug.write ("\nStandard output:\n");
for (int c; (c = output.read ()) >= 0; debug.write (c));
debug.write ("\nStandard error:\n");
for (int c; (c = error.read ()) >= 0; debug.write (c));
}
debug.flush ();
log.debug (buffer.toString ());
} catch (Exception e) {
log.warn ("Unable to dump debug output for R process " + script, e);
}
if (result == 0)
return result;
else
throw new RuntimeException ("Exited with abnormal return code " + result);
}
} finally {
script.delete ();
}
} catch (Exception e) {
throw new ScriptException (e);
}
}
|
diff --git a/srcj/com/sun/electric/technology/TechFactory.java b/srcj/com/sun/electric/technology/TechFactory.java
index f5e2f8a79..0d68c41ea 100644
--- a/srcj/com/sun/electric/technology/TechFactory.java
+++ b/srcj/com/sun/electric/technology/TechFactory.java
@@ -1,349 +1,349 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: TechFactory.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.technology;
import com.sun.electric.Main;
import com.sun.electric.database.id.IdManager;
import com.sun.electric.database.id.IdReader;
import com.sun.electric.database.id.IdWriter;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.user.ActivityLogger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
*
*/
public abstract class TechFactory {
final String techName;
private final List<Param> techParams;
public static class Param {
public final String xmlPath;
public final String prefPath;
public final Object factoryValue;
public Param(String xmlPath, String prefPath, Object factoryValue) {
this.xmlPath = xmlPath;
this.prefPath = prefPath;
this.factoryValue = factoryValue;
}
@Override
public boolean equals(Object o) {
return o instanceof Param && xmlPath.equals(((Param)o).xmlPath);
}
@Override
public int hashCode() {
return xmlPath.hashCode();
}
@Override
public String toString() { return xmlPath; }
}
public static TechFactory fromXml(URL url, Xml.Technology xmlTech) {
String techName = null;
if (xmlTech != null)
techName = xmlTech.techName;
if (techName == null)
techName = TextUtils.getFileNameWithoutExtension(url);
return new FromXml(techName, true, url, xmlTech);
}
public Technology newInstance(Generic generic) {
return newInstance(generic, Collections.<Param,Object>emptyMap());
}
public Technology newInstance(Generic generic, Map<Param,Object> paramValues) {
try {
Map<Param,Object> fixedParamValues = new HashMap<Param,Object>();
for (Param param: techParams) {
Object value = paramValues.get(param);
if (value == null || value.getClass() != param.factoryValue.getClass())
value = param.factoryValue;
fixedParamValues.put(param, value);
}
Technology tech = newInstanceImpl(generic, fixedParamValues);
// make sure the name is unique
- Technology already = Technology.findTechnology(tech.getTechName());
- if (already != null)
- {
- System.out.println("ERROR: Multiple technologies named '" + tech.getTechName() + "'");
- return null;
- }
+// Technology already = Technology.findTechnology(tech.getTechName());
+// if (already != null)
+// {
+// System.out.println("ERROR: Multiple technologies named '" + tech.getTechName() + "'");
+// return null;
+// }
tech.setup();
return tech;
} catch (ClassNotFoundException e) {
if (Job.getDebug())
System.out.println("GNU Release can't find extra technologies");
} catch (Exception e) {
System.out.println("Exceptions while importing extra technology " + getDescription());
// if (Job.getDebug())
ActivityLogger.logException(e);
}
return null;
}
public List<Param> getTechParams() {
return techParams;
}
abstract String getDescription();
void write(IdWriter writer) throws IOException {
writer.writeString(techName);
writer.writeBoolean(false);
}
@Override
public String toString() { return techName; }
public static TechFactory getGenericFactory() {
return new FromClass("generic", "com.sun.electric.technology.technologies.Generic");
}
public static Map<String,TechFactory> getKnownTechs() {
LinkedHashMap<String,TechFactory> m = new LinkedHashMap<String,TechFactory>();
c(m, "artwork", "com.sun.electric.technology.technologies.Artwork");
c(m, "fpga", "com.sun.electric.technology.technologies.FPGA");
c(m, "schematic", "com.sun.electric.technology.technologies.Schematics");
r(m, "bicmos", "technology/technologies/bicmos.xml");
r(m, "bipolar", "technology/technologies/bipolar.xml");
r(m, "cmos", "technology/technologies/cmos.xml");
c(m, "efido", "com.sun.electric.technology.technologies.EFIDO");
c(m, "gem", "com.sun.electric.technology.technologies.GEM");
c(m, "pcb", "com.sun.electric.technology.technologies.PCB");
c(m, "rcmos", "com.sun.electric.technology.technologies.RCMOS");
p(m, "mocmos","com.sun.electric.technology.technologies.MoCMOS");
r(m, "mocmosold", "technology/technologies/mocmosold.xml");
r(m, "mocmossub", "technology/technologies/mocmossub.xml");
r(m, "nmos", "technology/technologies/nmos.xml");
r(m, "tft", "technology/technologies/tft.xml");
p(m, "tsmc180", "com.sun.electric.plugins.tsmc.TSMC180");
p(m, "cmos90","com.sun.electric.plugins.tsmc.CMOS90");
r(m, "tsmcSun40GP", "plugins/tsmc/tsmcSun40GP.xml");
// c(m, "tsmc45", "com.sun.electric.plugins.tsmc.TSMC45");
return Collections.unmodifiableMap(m);
}
public static TechFactory getTechFactory(String techName) { return getKnownTechs().get(techName); }
TechFactory(String techName) {
this(techName, Collections.<Param>emptyList());
}
TechFactory(String techName, List<Param> techParams) {
this.techName = techName;
this.techParams = Collections.unmodifiableList(new ArrayList<Param>(techParams));
}
private static void p(Map<String,TechFactory> m, String techName, String techClassName) {
TechFactory techFactory;
List<Param> params;
try {
Class<?> techClass = Class.forName(techClassName);
Method getTechParamsMethod = techClass.getMethod("getTechParams");
params = (List<Param>)getTechParamsMethod.invoke(null);
techFactory = new FromParamClass(techName, techClass, params);
} catch (Exception e) {
if (Job.getDebug())
e.printStackTrace();
return;
}
m.put(techName, techFactory);
}
private static void c(Map<String,TechFactory> m, String techName, String techClassName) {
m.put(techName, new FromClass(techName, techClassName));
}
private static void r(Map<String,TechFactory> m, String techName, String resourceName) {
assert techName != null;
URL url = Main.class.getResource(resourceName);
if (url == null)
return;
m.put(techName, new FromXml(techName, false, url, null));
}
abstract Technology newInstanceImpl(Generic generic, Map<Param,Object> paramValues) throws Exception;
public abstract Xml.Technology getXml(final Map<Param,Object> params) throws Exception;
static TechFactory read(IdReader reader) throws IOException {
String techName = reader.readString();
boolean userDefined = reader.readBoolean();
if (!userDefined)
return getKnownTechs().get(techName);
boolean hasUrl = reader.readBoolean();
URL xmlUrl = hasUrl ? new URL(reader.readString()) : null;
byte[] serializedXml = reader.readBytes();
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serializedXml));
Xml.Technology xmlTech = (Xml.Technology)in.readObject();
in.close();
return fromXml(xmlUrl, xmlTech);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
private static class FromClass extends TechFactory {
private final String techClassName;
private FromClass(String techName, String techClassName) {
super(techName, Collections.<Param>emptyList());
this.techClassName = techClassName;
}
@Override
Technology newInstanceImpl(Generic generic, Map<Param,Object> paramValues) throws Exception {
assert paramValues.isEmpty();
Class<?> techClass = Class.forName(techClassName);
return (Technology)techClass.getConstructor(Generic.class, TechFactory.class).newInstance(generic, this);
}
@Override
public Xml.Technology getXml(final Map<Param,Object> params) throws Exception {
IdManager idManager = new IdManager();
Generic generic = Generic.newInstance(idManager);
Technology tech = newInstance(generic, params);
return tech.makeXml();
}
@Override
String getDescription() { return "from " + techClassName;}
}
private static class FromParamClass extends TechFactory {
// private final Class<?> techClass;
private final Method getPatchedXmlMethod;
Constructor techConstructor;
private FromParamClass(String techName, Class<?> techClass, List<Param> techParams) throws Exception {
super(techName, techParams);
// this.techClass = techClass;
getPatchedXmlMethod = techClass.getMethod("getPatchedXml", Map.class);
techConstructor = techClass.getConstructor(Generic.class, TechFactory.class, Map.class, Xml.Technology.class);
}
@Override
Technology newInstanceImpl(Generic generic, Map<Param,Object> paramValues) throws Exception {
return (Technology)techConstructor.newInstance(generic, this, paramValues, getXml(paramValues));
}
@Override
public Xml.Technology getXml(final Map<Param,Object> params) throws Exception {
return (Xml.Technology)getPatchedXmlMethod.invoke(null, params);
}
@Override
String getDescription() { return "from " + getPatchedXmlMethod.getName();}
}
private static class FromXml extends TechFactory {
private final boolean userDefined;
private final URL urlXml;
private Xml.Technology xmlTech;
private boolean xmlParsed;
private FromXml(String techName, boolean userDefined, URL urlXml, Xml.Technology xmlTech) {
super(techName);
this.userDefined = userDefined;
this.urlXml = urlXml;
this.xmlTech = xmlTech;
}
@Override
Technology newInstanceImpl(Generic generic, Map<Param,Object> paramValues) throws Exception {
assert paramValues.isEmpty();
Xml.Technology xml = getXml(paramValues);
if (xml == null)
return null;
Class<?> techClass = Technology.class;
if (xml.className != null)
techClass = Class.forName(xml.className);
return (Technology)techClass.getConstructor(Generic.class, TechFactory.class, Map.class, Xml.Technology.class).newInstance(generic, this, Collections.emptyMap(), xml);
}
@Override
String getDescription() { return "from " + urlXml.getFile();}
public Xml.Technology getXml(final Map<Param,Object> paramValues) throws Exception {
assert paramValues.isEmpty();
if (xmlTech == null && !xmlParsed) {
xmlTech = Xml.parseTechnology(urlXml);
xmlParsed = true;
if (xmlTech == null)
throw new Exception("Can't load extra technology: " + urlXml);
if (!xmlTech.techName.equals(techName)) {
String techName = xmlTech.techName;
xmlTech = null;
throw new Exception("Tech name " + techName + " doesn't match file name:" +urlXml);
}
}
return xmlTech;
}
void write(IdWriter writer) throws IOException {
writer.writeString(techName);
writer.writeBoolean(userDefined);
if (!userDefined) return;
boolean hasUrl = urlXml != null;
writer.writeBoolean(hasUrl);
if (hasUrl)
writer.writeString(urlXml.toString());
byte[] serializedXml;
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteStream);
out.writeObject(xmlTech);
out.flush();
serializedXml = byteStream.toByteArray();
} catch (Throwable e) {
e.printStackTrace();
serializedXml = new byte[0];
}
writer.writeBytes(serializedXml);
}
}
}
| true | true | public Technology newInstance(Generic generic, Map<Param,Object> paramValues) {
try {
Map<Param,Object> fixedParamValues = new HashMap<Param,Object>();
for (Param param: techParams) {
Object value = paramValues.get(param);
if (value == null || value.getClass() != param.factoryValue.getClass())
value = param.factoryValue;
fixedParamValues.put(param, value);
}
Technology tech = newInstanceImpl(generic, fixedParamValues);
// make sure the name is unique
Technology already = Technology.findTechnology(tech.getTechName());
if (already != null)
{
System.out.println("ERROR: Multiple technologies named '" + tech.getTechName() + "'");
return null;
}
tech.setup();
return tech;
} catch (ClassNotFoundException e) {
if (Job.getDebug())
System.out.println("GNU Release can't find extra technologies");
} catch (Exception e) {
System.out.println("Exceptions while importing extra technology " + getDescription());
// if (Job.getDebug())
ActivityLogger.logException(e);
}
return null;
}
| public Technology newInstance(Generic generic, Map<Param,Object> paramValues) {
try {
Map<Param,Object> fixedParamValues = new HashMap<Param,Object>();
for (Param param: techParams) {
Object value = paramValues.get(param);
if (value == null || value.getClass() != param.factoryValue.getClass())
value = param.factoryValue;
fixedParamValues.put(param, value);
}
Technology tech = newInstanceImpl(generic, fixedParamValues);
// make sure the name is unique
// Technology already = Technology.findTechnology(tech.getTechName());
// if (already != null)
// {
// System.out.println("ERROR: Multiple technologies named '" + tech.getTechName() + "'");
// return null;
// }
tech.setup();
return tech;
} catch (ClassNotFoundException e) {
if (Job.getDebug())
System.out.println("GNU Release can't find extra technologies");
} catch (Exception e) {
System.out.println("Exceptions while importing extra technology " + getDescription());
// if (Job.getDebug())
ActivityLogger.logException(e);
}
return null;
}
|
diff --git a/src/com/dmdirc/ui/swing/components/TextFrame.java b/src/com/dmdirc/ui/swing/components/TextFrame.java
index c4c7c4eab..4b1483e2d 100644
--- a/src/com/dmdirc/ui/swing/components/TextFrame.java
+++ b/src/com/dmdirc/ui/swing/components/TextFrame.java
@@ -1,872 +1,873 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.ui.swing.components;
import com.dmdirc.FrameContainer;
import com.dmdirc.Main;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.commandparser.PopupManager;
import com.dmdirc.commandparser.PopupMenu;
import com.dmdirc.commandparser.PopupMenuItem;
import com.dmdirc.commandparser.PopupType;
import com.dmdirc.commandparser.parsers.GlobalCommandParser;
import com.dmdirc.util.StringTranscoder;
import com.dmdirc.config.ConfigManager;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.interfaces.IconChangeListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.ui.WindowManager;
import com.dmdirc.ui.interfaces.InputWindow;
import com.dmdirc.ui.interfaces.Window;
import com.dmdirc.ui.messages.Formatter;
import com.dmdirc.ui.swing.MainFrame;
import com.dmdirc.ui.swing.actions.ChannelCopyAction;
import com.dmdirc.ui.swing.actions.CommandAction;
import com.dmdirc.ui.swing.actions.HyperlinkCopyAction;
import com.dmdirc.ui.swing.actions.NicknameCopyAction;
import com.dmdirc.ui.swing.actions.SearchAction;
import com.dmdirc.ui.swing.actions.TextPaneCopyAction;
import com.dmdirc.ui.swing.textpane.LineInfo;
import com.dmdirc.ui.swing.textpane.TextPane;
import com.dmdirc.ui.swing.textpane.TextPane.ClickType;
import com.dmdirc.ui.swing.textpane.TextPanePageUpAction;
import com.dmdirc.ui.swing.textpane.TextPanePageDownAction;
import com.dmdirc.util.URLHandler;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import javax.swing.plaf.synth.SynthLookAndFeel;
/**
* Implements a generic (internal) frame.
*/
public abstract class TextFrame extends JInternalFrame implements Window,
PropertyChangeListener, InternalFrameListener,
MouseListener, KeyListener, ConfigChangeListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 5;
/** The channel object that owns this frame. */
private final FrameContainer parent;
/** Frame output pane. */
private TextPane textPane;
/** search bar. */
private SwingSearchBar searchBar;
/** String transcoder. */
private StringTranscoder transcoder;
/** Frame buffer size. */
private int frameBufferSize;
/** Quick copy? */
private boolean quickCopy;
/** Are we closing? */
private boolean closing = false;
/** Input window for popup commands. */
private Window inputWindow;
/** Click types. */
public enum MouseClickType {
/** Clicked. */
CLICKED,
/** Released. */
RELEASED,
/** Pressed. */
PRESSED,
}
/**
* Creates a new instance of Frame.
*
* @param owner FrameContainer owning this frame.
*/
public TextFrame(final FrameContainer owner) {
super();
final ConfigManager config = owner.getConfigManager();
final Boolean pref = config.getOptionBool("ui", "maximisewindows",
false);
frameBufferSize = config.getOptionInt("ui", "frameBufferSize",
Integer.MAX_VALUE);
quickCopy = config.getOptionBool("ui", "quickCopy", false);
parent = owner;
setFrameIcon(owner.getIcon());
owner.addIconChangeListener(new IconChangeListener() {
/** {@inheritDoc} */
@Override
public void iconChanged(final Window window, final Icon icon) {
setFrameIcon(icon);
}
});
try {
transcoder = new StringTranscoder(Charset.forName(
config.getOption("channel", "encoding", "UTF-8")));
} catch (UnsupportedCharsetException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
} catch (IllegalCharsetNameException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
} catch (IllegalArgumentException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
}
inputWindow = this;
while (!(inputWindow instanceof InputWindow) && inputWindow != null) {
inputWindow = WindowManager.getParent(inputWindow);
}
initComponents();
setMaximizable(true);
setClosable(true);
setResizable(true);
setIconifiable(true);
+ setFocusable(true);
setPreferredSize(new Dimension(((MainFrame) Main.getUI().getMainWindow()).getWidth() /
2,
((MainFrame) Main.getUI().getMainWindow()).getHeight() / 3));
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addPropertyChangeListener("maximum", this);
addPropertyChangeListener("UI", this);
addInternalFrameListener(this);
getTextPane().setBackground(config.getOptionColour("ui",
"backgroundcolour", Color.WHITE));
getTextPane().setForeground(config.getOptionColour("ui",
"foregroundcolour", Color.BLACK));
config.addChangeListener("ui", "foregroundcolour", this);
config.addChangeListener("ui", "backgroundcolour", this);
config.addChangeListener("ui", "quickCopy", this);
if (pref || Main.getUI().getMainWindow().getMaximised()) {
hideTitlebar();
}
}
/** {@inheritDoc} */
@Override
public void setTitle(final String title) {
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
TextFrame.super.setTitle(title);
}
});
}
/** {@inheritDoc} */
@Override
public void open() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setVisible(true);
}
});
}
/** {@inheritDoc} */
@Override
public final void addLine(final String line, final boolean timestamp) {
final String encodedLine = transcoder.decode(line);
SwingUtilities.invokeLater(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
for (String myLine : encodedLine.split("\n")) {
if (timestamp) {
getTextPane().addStyledString(new String[]{
Formatter.formatMessage(getConfigManager(),
"timestamp", new Date()), myLine,
});
} else {
getTextPane().addStyledString(myLine);
}
ActionManager.processEvent(CoreActionType.CLIENT_LINE_ADDED,
null, getContainer(), myLine);
if (frameBufferSize > 0) {
textPane.trim(frameBufferSize);
}
}
}
});
}
/** {@inheritDoc} */
@Override
public final void addLine(final String messageType, final Object... args) {
if (!messageType.isEmpty()) {
addLine(Formatter.formatMessage(getConfigManager(), messageType,
args), true);
}
}
/** {@inheritDoc} */
@Override
public final void addLine(final StringBuffer messageType,
final Object... args) {
if (messageType != null) {
addLine(messageType.toString(), args);
}
}
/** {@inheritDoc} */
@Override
public final void clear() {
getTextPane().clear();
}
/**
* Initialises the components for this frame.
*/
private void initComponents() {
setTextPane(new TextPane(getContainer()));
getTextPane().addMouseListener(this);
getTextPane().addKeyListener(this);
searchBar = new SwingSearchBar(this);
searchBar.setVisible(false);
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0),
"pageUpAction");
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0),
"pageDownAction");
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), "searchAction");
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_F,
InputEvent.CTRL_DOWN_MASK), "searchAction");
getActionMap().put("pageUpAction",
new TextPanePageUpAction(getTextPane()));
getActionMap().put("pageDownAction",
new TextPanePageDownAction(getTextPane()));
getActionMap().put("searchAction", new SearchAction(searchBar));
}
/**
* Removes and reinserts the border of an internal frame on maximising.
* {@inheritDoc}
*
* @param event Property change event
*/
@Override
public final void propertyChange(final PropertyChangeEvent event) {
if ("maximum".equals(event.getPropertyName())) {
if (event.getNewValue().equals(Boolean.TRUE)) {
hideTitlebar();
Main.getUI().getMainWindow().setMaximised(true);
} else {
showTitlebar();
Main.getUI().getMainWindow().setMaximised(false);
Main.getUI().getMainWindow().setActiveFrame(this);
}
} else if ("UI".equals(event.getPropertyName()) && isMaximum()) {
hideTitlebar();
}
}
/** Hides the titlebar for this frame. */
private void hideTitlebar() {
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
((BasicInternalFrameUI) getUI()).setNorthPane(null);
}
/** Shows the titlebar for this frame. */
private void showTitlebar() {
final Class<?> c;
Object temp = null;
Constructor<?> constructor;
final String componentUI = (String) UIManager.get("InternalFrameUI");
if ("javax.swing.plaf.synth.SynthLookAndFeel".equals(componentUI)) {
temp = SynthLookAndFeel.createUI(this);
} else {
try {
c = getClass().getClassLoader().loadClass(componentUI);
constructor =
c.getConstructor(new Class[]{javax.swing.JInternalFrame.class});
temp = constructor.newInstance(new Object[]{this});
} catch (ClassNotFoundException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to readd titlebar",
ex);
} catch (NoSuchMethodException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to readd titlebar",
ex);
} catch (InstantiationException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to readd titlebar",
ex);
} catch (IllegalAccessException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to readd titlebar",
ex);
} catch (InvocationTargetException ex) {
Logger.appError(ErrorLevel.MEDIUM, "Unable to readd titlebar",
ex);
}
}
setBorder(UIManager.getBorder("InternalFrame.border"));
if (temp == null) {
temp = new BasicInternalFrameUI(this);
}
this.setUI((BasicInternalFrameUI) temp);
}
/**
* Not needed for this class. {@inheritDoc}
*
* @param event Internal frame event
*/
@Override
public void internalFrameOpened(final InternalFrameEvent event) {
parent.windowOpened();
}
/**
* Not needed for this class. {@inheritDoc}
*
* @param event Internal frame event
*/
@Override
public void internalFrameClosing(final InternalFrameEvent event) {
parent.windowClosing();
}
/**
* Not needed for this class. {@inheritDoc}
*
* @param event Internal frame event
*/
@Override
public void internalFrameClosed(final InternalFrameEvent event) {
parent.windowClosed();
}
/**
* Makes the internal frame invisible. {@inheritDoc}
*
* @param event Internal frame event
*/
@Override
public void internalFrameIconified(final InternalFrameEvent event) {
event.getInternalFrame().setVisible(false);
}
/**
* Not needed for this class. {@inheritDoc}
*
* @param event Internal frame event
*/
@Override
public void internalFrameDeiconified(final InternalFrameEvent event) {
//Ignore.
}
/**
* Activates the input field on frame focus. {@inheritDoc}
*
* @param event Internal frame event
*/
@Override
public void internalFrameActivated(final InternalFrameEvent event) {
parent.windowActivated();
}
/**
* Not needed for this class. {@inheritDoc}
*
* @param event Internal frame event
*/
@Override
public void internalFrameDeactivated(final InternalFrameEvent event) {
parent.windowDeactivated();
}
/** {@inheritDoc} */
@Override
public FrameContainer getContainer() {
return parent;
}
/** {@inheritDoc} */
@Override
public ConfigManager getConfigManager() {
return getContainer().getConfigManager();
}
/**
* Returns the text pane for this frame.
*
* @return Text pane for this frame
*/
public final TextPane getTextPane() {
return textPane;
}
/**
* Returns the transcoder for this frame.
*
* @return String transcoder for this frame
*/
@Override
public StringTranscoder getTranscoder() {
return transcoder;
}
/** {@inheritDoc} */
@Override
public final String getName() {
if (parent == null) {
return "";
}
return parent.toString();
}
/**
* Sets the frames text pane.
*
* @param newTextPane new text pane to use
*/
protected final void setTextPane(final TextPane newTextPane) {
this.textPane = newTextPane;
}
/**
* {@inheritDoc}
*
* @param mouseEvent Mouse event
*/
@Override
public void mouseClicked(final MouseEvent mouseEvent) {
if (mouseEvent.getSource() == getTextPane()) {
processMouseClickEvent(mouseEvent, MouseClickType.CLICKED);
}
}
/**
* {@inheritDoc}
*
* @param mouseEvent Mouse event
*/
@Override
public void mousePressed(final MouseEvent mouseEvent) {
processMouseClickEvent(mouseEvent, MouseClickType.PRESSED);
}
/**
* {@inheritDoc}
*
* @param mouseEvent Mouse event
*/
@Override
public void mouseReleased(final MouseEvent mouseEvent) {
if (quickCopy && mouseEvent.getSource() == getTextPane()) {
getTextPane().copy();
getTextPane().clearSelection();
}
processMouseClickEvent(mouseEvent, MouseClickType.RELEASED);
}
/**
* {@inheritDoc}
*
* @param mouseEvent Mouse event
*/
@Override
public void mouseEntered(final MouseEvent mouseEvent) {
//Ignore.
}
/**
* {@inheritDoc}
*
* @param mouseEvent Mouse event
*/
@Override
public void mouseExited(final MouseEvent mouseEvent) {
//Ignore.
}
/**
* Processes every mouse button event to check for a popup trigger.
*
* @param e mouse event
* @param type
*/
public void processMouseClickEvent(final MouseEvent e,
final MouseClickType type) {
final Point point = getTextPane().getMousePosition();
if (e.getSource() == getTextPane() && point != null) {
final LineInfo lineInfo = getTextPane().getClickPosition(point);
final ClickType clickType = getTextPane().getClickType(lineInfo);
final String attribute = (String) getTextPane().getAttributeValueAtPoint(lineInfo);
if (e.isPopupTrigger()) {
showPopupMenuInternal(clickType, point, attribute);
} else {
if (type == MouseClickType.CLICKED) {
switch (clickType) {
case CHANNEL:
parent.getServer().join(attribute);
break;
case HYPERLINK:
URLHandler.getURLHander().launchApp(attribute);
break;
case NICKNAME:
if (getContainer().getServer().hasQuery(attribute)) {
getContainer().getServer().getQuery(attribute).
activateFrame();
} else {
getContainer().getServer().addQuery(attribute);
getContainer().getServer().getQuery(attribute).
show();
}
break;
default:
break;
}
}
}
}
super.processMouseEvent(e);
}
/**
* What popup type should be used for popup menus for nicknames
*
* @return Appropriate popuptype for this frame
*/
public abstract PopupType getNicknamePopupType();
/**
* What popup type should be used for popup menus for channels
*
* @return Appropriate popuptype for this frame
*/
public abstract PopupType getChannelPopupType();
/**
* What popup type should be used for popup menus for hyperlinks
*
* @return Appropriate popuptype for this frame
*/
public abstract PopupType getHyperlinkPopupType();
/**
* What popup type should be used for popup menus for normal clicks
*
* @return Appropriate popuptype for this frame
*/
public abstract PopupType getNormalPopupType();
/**
* A method called to add custom popup items.
*
* @param popupMenu Popup menu to add popup items to
*/
public abstract void addCustomPopupItems(final JPopupMenu popupMenu);
/**
* Shows a popup menu at the specified point for the specified click type
*
* @param type ClickType Click type
* @param point Point Point of the click
* @param argument Word under the click
*/
private void showPopupMenuInternal(final ClickType type,
final Point point,
final String argument) {
final JPopupMenu popupMenu;
switch (type) {
case CHANNEL:
popupMenu = getPopupMenu(getChannelPopupType(), argument);
popupMenu.add(new ChannelCopyAction(argument));
if (popupMenu.getComponentCount() > 1) {
popupMenu.addSeparator();
}
break;
case HYPERLINK:
popupMenu = getPopupMenu(getHyperlinkPopupType(), argument);
popupMenu.add(new HyperlinkCopyAction(argument));
if (popupMenu.getComponentCount() > 1) {
popupMenu.addSeparator();
}
break;
case NICKNAME:
popupMenu = getPopupMenu(getNicknamePopupType(), argument);
if (popupMenu.getComponentCount() > 0) {
popupMenu.addSeparator();
}
popupMenu.add(new NicknameCopyAction(argument));
break;
default:
popupMenu = getPopupMenu(null, argument);
break;
}
popupMenu.add(new TextPaneCopyAction(getTextPane()));
addCustomPopupItems(popupMenu);
popupMenu.show(this, (int) point.getX(), (int) point.getY());
}
/**
* Shows a popup menu at the specified point for the specified click type
*
* @param type ClickType Click type
* @param point Point Point of the click
* @param argument Word under the click
*/
public void showPopupMenu(final ClickType type, final Point point,
final String argument) {
final JPopupMenu popupMenu;
switch (type) {
case CHANNEL:
popupMenu = getPopupMenu(getChannelPopupType(), argument);
popupMenu.add(new ChannelCopyAction(argument));
if (popupMenu.getComponentCount() > 1) {
popupMenu.addSeparator();
}
break;
case HYPERLINK:
popupMenu = getPopupMenu(getHyperlinkPopupType(), argument);
popupMenu.add(new HyperlinkCopyAction(argument));
if (popupMenu.getComponentCount() > 1) {
popupMenu.addSeparator();
}
break;
case NICKNAME:
popupMenu = getPopupMenu(getNicknamePopupType(), argument);
if (popupMenu.getComponentCount() > 0) {
popupMenu.addSeparator();
}
popupMenu.add(new NicknameCopyAction(argument));
break;
default:
popupMenu = getPopupMenu(null, argument);
break;
}
popupMenu.show(this, (int) point.getX(), (int) point.getY());
}
/**
* Builds a popup menu of a specified type
*
* @param type type of menu to build
* @param arguments Arguments for the command
*
* @return PopupMenu
*/
public JPopupMenu getPopupMenu(final PopupType type,
final Object... arguments) {
JPopupMenu popupMenu = new JPopupMenu();
if (type != null) {
popupMenu = (JPopupMenu) populatePopupMenu(popupMenu,
PopupManager.getMenu(type, getConfigManager()),
arguments);
}
return popupMenu;
}
/**
* Populates the specified popupmenu
*
* @param menu Menu component
* @param popup Popup to get info from
* @param arguments Arguments for the command
*
* @return Populated popup
*/
private JComponent populatePopupMenu(final JComponent menu,
final PopupMenu popup, final Object... arguments) {
for (PopupMenuItem menuItem : popup.getItems()) {
if (menuItem.isDivider()) {
menu.add(new JSeparator());
} else if (menuItem.isSubMenu()) {
menu.add(populatePopupMenu(new JMenu(menuItem.getName()),
menuItem.getSubMenu(), arguments));
} else {
menu.add(new JMenuItem(new CommandAction(inputWindow == null ? GlobalCommandParser.getGlobalCommandParser()
: ((InputWindow) inputWindow).getCommandParser(),
(InputWindow) inputWindow, menuItem.getName(),
menuItem.getCommand(arguments))));
}
}
return menu;
}
/**
* {@inheritDoc}
*
* @param event Key event
*/
@Override
public void keyTyped(final KeyEvent event) {
//Ignore.
}
/**
* {@inheritDoc}
*
* @param event Key event
*/
@Override
public void keyPressed(final KeyEvent event) {
if (!quickCopy && (event.getModifiers() & KeyEvent.CTRL_MASK) != 0 &&
event.getKeyCode() == KeyEvent.VK_C) {
getTextPane().copy();
}
}
/**
* {@inheritDoc}
*
* @param event Key event
*/
@Override
public void keyReleased(final KeyEvent event) {
//Ignore.
}
/**
* Gets the search bar.
*
* @return the frames search bar
*/
public final SwingSearchBar getSearchBar() {
return searchBar;
}
/** Closes this frame. */
@Override
public void close() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (closing) {
return;
}
closing = true;
try {
setClosed(true);
} catch (PropertyVetoException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to close frame");
}
}
});
}
/** Minimises the frame. */
public void minimise() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
setIcon(true);
} catch (PropertyVetoException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to minimise frame");
}
}
});
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
if (getConfigManager() == null) {
return;
}
if ("ui".equals(domain)) {
if ("foregroundcolour".equals(key) && getTextPane() != null) {
getTextPane().setForeground(getConfigManager().
getOptionColour("ui", "foregroundcolour", Color.BLACK));
} else if ("backgroundcolour".equals(key) && getTextPane() != null) {
getTextPane().setBackground(getConfigManager().
getOptionColour("ui", "backgroundcolour", Color.WHITE));
} else if ("frameBufferSize".equals(key)) {
frameBufferSize = getContainer().getConfigManager().
getOptionInt("ui", "frameBufferSize", Integer.MAX_VALUE);
} else if ("quickCopy".equals(key)) {
quickCopy = getContainer().getConfigManager().
getOptionBool("ui", "quickCopy", false);
}
}
}
}
| true | true | public TextFrame(final FrameContainer owner) {
super();
final ConfigManager config = owner.getConfigManager();
final Boolean pref = config.getOptionBool("ui", "maximisewindows",
false);
frameBufferSize = config.getOptionInt("ui", "frameBufferSize",
Integer.MAX_VALUE);
quickCopy = config.getOptionBool("ui", "quickCopy", false);
parent = owner;
setFrameIcon(owner.getIcon());
owner.addIconChangeListener(new IconChangeListener() {
/** {@inheritDoc} */
@Override
public void iconChanged(final Window window, final Icon icon) {
setFrameIcon(icon);
}
});
try {
transcoder = new StringTranscoder(Charset.forName(
config.getOption("channel", "encoding", "UTF-8")));
} catch (UnsupportedCharsetException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
} catch (IllegalCharsetNameException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
} catch (IllegalArgumentException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
}
inputWindow = this;
while (!(inputWindow instanceof InputWindow) && inputWindow != null) {
inputWindow = WindowManager.getParent(inputWindow);
}
initComponents();
setMaximizable(true);
setClosable(true);
setResizable(true);
setIconifiable(true);
setPreferredSize(new Dimension(((MainFrame) Main.getUI().getMainWindow()).getWidth() /
2,
((MainFrame) Main.getUI().getMainWindow()).getHeight() / 3));
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addPropertyChangeListener("maximum", this);
addPropertyChangeListener("UI", this);
addInternalFrameListener(this);
getTextPane().setBackground(config.getOptionColour("ui",
"backgroundcolour", Color.WHITE));
getTextPane().setForeground(config.getOptionColour("ui",
"foregroundcolour", Color.BLACK));
config.addChangeListener("ui", "foregroundcolour", this);
config.addChangeListener("ui", "backgroundcolour", this);
config.addChangeListener("ui", "quickCopy", this);
if (pref || Main.getUI().getMainWindow().getMaximised()) {
hideTitlebar();
}
}
| public TextFrame(final FrameContainer owner) {
super();
final ConfigManager config = owner.getConfigManager();
final Boolean pref = config.getOptionBool("ui", "maximisewindows",
false);
frameBufferSize = config.getOptionInt("ui", "frameBufferSize",
Integer.MAX_VALUE);
quickCopy = config.getOptionBool("ui", "quickCopy", false);
parent = owner;
setFrameIcon(owner.getIcon());
owner.addIconChangeListener(new IconChangeListener() {
/** {@inheritDoc} */
@Override
public void iconChanged(final Window window, final Icon icon) {
setFrameIcon(icon);
}
});
try {
transcoder = new StringTranscoder(Charset.forName(
config.getOption("channel", "encoding", "UTF-8")));
} catch (UnsupportedCharsetException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
} catch (IllegalCharsetNameException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
} catch (IllegalArgumentException ex) {
transcoder = new StringTranscoder(Charset.forName("UTF-8"));
}
inputWindow = this;
while (!(inputWindow instanceof InputWindow) && inputWindow != null) {
inputWindow = WindowManager.getParent(inputWindow);
}
initComponents();
setMaximizable(true);
setClosable(true);
setResizable(true);
setIconifiable(true);
setFocusable(true);
setPreferredSize(new Dimension(((MainFrame) Main.getUI().getMainWindow()).getWidth() /
2,
((MainFrame) Main.getUI().getMainWindow()).getHeight() / 3));
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addPropertyChangeListener("maximum", this);
addPropertyChangeListener("UI", this);
addInternalFrameListener(this);
getTextPane().setBackground(config.getOptionColour("ui",
"backgroundcolour", Color.WHITE));
getTextPane().setForeground(config.getOptionColour("ui",
"foregroundcolour", Color.BLACK));
config.addChangeListener("ui", "foregroundcolour", this);
config.addChangeListener("ui", "backgroundcolour", this);
config.addChangeListener("ui", "quickCopy", this);
if (pref || Main.getUI().getMainWindow().getMaximised()) {
hideTitlebar();
}
}
|
diff --git a/src/main/java/net/daboross/bungeedev/nchat/JoinListener.java b/src/main/java/net/daboross/bungeedev/nchat/JoinListener.java
index 258d698..ba4328c 100644
--- a/src/main/java/net/daboross/bungeedev/nchat/JoinListener.java
+++ b/src/main/java/net/daboross/bungeedev/nchat/JoinListener.java
@@ -1,35 +1,35 @@
/*
* Copyright (C) 2013 Dabo Ross <www.daboross.net>
*/
package net.daboross.bungeedev.nchat;
import net.daboross.bungeedev.ncommon.utils.ConnectorUtils;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
/**
*
* @author daboross
*/
public class JoinListener implements Listener {
private final NChatPlugin plugin;
public JoinListener(NChatPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onJoin(ServerConnectedEvent evt) {
final ProxiedPlayer p = evt.getPlayer();
String name = plugin.getDisplayNameDatabase().getDisplayName(p.getName());
if (name == null) {
- name = ChatColor.BLUE + p.getName();
+ name = ChatSensor.formatPlayerDisplayname(name);
}
p.setDisplayName(name);
ConnectorUtils.setDisplayName(evt.getServer(), name);
}
}
| true | true | public void onJoin(ServerConnectedEvent evt) {
final ProxiedPlayer p = evt.getPlayer();
String name = plugin.getDisplayNameDatabase().getDisplayName(p.getName());
if (name == null) {
name = ChatColor.BLUE + p.getName();
}
p.setDisplayName(name);
ConnectorUtils.setDisplayName(evt.getServer(), name);
}
| public void onJoin(ServerConnectedEvent evt) {
final ProxiedPlayer p = evt.getPlayer();
String name = plugin.getDisplayNameDatabase().getDisplayName(p.getName());
if (name == null) {
name = ChatSensor.formatPlayerDisplayname(name);
}
p.setDisplayName(name);
ConnectorUtils.setDisplayName(evt.getServer(), name);
}
|
diff --git a/appinventor/components/src/com/google/appinventor/components/runtime/ReplForm.java b/appinventor/components/src/com/google/appinventor/components/runtime/ReplForm.java
index c4262f95..44af4449 100644
--- a/appinventor/components/src/com/google/appinventor/components/runtime/ReplForm.java
+++ b/appinventor/components/src/com/google/appinventor/components/runtime/ReplForm.java
@@ -1,174 +1,175 @@
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
package com.google.appinventor.components.runtime;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.io.File;
import java.io.IOException;
import com.google.appinventor.components.runtime.util.ReplCommController;
import com.google.appinventor.components.runtime.util.AppInvHTTPD;
import com.google.appinventor.components.runtime.util.SdkLevel;
import com.google.appinventor.components.runtime.util.EclairUtil;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Activity;
import android.content.Context;
/**
* Subclass of Form used by the 'stem cell apk', i.e. the Android app that allows communication
* via the Repl
*
* @author [email protected] (Your Name Here)
*/
public class ReplForm extends Form {
// Controller for the ReplCommController associated with this form
private ReplCommController formReplCommController = null;
private AppInvHTTPD assetServer = null;
public static ReplForm topform;
private static final String REPL_ASSET_DIR = "/sdcard/AppInventor/assets/";
private boolean IsUSBRepl = false;
private boolean assetsLoaded = false;
public ReplForm() {
super();
topform = this;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (IsUSBRepl) {
PackageManager packageManager = this.$context().getPackageManager();
// the following is intended to prevent the application from being restarted
// once it has ever run (so it can be run only once after it is installed)
packageManager.setComponentEnabledSetting(
new ComponentName(this.getPackageName(), this.getClass().getName()),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
formReplCommController = new ReplCommController(this);
formReplCommController.startListening(true /*showAlert*/);
+ assetsLoaded = true; // we don't have any for the usb repl...
}
}
@Override
protected void onResume() {
super.onResume();
if (formReplCommController != null)
formReplCommController.startListening(true /*showAlert*/);
}
@Override
protected void onStop() {
super.onStop();
if (formReplCommController != null)
formReplCommController.stopListening(false /*showAlert*/);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (formReplCommController != null)
formReplCommController.destroy();
if (assetServer != null) {
assetServer.stop();
assetServer = null;
}
finish(); // Must really exit here, so if you hits the back button we terminate completely.
System.exit(0);
}
@Override
protected void startNewForm(String nextFormName, Object startupValue) {
// Switching forms is not allowed in REPL (yet?).
runOnUiThread(new Runnable() {
public void run() {
String message = "Switching forms is not currently supported during development.";
Toast.makeText(ReplForm.this, message, Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void closeForm(Intent resultIntent) {
// Switching forms is not allowed in REPL (yet?).
runOnUiThread(new Runnable() {
public void run() {
String message = "Closing forms is not currently supported during development.";
Toast.makeText(ReplForm.this, message, Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void closeApplicationFromBlocks() {
// Switching forms is not allowed in REPL (yet?).
runOnUiThread(new Runnable() {
public void run() {
String message = "Closing forms is not currently supported during development.";
Toast.makeText(ReplForm.this, message, Toast.LENGTH_LONG).show();
}
});
}
public void setIsUSBrepl() {
IsUSBRepl = true;
}
// Called from Screen1.yail after Screen1 is setup
public void startHTTPD() {
try {
if (assetServer == null) {
checkAssetDir();
assetServer = new AppInvHTTPD(8000, new File(REPL_ASSET_DIR), this); // Probably should make the port variable
Log.i("ReplForm", "started AppInvHTTPD");
}
} catch (IOException ex) {
Log.e("ReplForm", "Setting up NanoHTTPD: " + ex.toString());
}
}
public void startRepl() {
Log.i("ReplForm", "startRepl()");
formReplCommController = new ReplCommController(this);
formReplCommController.startListening(true /*showAlert*/);
}
// Make sure that the REPL asset directory exists.
private void checkAssetDir() {
File f = new File(REPL_ASSET_DIR);
if (!f.exists())
f.mkdirs(); // Create the directory and all parents
}
// We return true if the assets for the Companion have been loaded and
// displayed so we should look for all future assets in the sdcard which
// is where assets are placed for the companion.
// We return false until setAssetsLoaded is called which is done
// by the phone status block
public boolean isAssetsLoaded() {
return assetsLoaded;
}
public void setAssetsLoaded() {
assetsLoaded = true;
}
}
| true | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (IsUSBRepl) {
PackageManager packageManager = this.$context().getPackageManager();
// the following is intended to prevent the application from being restarted
// once it has ever run (so it can be run only once after it is installed)
packageManager.setComponentEnabledSetting(
new ComponentName(this.getPackageName(), this.getClass().getName()),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
formReplCommController = new ReplCommController(this);
formReplCommController.startListening(true /*showAlert*/);
}
}
| public void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (IsUSBRepl) {
PackageManager packageManager = this.$context().getPackageManager();
// the following is intended to prevent the application from being restarted
// once it has ever run (so it can be run only once after it is installed)
packageManager.setComponentEnabledSetting(
new ComponentName(this.getPackageName(), this.getClass().getName()),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
formReplCommController = new ReplCommController(this);
formReplCommController.startListening(true /*showAlert*/);
assetsLoaded = true; // we don't have any for the usb repl...
}
}
|
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/alerts/Alert.java b/tapestry-core/src/main/java/org/apache/tapestry5/alerts/Alert.java
index b7a8d8d90..e830ad971 100644
--- a/tapestry-core/src/main/java/org/apache/tapestry5/alerts/Alert.java
+++ b/tapestry-core/src/main/java/org/apache/tapestry5/alerts/Alert.java
@@ -1,99 +1,99 @@
// Copyright 2011 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.alerts;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.json.JSONObject;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;
/**
* An Alert that may be presented to the user. The Alert has a message, but also includes
* a severity (that controls how it is presented to the user), and a duration (that controls how long
* it is presented to the user).
*
* @since 5.3
*/
public class Alert implements Serializable
{
private static final AtomicLong idSource = new AtomicLong(System.currentTimeMillis());
/**
* A unique id (unique within this JVM and execution), used to identify an alert (used primarily
* when individually dismissing an alert).
*/
public final long id = idSource.getAndIncrement();
public final Duration duration;
public final Severity severity;
public final String message;
/**
* Alert with default duration of {@link Duration#SINGLE} and default severity
* of {@link Severity#INFO}.
*/
public Alert(String message)
{
this(Severity.INFO, message);
}
/**
* Alert with default duration of {@link Duration#SINGLE}.
*/
public Alert(Severity severity, String message)
{
this(Duration.SINGLE, severity, message);
}
public Alert(Duration duration, Severity severity, String message)
{
assert duration != null;
assert severity != null;
assert InternalUtils.isNonBlank(message);
this.duration = duration;
this.severity = severity;
this.message = message;
}
public String toString()
{
return String.format("Alert[%s %s %s]",
duration.name(),
severity.name(),
message);
}
public JSONObject toJSON()
{
JSONObject result = new JSONObject("message", message,
"severity", severity.name().toLowerCase() );
if (duration == Duration.TRANSIENT)
{
- result.put("transient", true);
+ result.put("ephemeral", true);
}
if (duration.persistent)
{
result.put("id", id);
}
return result;
}
}
| true | true | public JSONObject toJSON()
{
JSONObject result = new JSONObject("message", message,
"severity", severity.name().toLowerCase() );
if (duration == Duration.TRANSIENT)
{
result.put("transient", true);
}
if (duration.persistent)
{
result.put("id", id);
}
return result;
}
| public JSONObject toJSON()
{
JSONObject result = new JSONObject("message", message,
"severity", severity.name().toLowerCase() );
if (duration == Duration.TRANSIENT)
{
result.put("ephemeral", true);
}
if (duration.persistent)
{
result.put("id", id);
}
return result;
}
|
diff --git a/app/src/processing/app/syntax/PdeTextAreaDefaults.java b/app/src/processing/app/syntax/PdeTextAreaDefaults.java
index e6e1babee..d6d2ad3a6 100644
--- a/app/src/processing/app/syntax/PdeTextAreaDefaults.java
+++ b/app/src/processing/app/syntax/PdeTextAreaDefaults.java
@@ -1,201 +1,201 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
PdeTextAreaDefaults - grabs font/color settings for the editor
Part of the Processing project - http://processing.org
Copyright (c) 2004-06 Ben Fry and Casey Reas
Copyright (c) 2001-03 Massachusetts Institute of Technology
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
*/
package processing.app.syntax;
import processing.app.*;
public class PdeTextAreaDefaults extends TextAreaDefaults {
public PdeTextAreaDefaults() {
inputHandler = new DefaultInputHandler();
//inputHandler.addDefaultKeyBindings(); // 0122
// use option on mac for things that are ctrl on windows/linux
String mod = Base.isMacOS() ? "A" : "C";
// right now, ctrl-up/down is select up/down, but mod should be
// used instead, because the mac expects it to be option(alt)
inputHandler.addKeyBinding("BACK_SPACE", InputHandler.BACKSPACE);
inputHandler.addKeyBinding("DELETE", InputHandler.DELETE);
//inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.BACKSPACE);
// for 0122, shift-backspace is delete
inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.DELETE);
inputHandler.addKeyBinding("S+DELETE", InputHandler.DELETE);
// the following two were changing for 0122 for better mac/pc compatability
inputHandler.addKeyBinding(mod+"+BACK_SPACE", InputHandler.BACKSPACE_WORD);
inputHandler.addKeyBinding(mod+"+DELETE", InputHandler.DELETE_WORD);
// handled by listener, don't bother here
//inputHandler.addKeyBinding("ENTER", InputHandler.INSERT_BREAK);
//inputHandler.addKeyBinding("TAB", InputHandler.INSERT_TAB);
inputHandler.addKeyBinding("INSERT", InputHandler.OVERWRITE);
// http://dev.processing.org/bugs/show_bug.cgi?id=162
// added for 0176, though the bindings do not appear relevant for osx
if (!Base.isMacOS()) {
inputHandler.addKeyBinding("C+INSERT", InputHandler.CLIPBOARD_COPY);
inputHandler.addKeyBinding("S+INSERT", InputHandler.CLIPBOARD_PASTE);
inputHandler.addKeyBinding("S+DELETE", InputHandler.CLIPBOARD_CUT);
}
// disabling for 0122, not sure what this does
//inputHandler.addKeyBinding("C+\\", InputHandler.TOGGLE_RECT);
- // for 0122, these have been changed for better compatability
+ // for 0122, these have been changed for better compatibility
// HOME and END now mean the beginning/end of the document
if (Base.isMacOS()) {
inputHandler.addKeyBinding("HOME", InputHandler.DOCUMENT_HOME);
inputHandler.addKeyBinding("END", InputHandler.DOCUMENT_END);
inputHandler.addKeyBinding("S+HOME", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("S+END", InputHandler.SELECT_DOC_END);
} else {
// for 0123 added the proper windows defaults
inputHandler.addKeyBinding("HOME", InputHandler.HOME);
inputHandler.addKeyBinding("END", InputHandler.END);
inputHandler.addKeyBinding("S+HOME", InputHandler.SELECT_HOME);
inputHandler.addKeyBinding("S+END", InputHandler.SELECT_END);
inputHandler.addKeyBinding("C+HOME", InputHandler.DOCUMENT_HOME);
inputHandler.addKeyBinding("C+END", InputHandler.DOCUMENT_END);
inputHandler.addKeyBinding("CS+HOME", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("CS+END", InputHandler.SELECT_DOC_END);
}
if (Base.isMacOS()) {
inputHandler.addKeyBinding("M+LEFT", InputHandler.HOME);
inputHandler.addKeyBinding("M+RIGHT", InputHandler.END);
inputHandler.addKeyBinding("MS+LEFT", InputHandler.SELECT_HOME); // 0122
inputHandler.addKeyBinding("MS+RIGHT", InputHandler.SELECT_END); // 0122
} else {
inputHandler.addKeyBinding("C+LEFT", InputHandler.HOME); // 0122
inputHandler.addKeyBinding("C+RIGHT", InputHandler.END); // 0122
inputHandler.addKeyBinding("CS+HOME", InputHandler.SELECT_HOME); // 0122
inputHandler.addKeyBinding("CS+END", InputHandler.SELECT_END); // 0122
}
inputHandler.addKeyBinding("PAGE_UP", InputHandler.PREV_PAGE);
inputHandler.addKeyBinding("PAGE_DOWN", InputHandler.NEXT_PAGE);
inputHandler.addKeyBinding("S+PAGE_UP", InputHandler.SELECT_PREV_PAGE);
inputHandler.addKeyBinding("S+PAGE_DOWN", InputHandler.SELECT_NEXT_PAGE);
inputHandler.addKeyBinding("LEFT", InputHandler.PREV_CHAR);
inputHandler.addKeyBinding("S+LEFT", InputHandler.SELECT_PREV_CHAR);
inputHandler.addKeyBinding(mod + "+LEFT", InputHandler.PREV_WORD);
inputHandler.addKeyBinding(mod + "S+LEFT", InputHandler.SELECT_PREV_WORD);
inputHandler.addKeyBinding("RIGHT", InputHandler.NEXT_CHAR);
inputHandler.addKeyBinding("S+RIGHT", InputHandler.SELECT_NEXT_CHAR);
inputHandler.addKeyBinding(mod + "+RIGHT", InputHandler.NEXT_WORD);
inputHandler.addKeyBinding(mod + "S+RIGHT", InputHandler.SELECT_NEXT_WORD);
inputHandler.addKeyBinding("UP", InputHandler.PREV_LINE);
inputHandler.addKeyBinding(mod + "+UP", InputHandler.PREV_LINE); // p5
inputHandler.addKeyBinding("S+UP", InputHandler.SELECT_PREV_LINE);
inputHandler.addKeyBinding("DOWN", InputHandler.NEXT_LINE);
inputHandler.addKeyBinding(mod + "+DOWN", InputHandler.NEXT_LINE); // p5
inputHandler.addKeyBinding("S+DOWN", InputHandler.SELECT_NEXT_LINE);
inputHandler.addKeyBinding("MS+UP", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("CS+UP", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("MS+DOWN", InputHandler.SELECT_DOC_END);
inputHandler.addKeyBinding("CS+DOWN", InputHandler.SELECT_DOC_END);
inputHandler.addKeyBinding(mod + "+ENTER", InputHandler.REPEAT);
document = new SyntaxDocument();
editable = true;
electricScroll = 3;
cols = 80;
rows = 15;
// moved from SyntaxUtilities
//DEFAULTS.styles = SyntaxUtilities.getDefaultSyntaxStyles();
styles = new SyntaxStyle[Token.ID_COUNT];
// comments
styles[Token.COMMENT1] = Theme.getStyle("comment1");
styles[Token.COMMENT2] = Theme.getStyle("comment2");
// abstract, final, private
styles[Token.KEYWORD1] = Theme.getStyle("keyword1");
// beginShape, point, line
styles[Token.KEYWORD2] = Theme.getStyle("keyword2");
// byte, char, short, color
styles[Token.KEYWORD3] = Theme.getStyle("keyword3");
// constants: null, true, this, RGB, TWO_PI
styles[Token.LITERAL1] = Theme.getStyle("literal1");
// p5 built in variables: mouseX, width, pixels
styles[Token.LITERAL2] = Theme.getStyle("literal2");
// ??
styles[Token.LABEL] = Theme.getStyle("label");
// + - = /
styles[Token.OPERATOR] = Theme.getStyle("operator");
// area that's not in use by the text (replaced with tildes)
styles[Token.INVALID] = Theme.getStyle("invalid");
// moved from TextAreaPainter
font = Preferences.getFont("editor.font");
fgcolor = Theme.getColor("editor.fgcolor");
bgcolor = Theme.getColor("editor.bgcolor");
caretVisible = true;
caretBlinks = Preferences.getBoolean("editor.caret.blink");
caretColor = Theme.getColor("editor.caret.color");
selectionColor = Theme.getColor("editor.selection.color");
lineHighlight =
Theme.getBoolean("editor.linehighlight");
lineHighlightColor =
Theme.getColor("editor.linehighlight.color");
bracketHighlight =
Theme.getBoolean("editor.brackethighlight");
bracketHighlightColor =
Theme.getColor("editor.brackethighlight.color");
eolMarkers = Theme.getBoolean("editor.eolmarkers");
eolMarkerColor = Theme.getColor("editor.eolmarkers.color");
paintInvalid = Theme.getBoolean("editor.invalid");
}
}
| true | true | public PdeTextAreaDefaults() {
inputHandler = new DefaultInputHandler();
//inputHandler.addDefaultKeyBindings(); // 0122
// use option on mac for things that are ctrl on windows/linux
String mod = Base.isMacOS() ? "A" : "C";
// right now, ctrl-up/down is select up/down, but mod should be
// used instead, because the mac expects it to be option(alt)
inputHandler.addKeyBinding("BACK_SPACE", InputHandler.BACKSPACE);
inputHandler.addKeyBinding("DELETE", InputHandler.DELETE);
//inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.BACKSPACE);
// for 0122, shift-backspace is delete
inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.DELETE);
inputHandler.addKeyBinding("S+DELETE", InputHandler.DELETE);
// the following two were changing for 0122 for better mac/pc compatability
inputHandler.addKeyBinding(mod+"+BACK_SPACE", InputHandler.BACKSPACE_WORD);
inputHandler.addKeyBinding(mod+"+DELETE", InputHandler.DELETE_WORD);
// handled by listener, don't bother here
//inputHandler.addKeyBinding("ENTER", InputHandler.INSERT_BREAK);
//inputHandler.addKeyBinding("TAB", InputHandler.INSERT_TAB);
inputHandler.addKeyBinding("INSERT", InputHandler.OVERWRITE);
// http://dev.processing.org/bugs/show_bug.cgi?id=162
// added for 0176, though the bindings do not appear relevant for osx
if (!Base.isMacOS()) {
inputHandler.addKeyBinding("C+INSERT", InputHandler.CLIPBOARD_COPY);
inputHandler.addKeyBinding("S+INSERT", InputHandler.CLIPBOARD_PASTE);
inputHandler.addKeyBinding("S+DELETE", InputHandler.CLIPBOARD_CUT);
}
// disabling for 0122, not sure what this does
//inputHandler.addKeyBinding("C+\\", InputHandler.TOGGLE_RECT);
// for 0122, these have been changed for better compatability
// HOME and END now mean the beginning/end of the document
if (Base.isMacOS()) {
inputHandler.addKeyBinding("HOME", InputHandler.DOCUMENT_HOME);
inputHandler.addKeyBinding("END", InputHandler.DOCUMENT_END);
inputHandler.addKeyBinding("S+HOME", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("S+END", InputHandler.SELECT_DOC_END);
} else {
// for 0123 added the proper windows defaults
inputHandler.addKeyBinding("HOME", InputHandler.HOME);
inputHandler.addKeyBinding("END", InputHandler.END);
inputHandler.addKeyBinding("S+HOME", InputHandler.SELECT_HOME);
inputHandler.addKeyBinding("S+END", InputHandler.SELECT_END);
inputHandler.addKeyBinding("C+HOME", InputHandler.DOCUMENT_HOME);
inputHandler.addKeyBinding("C+END", InputHandler.DOCUMENT_END);
inputHandler.addKeyBinding("CS+HOME", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("CS+END", InputHandler.SELECT_DOC_END);
}
if (Base.isMacOS()) {
inputHandler.addKeyBinding("M+LEFT", InputHandler.HOME);
inputHandler.addKeyBinding("M+RIGHT", InputHandler.END);
inputHandler.addKeyBinding("MS+LEFT", InputHandler.SELECT_HOME); // 0122
inputHandler.addKeyBinding("MS+RIGHT", InputHandler.SELECT_END); // 0122
} else {
inputHandler.addKeyBinding("C+LEFT", InputHandler.HOME); // 0122
inputHandler.addKeyBinding("C+RIGHT", InputHandler.END); // 0122
inputHandler.addKeyBinding("CS+HOME", InputHandler.SELECT_HOME); // 0122
inputHandler.addKeyBinding("CS+END", InputHandler.SELECT_END); // 0122
}
inputHandler.addKeyBinding("PAGE_UP", InputHandler.PREV_PAGE);
inputHandler.addKeyBinding("PAGE_DOWN", InputHandler.NEXT_PAGE);
inputHandler.addKeyBinding("S+PAGE_UP", InputHandler.SELECT_PREV_PAGE);
inputHandler.addKeyBinding("S+PAGE_DOWN", InputHandler.SELECT_NEXT_PAGE);
inputHandler.addKeyBinding("LEFT", InputHandler.PREV_CHAR);
inputHandler.addKeyBinding("S+LEFT", InputHandler.SELECT_PREV_CHAR);
inputHandler.addKeyBinding(mod + "+LEFT", InputHandler.PREV_WORD);
inputHandler.addKeyBinding(mod + "S+LEFT", InputHandler.SELECT_PREV_WORD);
inputHandler.addKeyBinding("RIGHT", InputHandler.NEXT_CHAR);
inputHandler.addKeyBinding("S+RIGHT", InputHandler.SELECT_NEXT_CHAR);
inputHandler.addKeyBinding(mod + "+RIGHT", InputHandler.NEXT_WORD);
inputHandler.addKeyBinding(mod + "S+RIGHT", InputHandler.SELECT_NEXT_WORD);
inputHandler.addKeyBinding("UP", InputHandler.PREV_LINE);
inputHandler.addKeyBinding(mod + "+UP", InputHandler.PREV_LINE); // p5
inputHandler.addKeyBinding("S+UP", InputHandler.SELECT_PREV_LINE);
inputHandler.addKeyBinding("DOWN", InputHandler.NEXT_LINE);
inputHandler.addKeyBinding(mod + "+DOWN", InputHandler.NEXT_LINE); // p5
inputHandler.addKeyBinding("S+DOWN", InputHandler.SELECT_NEXT_LINE);
inputHandler.addKeyBinding("MS+UP", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("CS+UP", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("MS+DOWN", InputHandler.SELECT_DOC_END);
inputHandler.addKeyBinding("CS+DOWN", InputHandler.SELECT_DOC_END);
inputHandler.addKeyBinding(mod + "+ENTER", InputHandler.REPEAT);
document = new SyntaxDocument();
editable = true;
electricScroll = 3;
cols = 80;
rows = 15;
// moved from SyntaxUtilities
//DEFAULTS.styles = SyntaxUtilities.getDefaultSyntaxStyles();
styles = new SyntaxStyle[Token.ID_COUNT];
// comments
styles[Token.COMMENT1] = Theme.getStyle("comment1");
styles[Token.COMMENT2] = Theme.getStyle("comment2");
// abstract, final, private
styles[Token.KEYWORD1] = Theme.getStyle("keyword1");
// beginShape, point, line
styles[Token.KEYWORD2] = Theme.getStyle("keyword2");
// byte, char, short, color
styles[Token.KEYWORD3] = Theme.getStyle("keyword3");
// constants: null, true, this, RGB, TWO_PI
styles[Token.LITERAL1] = Theme.getStyle("literal1");
// p5 built in variables: mouseX, width, pixels
styles[Token.LITERAL2] = Theme.getStyle("literal2");
// ??
styles[Token.LABEL] = Theme.getStyle("label");
// + - = /
styles[Token.OPERATOR] = Theme.getStyle("operator");
// area that's not in use by the text (replaced with tildes)
styles[Token.INVALID] = Theme.getStyle("invalid");
// moved from TextAreaPainter
font = Preferences.getFont("editor.font");
fgcolor = Theme.getColor("editor.fgcolor");
bgcolor = Theme.getColor("editor.bgcolor");
caretVisible = true;
caretBlinks = Preferences.getBoolean("editor.caret.blink");
caretColor = Theme.getColor("editor.caret.color");
selectionColor = Theme.getColor("editor.selection.color");
lineHighlight =
Theme.getBoolean("editor.linehighlight");
lineHighlightColor =
Theme.getColor("editor.linehighlight.color");
bracketHighlight =
Theme.getBoolean("editor.brackethighlight");
bracketHighlightColor =
Theme.getColor("editor.brackethighlight.color");
eolMarkers = Theme.getBoolean("editor.eolmarkers");
eolMarkerColor = Theme.getColor("editor.eolmarkers.color");
paintInvalid = Theme.getBoolean("editor.invalid");
}
| public PdeTextAreaDefaults() {
inputHandler = new DefaultInputHandler();
//inputHandler.addDefaultKeyBindings(); // 0122
// use option on mac for things that are ctrl on windows/linux
String mod = Base.isMacOS() ? "A" : "C";
// right now, ctrl-up/down is select up/down, but mod should be
// used instead, because the mac expects it to be option(alt)
inputHandler.addKeyBinding("BACK_SPACE", InputHandler.BACKSPACE);
inputHandler.addKeyBinding("DELETE", InputHandler.DELETE);
//inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.BACKSPACE);
// for 0122, shift-backspace is delete
inputHandler.addKeyBinding("S+BACK_SPACE", InputHandler.DELETE);
inputHandler.addKeyBinding("S+DELETE", InputHandler.DELETE);
// the following two were changing for 0122 for better mac/pc compatability
inputHandler.addKeyBinding(mod+"+BACK_SPACE", InputHandler.BACKSPACE_WORD);
inputHandler.addKeyBinding(mod+"+DELETE", InputHandler.DELETE_WORD);
// handled by listener, don't bother here
//inputHandler.addKeyBinding("ENTER", InputHandler.INSERT_BREAK);
//inputHandler.addKeyBinding("TAB", InputHandler.INSERT_TAB);
inputHandler.addKeyBinding("INSERT", InputHandler.OVERWRITE);
// http://dev.processing.org/bugs/show_bug.cgi?id=162
// added for 0176, though the bindings do not appear relevant for osx
if (!Base.isMacOS()) {
inputHandler.addKeyBinding("C+INSERT", InputHandler.CLIPBOARD_COPY);
inputHandler.addKeyBinding("S+INSERT", InputHandler.CLIPBOARD_PASTE);
inputHandler.addKeyBinding("S+DELETE", InputHandler.CLIPBOARD_CUT);
}
// disabling for 0122, not sure what this does
//inputHandler.addKeyBinding("C+\\", InputHandler.TOGGLE_RECT);
// for 0122, these have been changed for better compatibility
// HOME and END now mean the beginning/end of the document
if (Base.isMacOS()) {
inputHandler.addKeyBinding("HOME", InputHandler.DOCUMENT_HOME);
inputHandler.addKeyBinding("END", InputHandler.DOCUMENT_END);
inputHandler.addKeyBinding("S+HOME", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("S+END", InputHandler.SELECT_DOC_END);
} else {
// for 0123 added the proper windows defaults
inputHandler.addKeyBinding("HOME", InputHandler.HOME);
inputHandler.addKeyBinding("END", InputHandler.END);
inputHandler.addKeyBinding("S+HOME", InputHandler.SELECT_HOME);
inputHandler.addKeyBinding("S+END", InputHandler.SELECT_END);
inputHandler.addKeyBinding("C+HOME", InputHandler.DOCUMENT_HOME);
inputHandler.addKeyBinding("C+END", InputHandler.DOCUMENT_END);
inputHandler.addKeyBinding("CS+HOME", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("CS+END", InputHandler.SELECT_DOC_END);
}
if (Base.isMacOS()) {
inputHandler.addKeyBinding("M+LEFT", InputHandler.HOME);
inputHandler.addKeyBinding("M+RIGHT", InputHandler.END);
inputHandler.addKeyBinding("MS+LEFT", InputHandler.SELECT_HOME); // 0122
inputHandler.addKeyBinding("MS+RIGHT", InputHandler.SELECT_END); // 0122
} else {
inputHandler.addKeyBinding("C+LEFT", InputHandler.HOME); // 0122
inputHandler.addKeyBinding("C+RIGHT", InputHandler.END); // 0122
inputHandler.addKeyBinding("CS+HOME", InputHandler.SELECT_HOME); // 0122
inputHandler.addKeyBinding("CS+END", InputHandler.SELECT_END); // 0122
}
inputHandler.addKeyBinding("PAGE_UP", InputHandler.PREV_PAGE);
inputHandler.addKeyBinding("PAGE_DOWN", InputHandler.NEXT_PAGE);
inputHandler.addKeyBinding("S+PAGE_UP", InputHandler.SELECT_PREV_PAGE);
inputHandler.addKeyBinding("S+PAGE_DOWN", InputHandler.SELECT_NEXT_PAGE);
inputHandler.addKeyBinding("LEFT", InputHandler.PREV_CHAR);
inputHandler.addKeyBinding("S+LEFT", InputHandler.SELECT_PREV_CHAR);
inputHandler.addKeyBinding(mod + "+LEFT", InputHandler.PREV_WORD);
inputHandler.addKeyBinding(mod + "S+LEFT", InputHandler.SELECT_PREV_WORD);
inputHandler.addKeyBinding("RIGHT", InputHandler.NEXT_CHAR);
inputHandler.addKeyBinding("S+RIGHT", InputHandler.SELECT_NEXT_CHAR);
inputHandler.addKeyBinding(mod + "+RIGHT", InputHandler.NEXT_WORD);
inputHandler.addKeyBinding(mod + "S+RIGHT", InputHandler.SELECT_NEXT_WORD);
inputHandler.addKeyBinding("UP", InputHandler.PREV_LINE);
inputHandler.addKeyBinding(mod + "+UP", InputHandler.PREV_LINE); // p5
inputHandler.addKeyBinding("S+UP", InputHandler.SELECT_PREV_LINE);
inputHandler.addKeyBinding("DOWN", InputHandler.NEXT_LINE);
inputHandler.addKeyBinding(mod + "+DOWN", InputHandler.NEXT_LINE); // p5
inputHandler.addKeyBinding("S+DOWN", InputHandler.SELECT_NEXT_LINE);
inputHandler.addKeyBinding("MS+UP", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("CS+UP", InputHandler.SELECT_DOC_HOME);
inputHandler.addKeyBinding("MS+DOWN", InputHandler.SELECT_DOC_END);
inputHandler.addKeyBinding("CS+DOWN", InputHandler.SELECT_DOC_END);
inputHandler.addKeyBinding(mod + "+ENTER", InputHandler.REPEAT);
document = new SyntaxDocument();
editable = true;
electricScroll = 3;
cols = 80;
rows = 15;
// moved from SyntaxUtilities
//DEFAULTS.styles = SyntaxUtilities.getDefaultSyntaxStyles();
styles = new SyntaxStyle[Token.ID_COUNT];
// comments
styles[Token.COMMENT1] = Theme.getStyle("comment1");
styles[Token.COMMENT2] = Theme.getStyle("comment2");
// abstract, final, private
styles[Token.KEYWORD1] = Theme.getStyle("keyword1");
// beginShape, point, line
styles[Token.KEYWORD2] = Theme.getStyle("keyword2");
// byte, char, short, color
styles[Token.KEYWORD3] = Theme.getStyle("keyword3");
// constants: null, true, this, RGB, TWO_PI
styles[Token.LITERAL1] = Theme.getStyle("literal1");
// p5 built in variables: mouseX, width, pixels
styles[Token.LITERAL2] = Theme.getStyle("literal2");
// ??
styles[Token.LABEL] = Theme.getStyle("label");
// + - = /
styles[Token.OPERATOR] = Theme.getStyle("operator");
// area that's not in use by the text (replaced with tildes)
styles[Token.INVALID] = Theme.getStyle("invalid");
// moved from TextAreaPainter
font = Preferences.getFont("editor.font");
fgcolor = Theme.getColor("editor.fgcolor");
bgcolor = Theme.getColor("editor.bgcolor");
caretVisible = true;
caretBlinks = Preferences.getBoolean("editor.caret.blink");
caretColor = Theme.getColor("editor.caret.color");
selectionColor = Theme.getColor("editor.selection.color");
lineHighlight =
Theme.getBoolean("editor.linehighlight");
lineHighlightColor =
Theme.getColor("editor.linehighlight.color");
bracketHighlight =
Theme.getBoolean("editor.brackethighlight");
bracketHighlightColor =
Theme.getColor("editor.brackethighlight.color");
eolMarkers = Theme.getBoolean("editor.eolmarkers");
eolMarkerColor = Theme.getColor("editor.eolmarkers.color");
paintInvalid = Theme.getBoolean("editor.invalid");
}
|
diff --git a/srcj/com/sun/electric/database/hierarchy/RTNode.java b/srcj/com/sun/electric/database/hierarchy/RTNode.java
index 1a08e1f5e..3784bc868 100644
--- a/srcj/com/sun/electric/database/hierarchy/RTNode.java
+++ b/srcj/com/sun/electric/database/hierarchy/RTNode.java
@@ -1,794 +1,794 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: RTNode.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.database.hierarchy;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.Geometric;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
/**
* The RTNode class implements R-Trees.
* R-trees come from this paper: Guttman, Antonin, "R-Trees: A Dynamic Index Structure for Spatial Searching",
* ACM SIGMOD, 14:2, 47-57, June 1984.
* <P>
* R-trees are height-balanced trees in which all leaves are at the same depth and contain Geometric objects (the
* NodeInsts and ArcInsts). Entries higher in the tree store boundary information that tightly encloses the leaves
* below. All nodes hold from M to 2M entries, where M is 4. The bounding boxes of two entries may
* overlap, which allows arbitrary structures to be represented. A search for a point or an area is a simple
* recursive walk through the tree to collect appropriate leaf nodes. Insertion and deletion, however, are more
* complex operations. The figure below illustrates how R-Trees work:
* <P>
* <CENTER><IMG SRC="doc-files/Geometric-1.gif"></CENTER>
*/
class RTNode
{
/** lower bound on R-tree node size */ private static final int MINRTNODESIZE = 4;
/** upper bound on R-tree node size */ private static final int MAXRTNODESIZE = (MINRTNODESIZE*2);
/** bounds of this node and its children */ private Rectangle2D bounds;
/** number of children */ private int total;
/** children */ private Object [] pointers;
/** nonzero if children are terminal */ private boolean flag;
/** parent node */ private RTNode parent;
private RTNode()
{
pointers = new Object[MAXRTNODESIZE];
bounds = new Rectangle2D.Double();
}
/** Method to get the number of children of this RTNode. */
private int getTotal() { return total; }
/** Method to set the number of children of this RTNode. */
private void setTotal(int total) { this.total = total; }
/** Method to get the parent of this RTNode. */
private RTNode getParent() { return parent; }
/** Method to set the parent of this RTNode. */
private void setParent(RTNode parent) { this.parent = parent; }
/** Method to get the number of children of this RTNode. */
private Object getChild(int index) { return pointers[index]; }
/** Method to set the number of children of this RTNode. */
private void setChild(int index, Object obj) { this.pointers[index] = obj; }
/** Method to get the leaf/branch flag of this RTNode. */
private boolean getFlag() { return flag; }
/** Method to set the leaf/branch flag of this RTNode. */
private void setFlag(boolean flag) { this.flag = flag; }
/** Method to get the bounds of this RTNode. */
private Rectangle2D getBounds() { return bounds; }
/** Method to set the bounds of this RTNode. */
private void setBounds(Rectangle2D bounds) { this.bounds.setRect(bounds); }
/** Method to extend the bounds of this RTNode by "bounds". */
private void unionBounds(Rectangle2D bounds) { Rectangle2D.union(this.bounds, bounds, this.bounds); }
/**
* Method to create the top-level R-Tree structure for a new Cell.
* @return an RTNode object that is empty.
*/
static RTNode makeTopLevel()
{
RTNode top = new RTNode();
top.total = 0;
top.flag = true;
top.parent = null;
return top;
}
/**
* Method to link this Geometric into the R-tree of its parent Cell.
* @param cell the parent Cell.
*/
static void linkGeom(Cell cell, Geometric geom)
{
// find the bottom-level branch (a RTNode with leafs) that would expand least by adding this Geometric
RTNode rtn = cell.getRTree();
if (rtn == null) return;
for(;;)
{
// if R-tree node contains primitives, exit loop
if (rtn.getFlag()) break;
// find sub-node that would expand the least
double bestExpand = 0;
int bestSubNode = 0;
for(int i=0; i<rtn.getTotal(); i++)
{
// get bounds and area of sub-node
RTNode subrtn = (RTNode)rtn.getChild(i);
Rectangle2D bounds = subrtn.getBounds();
double area = bounds.getWidth() * bounds.getHeight();
// get area of sub-node with new element
Rectangle2D newUnion = new Rectangle2D.Double();
Rectangle2D.union(geom.getBounds(), bounds, newUnion);
double newArea = newUnion.getWidth() * newUnion.getHeight();
// accumulate the least expansion
double expand = newArea - area;
// remember the child that expands the least
if (i != 0 && expand > bestExpand) continue;
bestExpand = expand;
bestSubNode = i;
}
// recurse down to sub-node that expanded least
rtn = (RTNode)rtn.getChild(bestSubNode);
}
// add this geometry element to the correct leaf R-tree node
rtn.addToRTNode(geom, cell);
}
/**
* Method to remove this geometry from the R-tree its parent cell.
* @param cell the parent Cell.
*/
static void unLinkGeom(Cell cell, Geometric geom)
{
// find this node in the tree
RTNode whichRTN = null;
int whichInd = 0;
RTNode rtn = cell.getRTree();
if (rtn == null) return;
Object[] result = rtn.findGeom(geom);
if (result != null)
{
whichRTN = (RTNode)result[0];
whichInd = ((Integer)result[1]).intValue();
} else
{
result = (cell.getRTree()).findGeomAnywhere(geom);
if (result == null)
{
System.out.println("Internal error: " + cell + " cannot find " + geom + " in R-Tree...Rebuilding R-Tree");
cell.setRTree(makeTopLevel());
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
linkGeom(cell, (Geometric)it.next());
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
linkGeom(cell, (Geometric)it.next());
return;
}
whichRTN = (RTNode)result[0];
whichInd = ((Integer)result[1]).intValue();
System.out.println("Internal warning: " + geom + " not in proper R-Tree location in " + cell);
}
// delete geom from this R-tree node
whichRTN.removeRTNode(whichInd, cell);
}
private static int branchCount;
/**
* Debugging method to print this R-Tree.
* @param indent the level of the tree, for proper indentation.
*/
public void printRTree(int indent)
{
if (indent == 0) branchCount = 0;
StringBuffer line = new StringBuffer();
for(int i=0; i<indent; i++) line.append(" ");
line.append("RTNode");
if (flag)
{
branchCount++;
line.append(" NUMBER " + branchCount);
}
line.append(" X(" + bounds.getMinX() + "-" + bounds.getMaxX() + ") Y(" + bounds.getMinY() + "-" + bounds.getMaxY() + ") has " +
total + " children:");
System.out.println(line);
for(int j=0; j<total; j++)
{
if (flag)
{
line = new StringBuffer();
for(int i=0; i<indent+3; i++) line.append(" ");
Geometric child = (Geometric)getChild(j);
Rectangle2D childBounds = child.getBounds();
line.append("Child X(" + childBounds.getMinX() + "-" + childBounds.getMaxX() + ") Y(" +
childBounds.getMinY() + "-" + childBounds.getMaxY() + ") is " + child.describe(true));
System.out.println(line);
} else
{
((RTNode)getChild(j)).printRTree(indent+3);
}
}
}
/**
* Method to check the validity of an RTree node.
* @param level the level of the node in the tree (for error reporting purposes).
* @param cell the Cell on which this node resides.
*/
public void checkRTree(int level, Cell cell)
{
Rectangle2D localBounds = new Rectangle2D.Double();
if (total == 0)
{
localBounds.setRect(0, 0, 0, 0);
} else
{
localBounds.setRect(getBBox(0));
for(int i=1; i<total; i++)
Rectangle2D.union(localBounds, getBBox(i), localBounds);
}
if (!localBounds.equals(bounds))
{
if (Math.abs(localBounds.getMinX() - bounds.getMinX()) >= DBMath.getEpsilon() ||
Math.abs(localBounds.getMinY() - bounds.getMinY()) >= DBMath.getEpsilon() ||
Math.abs(localBounds.getWidth() - bounds.getWidth()) >= DBMath.getEpsilon() ||
Math.abs(localBounds.getHeight() - bounds.getHeight()) >= DBMath.getEpsilon())
{
System.out.println("Tree of "+cell.describe(true)+" at level "+level+" has bounds "+localBounds+" but stored bounds are "+bounds);
for(int i=0; i<total; i++)
System.out.println(" ---Child "+i+" is "+ getBBox(i));
}
}
if (!flag)
{
for(int j=0; j<total; j++)
{
((RTNode)getChild(j)).checkRTree(level+1, cell);
}
}
}
/**
* Method to get the bounding box of child "child" of this R-tree node.
*/
private Rectangle2D getBBox(int child)
{
if (flag)
{
Geometric geom = (Geometric)pointers[child];
// @TODO: GVG if pointers is null (bad file read in), we get an exception
return geom.getBounds();
} else
{
RTNode subrtn = (RTNode)pointers[child];
return subrtn.getBounds();
}
}
/**
* Method to recompute the bounds of this R-tree node.
*/
private void figBounds()
{
if (total == 0)
{
bounds.setRect(0, 0, 0, 0);
return;
}
bounds.setRect(getBBox(0));
for(int i=1; i<total; i++)
unionBounds(getBBox(i));
}
/**
* Method to add object "rtnInsert" to this R-tree node, which is in cell "cell". Method may have to
* split the node and recurse up the tree
*/
private void addToRTNode(Object rtnInsert, Cell cell)
{
// see if there is room in the R-tree node
if (getTotal() >= MAXRTNODESIZE)
{
// no room: copy list to temp one
RTNode temp = new RTNode();
temp.setTotal(getTotal());
temp.setFlag(getFlag());
for(int i=0; i<getTotal(); i++)
temp.setChild(i, getChild(i));
// find the element farthest from new object
Rectangle2D bounds;
if (rtnInsert instanceof Geometric)
{
Geometric geom = (Geometric)rtnInsert;
bounds = geom.getBounds();
} else
{
RTNode subrtn = (RTNode)rtnInsert;
bounds = subrtn.getBounds();
}
Point2D thisCenter = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
double newDist = 0;
int newN = 0;
for(int i=0; i<temp.getTotal(); i++)
{
Rectangle2D thisv = temp.getBBox(i);
double dist = thisCenter.distance(thisv.getCenterX(), thisv.getCenterY());
if (dist >= newDist)
{
newDist = dist;
newN = i;
}
}
// now find element farthest from "newN"
bounds = temp.getBBox(newN);
thisCenter = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
double oldDist = 0;
int oldN = 0;
if (oldN == newN) oldN++;
for(int i=0; i<temp.getTotal(); i++)
{
if (i == newN) continue;
Rectangle2D thisv = temp.getBBox(i);
double dist = thisCenter.distance(thisv.getCenterX(), thisv.getCenterY());
if (dist >= oldDist)
{
oldDist = dist;
oldN = i;
}
}
// allocate a new R-tree node
RTNode newrtn = new RTNode();
newrtn.setFlag(getFlag());
newrtn.setParent(getParent());
// put the first seed element into the new RTree
Object obj = temp.getChild(newN);
temp.setChild(newN, null);
newrtn.setChild(0, obj);
newrtn.setTotal(1);
if (!newrtn.getFlag()) ((RTNode)obj).setParent(newrtn);
Rectangle2D newBounds = newrtn.getBBox(0);
newrtn.setBounds(newBounds);
double newArea = newBounds.getWidth() * newBounds.getHeight();
// initialize the old R-tree node and put in the other seed element
obj = temp.getChild(oldN);
temp.setChild(oldN, null);
setChild(0, obj);
for(int i=1; i<getTotal(); i++) setChild(i, null);
setTotal(1);
if (!getFlag()) ((RTNode)obj).setParent(this);
Rectangle2D oldBounds = getBBox(0);
setBounds(oldBounds);
double oldArea = oldBounds.getWidth() * oldBounds.getHeight();
// cluster the rest of the nodes
for(;;)
{
// search for a cluster about each new node
int bestNewNode = -1, bestOldNode = -1;
double bestNewExpand = 0, bestOldExpand = 0;
for(int i=0; i<temp.getTotal(); i++)
{
obj = temp.getChild(i);
if (obj == null) continue;
bounds = temp.getBBox(i);
Rectangle2D newUnion = new Rectangle2D.Double();
Rectangle2D oldUnion = new Rectangle2D.Double();
Rectangle2D.union(newBounds, bounds, newUnion);
Rectangle2D.union(oldBounds, bounds, oldUnion);
double newAreaPlus = newUnion.getWidth() * newUnion.getHeight();
double oldAreaPlus = oldUnion.getWidth() * oldUnion.getHeight();
// remember the child that expands the new node the least
if (bestNewNode < 0 || newAreaPlus-newArea < bestNewExpand)
{
bestNewExpand = newAreaPlus-newArea;
bestNewNode = i;
}
// remember the child that expands the old node the least
if (bestOldNode < 0 || oldAreaPlus-oldArea < bestOldExpand)
{
bestOldExpand = oldAreaPlus-oldArea;
bestOldNode = i;
}
}
// if there were no nodes added, all have been clustered
if (bestNewNode == -1 && bestOldNode == -1) break;
// if both selected the same object, select another "old node"
if (bestNewNode == bestOldNode)
{
bestOldNode = -1;
for(int i=0; i<temp.getTotal(); i++)
{
if (i == bestNewNode) continue;
obj = temp.getChild(i);
if (obj == null) continue;
bounds = temp.getBBox(i);
Rectangle2D oldUnion = new Rectangle2D.Double();
Rectangle2D.union(oldBounds, bounds, oldUnion);
double oldAreaPlus = oldUnion.getWidth() * oldUnion.getHeight();
// remember the child that expands the old node the least
if (bestOldNode < 0 || oldAreaPlus-oldArea < bestOldExpand)
{
bestOldExpand = oldAreaPlus-oldArea;
bestOldNode = i;
}
}
}
// add to the proper "old node" to the old node cluster
if (bestOldNode != -1)
{
// add this node to "rtn"
obj = temp.getChild(bestOldNode);
temp.setChild(bestOldNode, null);
int curPos = getTotal();
setChild(curPos, obj);
setTotal(curPos+1);
if (!getFlag()) ((RTNode)obj).setParent(this);
unionBounds(getBBox(curPos));
oldBounds = getBounds();
oldArea = oldBounds.getWidth() * oldBounds.getHeight();
}
// add to proper "new node" to the new node cluster
if (bestNewNode != -1)
{
// add this node to "newrtn"
obj = temp.getChild(bestNewNode);
temp.setChild(bestNewNode, null);
int curPos = newrtn.getTotal();
newrtn.setChild(curPos, obj);
newrtn.setTotal(curPos+1);
if (!newrtn.getFlag()) ((RTNode)obj).setParent(newrtn);
newrtn.unionBounds(newrtn.getBBox(curPos));
newBounds = newrtn.getBounds();
newArea = newBounds.getWidth() * newBounds.getHeight();
}
}
// sensibility check
if (temp.getTotal() != getTotal() + newrtn.getTotal())
System.out.println("R-trees: " + temp.getTotal() + " nodes split to " +
getTotal()+ " and " + newrtn.getTotal() + "!");
// now recursively insert this new element up the tree
if (getParent() == null)
{
// at top of tree: create a new level
RTNode newroot = new RTNode();
newroot.setTotal(2);
newroot.setChild(0, this);
newroot.setChild(1, newrtn);
newroot.setFlag(false);
newroot.setParent(null);
setParent(newroot);
newrtn.setParent(newroot);
newroot.figBounds();
cell.setRTree(newroot);
} else
{
// first recompute bounding box of R-tree nodes up the tree
for(RTNode r = getParent(); r != null; r = r.getParent()) r.figBounds();
// now add the new node up the tree
getParent().addToRTNode(newrtn, cell);
}
}
// now add "rtnInsert" to the R-tree node
int curPos = getTotal();
setChild(curPos, rtnInsert);
setTotal(curPos+1);
// compute the new bounds
Rectangle2D bounds = getBBox(curPos);
if (getTotal() == 1 && getParent() == null)
{
// special case when adding the first node in a cell
setBounds(bounds);
return;
}
// recursively update node sizes
RTNode climb = this;
for(;;)
{
climb.unionBounds(bounds);
if (climb.getParent() == null) break;
climb = climb.getParent();
}
// now check the RTree
- checkRTree(0, cell);
+// checkRTree(0, cell);
}
/**
* Method to remove entry "ind" from this R-tree node in cell "cell"
*/
private void removeRTNode(int ind, Cell cell)
{
// delete entry from this R-tree node
int j = 0;
for(int i=0; i<getTotal(); i++)
if (i != ind) setChild(j++, getChild(i));
setTotal(j);
// see if node is now too small
if (getTotal() < MINRTNODESIZE)
{
// if recursed to top, shorten R-tree
RTNode prtn = getParent();
if (prtn == null)
{
// if tree has no hierarchy, allow short node
if (getFlag())
{
// compute correct bounds of the top node
figBounds();
return;
}
// save all top-level entries
RTNode temp = new RTNode();
temp.setTotal(getTotal());
temp.setFlag(true);
for(int i=0; i<getTotal(); i++)
temp.setChild(i, getChild(i));
// erase top level
setTotal(0);
setFlag(true);
// reinsert all data
for(int i=0; i<temp.getTotal(); i++) ((RTNode)temp.getChild(i)).reInsert(cell);
return;
}
// node has too few entries, must delete it and reinsert members
int found = -1;
for(int i=0; i<prtn.getTotal(); i++)
if (prtn.getChild(i) == this) { found = i; break; }
if (found < 0) System.out.println("R-trees: cannot find entry in parent");
// remove this entry from its parent
prtn.removeRTNode(found, cell);
// reinsert the entries
reInsert(cell);
return;
}
// recompute bounding box of this R-tree node and all up the tree
RTNode climb = this;
for(;;)
{
climb.figBounds();
if (climb.getParent() == null) break;
climb = climb.getParent();
}
}
/**
* Method to reinsert the tree of nodes below this RTNode into cell "cell".
*/
private void reInsert(Cell cell)
{
if (getFlag())
{
for(int i=0; i<getTotal(); i++) linkGeom(cell, (Geometric)getChild(i));
} else
{
for(int i=0; i<getTotal(); i++)
((RTNode)getChild(i)).reInsert(cell);
}
}
/**
* Method to find the location of geometry module "geom" in the R-tree
* below this. The subnode that contains this module is placed in "subrtn"
* and the index in that subnode is placed in "subind". The method returns
* null if it is unable to find the geometry module.
*/
private Object [] findGeom(Geometric geom)
{
// if R-tree node contains primitives, search for direct hit
if (getFlag())
{
for(int i=0; i<getTotal(); i++)
{
if (getChild(i) == geom)
{
Object [] retObj = new Object[2];
retObj[0] = this;
retObj[1] = new Integer(i);
return retObj;
}
}
return null;
}
// recurse on all sub-nodes that would contain this geometry module
Rectangle2D geomBounds = geom.getBounds();
for(int i=0; i<getTotal(); i++)
{
// get bounds and area of sub-node
Rectangle2D bounds = getBBox(i);
if (bounds.getMaxX() < geomBounds.getMinX()-DBMath.getEpsilon()) continue;
if (bounds.getMinX() > geomBounds.getMaxX()+DBMath.getEpsilon()) continue;
if (bounds.getMaxY() < geomBounds.getMinY()-DBMath.getEpsilon()) continue;
if (bounds.getMinY() > geomBounds.getMaxY()+DBMath.getEpsilon()) continue;
Object [] subRet = ((RTNode)getChild(i)).findGeom(geom);
if (subRet != null) return subRet;
}
return null;
}
/**
* Method to find the location of geometry module "geom" anywhere in the R-tree
* at "rtn". The subnode that contains this module is placed in "subrtn"
* and the index in that subnode is placed in "subind". The method returns
* false if it is unable to find the geometry module.
*/
private Object [] findGeomAnywhere(Geometric geom)
{
// if R-tree node contains primitives, search for direct hit
if (getFlag())
{
for(int i=0; i<getTotal(); i++)
{
if (getChild(i) == geom)
{
Object [] retVal = new Object[2];
retVal[0] = this;
retVal[1] = new Integer(i);
return retVal;
}
}
return null;
}
// recurse on all sub-nodes
for(int i=0; i<getTotal(); i++)
{
Object [] retVal = ((RTNode)getChild(i)).findGeomAnywhere(geom);
if (retVal != null) return retVal;
}
return null;
}
/**
* Class to search a given area of a Cell.
* This class acts like an Iterator, returning Geometric objects that are inside the selected area.
* <P>
* For example, here is the code to search cell "myCell" in the area "bounds" (in database coordinates):
* <P>
* <PRE>
* for(RTNode.Search sea = <B>new RTNode.Search(bounds, cell)</B>; sea.hasNext(); )
* {
* Geometric geom = (Geometric)sea.next();
* if (geom instanceof NodeInst)
* {
* NodeInst ni = (NodeInst)geom;
* // process NodeInst ni in the selected area
* } else
* {
* ArcInst ai = (ArcInst)geom;
* // process ArcInst ai in the selected area
* }
* }
* </PRE>
*/
static class Search implements Iterator<Geometric>
{
/** maximum depth of search */ private static final int MAXDEPTH = 100;
/** current depth of search */ private int depth;
/** RTNode stack of search */ private RTNode [] rtn;
/** index stack of search */ private int [] position;
/** desired search bounds */ private Rectangle2D searchBounds;
/** the next object to return */ private Geometric nextObj;
Search(Rectangle2D bounds, Cell cell)
{
this.depth = 0;
this.rtn = new RTNode[MAXDEPTH];
this.position = new int[MAXDEPTH];
this.rtn[0] = cell.getRTree();
this.searchBounds = new Rectangle2D.Double();
this.searchBounds.setRect(bounds);
this.nextObj = null;
}
/**
* Method to return the next object in the bounds of the search.
* @return the next object found. Returns null when all objects have been reported.
*/
private Geometric nextObject()
{
for(;;)
{
RTNode rtnode = rtn[depth];
int i = position[depth]++;
if (i < rtnode.getTotal())
{
Rectangle2D nodeBounds = rtnode.getBBox(i);
if (nodeBounds.getMaxX() < searchBounds.getMinX()) continue;
if (nodeBounds.getMinX() > searchBounds.getMaxX()) continue;
if (nodeBounds.getMaxY() < searchBounds.getMinY()) continue;
if (nodeBounds.getMinY() > searchBounds.getMaxY()) continue;
if (rtnode.getFlag()) return((Geometric)rtnode.getChild(i));
// look down the hierarchy
if (depth >= MAXDEPTH-1)
{
System.out.println("R-trees: search too deep");
continue;
}
depth++;
rtn[depth] = (RTNode)rtnode.getChild(i);
position[depth] = 0;
} else
{
// pop up the hierarchy
if (depth == 0) break;
depth--;
}
}
return null;
}
public boolean hasNext()
{
if (nextObj == null)
{
nextObj = nextObject();
}
return nextObj != null;
}
public Geometric next()
{
if (nextObj != null)
{
Geometric ret = nextObj;
nextObj = null;
return ret;
}
return nextObject();
}
public void remove() { throw new UnsupportedOperationException("Search.remove()"); };
}
}
| true | true | private void addToRTNode(Object rtnInsert, Cell cell)
{
// see if there is room in the R-tree node
if (getTotal() >= MAXRTNODESIZE)
{
// no room: copy list to temp one
RTNode temp = new RTNode();
temp.setTotal(getTotal());
temp.setFlag(getFlag());
for(int i=0; i<getTotal(); i++)
temp.setChild(i, getChild(i));
// find the element farthest from new object
Rectangle2D bounds;
if (rtnInsert instanceof Geometric)
{
Geometric geom = (Geometric)rtnInsert;
bounds = geom.getBounds();
} else
{
RTNode subrtn = (RTNode)rtnInsert;
bounds = subrtn.getBounds();
}
Point2D thisCenter = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
double newDist = 0;
int newN = 0;
for(int i=0; i<temp.getTotal(); i++)
{
Rectangle2D thisv = temp.getBBox(i);
double dist = thisCenter.distance(thisv.getCenterX(), thisv.getCenterY());
if (dist >= newDist)
{
newDist = dist;
newN = i;
}
}
// now find element farthest from "newN"
bounds = temp.getBBox(newN);
thisCenter = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
double oldDist = 0;
int oldN = 0;
if (oldN == newN) oldN++;
for(int i=0; i<temp.getTotal(); i++)
{
if (i == newN) continue;
Rectangle2D thisv = temp.getBBox(i);
double dist = thisCenter.distance(thisv.getCenterX(), thisv.getCenterY());
if (dist >= oldDist)
{
oldDist = dist;
oldN = i;
}
}
// allocate a new R-tree node
RTNode newrtn = new RTNode();
newrtn.setFlag(getFlag());
newrtn.setParent(getParent());
// put the first seed element into the new RTree
Object obj = temp.getChild(newN);
temp.setChild(newN, null);
newrtn.setChild(0, obj);
newrtn.setTotal(1);
if (!newrtn.getFlag()) ((RTNode)obj).setParent(newrtn);
Rectangle2D newBounds = newrtn.getBBox(0);
newrtn.setBounds(newBounds);
double newArea = newBounds.getWidth() * newBounds.getHeight();
// initialize the old R-tree node and put in the other seed element
obj = temp.getChild(oldN);
temp.setChild(oldN, null);
setChild(0, obj);
for(int i=1; i<getTotal(); i++) setChild(i, null);
setTotal(1);
if (!getFlag()) ((RTNode)obj).setParent(this);
Rectangle2D oldBounds = getBBox(0);
setBounds(oldBounds);
double oldArea = oldBounds.getWidth() * oldBounds.getHeight();
// cluster the rest of the nodes
for(;;)
{
// search for a cluster about each new node
int bestNewNode = -1, bestOldNode = -1;
double bestNewExpand = 0, bestOldExpand = 0;
for(int i=0; i<temp.getTotal(); i++)
{
obj = temp.getChild(i);
if (obj == null) continue;
bounds = temp.getBBox(i);
Rectangle2D newUnion = new Rectangle2D.Double();
Rectangle2D oldUnion = new Rectangle2D.Double();
Rectangle2D.union(newBounds, bounds, newUnion);
Rectangle2D.union(oldBounds, bounds, oldUnion);
double newAreaPlus = newUnion.getWidth() * newUnion.getHeight();
double oldAreaPlus = oldUnion.getWidth() * oldUnion.getHeight();
// remember the child that expands the new node the least
if (bestNewNode < 0 || newAreaPlus-newArea < bestNewExpand)
{
bestNewExpand = newAreaPlus-newArea;
bestNewNode = i;
}
// remember the child that expands the old node the least
if (bestOldNode < 0 || oldAreaPlus-oldArea < bestOldExpand)
{
bestOldExpand = oldAreaPlus-oldArea;
bestOldNode = i;
}
}
// if there were no nodes added, all have been clustered
if (bestNewNode == -1 && bestOldNode == -1) break;
// if both selected the same object, select another "old node"
if (bestNewNode == bestOldNode)
{
bestOldNode = -1;
for(int i=0; i<temp.getTotal(); i++)
{
if (i == bestNewNode) continue;
obj = temp.getChild(i);
if (obj == null) continue;
bounds = temp.getBBox(i);
Rectangle2D oldUnion = new Rectangle2D.Double();
Rectangle2D.union(oldBounds, bounds, oldUnion);
double oldAreaPlus = oldUnion.getWidth() * oldUnion.getHeight();
// remember the child that expands the old node the least
if (bestOldNode < 0 || oldAreaPlus-oldArea < bestOldExpand)
{
bestOldExpand = oldAreaPlus-oldArea;
bestOldNode = i;
}
}
}
// add to the proper "old node" to the old node cluster
if (bestOldNode != -1)
{
// add this node to "rtn"
obj = temp.getChild(bestOldNode);
temp.setChild(bestOldNode, null);
int curPos = getTotal();
setChild(curPos, obj);
setTotal(curPos+1);
if (!getFlag()) ((RTNode)obj).setParent(this);
unionBounds(getBBox(curPos));
oldBounds = getBounds();
oldArea = oldBounds.getWidth() * oldBounds.getHeight();
}
// add to proper "new node" to the new node cluster
if (bestNewNode != -1)
{
// add this node to "newrtn"
obj = temp.getChild(bestNewNode);
temp.setChild(bestNewNode, null);
int curPos = newrtn.getTotal();
newrtn.setChild(curPos, obj);
newrtn.setTotal(curPos+1);
if (!newrtn.getFlag()) ((RTNode)obj).setParent(newrtn);
newrtn.unionBounds(newrtn.getBBox(curPos));
newBounds = newrtn.getBounds();
newArea = newBounds.getWidth() * newBounds.getHeight();
}
}
// sensibility check
if (temp.getTotal() != getTotal() + newrtn.getTotal())
System.out.println("R-trees: " + temp.getTotal() + " nodes split to " +
getTotal()+ " and " + newrtn.getTotal() + "!");
// now recursively insert this new element up the tree
if (getParent() == null)
{
// at top of tree: create a new level
RTNode newroot = new RTNode();
newroot.setTotal(2);
newroot.setChild(0, this);
newroot.setChild(1, newrtn);
newroot.setFlag(false);
newroot.setParent(null);
setParent(newroot);
newrtn.setParent(newroot);
newroot.figBounds();
cell.setRTree(newroot);
} else
{
// first recompute bounding box of R-tree nodes up the tree
for(RTNode r = getParent(); r != null; r = r.getParent()) r.figBounds();
// now add the new node up the tree
getParent().addToRTNode(newrtn, cell);
}
}
// now add "rtnInsert" to the R-tree node
int curPos = getTotal();
setChild(curPos, rtnInsert);
setTotal(curPos+1);
// compute the new bounds
Rectangle2D bounds = getBBox(curPos);
if (getTotal() == 1 && getParent() == null)
{
// special case when adding the first node in a cell
setBounds(bounds);
return;
}
// recursively update node sizes
RTNode climb = this;
for(;;)
{
climb.unionBounds(bounds);
if (climb.getParent() == null) break;
climb = climb.getParent();
}
// now check the RTree
checkRTree(0, cell);
}
| private void addToRTNode(Object rtnInsert, Cell cell)
{
// see if there is room in the R-tree node
if (getTotal() >= MAXRTNODESIZE)
{
// no room: copy list to temp one
RTNode temp = new RTNode();
temp.setTotal(getTotal());
temp.setFlag(getFlag());
for(int i=0; i<getTotal(); i++)
temp.setChild(i, getChild(i));
// find the element farthest from new object
Rectangle2D bounds;
if (rtnInsert instanceof Geometric)
{
Geometric geom = (Geometric)rtnInsert;
bounds = geom.getBounds();
} else
{
RTNode subrtn = (RTNode)rtnInsert;
bounds = subrtn.getBounds();
}
Point2D thisCenter = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
double newDist = 0;
int newN = 0;
for(int i=0; i<temp.getTotal(); i++)
{
Rectangle2D thisv = temp.getBBox(i);
double dist = thisCenter.distance(thisv.getCenterX(), thisv.getCenterY());
if (dist >= newDist)
{
newDist = dist;
newN = i;
}
}
// now find element farthest from "newN"
bounds = temp.getBBox(newN);
thisCenter = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
double oldDist = 0;
int oldN = 0;
if (oldN == newN) oldN++;
for(int i=0; i<temp.getTotal(); i++)
{
if (i == newN) continue;
Rectangle2D thisv = temp.getBBox(i);
double dist = thisCenter.distance(thisv.getCenterX(), thisv.getCenterY());
if (dist >= oldDist)
{
oldDist = dist;
oldN = i;
}
}
// allocate a new R-tree node
RTNode newrtn = new RTNode();
newrtn.setFlag(getFlag());
newrtn.setParent(getParent());
// put the first seed element into the new RTree
Object obj = temp.getChild(newN);
temp.setChild(newN, null);
newrtn.setChild(0, obj);
newrtn.setTotal(1);
if (!newrtn.getFlag()) ((RTNode)obj).setParent(newrtn);
Rectangle2D newBounds = newrtn.getBBox(0);
newrtn.setBounds(newBounds);
double newArea = newBounds.getWidth() * newBounds.getHeight();
// initialize the old R-tree node and put in the other seed element
obj = temp.getChild(oldN);
temp.setChild(oldN, null);
setChild(0, obj);
for(int i=1; i<getTotal(); i++) setChild(i, null);
setTotal(1);
if (!getFlag()) ((RTNode)obj).setParent(this);
Rectangle2D oldBounds = getBBox(0);
setBounds(oldBounds);
double oldArea = oldBounds.getWidth() * oldBounds.getHeight();
// cluster the rest of the nodes
for(;;)
{
// search for a cluster about each new node
int bestNewNode = -1, bestOldNode = -1;
double bestNewExpand = 0, bestOldExpand = 0;
for(int i=0; i<temp.getTotal(); i++)
{
obj = temp.getChild(i);
if (obj == null) continue;
bounds = temp.getBBox(i);
Rectangle2D newUnion = new Rectangle2D.Double();
Rectangle2D oldUnion = new Rectangle2D.Double();
Rectangle2D.union(newBounds, bounds, newUnion);
Rectangle2D.union(oldBounds, bounds, oldUnion);
double newAreaPlus = newUnion.getWidth() * newUnion.getHeight();
double oldAreaPlus = oldUnion.getWidth() * oldUnion.getHeight();
// remember the child that expands the new node the least
if (bestNewNode < 0 || newAreaPlus-newArea < bestNewExpand)
{
bestNewExpand = newAreaPlus-newArea;
bestNewNode = i;
}
// remember the child that expands the old node the least
if (bestOldNode < 0 || oldAreaPlus-oldArea < bestOldExpand)
{
bestOldExpand = oldAreaPlus-oldArea;
bestOldNode = i;
}
}
// if there were no nodes added, all have been clustered
if (bestNewNode == -1 && bestOldNode == -1) break;
// if both selected the same object, select another "old node"
if (bestNewNode == bestOldNode)
{
bestOldNode = -1;
for(int i=0; i<temp.getTotal(); i++)
{
if (i == bestNewNode) continue;
obj = temp.getChild(i);
if (obj == null) continue;
bounds = temp.getBBox(i);
Rectangle2D oldUnion = new Rectangle2D.Double();
Rectangle2D.union(oldBounds, bounds, oldUnion);
double oldAreaPlus = oldUnion.getWidth() * oldUnion.getHeight();
// remember the child that expands the old node the least
if (bestOldNode < 0 || oldAreaPlus-oldArea < bestOldExpand)
{
bestOldExpand = oldAreaPlus-oldArea;
bestOldNode = i;
}
}
}
// add to the proper "old node" to the old node cluster
if (bestOldNode != -1)
{
// add this node to "rtn"
obj = temp.getChild(bestOldNode);
temp.setChild(bestOldNode, null);
int curPos = getTotal();
setChild(curPos, obj);
setTotal(curPos+1);
if (!getFlag()) ((RTNode)obj).setParent(this);
unionBounds(getBBox(curPos));
oldBounds = getBounds();
oldArea = oldBounds.getWidth() * oldBounds.getHeight();
}
// add to proper "new node" to the new node cluster
if (bestNewNode != -1)
{
// add this node to "newrtn"
obj = temp.getChild(bestNewNode);
temp.setChild(bestNewNode, null);
int curPos = newrtn.getTotal();
newrtn.setChild(curPos, obj);
newrtn.setTotal(curPos+1);
if (!newrtn.getFlag()) ((RTNode)obj).setParent(newrtn);
newrtn.unionBounds(newrtn.getBBox(curPos));
newBounds = newrtn.getBounds();
newArea = newBounds.getWidth() * newBounds.getHeight();
}
}
// sensibility check
if (temp.getTotal() != getTotal() + newrtn.getTotal())
System.out.println("R-trees: " + temp.getTotal() + " nodes split to " +
getTotal()+ " and " + newrtn.getTotal() + "!");
// now recursively insert this new element up the tree
if (getParent() == null)
{
// at top of tree: create a new level
RTNode newroot = new RTNode();
newroot.setTotal(2);
newroot.setChild(0, this);
newroot.setChild(1, newrtn);
newroot.setFlag(false);
newroot.setParent(null);
setParent(newroot);
newrtn.setParent(newroot);
newroot.figBounds();
cell.setRTree(newroot);
} else
{
// first recompute bounding box of R-tree nodes up the tree
for(RTNode r = getParent(); r != null; r = r.getParent()) r.figBounds();
// now add the new node up the tree
getParent().addToRTNode(newrtn, cell);
}
}
// now add "rtnInsert" to the R-tree node
int curPos = getTotal();
setChild(curPos, rtnInsert);
setTotal(curPos+1);
// compute the new bounds
Rectangle2D bounds = getBBox(curPos);
if (getTotal() == 1 && getParent() == null)
{
// special case when adding the first node in a cell
setBounds(bounds);
return;
}
// recursively update node sizes
RTNode climb = this;
for(;;)
{
climb.unionBounds(bounds);
if (climb.getParent() == null) break;
climb = climb.getParent();
}
// now check the RTree
// checkRTree(0, cell);
}
|
diff --git a/hk2/config/src/main/java/org/jvnet/hk2/config/MessageInterpolatorImpl.java b/hk2/config/src/main/java/org/jvnet/hk2/config/MessageInterpolatorImpl.java
index b21c41709..012f18780 100644
--- a/hk2/config/src/main/java/org/jvnet/hk2/config/MessageInterpolatorImpl.java
+++ b/hk2/config/src/main/java/org/jvnet/hk2/config/MessageInterpolatorImpl.java
@@ -1,367 +1,367 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. 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_1_1.html
* or packager/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 packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [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.
*/
/*
* Portions of this code are subject to the following copyright:
*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jvnet.hk2.config;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeSet;
import java.util.WeakHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.MessageInterpolator;
import javax.validation.Payload;
import javax.validation.metadata.ConstraintDescriptor;
/*
* Custom MessageInterpolatorImpl for HK2
*
* This message interpolator is different from the default one in the following
* ways:
*
* 1. It uses a class specified in the "payload" argument to the annotation to
* find the class loader to find the resource bundle for messages. This allows
* classes that are in OSGi modules to specify a resource bundle for bean
* validation messages.
*
* 2. The "LocalStrings" resource bundle within the same package as the payload
* class is used to search for messages. If a message is not found, the message
* is obtained from the default bean validation resource bundle.
*
* This class borrows heavily from the RI implementation of the ResourcBundleMessageInterpolator
* authored by Emmanuel Bernard, Hardy Ferentschik, and Gunnar Morling.
*/
public class MessageInterpolatorImpl implements MessageInterpolator {
/**
* The name of the default message bundle.
*/
public static final String DEFAULT_VALIDATION_MESSAGES = "org.hibernate.validator.ValidationMessages";
/**
* The name of the user-provided message bundle as defined in the specification.
*/
public static final String USER_VALIDATION_MESSAGES = "ValidationMessages";
/**
* Regular expression used to do message interpolation.
*/
private static final Pattern MESSAGE_PARAMETER_PATTERN = Pattern.compile("(\\{[^\\}]+?\\})");
/**
* The default locale for the current user.
*/
private final Locale defaultLocale = Locale.getDefault();
/**
* Step 1-3 of message interpolation can be cached. We do this in this map.
*/
private final Map<LocalisedMessage, String> resolvedMessages = new WeakHashMap<LocalisedMessage, String>();
/**
* Flag indicating whether this interpolator should chance some of the interpolation steps.
*/
private final boolean cacheMessages = true;
public MessageInterpolatorImpl() { }
@Override
public String interpolate(String message, Context context) {
// probably no need for caching, but it could be done by parameters since the map
// is immutable and uniquely built per Validation definition, the comparison has to be based on == and not equals though
return interpolate(message, context, defaultLocale);
}
/**
* Runs the message interpolation according to algorithm specified in JSR 303.
* <br/>
* Note:
* <br/>
* Look-ups in user bundles is recursive whereas look-ups in default bundle are not!
*
* @param message the message to interpolate
* @param annotationParameters the parameters of the annotation for which to interpolate this message
* @param locale the {@code Locale} to use for the resource bundle.
*
* @return the interpolated message.
*/
@Override
public String interpolate(String message, Context context, Locale locale) {
Map<String, Object> annotationParameters = context.getConstraintDescriptor().getAttributes();
LocalisedMessage localisedMessage = new LocalisedMessage(message, locale);
String resolvedMessage = null;
if (cacheMessages) {
resolvedMessage = resolvedMessages.get(localisedMessage);
}
// if the message is not already in the cache we have to run step 1-3 of the message resolution
if (resolvedMessage == null) {
ResourceBundle userResourceBundle = new ContextResourceBundle(context, locale);
ResourceBundle defaultResourceBundle = ResourceBundle.getBundle(DEFAULT_VALIDATION_MESSAGES,
locale,
- Thread.currentThread().getContextClassLoader());
+ MessageInterpolator.class.getClassLoader());
String userBundleResolvedMessage;
resolvedMessage = message;
boolean evaluatedDefaultBundleOnce = false;
do {
// search the user bundle recursive (step1)
userBundleResolvedMessage = replaceVariables(
resolvedMessage, userResourceBundle, locale, true);
// exit condition - we have at least tried to validate against the default bundle and there was no
// further replacements
if (evaluatedDefaultBundleOnce
&& !hasReplacementTakenPlace(userBundleResolvedMessage, resolvedMessage)) {
break;
}
// search the default bundle non recursive (step2)
resolvedMessage = replaceVariables(userBundleResolvedMessage, defaultResourceBundle, locale, false);
evaluatedDefaultBundleOnce = true;
if (cacheMessages) {
resolvedMessages.put(localisedMessage, resolvedMessage);
}
} while (true);
}
// resolve annotation attributes (step 4)
resolvedMessage = replaceAnnotationAttributes(resolvedMessage, annotationParameters);
// last but not least we have to take care of escaped literals
resolvedMessage = resolvedMessage.replace("\\{", "{");
resolvedMessage = resolvedMessage.replace("\\}", "}");
resolvedMessage = resolvedMessage.replace("\\\\", "\\");
return resolvedMessage;
}
private boolean hasReplacementTakenPlace(String origMessage, String newMessage) {
return !origMessage.equals(newMessage);
}
private String replaceVariables(String message, ResourceBundle bundle, Locale locale, boolean recurse) {
Matcher matcher = MESSAGE_PARAMETER_PATTERN.matcher(message);
StringBuffer sb = new StringBuffer();
String resolvedParameterValue;
while (matcher.find()) {
String parameter = matcher.group(1);
resolvedParameterValue = resolveParameter(
parameter, bundle, locale, recurse);
matcher.appendReplacement(sb, escapeMetaCharacters(resolvedParameterValue));
}
matcher.appendTail(sb);
return sb.toString();
}
private String replaceAnnotationAttributes(String message, Map<String, Object> annotationParameters) {
Matcher matcher = MESSAGE_PARAMETER_PATTERN.matcher(message);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String resolvedParameterValue;
String parameter = matcher.group(1);
Object variable = annotationParameters.get(removeCurlyBrace(parameter));
if (variable != null) {
resolvedParameterValue = escapeMetaCharacters(variable.toString());
} else {
resolvedParameterValue = parameter;
}
matcher.appendReplacement(sb, resolvedParameterValue);
}
matcher.appendTail(sb);
return sb.toString();
}
private String resolveParameter(String parameterName, ResourceBundle bundle, Locale locale, boolean recurse) {
String parameterValue;
try {
if (bundle != null) {
parameterValue = bundle.getString(removeCurlyBrace(parameterName));
if (recurse) {
parameterValue = replaceVariables(parameterValue, bundle, locale, recurse);
}
} else {
parameterValue = parameterName;
}
} catch (MissingResourceException e) {
// return parameter itself
parameterValue = parameterName;
}
return parameterValue;
}
private String removeCurlyBrace(String parameter) {
return parameter.substring(1, parameter.length() - 1);
}
/**
* @param s The string in which to replace the meta characters '$' and '\'.
*
* @return A string where meta characters relevant for {@link Matcher#appendReplacement} are escaped.
*/
private String escapeMetaCharacters(String s) {
String escapedString = s.replace("\\", "\\\\");
escapedString = escapedString.replace("$", "\\$");
return escapedString;
}
/*
* A resource bundle that takes strings from the annotation context. This class
* looks for the "LocalStrings" resource bundle in the same package as the
* class that is specified in the payload of the annotation. If a String
* cannot be found there, then it looks in the user resource bundle as defined
* in JSR-303.
*/
private static class ContextResourceBundle extends ResourceBundle {
ResourceBundle contextBundle;
ResourceBundle userBundle;
ContextResourceBundle(Context context, Locale locale) {
ConstraintDescriptor descriptor = context.getConstraintDescriptor();
Set<Class<? extends Payload>> payload = descriptor.getPayload();
// Load the LogStrings.properties for the argument Locale, from the ClassLoader
// of the payload.
if (!payload.isEmpty()) {
Class payloadClass = payload.iterator().next();
String baseName = payloadClass.getPackage().getName() + ".LocalStrings";
ClassLoader cl = payloadClass.getClassLoader();
try {
contextBundle = ResourceBundle.getBundle(baseName, locale, cl);
} catch (MissingResourceException mre) {
contextBundle = null;
}
}
try {
userBundle = ResourceBundle.getBundle(USER_VALIDATION_MESSAGES,
locale,
Thread.currentThread().getContextClassLoader());
} catch (MissingResourceException mre) {
userBundle = null;
}
if (userBundle != null) {
setParent(userBundle);
}
}
@Override
protected Object handleGetObject(String key) {
if (contextBundle != null) {
return contextBundle.getObject(key);
}
return null;
}
@Override
public Enumeration<String> getKeys() {
Set<String> keys = new TreeSet<String>();
if (contextBundle != null) {
keys.addAll(Collections.list(contextBundle.getKeys()));
}
if (userBundle != null) {
keys.addAll(Collections.list(userBundle.getKeys()));
}
return Collections.enumeration(keys);
}
}
private static class LocalisedMessage {
private final String message;
private final Locale locale;
LocalisedMessage(String message, Locale locale) {
this.message = message;
this.locale = locale;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LocalisedMessage that = (LocalisedMessage) o;
if (locale != null ? !locale.equals(that.locale) : that.locale != null) {
return false;
}
if (message != null ? !message.equals(that.message) : that.message != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = message != null ? message.hashCode() : 0;
result = 31 * result + (locale != null ? locale.hashCode() : 0);
return result;
}
}
}
| true | true | public String interpolate(String message, Context context, Locale locale) {
Map<String, Object> annotationParameters = context.getConstraintDescriptor().getAttributes();
LocalisedMessage localisedMessage = new LocalisedMessage(message, locale);
String resolvedMessage = null;
if (cacheMessages) {
resolvedMessage = resolvedMessages.get(localisedMessage);
}
// if the message is not already in the cache we have to run step 1-3 of the message resolution
if (resolvedMessage == null) {
ResourceBundle userResourceBundle = new ContextResourceBundle(context, locale);
ResourceBundle defaultResourceBundle = ResourceBundle.getBundle(DEFAULT_VALIDATION_MESSAGES,
locale,
Thread.currentThread().getContextClassLoader());
String userBundleResolvedMessage;
resolvedMessage = message;
boolean evaluatedDefaultBundleOnce = false;
do {
// search the user bundle recursive (step1)
userBundleResolvedMessage = replaceVariables(
resolvedMessage, userResourceBundle, locale, true);
// exit condition - we have at least tried to validate against the default bundle and there was no
// further replacements
if (evaluatedDefaultBundleOnce
&& !hasReplacementTakenPlace(userBundleResolvedMessage, resolvedMessage)) {
break;
}
// search the default bundle non recursive (step2)
resolvedMessage = replaceVariables(userBundleResolvedMessage, defaultResourceBundle, locale, false);
evaluatedDefaultBundleOnce = true;
if (cacheMessages) {
resolvedMessages.put(localisedMessage, resolvedMessage);
}
} while (true);
}
// resolve annotation attributes (step 4)
resolvedMessage = replaceAnnotationAttributes(resolvedMessage, annotationParameters);
// last but not least we have to take care of escaped literals
resolvedMessage = resolvedMessage.replace("\\{", "{");
resolvedMessage = resolvedMessage.replace("\\}", "}");
resolvedMessage = resolvedMessage.replace("\\\\", "\\");
return resolvedMessage;
}
| public String interpolate(String message, Context context, Locale locale) {
Map<String, Object> annotationParameters = context.getConstraintDescriptor().getAttributes();
LocalisedMessage localisedMessage = new LocalisedMessage(message, locale);
String resolvedMessage = null;
if (cacheMessages) {
resolvedMessage = resolvedMessages.get(localisedMessage);
}
// if the message is not already in the cache we have to run step 1-3 of the message resolution
if (resolvedMessage == null) {
ResourceBundle userResourceBundle = new ContextResourceBundle(context, locale);
ResourceBundle defaultResourceBundle = ResourceBundle.getBundle(DEFAULT_VALIDATION_MESSAGES,
locale,
MessageInterpolator.class.getClassLoader());
String userBundleResolvedMessage;
resolvedMessage = message;
boolean evaluatedDefaultBundleOnce = false;
do {
// search the user bundle recursive (step1)
userBundleResolvedMessage = replaceVariables(
resolvedMessage, userResourceBundle, locale, true);
// exit condition - we have at least tried to validate against the default bundle and there was no
// further replacements
if (evaluatedDefaultBundleOnce
&& !hasReplacementTakenPlace(userBundleResolvedMessage, resolvedMessage)) {
break;
}
// search the default bundle non recursive (step2)
resolvedMessage = replaceVariables(userBundleResolvedMessage, defaultResourceBundle, locale, false);
evaluatedDefaultBundleOnce = true;
if (cacheMessages) {
resolvedMessages.put(localisedMessage, resolvedMessage);
}
} while (true);
}
// resolve annotation attributes (step 4)
resolvedMessage = replaceAnnotationAttributes(resolvedMessage, annotationParameters);
// last but not least we have to take care of escaped literals
resolvedMessage = resolvedMessage.replace("\\{", "{");
resolvedMessage = resolvedMessage.replace("\\}", "}");
resolvedMessage = resolvedMessage.replace("\\\\", "\\");
return resolvedMessage;
}
|
diff --git a/doxia-core/src/test/java/org/apache/maven/doxia/xsd/AbstractXmlValidatorTest.java b/doxia-core/src/test/java/org/apache/maven/doxia/xsd/AbstractXmlValidatorTest.java
index 7e4cc892..32810082 100644
--- a/doxia-core/src/test/java/org/apache/maven/doxia/xsd/AbstractXmlValidatorTest.java
+++ b/doxia-core/src/test/java/org/apache/maven/doxia/xsd/AbstractXmlValidatorTest.java
@@ -1,547 +1,547 @@
package org.apache.maven.doxia.xsd;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import junit.framework.AssertionFailedError;
import org.apache.maven.doxia.parser.AbstractXmlParser;
import org.codehaus.plexus.PlexusTestCase;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.ReaderFactory;
import org.codehaus.plexus.util.SelectorUtils;
import org.codehaus.plexus.util.xml.XmlUtil;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* Abstract class to validate XML files with DTD or XSD mainly for Doxia namespaces.
*
* @author <a href="mailto:[email protected]">Vincent Siveton</a>
* @version $Id$
* @since 1.0
*/
public abstract class AbstractXmlValidatorTest
extends PlexusTestCase
{
/** The vm line separator */
protected static final String EOL = System.getProperty( "line.separator" );
/** Simple cache mechanism to load test documents. */
private static final Map CACHE_DOXIA_TEST_DOCUMENTS = new Hashtable();
/** Maven resource in the doxia-test-docs-XXX.jar */
private static final String MAVEN_RESOURCE_PATH = "META-INF/maven/org.apache.maven.doxia/doxia-test-docs/";
/** XMLReader to validate xml file */
private XMLReader xmlReader;
/** {@inheritDoc} */
protected void setUp()
throws Exception
{
super.setUp();
}
/** {@inheritDoc} */
protected void tearDown()
throws Exception
{
super.tearDown();
xmlReader = null;
}
/**
* Validate tests documents with DTD or XSD using xerces.
*
* @throws Exception if any
* @see #addNamespaces(String)
* @see #getTestDocuments()
*/
public void testValidateFiles()
throws Exception
{
for ( Iterator it = getTestDocuments().entrySet().iterator(); it.hasNext(); )
{
Map.Entry entry = (Map.Entry) it.next();
if ( getContainer().getLogger().isDebugEnabled() )
{
getContainer().getLogger().debug( "Validate '" + entry.getKey() + "'" );
}
List errors = parseXML( entry.getValue().toString() );
for ( Iterator it2 = errors.iterator(); it2.hasNext(); )
{
ErrorMessage error = (ErrorMessage) it2.next();
if ( isFailErrorMessage( error.getMessage() ) )
{
fail( entry.getKey() + EOL + error.toString() );
}
else
{
if ( getContainer().getLogger().isDebugEnabled() )
{
getContainer().getLogger().debug( entry.getKey() + EOL + error.toString() );
}
}
}
}
}
// ----------------------------------------------------------------------
// Protected methods
// ----------------------------------------------------------------------
/**
* @return a non null patterns to includes specific test files.
* @see AbstractXmlValidatorTest#getTestDocuments()
*/
protected abstract String[] getIncludes();
/**
* @param content xml content not null
* @return xml content with the wanted Doxia namespace
*/
protected abstract String addNamespaces( String content );
/**
* @return a map of test resources filtered by patterns from {@link #getIncludes()}.
* @throws IOException if any
* @see #getIncludes()
* @see #getAllTestDocuments()
*/
protected Map getTestDocuments()
throws IOException
{
if ( getIncludes() == null )
{
return Collections.EMPTY_MAP;
}
Map testDocs = getAllTestDocuments();
Map ret = new Hashtable();
ret.putAll( testDocs );
for ( Iterator it = testDocs.keySet().iterator(); it.hasNext(); )
{
String key = it.next().toString();
for ( int i = 0; i < getIncludes().length; i++ )
{
if ( !SelectorUtils.matchPath( getIncludes()[i], key.toLowerCase( Locale.ENGLISH ) ) )
{
ret.remove( key );
}
}
}
return ret;
}
/**
* Find test resources in the <code>doxia-test-docs-XXX.jar</code> or in an IDE project.
*
* @return a map of test resources defined as follow:
* <ul>
* <li>key, the full url of test documents,
* i.e. <code>jar:file:/.../doxia-test-docs-XXX.jar!/path/to/resource</code></li>
* <li>value, the content for the resource defined by the key</li>
* </ul>
* @throws IOException if any
*/
protected static Map getAllTestDocuments()
throws IOException
{
if ( CACHE_DOXIA_TEST_DOCUMENTS != null && !CACHE_DOXIA_TEST_DOCUMENTS.isEmpty() )
{
return CACHE_DOXIA_TEST_DOCUMENTS;
}
URL testJar = AbstractXmlValidatorTest.class.getClassLoader().getResource( MAVEN_RESOURCE_PATH );
if ( testJar == null )
{
// maybe in an IDE project
testJar = AbstractXmlValidatorTest.class.getClassLoader().getResource( "doxia-site" );
if ( testJar == null )
{
throw new RuntimeException(
"Could not find the Doxia test documents artefact i.e. doxia-test-docs-XXX.jar" );
}
}
if ( testJar.toString().startsWith( "jar" ))
{
JarURLConnection conn = (JarURLConnection) testJar.openConnection();
JarFile jarFile = conn.getJarFile();
for ( Enumeration e = jarFile.entries(); e.hasMoreElements(); )
{
JarEntry entry = (JarEntry) e.nextElement();
if ( entry.getName().startsWith( "META-INF" ) )
{
continue;
}
if ( entry.isDirectory() )
{
continue;
}
InputStream in = null;
try
{
in = AbstractXmlValidatorTest.class.getClassLoader().getResource( entry.getName() ).openStream();
String content = IOUtil.toString( in, "UTF-8" );
CACHE_DOXIA_TEST_DOCUMENTS.put( "jar:" + conn.getJarFileURL() + "!/" + entry.getName(), content );
}
finally
{
IOUtil.close( in );
}
}
}
else
{
// IDE projects
- File testDocsDir = new File( testJar.getFile() ).getParentFile();
+ File testDocsDir = FileUtils.toFile( testJar ).getParentFile();
List files = FileUtils.getFiles( testDocsDir, "**/*.*", FileUtils.getDefaultExcludesAsString(), true );
for ( Iterator it = files.iterator(); it.hasNext();)
{
File file = new File( it.next().toString() );
if ( file.getAbsolutePath().indexOf( "META-INF" ) != -1 )
{
continue;
}
Reader reader = null;
if ( XmlUtil.isXml( file ))
{
reader = ReaderFactory.newXmlReader( file );
}
else
{
reader = ReaderFactory.newReader( file, "UTF-8" );
}
String content = IOUtil.toString( reader );
CACHE_DOXIA_TEST_DOCUMENTS.put( file.toURI().toString(), content );
}
}
return CACHE_DOXIA_TEST_DOCUMENTS;
}
/**
* Filter fail message.
*
* @param message not null
* @return <code>true</code> if the given message will fail the test.
* @since 1.1.1
*/
protected boolean isFailErrorMessage( String message )
{
if ( message
.indexOf( "schema_reference.4: Failed to read schema document 'http://www.w3.org/2001/xml.xsd'" ) == -1
&& message.indexOf( "cvc-complex-type.4: Attribute 'alt' must appear on element 'img'." ) == -1
&& message.indexOf( "cvc-complex-type.2.4.a: Invalid content starting with element" ) == -1
&& message.indexOf( "cvc-complex-type.2.4.a: Invalid content was found starting with element" ) == -1
&& message.indexOf( "cvc-datatype-valid.1.2.1:" ) == -1 // Doxia allow space
&& message.indexOf( "cvc-attribute.3:" ) == -1 ) // Doxia allow space
{
return true;
}
return false;
}
// ----------------------------------------------------------------------
// Private methods
// ----------------------------------------------------------------------
private XMLReader getXMLReader()
{
if ( xmlReader == null )
{
try
{
xmlReader = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser" );
xmlReader.setFeature( "http://xml.org/sax/features/validation", true );
xmlReader.setFeature( "http://apache.org/xml/features/validation/schema", true );
xmlReader.setErrorHandler( new MessagesErrorHandler() );
xmlReader.setEntityResolver( new AbstractXmlParser.CachedFileEntityResolver() );
}
catch ( SAXNotRecognizedException e )
{
throw new AssertionFailedError( "SAXNotRecognizedException: " + e.getMessage() );
}
catch ( SAXNotSupportedException e )
{
throw new AssertionFailedError( "SAXNotSupportedException: " + e.getMessage() );
}
catch ( SAXException e )
{
throw new AssertionFailedError( "SAXException: " + e.getMessage() );
}
}
( (MessagesErrorHandler) xmlReader.getErrorHandler() ).clearMessages();
return xmlReader;
}
/**
* @param xmlContent
* @return a list of ErrorMessage
* @throws IOException is any
* @throws SAXException if any
*/
private List parseXML( String xmlContent )
throws IOException, SAXException
{
xmlContent = addNamespaces( xmlContent );
MessagesErrorHandler errorHandler = (MessagesErrorHandler) getXMLReader().getErrorHandler();
getXMLReader().parse( new InputSource( new StringReader( xmlContent ) ) );
return errorHandler.getMessages();
}
private static class ErrorMessage
extends DefaultHandler
{
private final String level;
private final String publicID;
private final String systemID;
private final int lineNumber;
private final int columnNumber;
private final String message;
public ErrorMessage( String level, String publicID, String systemID, int lineNumber, int columnNumber,
String message )
{
super();
this.level = level;
this.publicID = publicID;
this.systemID = systemID;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.message = message;
}
/**
* @return the level
*/
protected String getLevel()
{
return level;
}
/**
* @return the publicID
*/
protected String getPublicID()
{
return publicID;
}
/**
* @return the systemID
*/
protected String getSystemID()
{
return systemID;
}
/**
* @return the lineNumber
*/
protected int getLineNumber()
{
return lineNumber;
}
/**
* @return the columnNumber
*/
protected int getColumnNumber()
{
return columnNumber;
}
/**
* @return the message
*/
protected String getMessage()
{
return message;
}
/** {@inheritDoc} */
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append( level ).append( EOL );
sb.append( " Public ID: " ).append( publicID ).append( EOL );
sb.append( " System ID: " ).append( systemID ).append( EOL );
sb.append( " Line number: " ).append( lineNumber ).append( EOL );
sb.append( " Column number: " ).append( columnNumber ).append( EOL );
sb.append( " Message: " ).append( message ).append( EOL );
return sb.toString();
}
/** {@inheritDoc} */
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + columnNumber;
result = prime * result + ( ( level == null ) ? 0 : level.hashCode() );
result = prime * result + lineNumber;
result = prime * result + ( ( message == null ) ? 0 : message.hashCode() );
result = prime * result + ( ( publicID == null ) ? 0 : publicID.hashCode() );
result = prime * result + ( ( systemID == null ) ? 0 : systemID.hashCode() );
return result;
}
/** {@inheritDoc} */
public boolean equals( Object obj )
{
if ( this == obj )
return true;
if ( obj == null )
return false;
if ( getClass() != obj.getClass() )
return false;
ErrorMessage other = (ErrorMessage) obj;
if ( columnNumber != other.columnNumber )
return false;
if ( level == null )
{
if ( other.level != null )
return false;
}
else if ( !level.equals( other.level ) )
return false;
if ( lineNumber != other.lineNumber )
return false;
if ( message == null )
{
if ( other.message != null )
return false;
}
else if ( !message.equals( other.message ) )
return false;
if ( publicID == null )
{
if ( other.publicID != null )
return false;
}
else if ( !publicID.equals( other.publicID ) )
return false;
if ( systemID == null )
{
if ( other.systemID != null )
return false;
}
else if ( !systemID.equals( other.systemID ) )
return false;
return true;
}
}
private static class MessagesErrorHandler
extends DefaultHandler
{
private final List messages;
public MessagesErrorHandler()
{
messages = new ArrayList();
}
/** {@inheritDoc} */
public void warning( SAXParseException e )
throws SAXException
{
addMessage( "Warning", e );
}
/** {@inheritDoc} */
public void error( SAXParseException e )
throws SAXException
{
addMessage( "Error", e );
}
/** {@inheritDoc} */
public void fatalError( SAXParseException e )
throws SAXException
{
addMessage( "Fatal error", e );
}
private void addMessage( String pre, SAXParseException e )
{
ErrorMessage error =
new ErrorMessage( pre, e.getPublicId(), e.getSystemId(), e.getLineNumber(), e.getColumnNumber(),
e.getMessage() );
messages.add( error );
}
protected List getMessages()
{
return messages;
}
protected void clearMessages()
{
messages.clear();
}
}
}
| true | true | protected static Map getAllTestDocuments()
throws IOException
{
if ( CACHE_DOXIA_TEST_DOCUMENTS != null && !CACHE_DOXIA_TEST_DOCUMENTS.isEmpty() )
{
return CACHE_DOXIA_TEST_DOCUMENTS;
}
URL testJar = AbstractXmlValidatorTest.class.getClassLoader().getResource( MAVEN_RESOURCE_PATH );
if ( testJar == null )
{
// maybe in an IDE project
testJar = AbstractXmlValidatorTest.class.getClassLoader().getResource( "doxia-site" );
if ( testJar == null )
{
throw new RuntimeException(
"Could not find the Doxia test documents artefact i.e. doxia-test-docs-XXX.jar" );
}
}
if ( testJar.toString().startsWith( "jar" ))
{
JarURLConnection conn = (JarURLConnection) testJar.openConnection();
JarFile jarFile = conn.getJarFile();
for ( Enumeration e = jarFile.entries(); e.hasMoreElements(); )
{
JarEntry entry = (JarEntry) e.nextElement();
if ( entry.getName().startsWith( "META-INF" ) )
{
continue;
}
if ( entry.isDirectory() )
{
continue;
}
InputStream in = null;
try
{
in = AbstractXmlValidatorTest.class.getClassLoader().getResource( entry.getName() ).openStream();
String content = IOUtil.toString( in, "UTF-8" );
CACHE_DOXIA_TEST_DOCUMENTS.put( "jar:" + conn.getJarFileURL() + "!/" + entry.getName(), content );
}
finally
{
IOUtil.close( in );
}
}
}
else
{
// IDE projects
File testDocsDir = new File( testJar.getFile() ).getParentFile();
List files = FileUtils.getFiles( testDocsDir, "**/*.*", FileUtils.getDefaultExcludesAsString(), true );
for ( Iterator it = files.iterator(); it.hasNext();)
{
File file = new File( it.next().toString() );
if ( file.getAbsolutePath().indexOf( "META-INF" ) != -1 )
{
continue;
}
Reader reader = null;
if ( XmlUtil.isXml( file ))
{
reader = ReaderFactory.newXmlReader( file );
}
else
{
reader = ReaderFactory.newReader( file, "UTF-8" );
}
String content = IOUtil.toString( reader );
CACHE_DOXIA_TEST_DOCUMENTS.put( file.toURI().toString(), content );
}
}
return CACHE_DOXIA_TEST_DOCUMENTS;
}
| protected static Map getAllTestDocuments()
throws IOException
{
if ( CACHE_DOXIA_TEST_DOCUMENTS != null && !CACHE_DOXIA_TEST_DOCUMENTS.isEmpty() )
{
return CACHE_DOXIA_TEST_DOCUMENTS;
}
URL testJar = AbstractXmlValidatorTest.class.getClassLoader().getResource( MAVEN_RESOURCE_PATH );
if ( testJar == null )
{
// maybe in an IDE project
testJar = AbstractXmlValidatorTest.class.getClassLoader().getResource( "doxia-site" );
if ( testJar == null )
{
throw new RuntimeException(
"Could not find the Doxia test documents artefact i.e. doxia-test-docs-XXX.jar" );
}
}
if ( testJar.toString().startsWith( "jar" ))
{
JarURLConnection conn = (JarURLConnection) testJar.openConnection();
JarFile jarFile = conn.getJarFile();
for ( Enumeration e = jarFile.entries(); e.hasMoreElements(); )
{
JarEntry entry = (JarEntry) e.nextElement();
if ( entry.getName().startsWith( "META-INF" ) )
{
continue;
}
if ( entry.isDirectory() )
{
continue;
}
InputStream in = null;
try
{
in = AbstractXmlValidatorTest.class.getClassLoader().getResource( entry.getName() ).openStream();
String content = IOUtil.toString( in, "UTF-8" );
CACHE_DOXIA_TEST_DOCUMENTS.put( "jar:" + conn.getJarFileURL() + "!/" + entry.getName(), content );
}
finally
{
IOUtil.close( in );
}
}
}
else
{
// IDE projects
File testDocsDir = FileUtils.toFile( testJar ).getParentFile();
List files = FileUtils.getFiles( testDocsDir, "**/*.*", FileUtils.getDefaultExcludesAsString(), true );
for ( Iterator it = files.iterator(); it.hasNext();)
{
File file = new File( it.next().toString() );
if ( file.getAbsolutePath().indexOf( "META-INF" ) != -1 )
{
continue;
}
Reader reader = null;
if ( XmlUtil.isXml( file ))
{
reader = ReaderFactory.newXmlReader( file );
}
else
{
reader = ReaderFactory.newReader( file, "UTF-8" );
}
String content = IOUtil.toString( reader );
CACHE_DOXIA_TEST_DOCUMENTS.put( file.toURI().toString(), content );
}
}
return CACHE_DOXIA_TEST_DOCUMENTS;
}
|
diff --git a/MPDroid/src/com/namelessdev/mpdroid/fragments/NowPlayingSmallFragment.java b/MPDroid/src/com/namelessdev/mpdroid/fragments/NowPlayingSmallFragment.java
index bc951709..fc4b91c1 100644
--- a/MPDroid/src/com/namelessdev/mpdroid/fragments/NowPlayingSmallFragment.java
+++ b/MPDroid/src/com/namelessdev/mpdroid/fragments/NowPlayingSmallFragment.java
@@ -1,333 +1,334 @@
package com.namelessdev.mpdroid.fragments;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.namelessdev.mpdroid.MPDApplication;
import com.namelessdev.mpdroid.R;
import com.namelessdev.mpdroid.cover.CoverBitmapDrawable;
import com.namelessdev.mpdroid.helpers.AlbumCoverDownloadListener;
import com.namelessdev.mpdroid.helpers.CoverAsyncHelper;
import com.namelessdev.mpdroid.helpers.CoverInfo;
import org.a0z.mpd.AlbumInfo;
import org.a0z.mpd.MPD;
import org.a0z.mpd.MPDStatus;
import org.a0z.mpd.Music;
import org.a0z.mpd.event.StatusChangeListener;
import org.a0z.mpd.exception.MPDServerException;
public class NowPlayingSmallFragment extends Fragment implements StatusChangeListener {
private MPDApplication app;
private CoverAsyncHelper coverHelper;
private TextView songTitle;
private TextView songArtist;
private AlbumCoverDownloadListener coverArtListener;
private ImageView coverArt;
private ProgressBar coverArtProgress;
private ImageButton buttonPrev;
private ImageButton buttonPlayPause;
private ImageButton buttonNext;
private String lastArtist = "";
private String lastAlbum = "";
private boolean showAlbumArtist;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (MPDApplication) activity.getApplication();
}
@Override
public void onStart() {
super.onStart();
app.oMPDAsyncHelper.addStatusChangeListener(this);
new updateTrackInfoAsync().execute((MPDStatus[]) null);
}
@Override
public void onStop() {
app.oMPDAsyncHelper.removeStatusChangeListener(this);
super.onStop();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.now_playing_small_fragment, container, false);
songTitle = (TextView) view.findViewById(R.id.song_title);
songTitle.setSelected(true);
songArtist = (TextView) view.findViewById(R.id.song_artist);
songArtist.setSelected(true);
buttonPrev = (ImageButton) view.findViewById(R.id.prev);
buttonPlayPause = (ImageButton) view.findViewById(R.id.playpause);
buttonNext = (ImageButton) view.findViewById(R.id.next);
buttonPrev.setOnClickListener(buttonClickListener);
buttonPlayPause.setOnClickListener(buttonClickListener);
buttonNext.setOnClickListener(buttonClickListener);
coverArt = (ImageView) view.findViewById(R.id.albumCover);
coverArtProgress = (ProgressBar) view.findViewById(R.id.albumCoverProgress);
coverArtListener = new AlbumCoverDownloadListener(getActivity(), coverArt, coverArtProgress, app.isLightThemeSelected(), false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
showAlbumArtist = settings.getBoolean("showAlbumArtist", true);
coverHelper = new CoverAsyncHelper(app, settings);
coverHelper.setCoverMaxSizeFromScreen(getActivity());
final ViewTreeObserver vto = coverArt.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
if (coverHelper != null)
coverHelper.setCachedCoverMaxSize(coverArt.getMeasuredHeight());
return true;
}
});
coverHelper.addCoverDownloadListener(coverArtListener);
return view;
}
@Override
public void onDestroyView() {
if (coverArt != null) {
final Drawable oldDrawable = coverArt.getDrawable();
coverArt.setImageResource(R.drawable.no_cover_art);
if (oldDrawable != null && oldDrawable instanceof CoverBitmapDrawable) {
final Bitmap oldBitmap = ((CoverBitmapDrawable) oldDrawable).getBitmap();
if (oldBitmap != null)
oldBitmap.recycle();
}
}
super.onDestroyView();
}
final OnClickListener buttonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.prev:
new Thread(new Runnable() {
@Override
public void run() {
try {
app.oMPDAsyncHelper.oMPD.previous();
} catch (MPDServerException e) {
Log.w(MPDApplication.TAG, e.getMessage());
}
}
}).start();
break;
case R.id.playpause:
new Thread(new Runnable() {
@Override
public void run() {
try {
final MPD mpd = app.oMPDAsyncHelper.oMPD;
final String state = mpd.getStatus().getState();
if (state.equals(MPDStatus.MPD_STATE_PLAYING) || state.equals(MPDStatus.MPD_STATE_PAUSED)) {
mpd.pause();
} else {
mpd.play();
}
} catch (MPDServerException e) {
Log.w(MPDApplication.TAG, e.getMessage());
}
}
}).start();
break;
case R.id.next:
new Thread(new Runnable() {
@Override
public void run() {
try {
app.oMPDAsyncHelper.oMPD.next();
} catch (MPDServerException e) {
Log.w(MPDApplication.TAG, e.getMessage());
}
}
}).start();
break;
}
}
};
@Override
public void trackChanged(MPDStatus mpdStatus, int oldTrack) {
new updateTrackInfoAsync().execute(mpdStatus);
}
@Override
public void playlistChanged(MPDStatus mpdStatus, int oldPlaylistVersion) {
if (isDetached())
return;
// If the playlist changed but not the song position in the playlist
// We end up being desynced. Update the current song.
new updateTrackInfoAsync().execute((MPDStatus[]) null);
}
@Override
public void stateChanged(MPDStatus status, String oldState) {
if (isDetached())
return;
app.getApplicationState().currentMpdStatus = status;
if (status.getState() != null && buttonPlayPause != null) {
if (status.getState().equals(MPDStatus.MPD_STATE_PLAYING)) {
buttonPlayPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_pause));
} else {
buttonPlayPause.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_play));
}
}
}
@Override
public void connectionStateChanged(boolean connected, boolean connectionLost) {
if (isDetached() || songTitle == null || songArtist == null)
return;
connected = ((MPDApplication) getActivity().getApplication()).oMPDAsyncHelper.oMPD.isConnected();
if (connected) {
songTitle.setText(getResources().getString(R.string.noSongInfo));
songArtist.setText("");
} else {
songTitle.setText(getResources().getString(R.string.notConnected));
songArtist.setText("");
}
return;
}
public class updateTrackInfoAsync extends AsyncTask<MPDStatus, Void, Boolean> {
Music actSong = null;
MPDStatus status = null;
@Override
protected Boolean doInBackground(MPDStatus... params) {
if (params == null) {
try {
// A recursive call doesn't seem that bad here.
return doInBackground(app.oMPDAsyncHelper.oMPD.getStatus());
} catch (MPDServerException e) {
e.printStackTrace();
}
return false;
}
if (params[0] != null) {
String state = params[0].getState();
if (state != null) {
int songPos = params[0].getSongPos();
if (songPos >= 0) {
actSong = app.oMPDAsyncHelper.oMPD.getPlaylist().getByIndex(songPos);
status = params[0];
return true;
}
}
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
if (result != null && result) {
String albumartist = null;
String artist = null;
String artistlabel = null;
String title = null;
String album = null;
boolean noSong = actSong == null || status.getPlaylistLength() == 0;
if (noSong) {
title = getResources().getString(R.string.noSongInfo);
} else {
if (actSong.isStream()) {
if (actSong.haveTitle()) {
title = actSong.getTitle();
artist = actSong.getName();
} else {
title = actSong.getName();
artist = "";
}
} else {
albumartist = actSong.getAlbumArtist();
artist = actSong.getArtist();
if (!showAlbumArtist ||
albumartist == null || "".equals(albumartist) ||
artist.toLowerCase().contains(albumartist.toLowerCase()))
artistlabel = ""+artist;
else if ("".equals(artist))
artistlabel = "" + albumartist;
else {
artistlabel = albumartist + " / " + artist;
artist = albumartist;
}
title = actSong.getTitle();
album = actSong.getAlbum();
}
}
artist = artist == null ? "" : artist;
title = title == null ? "" : title;
album = album == null ? "" : album;
+ artistlabel = artistlabel.equals("null") ? "" : artistlabel;
songArtist.setText(artistlabel);
songTitle.setText(title);
if (noSong || actSong.isStream()) {
lastArtist = artist;
lastAlbum = album;
coverArtListener.onCoverNotFound(new CoverInfo(artist, album));
} else if (!lastAlbum.equals(album) || !lastArtist.equals(artist)) {
coverHelper.downloadCover(actSong.getAlbumInfo());
lastArtist = artist;
lastAlbum = album;
}
stateChanged(status, null);
} else {
songArtist.setText("");
songTitle.setText(R.string.noSongInfo);
}
}
}
/**
* **************************
* Stuff we don't care about *
* **************************
*/
@Override
public void volumeChanged(MPDStatus mpdStatus, int oldVolume) {
}
@Override
public void repeatChanged(boolean repeating) {
}
@Override
public void randomChanged(boolean random) {
}
@Override
public void libraryStateChanged(boolean updating) {
}
public void updateCover(AlbumInfo albumInfo) {
if (coverArt != null && null != coverArt.getTag() && coverArt.getTag().equals(albumInfo.getKey())) {
coverHelper.downloadCover(albumInfo);
}
}
}
| true | true | protected void onPostExecute(Boolean result) {
if (result != null && result) {
String albumartist = null;
String artist = null;
String artistlabel = null;
String title = null;
String album = null;
boolean noSong = actSong == null || status.getPlaylistLength() == 0;
if (noSong) {
title = getResources().getString(R.string.noSongInfo);
} else {
if (actSong.isStream()) {
if (actSong.haveTitle()) {
title = actSong.getTitle();
artist = actSong.getName();
} else {
title = actSong.getName();
artist = "";
}
} else {
albumartist = actSong.getAlbumArtist();
artist = actSong.getArtist();
if (!showAlbumArtist ||
albumartist == null || "".equals(albumartist) ||
artist.toLowerCase().contains(albumartist.toLowerCase()))
artistlabel = ""+artist;
else if ("".equals(artist))
artistlabel = "" + albumartist;
else {
artistlabel = albumartist + " / " + artist;
artist = albumartist;
}
title = actSong.getTitle();
album = actSong.getAlbum();
}
}
artist = artist == null ? "" : artist;
title = title == null ? "" : title;
album = album == null ? "" : album;
songArtist.setText(artistlabel);
songTitle.setText(title);
if (noSong || actSong.isStream()) {
lastArtist = artist;
lastAlbum = album;
coverArtListener.onCoverNotFound(new CoverInfo(artist, album));
} else if (!lastAlbum.equals(album) || !lastArtist.equals(artist)) {
coverHelper.downloadCover(actSong.getAlbumInfo());
lastArtist = artist;
lastAlbum = album;
}
stateChanged(status, null);
} else {
songArtist.setText("");
songTitle.setText(R.string.noSongInfo);
}
}
| protected void onPostExecute(Boolean result) {
if (result != null && result) {
String albumartist = null;
String artist = null;
String artistlabel = null;
String title = null;
String album = null;
boolean noSong = actSong == null || status.getPlaylistLength() == 0;
if (noSong) {
title = getResources().getString(R.string.noSongInfo);
} else {
if (actSong.isStream()) {
if (actSong.haveTitle()) {
title = actSong.getTitle();
artist = actSong.getName();
} else {
title = actSong.getName();
artist = "";
}
} else {
albumartist = actSong.getAlbumArtist();
artist = actSong.getArtist();
if (!showAlbumArtist ||
albumartist == null || "".equals(albumartist) ||
artist.toLowerCase().contains(albumartist.toLowerCase()))
artistlabel = ""+artist;
else if ("".equals(artist))
artistlabel = "" + albumartist;
else {
artistlabel = albumartist + " / " + artist;
artist = albumartist;
}
title = actSong.getTitle();
album = actSong.getAlbum();
}
}
artist = artist == null ? "" : artist;
title = title == null ? "" : title;
album = album == null ? "" : album;
artistlabel = artistlabel.equals("null") ? "" : artistlabel;
songArtist.setText(artistlabel);
songTitle.setText(title);
if (noSong || actSong.isStream()) {
lastArtist = artist;
lastAlbum = album;
coverArtListener.onCoverNotFound(new CoverInfo(artist, album));
} else if (!lastAlbum.equals(album) || !lastArtist.equals(artist)) {
coverHelper.downloadCover(actSong.getAlbumInfo());
lastArtist = artist;
lastAlbum = album;
}
stateChanged(status, null);
} else {
songArtist.setText("");
songTitle.setText(R.string.noSongInfo);
}
}
|
diff --git a/patcher/BTWTweaker.java b/patcher/BTWTweaker.java
index 0f5f9fc..3f726c1 100644
--- a/patcher/BTWTweaker.java
+++ b/patcher/BTWTweaker.java
@@ -1,305 +1,304 @@
import java.io.*;
import java.util.*;
import java.util.zip.*;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.*;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import sun.org.mozilla.javascript.internal.*;
import mEScriptEngine.*;
public class BTWTweaker
{
private static final Class MAIN_CLASS = BTWTweaker.class;
private static final int ACTION_OVERWRITE = 0;
private static final int ACTION_TWEAK = 1;
private static final int ACTION_ADAPTSERVER = 2;
private static final int ACTION_COPY = 3;
public static final int STATUS_NOBTW = 0;
public static final int STATUS_BTWCLIENT = 1;
public static final int STATUS_BTWSERVER = 2;
public static final int STATUS_BTWPACKAGE = 3;
public static final int STATUS_TWEAKED = 4;
public static final int STATUS_NOTFOUND = 5;
protected static RhinoScriptEngine engine;
public static boolean onServer = false;
public static int failures = 0;
public static String btwVersion = "unknown";
public static void log(String s)
{
System.out.println("[BTWTweak] " + s);
}
public static void log(String s, Object... fmt)
{
log(String.format(s, fmt));
}
public static void logRhinoException(RhinoException ex)
{
log("!SE! " + getScriptStacktrace(ex));
}
public static String getScriptStacktrace(RhinoException ex)
{
CharArrayWriter ca = new CharArrayWriter();
ex.printStackTrace(new PrintWriter(ca));
String boring = "sun\\.org\\.mozilla\\.javascript\\.internal\\.";
return ca.toString().replaceAll("\tat "+boring+"[^\n]+\n", "").replaceFirst(boring, "");
}
public static Object execResource(String str) throws RhinoException
{
InputStream s = MAIN_CLASS.getResourceAsStream(str);
if (s == null)
{
log("Error: unable to find '%s' to include", str);
return null;
}
return execStream(new InputStreamReader(s), str);
}
public static Object execStream(Reader reader, String name) throws RhinoException
{
engine.put("javax.script.filename", name);
return engine.eval(reader);
}
public static boolean hasResource(String name)
{
InputStream s = MAIN_CLASS.getResourceAsStream(name);
if (s == null) return false;
try
{
s.close();
}
catch(IOException e){}
return true;
}
public static String stream2String(InputStream stream) throws IOException
{
int len;
byte[] buffer = new byte[2048];
StringWriter sw = new StringWriter();
while ((len = stream.read(buffer, 0, 2048)) > 0)
{
sw.write(new String(buffer).toCharArray(), 0, len);
}
return sw.toString();
}
public static void main(final String args[]) throws Exception
{
if (args.length == 0 || args.length == 1 && args[0].equals("--help"))
{
log("BTWTweak by Grom PE for Better Than Wolves mod for Minecraft 1.5.2");
//log("Usage: btwtweak minecraft.jar|minecraft_server.jar|BTWMod4-*.zip");
log("Usage: btwtweak minecraft.jar|minecraft_server.jar");
return;
}
String jarname = args[0];
//if (jarname.indexOf("server") != -1) onServer = true;
int jartype = checkClientServerBTWZip(jarname);
log(jarname + ": "+explainStatus(jartype));
if (jartype == STATUS_NOBTW)
{
log("Please install Better Than Wolves mod inside the file and run me again.");
return;
}
if (jartype == STATUS_TWEAKED)
{
log("Please reinstall on fresh Better Than Wolves mod from scratch.");
return;
}
if (jartype == STATUS_BTWPACKAGE)
{
log("Tweaking BTW package is not yet implemented.\nPlease install on minecraft(_server).jar with BTW inside.");
return;
}
onServer = (jartype == STATUS_BTWSERVER);
tweak(jarname, jartype);
}
public static String explainStatus(int status)
{
if (status == STATUS_NOBTW) return "no BTW";
String s = " with BTW version " + btwVersion;
if (status == STATUS_BTWCLIENT) return "BTW client" + s;
if (status == STATUS_BTWSERVER) return "BTW server" + s;
if (status == STATUS_BTWPACKAGE) return "BTW package" + s;
if (status == STATUS_TWEAKED) return "BTWTweak already installed";
return "Unknown";
}
public static int checkClientServerBTWZip(String jarname) throws Exception
{
int status;
ZipFile zip = new ZipFile(new File(jarname));
ZipEntry btwentry = zip.getEntry("FCBetterThanWolves.class");
if (btwentry == null)
{
status = STATUS_BTWPACKAGE;
btwentry = zip.getEntry("MINECRAFT-JAR/FCBetterThanWolves.class");
if (btwentry == null) status = STATUS_NOBTW;
} else {
ZipEntry entry = zip.getEntry("net/minecraft/client/Minecraft.class");
status = (entry == null) ? STATUS_BTWSERVER : STATUS_BTWCLIENT;
}
if (zip.getEntry(status == STATUS_BTWPACKAGE ? "MINECRAFT-JAR/GPEBTWTweak.class" : "GPEBTWTweak.class") != null)
status = STATUS_TWEAKED;
if (btwentry != null && status != STATUS_TWEAKED)
{
InputStream stream = zip.getInputStream(btwentry);
String s = stream2String(stream);
// Possible todo: use ASM for more reliable version detection
stream.close();
int p = s.indexOf("4.");
if (p != -1)
{
btwVersion = s.substring(p, p + (byte)s.charAt(p-1));
}
}
zip.close();
return status;
}
public static void tweak(String jarname, int jartype) throws Exception
{
try
{
engine = new RhinoScriptEngine();
- engine.put("__main_class__", MAIN_CLASS);
execResource("scripts/opcodes.js");
execResource("scripts/tweaks.js");
}
catch(RhinoException e)
{
logRhinoException(e);
}
File jar = new File(jarname);
String outputname = jarname.replaceFirst("\\.([^.]+)$", "_tweak.$1");
if (outputname.equals(jarname)) outputname = outputname + ".tweak.zip";
int pass = 0;
ZipInputStream zis;
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputname)));
ZipEntry entry = null;
byte[] buf = new byte[4096];
int len;
InputStream instream;
while (pass <= 1)
{
if (pass == 0)
{
log("Reading " + jarname + "...");
instream = new FileInputStream(jar);
} else {
log("Reading GPEBTWTweak_files.zip...");
instream = MAIN_CLASS.getResourceAsStream("GPEBTWTweak_files.zip");
}
zis = new ZipInputStream(instream);
while ((entry = zis.getNextEntry()) != null)
{
String name = entry.getName();
String classname = "";
int action = ACTION_COPY;
if (name.endsWith(".class"))
{
classname = name.substring(0, name.length() - 6);
action = (Integer)engine.invokeFunction("whatToDoWithClass", classname);
}
if (name.startsWith("btwmodtex") || name.startsWith("mob") || name.startsWith("textures"))
{
if (onServer || entry.isDirectory()) continue;
}
switch (action)
{
case ACTION_TWEAK:
case ACTION_ADAPTSERVER:
zos.putNextEntry(new ZipEntry(name));
ByteArrayOutputStream b = new ByteArrayOutputStream();
while ((len = zis.read(buf)) > 0)
{
b.write(buf, 0, len);
}
ClassReader cr = new ClassReader(b.toByteArray());
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
if (action == ACTION_TWEAK)
{
engine.invokeFunction("tweakClass", cn);
}
else if (action == ACTION_ADAPTSERVER)
{
Iterator<MethodNode> methods = cn.methods.iterator();
while(methods.hasNext())
{
MethodNode mn = methods.next();
if (onServer && mn.visibleAnnotations != null)
{
for (Object obj2 : mn.visibleAnnotations)
{
AnnotationNode an = (AnnotationNode)obj2;
if (an.desc.equals("LClientOnly;"))
{
methods.remove();
log("Class %s: Removed client-only method %s", classname, mn.name + mn.desc);
continue;
}
}
}
}
}
cn.accept(cw);
zos.write(cw.toByteArray());
zos.closeEntry();
break;
case ACTION_OVERWRITE:
case ACTION_COPY:
if ((action == ACTION_COPY) || (action == ACTION_OVERWRITE) && (pass == 1))
{
zos.putNextEntry(new ZipEntry(name));
while ((len = zis.read(buf)) > 0)
{
zos.write(buf, 0, len);
}
zos.closeEntry();
}
break;
}
}
zis.close();
pass++;
}
zos.close();
log("Wrote " + outputname);
if (failures == 0)
{
log("All OK!");
} else {
log("%d ERRORS during the patching - review the log, test and take care!", failures);
}
}
}
| true | true | public static void tweak(String jarname, int jartype) throws Exception
{
try
{
engine = new RhinoScriptEngine();
engine.put("__main_class__", MAIN_CLASS);
execResource("scripts/opcodes.js");
execResource("scripts/tweaks.js");
}
catch(RhinoException e)
{
logRhinoException(e);
}
File jar = new File(jarname);
String outputname = jarname.replaceFirst("\\.([^.]+)$", "_tweak.$1");
if (outputname.equals(jarname)) outputname = outputname + ".tweak.zip";
int pass = 0;
ZipInputStream zis;
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputname)));
ZipEntry entry = null;
byte[] buf = new byte[4096];
int len;
InputStream instream;
while (pass <= 1)
{
if (pass == 0)
{
log("Reading " + jarname + "...");
instream = new FileInputStream(jar);
} else {
log("Reading GPEBTWTweak_files.zip...");
instream = MAIN_CLASS.getResourceAsStream("GPEBTWTweak_files.zip");
}
zis = new ZipInputStream(instream);
while ((entry = zis.getNextEntry()) != null)
{
String name = entry.getName();
String classname = "";
int action = ACTION_COPY;
if (name.endsWith(".class"))
{
classname = name.substring(0, name.length() - 6);
action = (Integer)engine.invokeFunction("whatToDoWithClass", classname);
}
if (name.startsWith("btwmodtex") || name.startsWith("mob") || name.startsWith("textures"))
{
if (onServer || entry.isDirectory()) continue;
}
switch (action)
{
case ACTION_TWEAK:
case ACTION_ADAPTSERVER:
zos.putNextEntry(new ZipEntry(name));
ByteArrayOutputStream b = new ByteArrayOutputStream();
while ((len = zis.read(buf)) > 0)
{
b.write(buf, 0, len);
}
ClassReader cr = new ClassReader(b.toByteArray());
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
if (action == ACTION_TWEAK)
{
engine.invokeFunction("tweakClass", cn);
}
else if (action == ACTION_ADAPTSERVER)
{
Iterator<MethodNode> methods = cn.methods.iterator();
while(methods.hasNext())
{
MethodNode mn = methods.next();
if (onServer && mn.visibleAnnotations != null)
{
for (Object obj2 : mn.visibleAnnotations)
{
AnnotationNode an = (AnnotationNode)obj2;
if (an.desc.equals("LClientOnly;"))
{
methods.remove();
log("Class %s: Removed client-only method %s", classname, mn.name + mn.desc);
continue;
}
}
}
}
}
cn.accept(cw);
zos.write(cw.toByteArray());
zos.closeEntry();
break;
case ACTION_OVERWRITE:
case ACTION_COPY:
if ((action == ACTION_COPY) || (action == ACTION_OVERWRITE) && (pass == 1))
{
zos.putNextEntry(new ZipEntry(name));
while ((len = zis.read(buf)) > 0)
{
zos.write(buf, 0, len);
}
zos.closeEntry();
}
break;
}
}
zis.close();
pass++;
}
zos.close();
log("Wrote " + outputname);
if (failures == 0)
{
log("All OK!");
} else {
log("%d ERRORS during the patching - review the log, test and take care!", failures);
}
}
| public static void tweak(String jarname, int jartype) throws Exception
{
try
{
engine = new RhinoScriptEngine();
execResource("scripts/opcodes.js");
execResource("scripts/tweaks.js");
}
catch(RhinoException e)
{
logRhinoException(e);
}
File jar = new File(jarname);
String outputname = jarname.replaceFirst("\\.([^.]+)$", "_tweak.$1");
if (outputname.equals(jarname)) outputname = outputname + ".tweak.zip";
int pass = 0;
ZipInputStream zis;
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputname)));
ZipEntry entry = null;
byte[] buf = new byte[4096];
int len;
InputStream instream;
while (pass <= 1)
{
if (pass == 0)
{
log("Reading " + jarname + "...");
instream = new FileInputStream(jar);
} else {
log("Reading GPEBTWTweak_files.zip...");
instream = MAIN_CLASS.getResourceAsStream("GPEBTWTweak_files.zip");
}
zis = new ZipInputStream(instream);
while ((entry = zis.getNextEntry()) != null)
{
String name = entry.getName();
String classname = "";
int action = ACTION_COPY;
if (name.endsWith(".class"))
{
classname = name.substring(0, name.length() - 6);
action = (Integer)engine.invokeFunction("whatToDoWithClass", classname);
}
if (name.startsWith("btwmodtex") || name.startsWith("mob") || name.startsWith("textures"))
{
if (onServer || entry.isDirectory()) continue;
}
switch (action)
{
case ACTION_TWEAK:
case ACTION_ADAPTSERVER:
zos.putNextEntry(new ZipEntry(name));
ByteArrayOutputStream b = new ByteArrayOutputStream();
while ((len = zis.read(buf)) > 0)
{
b.write(buf, 0, len);
}
ClassReader cr = new ClassReader(b.toByteArray());
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
if (action == ACTION_TWEAK)
{
engine.invokeFunction("tweakClass", cn);
}
else if (action == ACTION_ADAPTSERVER)
{
Iterator<MethodNode> methods = cn.methods.iterator();
while(methods.hasNext())
{
MethodNode mn = methods.next();
if (onServer && mn.visibleAnnotations != null)
{
for (Object obj2 : mn.visibleAnnotations)
{
AnnotationNode an = (AnnotationNode)obj2;
if (an.desc.equals("LClientOnly;"))
{
methods.remove();
log("Class %s: Removed client-only method %s", classname, mn.name + mn.desc);
continue;
}
}
}
}
}
cn.accept(cw);
zos.write(cw.toByteArray());
zos.closeEntry();
break;
case ACTION_OVERWRITE:
case ACTION_COPY:
if ((action == ACTION_COPY) || (action == ACTION_OVERWRITE) && (pass == 1))
{
zos.putNextEntry(new ZipEntry(name));
while ((len = zis.read(buf)) > 0)
{
zos.write(buf, 0, len);
}
zos.closeEntry();
}
break;
}
}
zis.close();
pass++;
}
zos.close();
log("Wrote " + outputname);
if (failures == 0)
{
log("All OK!");
} else {
log("%d ERRORS during the patching - review the log, test and take care!", failures);
}
}
|
diff --git a/org.kompiro.jamcircle.kanban.ui.test/src_ui/org/kompiro/jamcircle/kanban/ui/internal/figure/LaneCustomizedIconFigureTest.java b/org.kompiro.jamcircle.kanban.ui.test/src_ui/org/kompiro/jamcircle/kanban/ui/internal/figure/LaneCustomizedIconFigureTest.java
index 6d3b0eff..65977aa0 100644
--- a/org.kompiro.jamcircle.kanban.ui.test/src_ui/org/kompiro/jamcircle/kanban/ui/internal/figure/LaneCustomizedIconFigureTest.java
+++ b/org.kompiro.jamcircle.kanban.ui.test/src_ui/org/kompiro/jamcircle/kanban/ui/internal/figure/LaneCustomizedIconFigureTest.java
@@ -1,37 +1,37 @@
package org.kompiro.jamcircle.kanban.ui.internal.figure;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.junit.Test;
public class LaneCustomizedIconFigureTest {
@Test
public void createFigure() throws Exception {
- Display display = new Display();
+ Display display = Display.getDefault();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
LightweightSystem lws = new LightweightSystem(shell);
LaneCustomizedIconFigure figure = new LaneCustomizedIconFigure();
figure.setStatus("test");
ImageLoader loader = new ImageLoader();
ImageData[] load = loader.load(this.getClass().getResourceAsStream("kanban_128.gif"));
Image image = new Image(display,load[0]);
figure.setImage(image);
lws.setContents(figure);
shell.pack();
shell.open();
load = loader.load(this.getClass().getResourceAsStream("trac_bullet.png"));
image = new Image(display,load[0]);
figure.setImage(image);
}
}
| true | true | public void createFigure() throws Exception {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
LightweightSystem lws = new LightweightSystem(shell);
LaneCustomizedIconFigure figure = new LaneCustomizedIconFigure();
figure.setStatus("test");
ImageLoader loader = new ImageLoader();
ImageData[] load = loader.load(this.getClass().getResourceAsStream("kanban_128.gif"));
Image image = new Image(display,load[0]);
figure.setImage(image);
lws.setContents(figure);
shell.pack();
shell.open();
load = loader.load(this.getClass().getResourceAsStream("trac_bullet.png"));
image = new Image(display,load[0]);
figure.setImage(image);
}
| public void createFigure() throws Exception {
Display display = Display.getDefault();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
LightweightSystem lws = new LightweightSystem(shell);
LaneCustomizedIconFigure figure = new LaneCustomizedIconFigure();
figure.setStatus("test");
ImageLoader loader = new ImageLoader();
ImageData[] load = loader.load(this.getClass().getResourceAsStream("kanban_128.gif"));
Image image = new Image(display,load[0]);
figure.setImage(image);
lws.setContents(figure);
shell.pack();
shell.open();
load = loader.load(this.getClass().getResourceAsStream("trac_bullet.png"));
image = new Image(display,load[0]);
figure.setImage(image);
}
|
diff --git a/myGov/src/com/scottcaruso/mygov/MainActivity.java b/myGov/src/com/scottcaruso/mygov/MainActivity.java
index a4e2b6d..fc2e61b 100644
--- a/myGov/src/com/scottcaruso/mygov/MainActivity.java
+++ b/myGov/src/com/scottcaruso/mygov/MainActivity.java
@@ -1,321 +1,322 @@
/* Scott Caruso
* Java 1 - 1307
* Week 4 Project
*/
package com.scottcaruso.mygov;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.scottcaruso.datafunctions.DataRetrievalService;
import com.scottcaruso.datafunctions.SaveFavoritesLocally;
import com.scottcaruso.datafunctions.SavedPoliticianProvider;
import com.scottcaruso.datafunctions.SavedPoliticianProvider.PoliticianData;
import com.scottcaruso.interfacefunctions.DisplayPoliticianResults;
import com.scottcaruso.utilities.Connection_Verification;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
static Context currentContext;
public static JSONObject jsonResponse;
static Spinner queryChoice;
public static Cursor thisCursor;
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
boolean viewingDisplay = DisplayPoliticianResults.isViewingDisplay();
boolean backButton = DisplayPoliticianResults.isBackButtonClicked();
if (viewingDisplay == true && backButton == false)
{
savedInstanceState.putBoolean("display exists", true);
savedInstanceState.putString("json object", DisplayPoliticianResults.getMasterPolObject().toString());
} else
{
savedInstanceState.putBoolean("display exists", false);
}
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
boolean displayExists = savedInstanceState.getBoolean("display exists");
if (displayExists)
{
try {
+ currentContext = this;
JSONObject savedObject = new JSONObject(savedInstanceState.getString("json object"));
DisplayPoliticianResults.showPoliticiansInMainView(savedObject, false);
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
DisplayPoliticianResults.setViewingDisplay(false);
this.setContentView(R.layout.main_screen);
//Allows the context to be passed across classes.
setCurrentContext(MainActivity.this);
//Create interface elements from the XML files
final EditText zipEntry = (EditText) findViewById(R.id.zipcodeentry);
final Button searchForPolsButton = (Button) findViewById(R.id.dosearchnow);
queryChoice = (Spinner) findViewById(R.id.spinner1);
final Button queryButton = (Button) findViewById(R.id.partyquery);
Log.i("Info","Created Main Menu elements based on XML files.");
searchForPolsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Build the onClick method, Handler, Intent, etc. See the method below!
buildClicker(zipEntry);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchForPolsButton.getWindowToken(), 0);
Log.i("Info","Hiding the keyboard");
}
});
//Click this button to retrieve politicians saved to local storage.
final Button retrieveSavedPols = (Button) findViewById(R.id.retrievefavorites);
retrieveSavedPols.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//String savedData; //This has been commented out because it is only used when accessing data directly.
Uri uri = PoliticianData.CONTENT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
}
});
//Handle a spinner click
queryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Info","Query clicked");
if (queryChoice.getSelectedItem().toString().equals("Republicans"))
{
Uri uri = PoliticianData.REPUBLICAN_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else if (queryChoice.getSelectedItem().toString().equals("Democrats"))
{
Uri uri = PoliticianData.DEMOCRAT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else
{
Toast toast = Toast.makeText(MainActivity.this, "There was an error making this query.", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
else
{
DisplayPoliticianResults.setViewingDisplay(false);
this.setContentView(R.layout.main_screen);
//Allows the context to be passed across classes.
setCurrentContext(MainActivity.this);
//Create interface elements from the XML files
final EditText zipEntry = (EditText) findViewById(R.id.zipcodeentry);
final Button searchForPolsButton = (Button) findViewById(R.id.dosearchnow);
queryChoice = (Spinner) findViewById(R.id.spinner1);
final Button queryButton = (Button) findViewById(R.id.partyquery);
Log.i("Info","Created Main Menu elements based on XML files.");
searchForPolsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Build the onClick method, Handler, Intent, etc. See the method below!
buildClicker(zipEntry);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchForPolsButton.getWindowToken(), 0);
Log.i("Info","Hiding the keyboard");
}
});
//Click this button to retrieve politicians saved to local storage.
final Button retrieveSavedPols = (Button) findViewById(R.id.retrievefavorites);
retrieveSavedPols.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//String savedData; //This has been commented out because it is only used when accessing data directly.
Uri uri = PoliticianData.CONTENT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
}
});
//Handle a spinner click
queryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Info","Query clicked");
if (queryChoice.getSelectedItem().toString().equals("Republicans"))
{
Uri uri = PoliticianData.REPUBLICAN_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else if (queryChoice.getSelectedItem().toString().equals("Democrats"))
{
Uri uri = PoliticianData.DEMOCRAT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else
{
Toast toast = Toast.makeText(MainActivity.this, "There was an error making this query.", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
public static void setCurrentContext (Context context)
{
currentContext = context;
}
public static Context getCurrentContext ()
{
return currentContext;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//Because there is so much going on here - and because we need to recreate all of this when the Back button is pressed.
public static void buildClicker(EditText zipEntry)
{
Log.i("Info","Attached onClick method to Zip Code entry button.");
Boolean connected = Connection_Verification.areWeConnected(getCurrentContext());
if (connected)
{
Log.i("Info","Connection established.");
String enteredZip = zipEntry.getText().toString();
Handler retrievalHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg.arg1 == RESULT_OK)
{
try {
jsonResponse = (JSONObject) msg.obj;
} catch (Exception e) {
Log.e("Error","There was a problem retrieving the json Response.");
}
if (jsonResponse == null)
{
Toast toast = Toast.makeText(MainActivity.getCurrentContext(), "You have entered an invalid zip code. Please try again.", Toast.LENGTH_LONG);
toast.show();
} else
{
DisplayPoliticianResults.showPoliticiansInMainView(jsonResponse, false);
}
}
}
};
Log.i("Info","Handler created.");
Messenger apiMessenger = new Messenger(retrievalHandler);
Intent startDataService = new Intent(getCurrentContext(), DataRetrievalService.class);
Log.i("Info","Intent to start data service started.");
startDataService.putExtra(DataRetrievalService.MESSENGER_KEY, apiMessenger);
startDataService.putExtra(DataRetrievalService.ZIP_KEY,enteredZip);
Log.i("Info","Put Messenger and Zip Code into Data Service intent.");
getCurrentContext().startService(startDataService);
} else
{
Log.i("Info","No internet connection found.");
Toast toast = Toast.makeText(getCurrentContext(), "There is no connection to the internet available. Please try again later, or view saved politicians.", Toast.LENGTH_LONG);
toast.show();
}
}
public static void turnCursorIntoDisplay(Cursor dataCursor)
{
JSONObject masterObject = new JSONObject();
JSONArray arrayOfPols = new JSONArray();
JSONObject thisObject = null;
if (dataCursor != null)
{
try
{
if (dataCursor.moveToFirst())
{
while(!dataCursor.isAfterLast())
{
thisObject = new JSONObject(dataCursor.getString(dataCursor.getColumnIndex("polObject")));
arrayOfPols.put(thisObject);
dataCursor.moveToNext();
}
masterObject.put("Politicians", arrayOfPols);
} else
{
if (SavedPoliticianProvider.JSONString != null)
{
Toast toast = Toast.makeText(MainActivity.getCurrentContext(), "There are no saved " + queryChoice.getSelectedItem().toString() + " to view.", Toast.LENGTH_LONG);
toast.show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
DisplayPoliticianResults.showPoliticiansInMainView(masterObject, true);
dataCursor.close();
} catch (Exception e) {
Toast toast = Toast.makeText(getCurrentContext(), "There are no politicians saved to storage.", Toast.LENGTH_LONG);
toast.show();
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
boolean displayExists = savedInstanceState.getBoolean("display exists");
if (displayExists)
{
try {
JSONObject savedObject = new JSONObject(savedInstanceState.getString("json object"));
DisplayPoliticianResults.showPoliticiansInMainView(savedObject, false);
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
DisplayPoliticianResults.setViewingDisplay(false);
this.setContentView(R.layout.main_screen);
//Allows the context to be passed across classes.
setCurrentContext(MainActivity.this);
//Create interface elements from the XML files
final EditText zipEntry = (EditText) findViewById(R.id.zipcodeentry);
final Button searchForPolsButton = (Button) findViewById(R.id.dosearchnow);
queryChoice = (Spinner) findViewById(R.id.spinner1);
final Button queryButton = (Button) findViewById(R.id.partyquery);
Log.i("Info","Created Main Menu elements based on XML files.");
searchForPolsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Build the onClick method, Handler, Intent, etc. See the method below!
buildClicker(zipEntry);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchForPolsButton.getWindowToken(), 0);
Log.i("Info","Hiding the keyboard");
}
});
//Click this button to retrieve politicians saved to local storage.
final Button retrieveSavedPols = (Button) findViewById(R.id.retrievefavorites);
retrieveSavedPols.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//String savedData; //This has been commented out because it is only used when accessing data directly.
Uri uri = PoliticianData.CONTENT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
}
});
//Handle a spinner click
queryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Info","Query clicked");
if (queryChoice.getSelectedItem().toString().equals("Republicans"))
{
Uri uri = PoliticianData.REPUBLICAN_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else if (queryChoice.getSelectedItem().toString().equals("Democrats"))
{
Uri uri = PoliticianData.DEMOCRAT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else
{
Toast toast = Toast.makeText(MainActivity.this, "There was an error making this query.", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
else
{
DisplayPoliticianResults.setViewingDisplay(false);
this.setContentView(R.layout.main_screen);
//Allows the context to be passed across classes.
setCurrentContext(MainActivity.this);
//Create interface elements from the XML files
final EditText zipEntry = (EditText) findViewById(R.id.zipcodeentry);
final Button searchForPolsButton = (Button) findViewById(R.id.dosearchnow);
queryChoice = (Spinner) findViewById(R.id.spinner1);
final Button queryButton = (Button) findViewById(R.id.partyquery);
Log.i("Info","Created Main Menu elements based on XML files.");
searchForPolsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Build the onClick method, Handler, Intent, etc. See the method below!
buildClicker(zipEntry);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchForPolsButton.getWindowToken(), 0);
Log.i("Info","Hiding the keyboard");
}
});
//Click this button to retrieve politicians saved to local storage.
final Button retrieveSavedPols = (Button) findViewById(R.id.retrievefavorites);
retrieveSavedPols.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//String savedData; //This has been commented out because it is only used when accessing data directly.
Uri uri = PoliticianData.CONTENT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
}
});
//Handle a spinner click
queryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Info","Query clicked");
if (queryChoice.getSelectedItem().toString().equals("Republicans"))
{
Uri uri = PoliticianData.REPUBLICAN_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else if (queryChoice.getSelectedItem().toString().equals("Democrats"))
{
Uri uri = PoliticianData.DEMOCRAT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else
{
Toast toast = Toast.makeText(MainActivity.this, "There was an error making this query.", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
boolean displayExists = savedInstanceState.getBoolean("display exists");
if (displayExists)
{
try {
currentContext = this;
JSONObject savedObject = new JSONObject(savedInstanceState.getString("json object"));
DisplayPoliticianResults.showPoliticiansInMainView(savedObject, false);
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
DisplayPoliticianResults.setViewingDisplay(false);
this.setContentView(R.layout.main_screen);
//Allows the context to be passed across classes.
setCurrentContext(MainActivity.this);
//Create interface elements from the XML files
final EditText zipEntry = (EditText) findViewById(R.id.zipcodeentry);
final Button searchForPolsButton = (Button) findViewById(R.id.dosearchnow);
queryChoice = (Spinner) findViewById(R.id.spinner1);
final Button queryButton = (Button) findViewById(R.id.partyquery);
Log.i("Info","Created Main Menu elements based on XML files.");
searchForPolsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Build the onClick method, Handler, Intent, etc. See the method below!
buildClicker(zipEntry);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchForPolsButton.getWindowToken(), 0);
Log.i("Info","Hiding the keyboard");
}
});
//Click this button to retrieve politicians saved to local storage.
final Button retrieveSavedPols = (Button) findViewById(R.id.retrievefavorites);
retrieveSavedPols.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//String savedData; //This has been commented out because it is only used when accessing data directly.
Uri uri = PoliticianData.CONTENT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
}
});
//Handle a spinner click
queryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Info","Query clicked");
if (queryChoice.getSelectedItem().toString().equals("Republicans"))
{
Uri uri = PoliticianData.REPUBLICAN_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else if (queryChoice.getSelectedItem().toString().equals("Democrats"))
{
Uri uri = PoliticianData.DEMOCRAT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else
{
Toast toast = Toast.makeText(MainActivity.this, "There was an error making this query.", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
else
{
DisplayPoliticianResults.setViewingDisplay(false);
this.setContentView(R.layout.main_screen);
//Allows the context to be passed across classes.
setCurrentContext(MainActivity.this);
//Create interface elements from the XML files
final EditText zipEntry = (EditText) findViewById(R.id.zipcodeentry);
final Button searchForPolsButton = (Button) findViewById(R.id.dosearchnow);
queryChoice = (Spinner) findViewById(R.id.spinner1);
final Button queryButton = (Button) findViewById(R.id.partyquery);
Log.i("Info","Created Main Menu elements based on XML files.");
searchForPolsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Build the onClick method, Handler, Intent, etc. See the method below!
buildClicker(zipEntry);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchForPolsButton.getWindowToken(), 0);
Log.i("Info","Hiding the keyboard");
}
});
//Click this button to retrieve politicians saved to local storage.
final Button retrieveSavedPols = (Button) findViewById(R.id.retrievefavorites);
retrieveSavedPols.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//String savedData; //This has been commented out because it is only used when accessing data directly.
Uri uri = PoliticianData.CONTENT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
}
});
//Handle a spinner click
queryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Info","Query clicked");
if (queryChoice.getSelectedItem().toString().equals("Republicans"))
{
Uri uri = PoliticianData.REPUBLICAN_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else if (queryChoice.getSelectedItem().toString().equals("Democrats"))
{
Uri uri = PoliticianData.DEMOCRAT_URI;
thisCursor = getContentResolver().query(uri, PoliticianData.PROJECTION, null, null, null);
turnCursorIntoDisplay(thisCursor);
} else
{
Toast toast = Toast.makeText(MainActivity.this, "There was an error making this query.", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}
|
diff --git a/maven/tests/org.jboss.tools.maven.configurators.tests/src/org/jboss/tools/maven/configurators/tests/JpaConfiguratorTest.java b/maven/tests/org.jboss.tools.maven.configurators.tests/src/org/jboss/tools/maven/configurators/tests/JpaConfiguratorTest.java
index 86e9c7d6..e55c6c52 100644
--- a/maven/tests/org.jboss.tools.maven.configurators.tests/src/org/jboss/tools/maven/configurators/tests/JpaConfiguratorTest.java
+++ b/maven/tests/org.jboss.tools.maven.configurators.tests/src/org/jboss/tools/maven/configurators/tests/JpaConfiguratorTest.java
@@ -1,83 +1,83 @@
package org.jboss.tools.maven.configurators.tests;
import org.eclipse.core.resources.IProject;
import org.eclipse.jpt.common.core.internal.resource.ResourceLocatorManager;
import org.eclipse.jpt.jpa.core.JpaFacet;
import org.eclipse.jpt.jpa.core.JpaProject;
import org.eclipse.jpt.jpa.core.JpaProjectManager;
import org.eclipse.jpt.jpa.core.JptJpaCorePlugin;
import org.eclipse.jst.common.project.facet.core.JavaFacet;
import org.eclipse.m2e.core.project.ResolverConfiguration;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.junit.Test;
@SuppressWarnings("restriction")
public class JpaConfiguratorTest extends AbstractMavenConfiguratorTest {
@Test
public void testSimpleJavaProjects() throws Exception {
IProject project = importProject( "projects/jpa/simple-2.0/pom.xml");
waitForJobsToComplete();
if (ResourceLocatorManager.instance().getResourceLocator(project) == null) {
//FIXME : JPT randomly decides to not pick up the
//MavenResourceLocator from our jpa plugin, leading to test failures
return;
}
assertIsJpaProject(project, JpaFacet.VERSION_2_0);
assertNoErrors(project);
JpaProjectManager manager = JptJpaCorePlugin.getJpaProjectManager();
JpaProject jpa = manager.getJpaProject(project);
String pid = jpa.getJpaPlatform().getId();
assertTrue(pid + " is not the expected platform", pid.startsWith("eclipselink") || pid.startsWith("generic"));
project = importProject( "projects/jpa/simple-1.0/pom.xml");
waitForJobsToComplete();
assertIsJpaProject(project, JpaFacet.VERSION_1_0);
assertNoErrors(project);
jpa = manager.getJpaProject(project);
pid = jpa.getJpaPlatform().getId();
- assertTrue(pid + " is not the expected hibernate platform", pid.startsWith("hibernate"));
+ assertTrue(pid + " is not the expected hibernate platform", pid.startsWith("hibernate") || pid.startsWith("generic"));
}
protected void assertIsJpaProject(IProject project, IProjectFacetVersion expectedJpaVersion) throws Exception {
IFacetedProject facetedProject = ProjectFacetsManager.create(project);
assertNotNull(project.getName() + " is not a faceted project", facetedProject);
assertEquals("Unexpected JPA Version", expectedJpaVersion, facetedProject.getInstalledVersion(JpaFacet.FACET));
assertTrue("Java Facet is missing", facetedProject.hasProjectFacet(JavaFacet.FACET));
}
/*
@Test
public void testMultiModule() throws Exception {
IProject[] projects = importProjects("projects/jpa/multi",
new String[]{ "pom.xml",
"multi-ear/pom.xml",
"multi-ejb/pom.xml",
"multi-web/pom.xml"},
new ResolverConfiguration());
waitForJobsToComplete();
IProject pom = projects[0];
IProject ear = projects[1];
IProject ejb = projects[2];
IProject web = projects[3];
if (ResourceLocatorManager.instance().getResourceLocator(ejb) == null) {
//FIXME : JPT randomly decides to not pick up the
//MavenResourceLocator from our jpa plugin, leading to test failures
return;
}
assertNoErrors(pom);
assertNoErrors(ejb);
assertNoErrors(ear);
assertNoErrors(web);
assertIsJpaProject(ejb, JpaFacet.VERSION_2_0);
}
*/
}
| true | true | public void testSimpleJavaProjects() throws Exception {
IProject project = importProject( "projects/jpa/simple-2.0/pom.xml");
waitForJobsToComplete();
if (ResourceLocatorManager.instance().getResourceLocator(project) == null) {
//FIXME : JPT randomly decides to not pick up the
//MavenResourceLocator from our jpa plugin, leading to test failures
return;
}
assertIsJpaProject(project, JpaFacet.VERSION_2_0);
assertNoErrors(project);
JpaProjectManager manager = JptJpaCorePlugin.getJpaProjectManager();
JpaProject jpa = manager.getJpaProject(project);
String pid = jpa.getJpaPlatform().getId();
assertTrue(pid + " is not the expected platform", pid.startsWith("eclipselink") || pid.startsWith("generic"));
project = importProject( "projects/jpa/simple-1.0/pom.xml");
waitForJobsToComplete();
assertIsJpaProject(project, JpaFacet.VERSION_1_0);
assertNoErrors(project);
jpa = manager.getJpaProject(project);
pid = jpa.getJpaPlatform().getId();
assertTrue(pid + " is not the expected hibernate platform", pid.startsWith("hibernate"));
}
| public void testSimpleJavaProjects() throws Exception {
IProject project = importProject( "projects/jpa/simple-2.0/pom.xml");
waitForJobsToComplete();
if (ResourceLocatorManager.instance().getResourceLocator(project) == null) {
//FIXME : JPT randomly decides to not pick up the
//MavenResourceLocator from our jpa plugin, leading to test failures
return;
}
assertIsJpaProject(project, JpaFacet.VERSION_2_0);
assertNoErrors(project);
JpaProjectManager manager = JptJpaCorePlugin.getJpaProjectManager();
JpaProject jpa = manager.getJpaProject(project);
String pid = jpa.getJpaPlatform().getId();
assertTrue(pid + " is not the expected platform", pid.startsWith("eclipselink") || pid.startsWith("generic"));
project = importProject( "projects/jpa/simple-1.0/pom.xml");
waitForJobsToComplete();
assertIsJpaProject(project, JpaFacet.VERSION_1_0);
assertNoErrors(project);
jpa = manager.getJpaProject(project);
pid = jpa.getJpaPlatform().getId();
assertTrue(pid + " is not the expected hibernate platform", pid.startsWith("hibernate") || pid.startsWith("generic"));
}
|
diff --git a/bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/commands/DeleteCommand.java b/bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/commands/DeleteCommand.java
index 8a5308171..500110456 100644
--- a/bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/commands/DeleteCommand.java
+++ b/bundles/org.eclipse.wst.xsd.ui/src-common/org/eclipse/wst/xsd/ui/internal/common/commands/DeleteCommand.java
@@ -1,120 +1,125 @@
/*******************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.xsd.ui.internal.common.commands;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.wst.xsd.ui.internal.adapters.XSDVisitor;
import org.eclipse.xsd.XSDAttributeDeclaration;
import org.eclipse.xsd.XSDAttributeGroupDefinition;
import org.eclipse.xsd.XSDAttributeUse;
import org.eclipse.xsd.XSDComplexTypeDefinition;
import org.eclipse.xsd.XSDConcreteComponent;
import org.eclipse.xsd.XSDElementDeclaration;
import org.eclipse.xsd.XSDEnumerationFacet;
import org.eclipse.xsd.XSDModelGroup;
import org.eclipse.xsd.XSDModelGroupDefinition;
import org.eclipse.xsd.XSDParticle;
import org.eclipse.xsd.XSDSchema;
import org.eclipse.xsd.XSDSimpleTypeDefinition;
public class DeleteCommand extends BaseCommand
{
XSDConcreteComponent target;
public DeleteCommand(String label, XSDConcreteComponent target)
{
super(label);
this.target = target;
}
public void execute()
{
XSDVisitor visitor = new XSDVisitor()
{
public void visitElementDeclaration(org.eclipse.xsd.XSDElementDeclaration element)
{
if (element.getTypeDefinition() == target)
{
XSDSimpleTypeDefinition type = target.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("string"); //$NON-NLS-1$
element.setTypeDefinition(type);
}
super.visitElementDeclaration(element);
}
};
XSDConcreteComponent parent = target.getContainer();
if (target instanceof XSDModelGroup || target instanceof XSDElementDeclaration || target instanceof XSDModelGroupDefinition)
{
if (parent instanceof XSDParticle)
{
if (parent.getContainer() instanceof XSDModelGroup)
{
XSDModelGroup modelGroup = (XSDModelGroup) ((XSDParticle) parent).getContainer();
modelGroup.getContents().remove(parent);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeDeclaration)
{
if (parent instanceof XSDAttributeUse)
{
EObject obj = parent.eContainer();
XSDComplexTypeDefinition complexType = null;
while (obj != null)
{
if (obj instanceof XSDComplexTypeDefinition)
{
complexType = (XSDComplexTypeDefinition) obj;
break;
}
obj = obj.eContainer();
}
if (complexType != null)
{
complexType.getAttributeContents().remove(parent);
}
if (parent.getContainer() instanceof XSDAttributeGroupDefinition)
{
XSDAttributeGroupDefinition attrGroup = (XSDAttributeGroupDefinition) parent.getContainer();
attrGroup.getContents().remove(parent);
}
}
+ else if (parent instanceof XSDSchema)
+ {
+ visitor.visitSchema(target.getSchema());
+ ((XSDSchema) parent).getContents().remove(target);
+ }
}
else if (target instanceof XSDAttributeGroupDefinition &&
parent instanceof XSDComplexTypeDefinition)
{
((XSDComplexTypeDefinition)parent).getAttributeContents().remove(target);
}
else if (target instanceof XSDEnumerationFacet)
{
XSDEnumerationFacet enumerationFacet = (XSDEnumerationFacet)target;
enumerationFacet.getSimpleTypeDefinition().getFacetContents().remove(enumerationFacet);
}
else
{
if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
}
}
| true | true | public void execute()
{
XSDVisitor visitor = new XSDVisitor()
{
public void visitElementDeclaration(org.eclipse.xsd.XSDElementDeclaration element)
{
if (element.getTypeDefinition() == target)
{
XSDSimpleTypeDefinition type = target.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("string"); //$NON-NLS-1$
element.setTypeDefinition(type);
}
super.visitElementDeclaration(element);
}
};
XSDConcreteComponent parent = target.getContainer();
if (target instanceof XSDModelGroup || target instanceof XSDElementDeclaration || target instanceof XSDModelGroupDefinition)
{
if (parent instanceof XSDParticle)
{
if (parent.getContainer() instanceof XSDModelGroup)
{
XSDModelGroup modelGroup = (XSDModelGroup) ((XSDParticle) parent).getContainer();
modelGroup.getContents().remove(parent);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeDeclaration)
{
if (parent instanceof XSDAttributeUse)
{
EObject obj = parent.eContainer();
XSDComplexTypeDefinition complexType = null;
while (obj != null)
{
if (obj instanceof XSDComplexTypeDefinition)
{
complexType = (XSDComplexTypeDefinition) obj;
break;
}
obj = obj.eContainer();
}
if (complexType != null)
{
complexType.getAttributeContents().remove(parent);
}
if (parent.getContainer() instanceof XSDAttributeGroupDefinition)
{
XSDAttributeGroupDefinition attrGroup = (XSDAttributeGroupDefinition) parent.getContainer();
attrGroup.getContents().remove(parent);
}
}
}
else if (target instanceof XSDAttributeGroupDefinition &&
parent instanceof XSDComplexTypeDefinition)
{
((XSDComplexTypeDefinition)parent).getAttributeContents().remove(target);
}
else if (target instanceof XSDEnumerationFacet)
{
XSDEnumerationFacet enumerationFacet = (XSDEnumerationFacet)target;
enumerationFacet.getSimpleTypeDefinition().getFacetContents().remove(enumerationFacet);
}
else
{
if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
}
| public void execute()
{
XSDVisitor visitor = new XSDVisitor()
{
public void visitElementDeclaration(org.eclipse.xsd.XSDElementDeclaration element)
{
if (element.getTypeDefinition() == target)
{
XSDSimpleTypeDefinition type = target.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("string"); //$NON-NLS-1$
element.setTypeDefinition(type);
}
super.visitElementDeclaration(element);
}
};
XSDConcreteComponent parent = target.getContainer();
if (target instanceof XSDModelGroup || target instanceof XSDElementDeclaration || target instanceof XSDModelGroupDefinition)
{
if (parent instanceof XSDParticle)
{
if (parent.getContainer() instanceof XSDModelGroup)
{
XSDModelGroup modelGroup = (XSDModelGroup) ((XSDParticle) parent).getContainer();
modelGroup.getContents().remove(parent);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeDeclaration)
{
if (parent instanceof XSDAttributeUse)
{
EObject obj = parent.eContainer();
XSDComplexTypeDefinition complexType = null;
while (obj != null)
{
if (obj instanceof XSDComplexTypeDefinition)
{
complexType = (XSDComplexTypeDefinition) obj;
break;
}
obj = obj.eContainer();
}
if (complexType != null)
{
complexType.getAttributeContents().remove(parent);
}
if (parent.getContainer() instanceof XSDAttributeGroupDefinition)
{
XSDAttributeGroupDefinition attrGroup = (XSDAttributeGroupDefinition) parent.getContainer();
attrGroup.getContents().remove(parent);
}
}
else if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
else if (target instanceof XSDAttributeGroupDefinition &&
parent instanceof XSDComplexTypeDefinition)
{
((XSDComplexTypeDefinition)parent).getAttributeContents().remove(target);
}
else if (target instanceof XSDEnumerationFacet)
{
XSDEnumerationFacet enumerationFacet = (XSDEnumerationFacet)target;
enumerationFacet.getSimpleTypeDefinition().getFacetContents().remove(enumerationFacet);
}
else
{
if (parent instanceof XSDSchema)
{
visitor.visitSchema(target.getSchema());
((XSDSchema) parent).getContents().remove(target);
}
}
}
|
diff --git a/src/com/nononsenseapps/notepad/NotesListFragment.java b/src/com/nononsenseapps/notepad/NotesListFragment.java
index 71185710..b76a87bb 100644
--- a/src/com/nononsenseapps/notepad/NotesListFragment.java
+++ b/src/com/nononsenseapps/notepad/NotesListFragment.java
@@ -1,2023 +1,2023 @@
/*
* Copyright (C) 2012 Jonas Kalderstam
*
* 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.nononsenseapps.notepad;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import com.nononsenseapps.helpers.UpdateNotifier;
import com.nononsenseapps.helpers.dualpane.DualLayoutActivity;
import com.nononsenseapps.helpers.dualpane.NoNonsenseListFragment;
import com.nononsenseapps.notepad.interfaces.OnModalDeleteListener;
import com.nononsenseapps.notepad.prefs.MainPrefs;
import com.nononsenseapps.notepad.prefs.SyncPrefs;
import com.nononsenseapps.notepad.sync.SyncAdapter;
import com.nononsenseapps.ui.NoteCheckBox;
import com.nononsenseapps.ui.SectionAdapter;
import com.nononsenseapps.util.TimeHelper;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.accounts.AccountManager;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;
import android.text.format.Time;
import com.nononsenseapps.helpers.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;
public class NotesListFragment extends NoNonsenseListFragment implements
SearchView.OnQueryTextListener, OnItemLongClickListener,
OnModalDeleteListener, LoaderManager.LoaderCallbacks<Cursor>,
OnSharedPreferenceChangeListener {
private Callbacks mCallbacks = sDummyCallbacks;
private int mActivatedPosition = 0; // ListView.INVALID_POSITION;
public interface Callbacks {
public void onItemSelected(long id);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(long id) {
}
};
// Parent, list used for dragdrop
private static final String[] PROJECTION = new String[] {
NotePad.Notes._ID, NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_NOTE,
NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE,
NotePad.Notes.COLUMN_NAME_DUE_DATE,
NotePad.Notes.COLUMN_NAME_INDENTLEVEL,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS,
NotePad.Notes.COLUMN_NAME_LIST };
// public static final String SELECTEDPOS = "selectedpos";
// public static final String SELECTEDID = "selectedid";
// For logging and debugging
private static final String TAG = "NotesListFragment";
private static final int CHECK_SINGLE = 1;
private static final int CHECK_MULTI = 2;
private static final int CHECK_SINGLE_FUTURE = 3;
private static final String SAVEDPOS = "listSavedPos";
private static final String SAVEDID = "listSavedId";
// private static final String SHOULD_OPEN_NOTE = "shouldOpenNote";
public static final String SECTION_STATE_LISTS = "listnames";
private static final int LOADER_LISTNAMES = -78;
// Will sort modification dates
private final Comparator<String> alphaComparator = new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
};
private static final int LOADER_REGULARLIST = -99;
// Date loaders
public static final String SECTION_STATE_DATE = MainPrefs.DUEDATESORT;
private static final int LOADER_DATEOVERDUE = -101;
private static final int LOADER_DATETODAY = -102;
private static final int LOADER_DATETOMORROW = -103;
private static final int LOADER_DATEWEEK = -104;
private static final int LOADER_DATEFUTURE = -105;
private static final int LOADER_DATENONE = -106;
private static final int LOADER_DATECOMPLETED = -107;
// This will sort date headers properly
private Comparator<String> dateComparator;
// Modification loaders
public static final String SECTION_STATE_MOD = MainPrefs.MODIFIEDSORT;
private static final int LOADER_MODTODAY = -201;
private static final int LOADER_MODYESTERDAY = -202;
private static final int LOADER_MODWEEK = -203;
private static final int LOADER_MODPAST = -204;
public static final String LISTID = "com.nononsenseapps.notepad.ListId";
// Will sort modification dates
private Comparator<String> modComparator;
private final Map<Long, String> listNames = new LinkedHashMap<Long, String>();
private long mCurId;
// private boolean idInvalid = false;
public SearchView mSearchView;
public MenuItem mSearchItem;
private String currentQuery = "";
private int checkMode = CHECK_SINGLE;
private ModeCallbackHC modeCallback;
private long mCurListId = -1;
// private OnEditorDeleteListener onDeleteListener;
// private SimpleCursorAdapter mAdapter;
private SectionAdapter mSectionAdapter;
private final HashSet<Integer> activeLoaders = new HashSet<Integer>();
private long newNoteIdToSelect = -1;
private Menu mOptionsMenu;
private View mRefreshIndeterminateProgressView = null;
private BroadcastReceiver syncFinishedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SyncAdapter.SYNC_STARTED)) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
setRefreshActionItemState(true);
}
});
} else if (intent.getAction().equals(SyncAdapter.SYNC_FINISHED)) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
setRefreshActionItemState(false);
}
});
tellUser(context,
intent.getExtras().getInt(SyncAdapter.SYNC_RESULT));
}
}
private void tellUser(Context context, int result) {
int text = R.string.sync_failed;
switch (result) {
case SyncAdapter.ERROR:
text = R.string.sync_failed;
break;
case SyncAdapter.LOGIN_FAIL:
text = R.string.sync_login_failed;
break;
case SyncAdapter.SUCCESS:
default:
return;
}
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
}
};
private static String sortType = NotePad.Notes.DUEDATE_SORT_TYPE;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
this.activity = (DualLayoutActivity) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
activity = null;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (this.mCurListId != -1) {
// activity.findViewById(R.id.listContainer).setVisibility(View.VISIBLE);
// activity.findViewById(R.id.progressContainer).setVisibility(View.GONE);
Bundle args = new Bundle();
// if (activity.getCurrentContent().equals(
// DualLayoutActivity.CONTENTVIEW.DUAL))
// args.putBoolean(SHOULD_OPEN_NOTE, true);
refreshList(args);
} else {
// activity.findViewById(R.id.listContainer).setVisibility(View.GONE);
// activity.findViewById(R.id.progressContainer).setVisibility(View.VISIBLE);
}
// Set list preferences
setSingleCheck();
}
public void handleNoteIntent(Intent intent) {
Log.d(TAG, "handleNoteIntent");
if (intent != null
&& (Intent.ACTION_EDIT.equals(intent.getAction()) || Intent.ACTION_VIEW
.equals(intent.getAction()))) {
// just highlight it
String newId = intent.getData().getPathSegments()
.get(NotePad.Notes.NOTE_ID_PATH_POSITION);
long noteId = Long.parseLong(newId);
int pos = getPosOfId(noteId);
if (pos > -1) {
setActivatedPosition(showNote(pos));
} else {
newNoteIdToSelect = noteId;
}
}
}
/**
* Will try to open the previously open note, but will default to first note
* if none was open
*/
/*
* private void showFirstBestNote() { if (mSectionAdapter != null) { if
* (mSectionAdapter.isEmpty()) { // DOn't do shit } else {
* setActivatedPosition(showNote(mActivatedPosition)); } } }
*/
private void setupSearchView() {
Log.d("NotesListFragment", "setup search view");
if (mSearchView != null) {
mSearchView.setIconifiedByDefault(true);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setQueryHint(getString(R.string.search_hint));
}
}
private int getPosOfId(long id) {
if (mSectionAdapter == null || mSectionAdapter.isSectioned())
return ListView.INVALID_POSITION;
int length = mSectionAdapter.getCount();
int position;
for (position = 0; position < length; position++) {
if (id == mSectionAdapter.getItemId(position)) {
break;
}
}
if (position == length) {
// Happens both if list is empty
// and if id is -1
position = ListView.INVALID_POSITION;
}
return position;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate menu from XML resource
// if (FragmentLayout.lightTheme)
// inflater.inflate(R.menu.list_options_menu_light, menu);
// else
mOptionsMenu = menu;
inflater.inflate(R.menu.list_options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) activity
.getSystemService(Context.SEARCH_SERVICE);
mSearchItem = menu.findItem(R.id.menu_search);
mSearchView = (SearchView) mSearchItem.getActionView();
if (mSearchView != null)
mSearchView.setSearchableInfo(searchManager
.getSearchableInfo(activity.getComponentName()));
// searchView.setIconifiedByDefault(true); // Do iconify the widget;
// Don't
// // expand by default
// searchView.setSubmitButtonEnabled(false);
// searchView.setOnCloseListener(this);
// searchView.setOnQueryTextListener(this);
setupSearchView();
// Generate any additional actions that can be performed on the
// overall list. In a normal install, there are no additional
// actions found here, but this allows other applications to extend
// our menu with their own actions.
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
public static int getNoteIdFromUri(Uri noteUri) {
if (noteUri != null)
return Integer.parseInt(noteUri.getPathSegments().get(
NotePad.Notes.NOTE_ID_PATH_POSITION));
else
return -1;
}
private void handleNoteCreation(long listId) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_INSERT);
intent.setData(NotePad.Notes.CONTENT_VISIBLE_URI);
intent.putExtra(NotePad.Notes.COLUMN_NAME_LIST, listId);
// If tablet mode, deliver directly
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
((MainActivity) activity).onNewIntent(intent);
}
// Otherwise start a new editor activity
else {
intent.setClass(activity, RightActivity.class);
startActivity(intent);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
handleNoteCreation(mCurListId);
return true;
case R.id.menu_clearcompleted:
ContentValues values = new ContentValues();
values.put(NotePad.Notes.COLUMN_NAME_MODIFIED, -1); // -1 anything
// that isnt 0
// or 1
// indicates
// that we dont
// want to
// change the
// current value
values.put(NotePad.Notes.COLUMN_NAME_LOCALHIDDEN, 1);
// Handle all notes showing
String inList;
String[] args;
if (mCurListId == MainActivity.ALL_NOTES_ID) {
inList = "";
args = new String[] { getText(R.string.gtask_status_completed)
.toString() };
} else {
inList = " AND " + NotePad.Notes.COLUMN_NAME_LIST + " IS ?";
args = new String[] {
getText(R.string.gtask_status_completed).toString(),
Long.toString(mCurListId) };
}
activity.getContentResolver().update(NotePad.Notes.CONTENT_URI,
values,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ?" + inList,
args);
UpdateNotifier.notifyChangeNote(activity);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To get the call back to add items to the menu
setHasOptionsMenu(true);
// Listen to changes to sort order
PreferenceManager.getDefaultSharedPreferences(activity)
.registerOnSharedPreferenceChangeListener(this);
if (getResources().getBoolean(R.bool.atLeast14)) {
// Share action provider
modeCallback = new ModeCallbackICS(this);
} else {
// Share button
modeCallback = new ModeCallbackHC(this);
}
if (modeCallback != null)
modeCallback.setDeleteListener(this);
this.mCurListId = -1;
if (getArguments() != null && getArguments().containsKey(LISTID)) {
mCurListId = getArguments().getLong(LISTID);
}
if (savedInstanceState != null) {
Log.d("NotesListFragment", "onCreate saved not null");
mCurListId = savedInstanceState.getLong(LISTID);
mActivatedPosition = savedInstanceState.getInt(SAVEDPOS, 0);
mCurId = savedInstanceState.getLong(SAVEDID, -1);
} else {
mActivatedPosition = 0;
mCurId = -1;
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("NotesListFragment", "onSaveInstanceState");
outState.putInt(SAVEDPOS, mActivatedPosition);
outState.putLong(SAVEDID, mCurId);
outState.putLong(LISTID, mCurListId);
}
@Override
public void onPause() {
super.onPause();
setSingleCheck();
activity.unregisterReceiver(syncFinishedReceiver);
}
@Override
public void onDestroy() {
super.onDestroy();
destroyActiveLoaders();
destroyDateLoaders();
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
@Override
public void onResume() {
super.onResume();
Log.d("NotesListFragment", "onResume");
activity.registerReceiver(syncFinishedReceiver, new IntentFilter(
SyncAdapter.SYNC_FINISHED));
activity.registerReceiver(syncFinishedReceiver, new IntentFilter(
SyncAdapter.SYNC_STARTED));
String accountName = PreferenceManager.getDefaultSharedPreferences(
activity).getString(SyncPrefs.KEY_ACCOUNT, "");
// Sync state might have changed, make sure we're spinning when we
// should
if (accountName != null && !accountName.isEmpty())
setRefreshActionItemState(ContentResolver.isSyncActive(SyncPrefs
.getAccount(AccountManager.get(activity), accountName),
NotePad.AUTHORITY));
}
@Override
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
Log.d("listproto", "OnListItemClick pos " + position + " id " + id);
// Will tell the activity to open the note
mActivatedPosition = showNote(position);
}
public void setActivateOnItemClick(boolean activateOnItemClick) {
getListView().setChoiceMode(
activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
public void setActivatedPosition(int position) {
if (checkMode == CHECK_SINGLE_FUTURE) {
setSingleCheck();
}
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
/**
* Larger values than the list contains are re-calculated to valid
* positions. If list is empty, no note is opened.
*
* returns position of note in list
*/
private int showNote(int index) {
// if it's -1 to start with, we try with zero
if (index < 0) {
index = 0;
}
if (mSectionAdapter != null) {
index = index >= mSectionAdapter.getCount() ? mSectionAdapter
.getCount() - 1 : index;
Log.d(TAG, "showNote valid index to show is: " + index);
if (index > -1) {
Log.d("listproto", "Going to try and open index: " + index);
Log.d("listproto", "Section adapter gave me this id: " + mCurId);
mCurId = mSectionAdapter.getItemId(index);
mCallbacks.onItemSelected(mCurId);
} else {
// Empty search, do NOT display new note.
mActivatedPosition = 0;
mCurId = -1;
// Default show first note when search is cancelled.
}
}
return index;
}
/**
* Will re-list all notes, and show the note with closest position to
* original
*/
/*
* public void onDelete() {
*
* Log.d(TAG, "onDelete"); // Only do anything if id is valid! if (mCurId >
* -1) { // if (onDeleteListener != null) { // // Tell fragment to delete
* the current note // onDeleteListener.onEditorDelete(mCurId); // } if
* (activity.getCurrentContent().equals(
* DualLayoutActivity.CONTENTVIEW.DUAL)) { autoOpenNote = true; }
*
* // if (FragmentLayout.LANDSCAPE_MODE) { // } else { // // Get the id of
* the currently "selected" note // // This matters if we switch to
* landscape mode // reCalculateValidValuesAfterDelete(); // } } }
*/
private void reCalculateValidValuesAfterDelete() {
int index = mActivatedPosition;
if (mSectionAdapter != null) {
index = index >= mSectionAdapter.getCount() ? mSectionAdapter
.getCount() - 1 : index;
Log.d(TAG, "ReCalculate valid index is: " + index);
if (index == -1) {
// Completely empty list.
mActivatedPosition = 0;
mCurId = -1;
} else { // if (index != -1) {
mActivatedPosition = index;
mCurId = mSectionAdapter.getItemId(index);
}
}
}
/**
* Recalculate note to select from id
*/
public void reSelectId() {
int pos = getPosOfId(mCurId);
Log.d(TAG, "reSelectId id pos: " + mCurId + " " + pos);
setActivatedPosition(pos);
}
private SimpleCursorAdapter getThemedAdapter(Cursor cursor) {
// The names of the cursor columns to display in the view,
// initialized
// to the title column
String[] dataColumns = { NotePad.Notes.COLUMN_NAME_INDENTLEVEL,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS,
NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_NOTE,
NotePad.Notes.COLUMN_NAME_DUE_DATE };
// The view IDs that will display the cursor columns, initialized to
// the TextView in noteslist_item.xml
// My hacked adapter allows the boolean to be set if the string matches
// gtasks string values for them. Needs id as well (set after first)
int[] viewIDs = { R.id.itemIndent, R.id.itemDone, R.id.itemTitle,
R.id.itemNote, R.id.itemDate };
int themed_item = R.layout.noteslist_item;
// Support two different list items
// if (activity != null) {
// if (PreferenceManager.getDefaultSharedPreferences(activity)
// .getBoolean(MainPrefs.KEY_LISTITEM, true)) {
// themed_item = R.layout.noteslist_item;
// } else {
// themed_item = R.layout.noteslist_item_doublenote;
// }
// }
// Set appearence settings
final boolean hidden_checkbox = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENCHECKBOX, false);
final boolean hidden_note = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENNOTE, false);
final boolean hidden_date = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENDATE, false);
final int title_rows = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_TITLEROWS, "2"));
// Creates the backing adapter for the ListView.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(activity,
themed_item, cursor, dataColumns, viewIDs, 0);
final OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean checked) {
ContentValues values = new ContentValues();
String status = getText(R.string.gtask_status_uncompleted)
.toString();
if (checked)
status = getText(R.string.gtask_status_completed)
.toString();
values.put(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS, status);
long id = ((NoteCheckBox) buttonView).getNoteId();
if (id > -1) {
activity.getContentResolver().update(
NotesEditorFragment.getUriFrom(id), values, null,
null);
UpdateNotifier.notifyChangeNote(activity,
NotesEditorFragment.getUriFrom(id));
}
}
};
// In order to set the checked state in the checkbox
// and other theme stuff
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
static final String indent = " ";
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS)) {
NoteCheckBox cb = (NoteCheckBox) view;
cb.setOnCheckedChangeListener(null);
long id = cursor.getLong(cursor
.getColumnIndex(BaseColumns._ID));
cb.setNoteId(id);
String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
cb.setChecked(true);
} else {
cb.setChecked(false);
}
// Set a simple on change listener that updates the note on
// changes.
cb.setOnCheckedChangeListener(listener);
// hide/show
if (hidden_checkbox)
((View) cb.getParent()).setVisibility(View.GONE);
else
((View) cb.getParent()).setVisibility(View.VISIBLE);
return true;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)
|| columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE)) {
final TextView tv = (TextView) view;
// Hide empty note
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)) {
final String noteText = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE));
final boolean isEmpty = noteText == null
|| noteText.isEmpty();
// Set height to zero if it's empty, otherwise wrap
if (hidden_note || isEmpty)
tv.setVisibility(View.GONE);
else
tv.setVisibility(View.VISIBLE);
} else {
// set number of rows
if (1 == title_rows || 2 == title_rows)
tv.setMaxLines(title_rows);
else
tv.setMaxLines(10);
}
// Set strike through on completed tasks
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
// Set appropriate BITMASK
tv.setPaintFlags(tv.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
} else {
// Will clear strike-through. Just a BITMASK so do some
// magic
if (Paint.STRIKE_THRU_TEXT_FLAG == (tv.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG))
tv.setPaintFlags(tv.getPaintFlags()
- Paint.STRIKE_THRU_TEXT_FLAG);
}
// Return false so the normal call is used to set the text
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE)) {
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE));
final TextView tv = (TextView) view;
if (text == null || text.isEmpty() || hidden_date) {
tv.setVisibility(View.GONE);
} else {
tv.setVisibility(View.VISIBLE);
}
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL)) {
// Should only set this on the sort options where it is
// expected
final TextView indentView = (TextView) view;
final int level = cursor.getInt(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL));
// Now set the width
String width = "";
if (sortType.equals(NotePad.Notes.POSSUBSORT_SORT_TYPE)) {
int l;
for (l = 0; l < level; l++) {
width += indent;
}
}
indentView.setText(width);
return true;
}
return false;
}
});
return adapter;
}
@Override
public boolean onQueryTextChange(String query) {
Log.d("NotesListFragment", "onQueryTextChange: " + query);
if (!currentQuery.equals(query)) {
Log.d("NotesListFragment", "this is a new query");
currentQuery = query;
refreshList(null);
// hide the clear completed option until search is over
MenuItem clearCompleted = mOptionsMenu
.findItem(R.id.menu_clearcompleted);
if (clearCompleted != null) {
// Only show this button if there is a list to create notes in
if ("".equals(query)) {
clearCompleted.setVisible(true);
} else {
clearCompleted.setVisible(false);
}
}
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// Just do what we do on text change
return onQueryTextChange(query);
}
public void setSingleCheck() {
Log.d(TAG, "setSingleCheck");
checkMode = CHECK_SINGLE;
ListView lv = getListView();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
// Fix the selection before releasing that
// lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
lv.setChoiceMode(ListView.CHOICE_MODE_NONE);
} else {
// Not nice to show selected item in list when no editor is showing
lv.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
lv.setLongClickable(true);
lv.setOnItemLongClickListener(this);
}
public void setFutureSingleCheck() {
// REsponsible for disabling the modal selector in the future.
// can't do it now because it has to destroy itself etc...
if (checkMode == CHECK_MULTI) {
checkMode = CHECK_SINGLE_FUTURE;
}
}
public void setMultiCheck(int pos) {
Log.d(TAG, "setMutliCheck: " + pos + " modeCallback = " + modeCallback);
// Do this on long press
checkMode = CHECK_MULTI;
ListView lv = getListView();
lv.clearChoices();
lv.setMultiChoiceModeListener(modeCallback);
lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setItemChecked(pos, true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.d(TAG, "onLongClick");
if (checkMode == CHECK_SINGLE) {
// get the position which was selected
Log.d("NotesListFragment", "onLongClick, selected item pos: "
+ position + ", id: " + id);
// change to multiselect mode and select that item
setMultiCheck(position);
} else {
// Should never happen
// Let modal listener handle it
}
return true;
}
public void setRefreshActionItemState(boolean refreshing) {
// On Honeycomb, we can set the state of the refresh button by giving it
// a custom
// action view.
Log.d(TAG, "setRefreshActionState");
if (mOptionsMenu == null) {
Log.d(TAG, "setRefreshActionState: menu is null, returning");
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_sync);
Log.d(TAG,
"setRefreshActionState: refreshItem not null? "
+ Boolean.toString(refreshItem != null));
if (refreshItem != null) {
if (refreshing) {
Log.d(TAG,
"setRefreshActionState: refreshing: "
+ Boolean.toString(refreshing));
if (mRefreshIndeterminateProgressView == null) {
Log.d(TAG,
"setRefreshActionState: mRefreshIndeterminateProgressView was null, inflating one...");
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRefreshIndeterminateProgressView = inflater.inflate(
R.layout.actionbar_indeterminate_progress, null);
}
refreshItem.setActionView(mRefreshIndeterminateProgressView);
} else {
Log.d(TAG, "setRefreshActionState: setting null actionview");
refreshItem.setActionView(null);
}
}
}
private class ModeCallbackHC implements MultiChoiceModeListener {
protected NotesListFragment list;
protected HashMap<Long, String> textToShare;
protected OnModalDeleteListener onDeleteListener;
protected HashSet<Integer> notesToDelete;
protected ActionMode mode;
public ModeCallbackHC(NotesListFragment list) {
textToShare = new HashMap<Long, String>();
notesToDelete = new HashSet<Integer>();
this.list = list;
}
public void setDeleteListener(OnModalDeleteListener onDeleteListener) {
this.onDeleteListener = onDeleteListener;
}
protected Intent createShareIntent(String text) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
return shareIntent;
}
protected void addTextToShare(long id) {
// Read note
Uri uri = NotesEditorFragment.getUriFrom(id);
Cursor cursor = openNote(uri);
if (cursor != null && !cursor.isClosed() && cursor.moveToFirst()) {
// Requery in case something changed while paused (such as the
// title)
// cursor.requery();
/*
* Moves to the first record. Always call moveToFirst() before
* accessing data in a Cursor for the first time. The semantics
* of using a Cursor are that when it is created, its internal
* index is pointing to a "place" immediately before the first
* record.
*/
String note = "";
int colTitleIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE);
if (colTitleIndex > -1)
note = cursor.getString(colTitleIndex) + "\n";
int colDueIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE);
String due = "";
if (colDueIndex > -1)
due = cursor.getString(colDueIndex);
if (due != null && !due.isEmpty()) {
Time date = new Time(Time.getCurrentTimezone());
date.parse3339(due);
note = note + "due date: " + date.format3339(true) + "\n";
}
int colNoteIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE);
if (colNoteIndex > -1)
note = note + "\n" + cursor.getString(colNoteIndex);
// Put in hash
textToShare.put(id, note);
}
if (cursor != null)
cursor.close();
}
protected void delTextToShare(long id) {
textToShare.remove(id);
}
protected String buildTextToShare() {
String text = "";
ArrayList<String> notes = new ArrayList<String>(
textToShare.values());
if (!notes.isEmpty()) {
text = text + notes.remove(0);
while (!notes.isEmpty()) {
text = text + "\n\n" + notes.remove(0);
}
}
return text;
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("MODALMAN", "onCreateActionMode mode: " + mode);
// Clear data!
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
// if (FragmentLayout.lightTheme)
// inflater.inflate(R.menu.list_select_menu_light, menu);
// else
inflater.inflate(R.menu.list_select_menu, menu);
// mode.setTitle(getResources().getQuantityString(R.plurals.mode_choose,
// 1, 1));
this.mode = mode;
return true;
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode,
android.view.MenuItem item) {
Log.d("MODALMAN", "onActionItemClicked mode: " + mode);
switch (item.getItemId()) {
case R.id.modal_share:
shareNote(buildTextToShare());
mode.finish();
break;
case R.id.modal_copy:
ClipboardManager clipboard = (ClipboardManager) activity
.getSystemService(Context.CLIPBOARD_SERVICE);
// ICS style
clipboard.setPrimaryClip(ClipData.newPlainText("Note",
buildTextToShare()));
int num = getListView().getCheckedItemCount();
Toast.makeText(
activity,
getResources().getQuantityString(
R.plurals.notecopied_msg, num, num),
Toast.LENGTH_SHORT).show();
mode.finish();
break;
case R.id.modal_delete:
onDeleteAction();
break;
default:
// Toast.makeText(activity, "Clicked " + item.getTitle(),
// Toast.LENGTH_SHORT).show();
break;
}
return true;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
Log.d("modeCallback", "onDestroyActionMode: " + mode.toString()
+ ", " + mode.getMenu().toString());
list.setFutureSingleCheck();
}
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
// Set the share intent with updated text
if (checked) {
addTextToShare(id);
this.notesToDelete.add(position);
} else {
delTextToShare(id);
this.notesToDelete.remove(position);
}
final int checkedCount = getListView().getCheckedItemCount();
mode.setTitle(getResources().getQuantityString(
R.plurals.mode_choose, checkedCount, checkedCount));
}
private void shareNote(String text) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, text);
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(share, "Share note"));
}
public Cursor openNote(Uri uri) {
/*
* Using the URI passed in with the triggering Intent, gets the note
* or notes in the provider. Note: This is being done on the UI
* thread. It will block the thread until the query completes. In a
* sample app, going against a simple provider based on a local
* database, the block will be momentary, but in a real app you
* should use android.content.AsyncQueryHandler or
* android.os.AsyncTask.
*/
Cursor cursor = activity.managedQuery(uri, // The URI that gets
// multiple
// notes from
// the provider.
NotesEditorFragment.PROJECTION, // A projection that returns
// the note ID and
// note
// content for each note.
null, // No "where" clause selection criteria.
null, // No "where" clause selection values.
null // Use the default sort order (modification date,
// descending)
);
// Or Honeycomb will crash
activity.stopManagingCursor(cursor);
return cursor;
}
public void onDeleteAction() {
int num = notesToDelete.size();
if (onDeleteListener != null) {
for (int pos : notesToDelete) {
Log.d(TAG, "Deleting key: " + pos);
}
onDeleteListener.onModalDelete(notesToDelete);
}
Toast.makeText(
activity,
getResources().getQuantityString(R.plurals.notedeleted_msg,
num, num), Toast.LENGTH_SHORT).show();
mode.finish();
}
}
@TargetApi(14)
private class ModeCallbackICS extends ModeCallbackHC {
protected ShareActionProvider actionProvider;
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
super.onItemCheckedStateChanged(mode, position, id, checked);
if (actionProvider != null) {
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
}
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("modeCallBack", "onCreateActionMode " + mode);
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.list_select_menu, menu);
// mode.setTitle(getResources().getQuantityString(R.plurals.mode_choose,
// 1, 1));
this.mode = mode;
// Set file with share history to the provider and set the share
// intent.
android.view.MenuItem actionItem = menu
.findItem(R.id.modal_item_share_action_provider_action_bar);
actionProvider = (ShareActionProvider) actionItem
.getActionProvider();
actionProvider
.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
// Note that you can set/change the intent any time,
// say when the user has selected an image.
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
return true;
}
public ModeCallbackICS(NotesListFragment list) {
super(list);
}
}
@Override
public void onModalDelete(Collection<Integer> positions) {
Log.d(TAG, "onModalDelete");
if (positions.contains(mActivatedPosition)) {
Log.d(TAG, "onModalDelete contained setting id invalid");
// idInvalid = true;
} else {
// We must recalculate the positions index of the current note
// This is always done when content changes
}
HashSet<Long> ids = new HashSet<Long>();
for (int pos : positions) {
Log.d(TAG, "onModalDelete pos: " + pos);
ids.add(mSectionAdapter.getItemId(pos));
}
((MainActivity) activity).onMultiDelete(ids, mCurId);
}
private boolean shouldDisplaySections(String sorting) {
if (mCurListId == MainActivity.ALL_NOTES_ID) {
return true;
} else if (sorting.equals(MainPrefs.DUEDATESORT)
|| sorting.equals(MainPrefs.MODIFIEDSORT)) {
return true;
} else {
return false;
}
}
private void refreshList(Bundle args) {
// We might need to construct a new adapter
final String sorting = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
if (shouldDisplaySections(sorting)) {
if (mSectionAdapter == null || !mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity, null);
// mSectionAdapter.changeState(sorting);
setListAdapter(mSectionAdapter);
}
} else if (mSectionAdapter == null || mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity,
getThemedAdapter(null));
setListAdapter(mSectionAdapter);
}
if (mSectionAdapter.isSectioned()) {
// If sort date, fire sorting loaders
// If mod date, fire modded loaders
if (mCurListId == MainActivity.ALL_NOTES_ID
&& PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTHEADERS, true)) {
destroyNonListNameLoaders();
activeLoaders.add(LOADER_LISTNAMES);
getLoaderManager().restartLoader(LOADER_LISTNAMES, args, this);
} else if (sorting.equals(MainPrefs.DUEDATESORT)) {
Log.d("listproto", "refreshing sectioned date list");
destroyNonDateLoaders();
activeLoaders.add(LOADER_DATEFUTURE);
activeLoaders.add(LOADER_DATENONE);
activeLoaders.add(LOADER_DATEOVERDUE);
activeLoaders.add(LOADER_DATETODAY);
activeLoaders.add(LOADER_DATETOMORROW);
activeLoaders.add(LOADER_DATEWEEK);
activeLoaders.add(LOADER_DATECOMPLETED);
getLoaderManager().restartLoader(LOADER_DATEFUTURE, args, this);
getLoaderManager().restartLoader(LOADER_DATENONE, args, this);
getLoaderManager()
.restartLoader(LOADER_DATEOVERDUE, args, this);
getLoaderManager().restartLoader(LOADER_DATETODAY, args, this);
getLoaderManager().restartLoader(LOADER_DATETOMORROW, args,
this);
getLoaderManager().restartLoader(LOADER_DATEWEEK, args, this);
getLoaderManager().restartLoader(LOADER_DATECOMPLETED, args,
this);
} else if (sorting.equals(MainPrefs.MODIFIEDSORT)) {
Log.d("listproto", "refreshing sectioned mod list");
destroyNonModLoaders();
activeLoaders.add(LOADER_MODPAST);
activeLoaders.add(LOADER_MODTODAY);
activeLoaders.add(LOADER_MODWEEK);
activeLoaders.add(LOADER_MODYESTERDAY);
getLoaderManager().restartLoader(LOADER_MODPAST, args, this);
getLoaderManager().restartLoader(LOADER_MODTODAY, args, this);
getLoaderManager().restartLoader(LOADER_MODWEEK, args, this);
getLoaderManager().restartLoader(LOADER_MODYESTERDAY, args,
this);
}
} else {
destroyNonRegularLoaders();
Log.d("listproto", "refreshing normal list");
activeLoaders.add(LOADER_REGULARLIST);
getLoaderManager().restartLoader(LOADER_REGULARLIST, args, this);
}
}
private void destroyActiveLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
private void destroyListLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
if (id > -1) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
}
private void destroyModLoaders() {
activeLoaders.remove(LOADER_MODPAST);
getLoaderManager().destroyLoader(LOADER_MODPAST);
activeLoaders.remove(LOADER_MODWEEK);
getLoaderManager().destroyLoader(LOADER_MODWEEK);
activeLoaders.remove(LOADER_MODYESTERDAY);
getLoaderManager().destroyLoader(LOADER_MODYESTERDAY);
activeLoaders.remove(LOADER_MODTODAY);
getLoaderManager().destroyLoader(LOADER_MODTODAY);
}
private void destroyDateLoaders() {
activeLoaders.remove(LOADER_DATECOMPLETED);
getLoaderManager().destroyLoader(LOADER_DATECOMPLETED);
activeLoaders.remove(LOADER_DATEFUTURE);
getLoaderManager().destroyLoader(LOADER_DATEFUTURE);
activeLoaders.remove(LOADER_DATENONE);
getLoaderManager().destroyLoader(LOADER_DATENONE);
activeLoaders.remove(LOADER_DATEOVERDUE);
getLoaderManager().destroyLoader(LOADER_DATEOVERDUE);
activeLoaders.remove(LOADER_DATETODAY);
getLoaderManager().destroyLoader(LOADER_DATETODAY);
activeLoaders.remove(LOADER_DATETOMORROW);
getLoaderManager().destroyLoader(LOADER_DATETOMORROW);
activeLoaders.remove(LOADER_DATEWEEK);
getLoaderManager().destroyLoader(LOADER_DATEWEEK);
}
private void destroyListNameLoaders() {
activeLoaders.remove(LOADER_LISTNAMES);
getLoaderManager().destroyLoader(LOADER_LISTNAMES);
}
private void destroyRegularLoaders() {
activeLoaders.remove(LOADER_REGULARLIST);
getLoaderManager().destroyLoader(LOADER_REGULARLIST);
}
private void destroyNonDateLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonListNameLoaders() {
destroyDateLoaders();
destroyModLoaders();
destroyRegularLoaders();
}
private void destroyNonModLoaders() {
destroyListNameLoaders();
destroyDateLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonRegularLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyDateLoaders();
}
private CursorLoader getAllNotesLoader(long listId) {
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Get current sort order or assemble the default one.
String sortChoice = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
String sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
if (MainPrefs.DUEDATESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
} else if (MainPrefs.TITLESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.ALPHABETIC_SORT_TYPE;
} else if (MainPrefs.MODIFIEDSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
} else if (MainPrefs.POSSUBSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
}
NotesListFragment.sortType = sortOrder;
sortOrder += " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
if (listId == MainActivity.ALL_NOTES_ID) {
return new CursorLoader(activity, baseUri, PROJECTION, null, null,
sortOrder);
} else {
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_LIST + " IS ?",
new String[] { Long.toString(listId) }, sortOrder);
}
}
private CursorLoader getSearchNotesLoader() {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
// Get current sort order or assemble the default one.
String sortOrder = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE,
NotePad.Notes.DEFAULT_SORT_TYPE)
+ " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// include title field in search
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_NOTE + " LIKE ?" + " OR "
+ NotePad.Notes.COLUMN_NAME_TITLE + " LIKE ?",
new String[] { "%" + currentQuery + "%",
"%" + currentQuery + "%" }, sortOrder);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader");
if (args != null) {
/*
* if (args.containsKey(SHOULD_OPEN_NOTE) &&
* args.getBoolean(SHOULD_OPEN_NOTE)) { autoOpenNote = true; }
*/
}
if (currentQuery != null && !currentQuery.isEmpty()) {
return getSearchNotesLoader();
} else {
// Important that these are in the correct order!
switch (id) {
case LOADER_DATEFUTURE:
case LOADER_DATENONE:
case LOADER_DATEOVERDUE:
case LOADER_DATETODAY:
case LOADER_DATETOMORROW:
case LOADER_DATEWEEK:
case LOADER_DATECOMPLETED:
return getDateLoader(id, mCurListId);
case LOADER_MODPAST:
case LOADER_MODTODAY:
case LOADER_MODWEEK:
case LOADER_MODYESTERDAY:
return getModLoader(id, mCurListId);
case LOADER_REGULARLIST:
Log.d("listproto", "Getting cursor normal list: " + mCurListId);
// Regular lists
return getAllNotesLoader(mCurListId);
case LOADER_LISTNAMES:
Log.d("listproto", "Getting cursor for list names");
// Section names
return getSectionNameLoader();
default:
Log.d("listproto", "Getting cursor for individual list: " + id);
// Individual lists. ID is actually be the list id
return getAllNotesLoader(id);
}
}
}
private CursorLoader getSectionNameLoader() {
// first check SharedPreferences for what the appropriate loader would
// be
// list names, due date, modification
return new CursorLoader(activity, NotePad.Lists.CONTENT_URI,
new String[] { NotePad.Lists._ID,
NotePad.Lists.COLUMN_NAME_TITLE },
NotePad.Lists.COLUMN_NAME_DELETED + " IS NOT 1", null,
NotePad.Lists.SORT_ORDER);
}
private CursorLoader getDateLoader(int id, long listId) {
Log.d("listproto", "getting date loader");
String sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
if (dateComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
dateComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.date_header_overdue),
"0");
put(activity
.getString(R.string.date_header_today),
"1");
put(activity
.getString(R.string.date_header_tomorrow),
"2");
put(activity
.getString(R.string.date_header_7days),
"3");
put(activity
.getString(R.string.date_header_future),
"4");
put(activity
.getString(R.string.date_header_none),
"5");
put(activity
.getString(R.string.date_header_completed),
"6");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
- if (ordering.equals(NotePad.Notes.DESCENDING_SORT_ORDERING))
+ if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
String[] vars = null;
String where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ? AND ";
switch (id) {
case LOADER_DATEFUTURE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") >= ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateEightDay() };
break;
case LOADER_DATEOVERDUE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETODAY:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETOMORROW:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow() };
break;
case LOADER_DATEWEEK:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") > ? AND date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow(), TimeHelper.dateEightDay() };
break;
case LOADER_DATECOMPLETED:
where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ?";
vars = new String[] { activity
.getString(R.string.gtask_status_completed) };
break;
case LOADER_DATENONE:
default:
where += "(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NULL OR "
+ NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS '')";
vars = new String[] { activity
.getString(R.string.gtask_status_uncompleted) };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private CursorLoader getModLoader(int id, long listId) {
Log.d("listproto", "getting mod loader");
String sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
String[] vars = null;
String where = "";
if (modComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
modComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.mod_header_today),
"0");
put(activity
.getString(R.string.mod_header_yesterday),
"1");
put(activity
.getString(R.string.mod_header_thisweek),
"2");
put(activity
.getString(R.string.mod_header_earlier),
"3");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
switch (id) {
case LOADER_MODTODAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " > ?";
vars = new String[] { TimeHelper.milliTodayStart() };
break;
case LOADER_MODYESTERDAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milliYesterdayStart(),
TimeHelper.milliTodayStart() };
break;
case LOADER_MODWEEK:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo(),
TimeHelper.milliYesterdayStart() };
break;
case LOADER_MODPAST:
default:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo() };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private void addSectionToAdapter(String sectionname, Cursor data,
Comparator<String> comp) {
addSectionToAdapter(-1, sectionname, data, comp);
}
private void addSectionToAdapter(long sectionId, String sectionname,
Cursor data, Comparator<String> comp) {
// Make sure an adapter exists
SimpleCursorAdapter adapter = mSectionAdapter.sections.get(sectionname);
if (adapter == null) {
adapter = getThemedAdapter(null);
if (sectionId > -1)
mSectionAdapter.addSection(sectionId, sectionname, adapter,
comp);
else
mSectionAdapter.addSection(sectionname, adapter, comp);
}
adapter.swapCursor(data);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
Log.d(TAG, "onLoadFinished");
Log.d("listproto", "loader id: " + loader.getId());
Log.d("listproto", "Current list " + mCurListId);
long listid;
String sectionname;
switch (loader.getId()) {
case LOADER_REGULARLIST:
if (!mSectionAdapter.isSectioned()) {
mSectionAdapter.swapCursor(data);
} else
Log.d("listproto",
"That's odd... List id invalid: " + loader.getId());
break;
case LOADER_LISTNAMES:
// Section names and starts loaders for individual sections
Log.d("listproto", "List names");
while (data != null && data.moveToNext()) {
listid = data.getLong(data.getColumnIndex(NotePad.Lists._ID));
sectionname = data.getString(data
.getColumnIndex(NotePad.Lists.COLUMN_NAME_TITLE));
Log.d("listproto", "Adding " + sectionname + " to headers");
listNames.put(listid, sectionname);
// Start loader for this list
Log.d("listproto", "Starting loader for " + sectionname
+ " id " + listid);
activeLoaders.add((int) listid);
getLoaderManager().restartLoader((int) listid, null, this);
}
break;
case LOADER_DATEFUTURE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_future);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATECOMPLETED:
Log.d("listproto", "got completed cursor");
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_completed);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATENONE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_none);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEOVERDUE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_overdue);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETODAY:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_today);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETOMORROW:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_tomorrow);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEWEEK:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_7days);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_MODPAST:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_earlier);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODTODAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_today);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODWEEK:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_thisweek);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODYESTERDAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_yesterday);
addSectionToAdapter(sectionname, data, modComparator);
break;
default:
mSectionAdapter.changeState(SECTION_STATE_LISTS);
// Individual lists have ids that are positive
if (loader.getId() >= 0) {
Log.d("listproto", "Sublists");
// Sublists
listid = loader.getId();
sectionname = listNames.get(listid);
Log.d("listproto", "Loader finished for list id: "
+ sectionname);
addSectionToAdapter(listid, sectionname, data, alphaComparator);
}
break;
}
// The list should now be shown.
if (getView() != null) {
if (this.getListAdapter().getCount() > 0) {
Log.d(TAG, "showing list");
getView().findViewById(R.id.listContainer).setVisibility(
View.VISIBLE);
getView().findViewById(R.id.hintContainer).setVisibility(
View.GONE);
} else {
Log.d(TAG, "no notes, hiding list");
getView().findViewById(R.id.listContainer).setVisibility(
View.GONE);
getView().findViewById(R.id.hintContainer).setVisibility(
View.VISIBLE);
}
}
// Reselect current note in list, if possible
// This happens in delete
/*
* if (idInvalid) { idInvalid = false; // Note is invalid, so
* recalculate a valid position and index
* reCalculateValidValuesAfterDelete(); reSelectId(); //if
* (activity.getCurrentContent().equals( //
* DualLayoutActivity.CONTENTVIEW.DUAL)) //autoOpenNote = true; } else {
*/
reSelectId();
// }
// If a note was created, it will be set in this variable
if (newNoteIdToSelect > -1) {
setActivatedPosition(showNote(getPosOfId(newNoteIdToSelect)));
newNoteIdToSelect = -1; // Should only be set to anything else on
// create
}
// Open first note if this is first start
// or if one was opened previously
/*
* else if (autoOpenNote && false) { autoOpenNote = false;
* showFirstBestNote(); } else { reSelectId(); }
*/
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
Log.d(TAG, "onLoaderReset");
if (mSectionAdapter.isSectioned()) {
// Sections
for (SimpleCursorAdapter adapter : mSectionAdapter.sections
.values()) {
adapter.swapCursor(null);
}
mSectionAdapter.headers.clear();
mSectionAdapter.sections.clear();
} else {
// Single list
mSectionAdapter.swapCursor(null);
}
}
/**
* Re list notes when sorting changes
*
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
try {
if (activity == null || activity.isFinishing()) {
Log.d(TAG, "isFinishing, should not update");
// Setting the summary now would crash it with
// IllegalStateException since we are not attached to a view
} else {
if (MainPrefs.KEY_SORT_TYPE.equals(key)
|| MainPrefs.KEY_SORT_ORDER.equals(key)) {
// rebuild comparators during refresh
dateComparator = modComparator = null;
refreshList(null);
}
}
} catch (IllegalStateException e) {
// This is just in case the "isFinishing" wouldn't be enough
// The isFinishing will try to prevent us from doing something
// stupid
// This catch prevents the app from crashing if we do something
// stupid
Log.d(TAG, "Exception was caught: " + e.getMessage());
}
}
}
| true | true | private void reCalculateValidValuesAfterDelete() {
int index = mActivatedPosition;
if (mSectionAdapter != null) {
index = index >= mSectionAdapter.getCount() ? mSectionAdapter
.getCount() - 1 : index;
Log.d(TAG, "ReCalculate valid index is: " + index);
if (index == -1) {
// Completely empty list.
mActivatedPosition = 0;
mCurId = -1;
} else { // if (index != -1) {
mActivatedPosition = index;
mCurId = mSectionAdapter.getItemId(index);
}
}
}
/**
* Recalculate note to select from id
*/
public void reSelectId() {
int pos = getPosOfId(mCurId);
Log.d(TAG, "reSelectId id pos: " + mCurId + " " + pos);
setActivatedPosition(pos);
}
private SimpleCursorAdapter getThemedAdapter(Cursor cursor) {
// The names of the cursor columns to display in the view,
// initialized
// to the title column
String[] dataColumns = { NotePad.Notes.COLUMN_NAME_INDENTLEVEL,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS,
NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_NOTE,
NotePad.Notes.COLUMN_NAME_DUE_DATE };
// The view IDs that will display the cursor columns, initialized to
// the TextView in noteslist_item.xml
// My hacked adapter allows the boolean to be set if the string matches
// gtasks string values for them. Needs id as well (set after first)
int[] viewIDs = { R.id.itemIndent, R.id.itemDone, R.id.itemTitle,
R.id.itemNote, R.id.itemDate };
int themed_item = R.layout.noteslist_item;
// Support two different list items
// if (activity != null) {
// if (PreferenceManager.getDefaultSharedPreferences(activity)
// .getBoolean(MainPrefs.KEY_LISTITEM, true)) {
// themed_item = R.layout.noteslist_item;
// } else {
// themed_item = R.layout.noteslist_item_doublenote;
// }
// }
// Set appearence settings
final boolean hidden_checkbox = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENCHECKBOX, false);
final boolean hidden_note = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENNOTE, false);
final boolean hidden_date = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENDATE, false);
final int title_rows = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_TITLEROWS, "2"));
// Creates the backing adapter for the ListView.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(activity,
themed_item, cursor, dataColumns, viewIDs, 0);
final OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean checked) {
ContentValues values = new ContentValues();
String status = getText(R.string.gtask_status_uncompleted)
.toString();
if (checked)
status = getText(R.string.gtask_status_completed)
.toString();
values.put(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS, status);
long id = ((NoteCheckBox) buttonView).getNoteId();
if (id > -1) {
activity.getContentResolver().update(
NotesEditorFragment.getUriFrom(id), values, null,
null);
UpdateNotifier.notifyChangeNote(activity,
NotesEditorFragment.getUriFrom(id));
}
}
};
// In order to set the checked state in the checkbox
// and other theme stuff
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
static final String indent = " ";
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS)) {
NoteCheckBox cb = (NoteCheckBox) view;
cb.setOnCheckedChangeListener(null);
long id = cursor.getLong(cursor
.getColumnIndex(BaseColumns._ID));
cb.setNoteId(id);
String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
cb.setChecked(true);
} else {
cb.setChecked(false);
}
// Set a simple on change listener that updates the note on
// changes.
cb.setOnCheckedChangeListener(listener);
// hide/show
if (hidden_checkbox)
((View) cb.getParent()).setVisibility(View.GONE);
else
((View) cb.getParent()).setVisibility(View.VISIBLE);
return true;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)
|| columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE)) {
final TextView tv = (TextView) view;
// Hide empty note
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)) {
final String noteText = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE));
final boolean isEmpty = noteText == null
|| noteText.isEmpty();
// Set height to zero if it's empty, otherwise wrap
if (hidden_note || isEmpty)
tv.setVisibility(View.GONE);
else
tv.setVisibility(View.VISIBLE);
} else {
// set number of rows
if (1 == title_rows || 2 == title_rows)
tv.setMaxLines(title_rows);
else
tv.setMaxLines(10);
}
// Set strike through on completed tasks
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
// Set appropriate BITMASK
tv.setPaintFlags(tv.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
} else {
// Will clear strike-through. Just a BITMASK so do some
// magic
if (Paint.STRIKE_THRU_TEXT_FLAG == (tv.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG))
tv.setPaintFlags(tv.getPaintFlags()
- Paint.STRIKE_THRU_TEXT_FLAG);
}
// Return false so the normal call is used to set the text
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE)) {
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE));
final TextView tv = (TextView) view;
if (text == null || text.isEmpty() || hidden_date) {
tv.setVisibility(View.GONE);
} else {
tv.setVisibility(View.VISIBLE);
}
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL)) {
// Should only set this on the sort options where it is
// expected
final TextView indentView = (TextView) view;
final int level = cursor.getInt(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL));
// Now set the width
String width = "";
if (sortType.equals(NotePad.Notes.POSSUBSORT_SORT_TYPE)) {
int l;
for (l = 0; l < level; l++) {
width += indent;
}
}
indentView.setText(width);
return true;
}
return false;
}
});
return adapter;
}
@Override
public boolean onQueryTextChange(String query) {
Log.d("NotesListFragment", "onQueryTextChange: " + query);
if (!currentQuery.equals(query)) {
Log.d("NotesListFragment", "this is a new query");
currentQuery = query;
refreshList(null);
// hide the clear completed option until search is over
MenuItem clearCompleted = mOptionsMenu
.findItem(R.id.menu_clearcompleted);
if (clearCompleted != null) {
// Only show this button if there is a list to create notes in
if ("".equals(query)) {
clearCompleted.setVisible(true);
} else {
clearCompleted.setVisible(false);
}
}
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// Just do what we do on text change
return onQueryTextChange(query);
}
public void setSingleCheck() {
Log.d(TAG, "setSingleCheck");
checkMode = CHECK_SINGLE;
ListView lv = getListView();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
// Fix the selection before releasing that
// lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
lv.setChoiceMode(ListView.CHOICE_MODE_NONE);
} else {
// Not nice to show selected item in list when no editor is showing
lv.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
lv.setLongClickable(true);
lv.setOnItemLongClickListener(this);
}
public void setFutureSingleCheck() {
// REsponsible for disabling the modal selector in the future.
// can't do it now because it has to destroy itself etc...
if (checkMode == CHECK_MULTI) {
checkMode = CHECK_SINGLE_FUTURE;
}
}
public void setMultiCheck(int pos) {
Log.d(TAG, "setMutliCheck: " + pos + " modeCallback = " + modeCallback);
// Do this on long press
checkMode = CHECK_MULTI;
ListView lv = getListView();
lv.clearChoices();
lv.setMultiChoiceModeListener(modeCallback);
lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setItemChecked(pos, true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.d(TAG, "onLongClick");
if (checkMode == CHECK_SINGLE) {
// get the position which was selected
Log.d("NotesListFragment", "onLongClick, selected item pos: "
+ position + ", id: " + id);
// change to multiselect mode and select that item
setMultiCheck(position);
} else {
// Should never happen
// Let modal listener handle it
}
return true;
}
public void setRefreshActionItemState(boolean refreshing) {
// On Honeycomb, we can set the state of the refresh button by giving it
// a custom
// action view.
Log.d(TAG, "setRefreshActionState");
if (mOptionsMenu == null) {
Log.d(TAG, "setRefreshActionState: menu is null, returning");
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_sync);
Log.d(TAG,
"setRefreshActionState: refreshItem not null? "
+ Boolean.toString(refreshItem != null));
if (refreshItem != null) {
if (refreshing) {
Log.d(TAG,
"setRefreshActionState: refreshing: "
+ Boolean.toString(refreshing));
if (mRefreshIndeterminateProgressView == null) {
Log.d(TAG,
"setRefreshActionState: mRefreshIndeterminateProgressView was null, inflating one...");
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRefreshIndeterminateProgressView = inflater.inflate(
R.layout.actionbar_indeterminate_progress, null);
}
refreshItem.setActionView(mRefreshIndeterminateProgressView);
} else {
Log.d(TAG, "setRefreshActionState: setting null actionview");
refreshItem.setActionView(null);
}
}
}
private class ModeCallbackHC implements MultiChoiceModeListener {
protected NotesListFragment list;
protected HashMap<Long, String> textToShare;
protected OnModalDeleteListener onDeleteListener;
protected HashSet<Integer> notesToDelete;
protected ActionMode mode;
public ModeCallbackHC(NotesListFragment list) {
textToShare = new HashMap<Long, String>();
notesToDelete = new HashSet<Integer>();
this.list = list;
}
public void setDeleteListener(OnModalDeleteListener onDeleteListener) {
this.onDeleteListener = onDeleteListener;
}
protected Intent createShareIntent(String text) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
return shareIntent;
}
protected void addTextToShare(long id) {
// Read note
Uri uri = NotesEditorFragment.getUriFrom(id);
Cursor cursor = openNote(uri);
if (cursor != null && !cursor.isClosed() && cursor.moveToFirst()) {
// Requery in case something changed while paused (such as the
// title)
// cursor.requery();
/*
* Moves to the first record. Always call moveToFirst() before
* accessing data in a Cursor for the first time. The semantics
* of using a Cursor are that when it is created, its internal
* index is pointing to a "place" immediately before the first
* record.
*/
String note = "";
int colTitleIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE);
if (colTitleIndex > -1)
note = cursor.getString(colTitleIndex) + "\n";
int colDueIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE);
String due = "";
if (colDueIndex > -1)
due = cursor.getString(colDueIndex);
if (due != null && !due.isEmpty()) {
Time date = new Time(Time.getCurrentTimezone());
date.parse3339(due);
note = note + "due date: " + date.format3339(true) + "\n";
}
int colNoteIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE);
if (colNoteIndex > -1)
note = note + "\n" + cursor.getString(colNoteIndex);
// Put in hash
textToShare.put(id, note);
}
if (cursor != null)
cursor.close();
}
protected void delTextToShare(long id) {
textToShare.remove(id);
}
protected String buildTextToShare() {
String text = "";
ArrayList<String> notes = new ArrayList<String>(
textToShare.values());
if (!notes.isEmpty()) {
text = text + notes.remove(0);
while (!notes.isEmpty()) {
text = text + "\n\n" + notes.remove(0);
}
}
return text;
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("MODALMAN", "onCreateActionMode mode: " + mode);
// Clear data!
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
// if (FragmentLayout.lightTheme)
// inflater.inflate(R.menu.list_select_menu_light, menu);
// else
inflater.inflate(R.menu.list_select_menu, menu);
// mode.setTitle(getResources().getQuantityString(R.plurals.mode_choose,
// 1, 1));
this.mode = mode;
return true;
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode,
android.view.MenuItem item) {
Log.d("MODALMAN", "onActionItemClicked mode: " + mode);
switch (item.getItemId()) {
case R.id.modal_share:
shareNote(buildTextToShare());
mode.finish();
break;
case R.id.modal_copy:
ClipboardManager clipboard = (ClipboardManager) activity
.getSystemService(Context.CLIPBOARD_SERVICE);
// ICS style
clipboard.setPrimaryClip(ClipData.newPlainText("Note",
buildTextToShare()));
int num = getListView().getCheckedItemCount();
Toast.makeText(
activity,
getResources().getQuantityString(
R.plurals.notecopied_msg, num, num),
Toast.LENGTH_SHORT).show();
mode.finish();
break;
case R.id.modal_delete:
onDeleteAction();
break;
default:
// Toast.makeText(activity, "Clicked " + item.getTitle(),
// Toast.LENGTH_SHORT).show();
break;
}
return true;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
Log.d("modeCallback", "onDestroyActionMode: " + mode.toString()
+ ", " + mode.getMenu().toString());
list.setFutureSingleCheck();
}
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
// Set the share intent with updated text
if (checked) {
addTextToShare(id);
this.notesToDelete.add(position);
} else {
delTextToShare(id);
this.notesToDelete.remove(position);
}
final int checkedCount = getListView().getCheckedItemCount();
mode.setTitle(getResources().getQuantityString(
R.plurals.mode_choose, checkedCount, checkedCount));
}
private void shareNote(String text) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, text);
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(share, "Share note"));
}
public Cursor openNote(Uri uri) {
/*
* Using the URI passed in with the triggering Intent, gets the note
* or notes in the provider. Note: This is being done on the UI
* thread. It will block the thread until the query completes. In a
* sample app, going against a simple provider based on a local
* database, the block will be momentary, but in a real app you
* should use android.content.AsyncQueryHandler or
* android.os.AsyncTask.
*/
Cursor cursor = activity.managedQuery(uri, // The URI that gets
// multiple
// notes from
// the provider.
NotesEditorFragment.PROJECTION, // A projection that returns
// the note ID and
// note
// content for each note.
null, // No "where" clause selection criteria.
null, // No "where" clause selection values.
null // Use the default sort order (modification date,
// descending)
);
// Or Honeycomb will crash
activity.stopManagingCursor(cursor);
return cursor;
}
public void onDeleteAction() {
int num = notesToDelete.size();
if (onDeleteListener != null) {
for (int pos : notesToDelete) {
Log.d(TAG, "Deleting key: " + pos);
}
onDeleteListener.onModalDelete(notesToDelete);
}
Toast.makeText(
activity,
getResources().getQuantityString(R.plurals.notedeleted_msg,
num, num), Toast.LENGTH_SHORT).show();
mode.finish();
}
}
@TargetApi(14)
private class ModeCallbackICS extends ModeCallbackHC {
protected ShareActionProvider actionProvider;
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
super.onItemCheckedStateChanged(mode, position, id, checked);
if (actionProvider != null) {
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
}
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("modeCallBack", "onCreateActionMode " + mode);
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.list_select_menu, menu);
// mode.setTitle(getResources().getQuantityString(R.plurals.mode_choose,
// 1, 1));
this.mode = mode;
// Set file with share history to the provider and set the share
// intent.
android.view.MenuItem actionItem = menu
.findItem(R.id.modal_item_share_action_provider_action_bar);
actionProvider = (ShareActionProvider) actionItem
.getActionProvider();
actionProvider
.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
// Note that you can set/change the intent any time,
// say when the user has selected an image.
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
return true;
}
public ModeCallbackICS(NotesListFragment list) {
super(list);
}
}
@Override
public void onModalDelete(Collection<Integer> positions) {
Log.d(TAG, "onModalDelete");
if (positions.contains(mActivatedPosition)) {
Log.d(TAG, "onModalDelete contained setting id invalid");
// idInvalid = true;
} else {
// We must recalculate the positions index of the current note
// This is always done when content changes
}
HashSet<Long> ids = new HashSet<Long>();
for (int pos : positions) {
Log.d(TAG, "onModalDelete pos: " + pos);
ids.add(mSectionAdapter.getItemId(pos));
}
((MainActivity) activity).onMultiDelete(ids, mCurId);
}
private boolean shouldDisplaySections(String sorting) {
if (mCurListId == MainActivity.ALL_NOTES_ID) {
return true;
} else if (sorting.equals(MainPrefs.DUEDATESORT)
|| sorting.equals(MainPrefs.MODIFIEDSORT)) {
return true;
} else {
return false;
}
}
private void refreshList(Bundle args) {
// We might need to construct a new adapter
final String sorting = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
if (shouldDisplaySections(sorting)) {
if (mSectionAdapter == null || !mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity, null);
// mSectionAdapter.changeState(sorting);
setListAdapter(mSectionAdapter);
}
} else if (mSectionAdapter == null || mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity,
getThemedAdapter(null));
setListAdapter(mSectionAdapter);
}
if (mSectionAdapter.isSectioned()) {
// If sort date, fire sorting loaders
// If mod date, fire modded loaders
if (mCurListId == MainActivity.ALL_NOTES_ID
&& PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTHEADERS, true)) {
destroyNonListNameLoaders();
activeLoaders.add(LOADER_LISTNAMES);
getLoaderManager().restartLoader(LOADER_LISTNAMES, args, this);
} else if (sorting.equals(MainPrefs.DUEDATESORT)) {
Log.d("listproto", "refreshing sectioned date list");
destroyNonDateLoaders();
activeLoaders.add(LOADER_DATEFUTURE);
activeLoaders.add(LOADER_DATENONE);
activeLoaders.add(LOADER_DATEOVERDUE);
activeLoaders.add(LOADER_DATETODAY);
activeLoaders.add(LOADER_DATETOMORROW);
activeLoaders.add(LOADER_DATEWEEK);
activeLoaders.add(LOADER_DATECOMPLETED);
getLoaderManager().restartLoader(LOADER_DATEFUTURE, args, this);
getLoaderManager().restartLoader(LOADER_DATENONE, args, this);
getLoaderManager()
.restartLoader(LOADER_DATEOVERDUE, args, this);
getLoaderManager().restartLoader(LOADER_DATETODAY, args, this);
getLoaderManager().restartLoader(LOADER_DATETOMORROW, args,
this);
getLoaderManager().restartLoader(LOADER_DATEWEEK, args, this);
getLoaderManager().restartLoader(LOADER_DATECOMPLETED, args,
this);
} else if (sorting.equals(MainPrefs.MODIFIEDSORT)) {
Log.d("listproto", "refreshing sectioned mod list");
destroyNonModLoaders();
activeLoaders.add(LOADER_MODPAST);
activeLoaders.add(LOADER_MODTODAY);
activeLoaders.add(LOADER_MODWEEK);
activeLoaders.add(LOADER_MODYESTERDAY);
getLoaderManager().restartLoader(LOADER_MODPAST, args, this);
getLoaderManager().restartLoader(LOADER_MODTODAY, args, this);
getLoaderManager().restartLoader(LOADER_MODWEEK, args, this);
getLoaderManager().restartLoader(LOADER_MODYESTERDAY, args,
this);
}
} else {
destroyNonRegularLoaders();
Log.d("listproto", "refreshing normal list");
activeLoaders.add(LOADER_REGULARLIST);
getLoaderManager().restartLoader(LOADER_REGULARLIST, args, this);
}
}
private void destroyActiveLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
private void destroyListLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
if (id > -1) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
}
private void destroyModLoaders() {
activeLoaders.remove(LOADER_MODPAST);
getLoaderManager().destroyLoader(LOADER_MODPAST);
activeLoaders.remove(LOADER_MODWEEK);
getLoaderManager().destroyLoader(LOADER_MODWEEK);
activeLoaders.remove(LOADER_MODYESTERDAY);
getLoaderManager().destroyLoader(LOADER_MODYESTERDAY);
activeLoaders.remove(LOADER_MODTODAY);
getLoaderManager().destroyLoader(LOADER_MODTODAY);
}
private void destroyDateLoaders() {
activeLoaders.remove(LOADER_DATECOMPLETED);
getLoaderManager().destroyLoader(LOADER_DATECOMPLETED);
activeLoaders.remove(LOADER_DATEFUTURE);
getLoaderManager().destroyLoader(LOADER_DATEFUTURE);
activeLoaders.remove(LOADER_DATENONE);
getLoaderManager().destroyLoader(LOADER_DATENONE);
activeLoaders.remove(LOADER_DATEOVERDUE);
getLoaderManager().destroyLoader(LOADER_DATEOVERDUE);
activeLoaders.remove(LOADER_DATETODAY);
getLoaderManager().destroyLoader(LOADER_DATETODAY);
activeLoaders.remove(LOADER_DATETOMORROW);
getLoaderManager().destroyLoader(LOADER_DATETOMORROW);
activeLoaders.remove(LOADER_DATEWEEK);
getLoaderManager().destroyLoader(LOADER_DATEWEEK);
}
private void destroyListNameLoaders() {
activeLoaders.remove(LOADER_LISTNAMES);
getLoaderManager().destroyLoader(LOADER_LISTNAMES);
}
private void destroyRegularLoaders() {
activeLoaders.remove(LOADER_REGULARLIST);
getLoaderManager().destroyLoader(LOADER_REGULARLIST);
}
private void destroyNonDateLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonListNameLoaders() {
destroyDateLoaders();
destroyModLoaders();
destroyRegularLoaders();
}
private void destroyNonModLoaders() {
destroyListNameLoaders();
destroyDateLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonRegularLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyDateLoaders();
}
private CursorLoader getAllNotesLoader(long listId) {
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Get current sort order or assemble the default one.
String sortChoice = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
String sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
if (MainPrefs.DUEDATESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
} else if (MainPrefs.TITLESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.ALPHABETIC_SORT_TYPE;
} else if (MainPrefs.MODIFIEDSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
} else if (MainPrefs.POSSUBSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
}
NotesListFragment.sortType = sortOrder;
sortOrder += " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
if (listId == MainActivity.ALL_NOTES_ID) {
return new CursorLoader(activity, baseUri, PROJECTION, null, null,
sortOrder);
} else {
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_LIST + " IS ?",
new String[] { Long.toString(listId) }, sortOrder);
}
}
private CursorLoader getSearchNotesLoader() {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
// Get current sort order or assemble the default one.
String sortOrder = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE,
NotePad.Notes.DEFAULT_SORT_TYPE)
+ " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// include title field in search
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_NOTE + " LIKE ?" + " OR "
+ NotePad.Notes.COLUMN_NAME_TITLE + " LIKE ?",
new String[] { "%" + currentQuery + "%",
"%" + currentQuery + "%" }, sortOrder);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader");
if (args != null) {
/*
* if (args.containsKey(SHOULD_OPEN_NOTE) &&
* args.getBoolean(SHOULD_OPEN_NOTE)) { autoOpenNote = true; }
*/
}
if (currentQuery != null && !currentQuery.isEmpty()) {
return getSearchNotesLoader();
} else {
// Important that these are in the correct order!
switch (id) {
case LOADER_DATEFUTURE:
case LOADER_DATENONE:
case LOADER_DATEOVERDUE:
case LOADER_DATETODAY:
case LOADER_DATETOMORROW:
case LOADER_DATEWEEK:
case LOADER_DATECOMPLETED:
return getDateLoader(id, mCurListId);
case LOADER_MODPAST:
case LOADER_MODTODAY:
case LOADER_MODWEEK:
case LOADER_MODYESTERDAY:
return getModLoader(id, mCurListId);
case LOADER_REGULARLIST:
Log.d("listproto", "Getting cursor normal list: " + mCurListId);
// Regular lists
return getAllNotesLoader(mCurListId);
case LOADER_LISTNAMES:
Log.d("listproto", "Getting cursor for list names");
// Section names
return getSectionNameLoader();
default:
Log.d("listproto", "Getting cursor for individual list: " + id);
// Individual lists. ID is actually be the list id
return getAllNotesLoader(id);
}
}
}
private CursorLoader getSectionNameLoader() {
// first check SharedPreferences for what the appropriate loader would
// be
// list names, due date, modification
return new CursorLoader(activity, NotePad.Lists.CONTENT_URI,
new String[] { NotePad.Lists._ID,
NotePad.Lists.COLUMN_NAME_TITLE },
NotePad.Lists.COLUMN_NAME_DELETED + " IS NOT 1", null,
NotePad.Lists.SORT_ORDER);
}
private CursorLoader getDateLoader(int id, long listId) {
Log.d("listproto", "getting date loader");
String sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
if (dateComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
dateComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.date_header_overdue),
"0");
put(activity
.getString(R.string.date_header_today),
"1");
put(activity
.getString(R.string.date_header_tomorrow),
"2");
put(activity
.getString(R.string.date_header_7days),
"3");
put(activity
.getString(R.string.date_header_future),
"4");
put(activity
.getString(R.string.date_header_none),
"5");
put(activity
.getString(R.string.date_header_completed),
"6");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.DESCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
String[] vars = null;
String where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ? AND ";
switch (id) {
case LOADER_DATEFUTURE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") >= ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateEightDay() };
break;
case LOADER_DATEOVERDUE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETODAY:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETOMORROW:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow() };
break;
case LOADER_DATEWEEK:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") > ? AND date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow(), TimeHelper.dateEightDay() };
break;
case LOADER_DATECOMPLETED:
where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ?";
vars = new String[] { activity
.getString(R.string.gtask_status_completed) };
break;
case LOADER_DATENONE:
default:
where += "(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NULL OR "
+ NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS '')";
vars = new String[] { activity
.getString(R.string.gtask_status_uncompleted) };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private CursorLoader getModLoader(int id, long listId) {
Log.d("listproto", "getting mod loader");
String sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
String[] vars = null;
String where = "";
if (modComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
modComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.mod_header_today),
"0");
put(activity
.getString(R.string.mod_header_yesterday),
"1");
put(activity
.getString(R.string.mod_header_thisweek),
"2");
put(activity
.getString(R.string.mod_header_earlier),
"3");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
switch (id) {
case LOADER_MODTODAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " > ?";
vars = new String[] { TimeHelper.milliTodayStart() };
break;
case LOADER_MODYESTERDAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milliYesterdayStart(),
TimeHelper.milliTodayStart() };
break;
case LOADER_MODWEEK:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo(),
TimeHelper.milliYesterdayStart() };
break;
case LOADER_MODPAST:
default:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo() };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private void addSectionToAdapter(String sectionname, Cursor data,
Comparator<String> comp) {
addSectionToAdapter(-1, sectionname, data, comp);
}
private void addSectionToAdapter(long sectionId, String sectionname,
Cursor data, Comparator<String> comp) {
// Make sure an adapter exists
SimpleCursorAdapter adapter = mSectionAdapter.sections.get(sectionname);
if (adapter == null) {
adapter = getThemedAdapter(null);
if (sectionId > -1)
mSectionAdapter.addSection(sectionId, sectionname, adapter,
comp);
else
mSectionAdapter.addSection(sectionname, adapter, comp);
}
adapter.swapCursor(data);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
Log.d(TAG, "onLoadFinished");
Log.d("listproto", "loader id: " + loader.getId());
Log.d("listproto", "Current list " + mCurListId);
long listid;
String sectionname;
switch (loader.getId()) {
case LOADER_REGULARLIST:
if (!mSectionAdapter.isSectioned()) {
mSectionAdapter.swapCursor(data);
} else
Log.d("listproto",
"That's odd... List id invalid: " + loader.getId());
break;
case LOADER_LISTNAMES:
// Section names and starts loaders for individual sections
Log.d("listproto", "List names");
while (data != null && data.moveToNext()) {
listid = data.getLong(data.getColumnIndex(NotePad.Lists._ID));
sectionname = data.getString(data
.getColumnIndex(NotePad.Lists.COLUMN_NAME_TITLE));
Log.d("listproto", "Adding " + sectionname + " to headers");
listNames.put(listid, sectionname);
// Start loader for this list
Log.d("listproto", "Starting loader for " + sectionname
+ " id " + listid);
activeLoaders.add((int) listid);
getLoaderManager().restartLoader((int) listid, null, this);
}
break;
case LOADER_DATEFUTURE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_future);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATECOMPLETED:
Log.d("listproto", "got completed cursor");
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_completed);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATENONE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_none);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEOVERDUE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_overdue);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETODAY:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_today);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETOMORROW:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_tomorrow);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEWEEK:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_7days);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_MODPAST:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_earlier);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODTODAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_today);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODWEEK:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_thisweek);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODYESTERDAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_yesterday);
addSectionToAdapter(sectionname, data, modComparator);
break;
default:
mSectionAdapter.changeState(SECTION_STATE_LISTS);
// Individual lists have ids that are positive
if (loader.getId() >= 0) {
Log.d("listproto", "Sublists");
// Sublists
listid = loader.getId();
sectionname = listNames.get(listid);
Log.d("listproto", "Loader finished for list id: "
+ sectionname);
addSectionToAdapter(listid, sectionname, data, alphaComparator);
}
break;
}
// The list should now be shown.
if (getView() != null) {
if (this.getListAdapter().getCount() > 0) {
Log.d(TAG, "showing list");
getView().findViewById(R.id.listContainer).setVisibility(
View.VISIBLE);
getView().findViewById(R.id.hintContainer).setVisibility(
View.GONE);
} else {
Log.d(TAG, "no notes, hiding list");
getView().findViewById(R.id.listContainer).setVisibility(
View.GONE);
getView().findViewById(R.id.hintContainer).setVisibility(
View.VISIBLE);
}
}
// Reselect current note in list, if possible
// This happens in delete
/*
* if (idInvalid) { idInvalid = false; // Note is invalid, so
* recalculate a valid position and index
* reCalculateValidValuesAfterDelete(); reSelectId(); //if
* (activity.getCurrentContent().equals( //
* DualLayoutActivity.CONTENTVIEW.DUAL)) //autoOpenNote = true; } else {
*/
reSelectId();
// }
// If a note was created, it will be set in this variable
if (newNoteIdToSelect > -1) {
setActivatedPosition(showNote(getPosOfId(newNoteIdToSelect)));
newNoteIdToSelect = -1; // Should only be set to anything else on
// create
}
// Open first note if this is first start
// or if one was opened previously
/*
* else if (autoOpenNote && false) { autoOpenNote = false;
* showFirstBestNote(); } else { reSelectId(); }
*/
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
Log.d(TAG, "onLoaderReset");
if (mSectionAdapter.isSectioned()) {
// Sections
for (SimpleCursorAdapter adapter : mSectionAdapter.sections
.values()) {
adapter.swapCursor(null);
}
mSectionAdapter.headers.clear();
mSectionAdapter.sections.clear();
} else {
// Single list
mSectionAdapter.swapCursor(null);
}
}
/**
* Re list notes when sorting changes
*
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
try {
if (activity == null || activity.isFinishing()) {
Log.d(TAG, "isFinishing, should not update");
// Setting the summary now would crash it with
// IllegalStateException since we are not attached to a view
} else {
if (MainPrefs.KEY_SORT_TYPE.equals(key)
|| MainPrefs.KEY_SORT_ORDER.equals(key)) {
// rebuild comparators during refresh
dateComparator = modComparator = null;
refreshList(null);
}
}
} catch (IllegalStateException e) {
// This is just in case the "isFinishing" wouldn't be enough
// The isFinishing will try to prevent us from doing something
// stupid
// This catch prevents the app from crashing if we do something
// stupid
Log.d(TAG, "Exception was caught: " + e.getMessage());
}
}
}
| private void reCalculateValidValuesAfterDelete() {
int index = mActivatedPosition;
if (mSectionAdapter != null) {
index = index >= mSectionAdapter.getCount() ? mSectionAdapter
.getCount() - 1 : index;
Log.d(TAG, "ReCalculate valid index is: " + index);
if (index == -1) {
// Completely empty list.
mActivatedPosition = 0;
mCurId = -1;
} else { // if (index != -1) {
mActivatedPosition = index;
mCurId = mSectionAdapter.getItemId(index);
}
}
}
/**
* Recalculate note to select from id
*/
public void reSelectId() {
int pos = getPosOfId(mCurId);
Log.d(TAG, "reSelectId id pos: " + mCurId + " " + pos);
setActivatedPosition(pos);
}
private SimpleCursorAdapter getThemedAdapter(Cursor cursor) {
// The names of the cursor columns to display in the view,
// initialized
// to the title column
String[] dataColumns = { NotePad.Notes.COLUMN_NAME_INDENTLEVEL,
NotePad.Notes.COLUMN_NAME_GTASKS_STATUS,
NotePad.Notes.COLUMN_NAME_TITLE,
NotePad.Notes.COLUMN_NAME_NOTE,
NotePad.Notes.COLUMN_NAME_DUE_DATE };
// The view IDs that will display the cursor columns, initialized to
// the TextView in noteslist_item.xml
// My hacked adapter allows the boolean to be set if the string matches
// gtasks string values for them. Needs id as well (set after first)
int[] viewIDs = { R.id.itemIndent, R.id.itemDone, R.id.itemTitle,
R.id.itemNote, R.id.itemDate };
int themed_item = R.layout.noteslist_item;
// Support two different list items
// if (activity != null) {
// if (PreferenceManager.getDefaultSharedPreferences(activity)
// .getBoolean(MainPrefs.KEY_LISTITEM, true)) {
// themed_item = R.layout.noteslist_item;
// } else {
// themed_item = R.layout.noteslist_item_doublenote;
// }
// }
// Set appearence settings
final boolean hidden_checkbox = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENCHECKBOX, false);
final boolean hidden_note = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENNOTE, false);
final boolean hidden_date = PreferenceManager
.getDefaultSharedPreferences(activity).getBoolean(
MainPrefs.KEY_HIDDENDATE, false);
final int title_rows = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_TITLEROWS, "2"));
// Creates the backing adapter for the ListView.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(activity,
themed_item, cursor, dataColumns, viewIDs, 0);
final OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean checked) {
ContentValues values = new ContentValues();
String status = getText(R.string.gtask_status_uncompleted)
.toString();
if (checked)
status = getText(R.string.gtask_status_completed)
.toString();
values.put(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS, status);
long id = ((NoteCheckBox) buttonView).getNoteId();
if (id > -1) {
activity.getContentResolver().update(
NotesEditorFragment.getUriFrom(id), values, null,
null);
UpdateNotifier.notifyChangeNote(activity,
NotesEditorFragment.getUriFrom(id));
}
}
};
// In order to set the checked state in the checkbox
// and other theme stuff
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
static final String indent = " ";
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS)) {
NoteCheckBox cb = (NoteCheckBox) view;
cb.setOnCheckedChangeListener(null);
long id = cursor.getLong(cursor
.getColumnIndex(BaseColumns._ID));
cb.setNoteId(id);
String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
cb.setChecked(true);
} else {
cb.setChecked(false);
}
// Set a simple on change listener that updates the note on
// changes.
cb.setOnCheckedChangeListener(listener);
// hide/show
if (hidden_checkbox)
((View) cb.getParent()).setVisibility(View.GONE);
else
((View) cb.getParent()).setVisibility(View.VISIBLE);
return true;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)
|| columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE)) {
final TextView tv = (TextView) view;
// Hide empty note
if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE)) {
final String noteText = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE));
final boolean isEmpty = noteText == null
|| noteText.isEmpty();
// Set height to zero if it's empty, otherwise wrap
if (hidden_note || isEmpty)
tv.setVisibility(View.GONE);
else
tv.setVisibility(View.VISIBLE);
} else {
// set number of rows
if (1 == title_rows || 2 == title_rows)
tv.setMaxLines(title_rows);
else
tv.setMaxLines(10);
}
// Set strike through on completed tasks
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_GTASKS_STATUS));
if (text != null
&& text.equals(getText(R.string.gtask_status_completed))) {
// Set appropriate BITMASK
tv.setPaintFlags(tv.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
} else {
// Will clear strike-through. Just a BITMASK so do some
// magic
if (Paint.STRIKE_THRU_TEXT_FLAG == (tv.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG))
tv.setPaintFlags(tv.getPaintFlags()
- Paint.STRIKE_THRU_TEXT_FLAG);
}
// Return false so the normal call is used to set the text
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE)) {
final String text = cursor.getString(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE));
final TextView tv = (TextView) view;
if (text == null || text.isEmpty() || hidden_date) {
tv.setVisibility(View.GONE);
} else {
tv.setVisibility(View.VISIBLE);
}
return false;
} else if (columnIndex == cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL)) {
// Should only set this on the sort options where it is
// expected
final TextView indentView = (TextView) view;
final int level = cursor.getInt(cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_INDENTLEVEL));
// Now set the width
String width = "";
if (sortType.equals(NotePad.Notes.POSSUBSORT_SORT_TYPE)) {
int l;
for (l = 0; l < level; l++) {
width += indent;
}
}
indentView.setText(width);
return true;
}
return false;
}
});
return adapter;
}
@Override
public boolean onQueryTextChange(String query) {
Log.d("NotesListFragment", "onQueryTextChange: " + query);
if (!currentQuery.equals(query)) {
Log.d("NotesListFragment", "this is a new query");
currentQuery = query;
refreshList(null);
// hide the clear completed option until search is over
MenuItem clearCompleted = mOptionsMenu
.findItem(R.id.menu_clearcompleted);
if (clearCompleted != null) {
// Only show this button if there is a list to create notes in
if ("".equals(query)) {
clearCompleted.setVisible(true);
} else {
clearCompleted.setVisible(false);
}
}
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// Just do what we do on text change
return onQueryTextChange(query);
}
public void setSingleCheck() {
Log.d(TAG, "setSingleCheck");
checkMode = CHECK_SINGLE;
ListView lv = getListView();
if (activity.getCurrentContent().equals(
DualLayoutActivity.CONTENTVIEW.DUAL)) {
// Fix the selection before releasing that
// lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
lv.setChoiceMode(ListView.CHOICE_MODE_NONE);
} else {
// Not nice to show selected item in list when no editor is showing
lv.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
lv.setLongClickable(true);
lv.setOnItemLongClickListener(this);
}
public void setFutureSingleCheck() {
// REsponsible for disabling the modal selector in the future.
// can't do it now because it has to destroy itself etc...
if (checkMode == CHECK_MULTI) {
checkMode = CHECK_SINGLE_FUTURE;
}
}
public void setMultiCheck(int pos) {
Log.d(TAG, "setMutliCheck: " + pos + " modeCallback = " + modeCallback);
// Do this on long press
checkMode = CHECK_MULTI;
ListView lv = getListView();
lv.clearChoices();
lv.setMultiChoiceModeListener(modeCallback);
lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setItemChecked(pos, true);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.d(TAG, "onLongClick");
if (checkMode == CHECK_SINGLE) {
// get the position which was selected
Log.d("NotesListFragment", "onLongClick, selected item pos: "
+ position + ", id: " + id);
// change to multiselect mode and select that item
setMultiCheck(position);
} else {
// Should never happen
// Let modal listener handle it
}
return true;
}
public void setRefreshActionItemState(boolean refreshing) {
// On Honeycomb, we can set the state of the refresh button by giving it
// a custom
// action view.
Log.d(TAG, "setRefreshActionState");
if (mOptionsMenu == null) {
Log.d(TAG, "setRefreshActionState: menu is null, returning");
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_sync);
Log.d(TAG,
"setRefreshActionState: refreshItem not null? "
+ Boolean.toString(refreshItem != null));
if (refreshItem != null) {
if (refreshing) {
Log.d(TAG,
"setRefreshActionState: refreshing: "
+ Boolean.toString(refreshing));
if (mRefreshIndeterminateProgressView == null) {
Log.d(TAG,
"setRefreshActionState: mRefreshIndeterminateProgressView was null, inflating one...");
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRefreshIndeterminateProgressView = inflater.inflate(
R.layout.actionbar_indeterminate_progress, null);
}
refreshItem.setActionView(mRefreshIndeterminateProgressView);
} else {
Log.d(TAG, "setRefreshActionState: setting null actionview");
refreshItem.setActionView(null);
}
}
}
private class ModeCallbackHC implements MultiChoiceModeListener {
protected NotesListFragment list;
protected HashMap<Long, String> textToShare;
protected OnModalDeleteListener onDeleteListener;
protected HashSet<Integer> notesToDelete;
protected ActionMode mode;
public ModeCallbackHC(NotesListFragment list) {
textToShare = new HashMap<Long, String>();
notesToDelete = new HashSet<Integer>();
this.list = list;
}
public void setDeleteListener(OnModalDeleteListener onDeleteListener) {
this.onDeleteListener = onDeleteListener;
}
protected Intent createShareIntent(String text) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
return shareIntent;
}
protected void addTextToShare(long id) {
// Read note
Uri uri = NotesEditorFragment.getUriFrom(id);
Cursor cursor = openNote(uri);
if (cursor != null && !cursor.isClosed() && cursor.moveToFirst()) {
// Requery in case something changed while paused (such as the
// title)
// cursor.requery();
/*
* Moves to the first record. Always call moveToFirst() before
* accessing data in a Cursor for the first time. The semantics
* of using a Cursor are that when it is created, its internal
* index is pointing to a "place" immediately before the first
* record.
*/
String note = "";
int colTitleIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE);
if (colTitleIndex > -1)
note = cursor.getString(colTitleIndex) + "\n";
int colDueIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_DUE_DATE);
String due = "";
if (colDueIndex > -1)
due = cursor.getString(colDueIndex);
if (due != null && !due.isEmpty()) {
Time date = new Time(Time.getCurrentTimezone());
date.parse3339(due);
note = note + "due date: " + date.format3339(true) + "\n";
}
int colNoteIndex = cursor
.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE);
if (colNoteIndex > -1)
note = note + "\n" + cursor.getString(colNoteIndex);
// Put in hash
textToShare.put(id, note);
}
if (cursor != null)
cursor.close();
}
protected void delTextToShare(long id) {
textToShare.remove(id);
}
protected String buildTextToShare() {
String text = "";
ArrayList<String> notes = new ArrayList<String>(
textToShare.values());
if (!notes.isEmpty()) {
text = text + notes.remove(0);
while (!notes.isEmpty()) {
text = text + "\n\n" + notes.remove(0);
}
}
return text;
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("MODALMAN", "onCreateActionMode mode: " + mode);
// Clear data!
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
// if (FragmentLayout.lightTheme)
// inflater.inflate(R.menu.list_select_menu_light, menu);
// else
inflater.inflate(R.menu.list_select_menu, menu);
// mode.setTitle(getResources().getQuantityString(R.plurals.mode_choose,
// 1, 1));
this.mode = mode;
return true;
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode,
android.view.MenuItem item) {
Log.d("MODALMAN", "onActionItemClicked mode: " + mode);
switch (item.getItemId()) {
case R.id.modal_share:
shareNote(buildTextToShare());
mode.finish();
break;
case R.id.modal_copy:
ClipboardManager clipboard = (ClipboardManager) activity
.getSystemService(Context.CLIPBOARD_SERVICE);
// ICS style
clipboard.setPrimaryClip(ClipData.newPlainText("Note",
buildTextToShare()));
int num = getListView().getCheckedItemCount();
Toast.makeText(
activity,
getResources().getQuantityString(
R.plurals.notecopied_msg, num, num),
Toast.LENGTH_SHORT).show();
mode.finish();
break;
case R.id.modal_delete:
onDeleteAction();
break;
default:
// Toast.makeText(activity, "Clicked " + item.getTitle(),
// Toast.LENGTH_SHORT).show();
break;
}
return true;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
Log.d("modeCallback", "onDestroyActionMode: " + mode.toString()
+ ", " + mode.getMenu().toString());
list.setFutureSingleCheck();
}
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
// Set the share intent with updated text
if (checked) {
addTextToShare(id);
this.notesToDelete.add(position);
} else {
delTextToShare(id);
this.notesToDelete.remove(position);
}
final int checkedCount = getListView().getCheckedItemCount();
mode.setTitle(getResources().getQuantityString(
R.plurals.mode_choose, checkedCount, checkedCount));
}
private void shareNote(String text) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, text);
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(Intent.createChooser(share, "Share note"));
}
public Cursor openNote(Uri uri) {
/*
* Using the URI passed in with the triggering Intent, gets the note
* or notes in the provider. Note: This is being done on the UI
* thread. It will block the thread until the query completes. In a
* sample app, going against a simple provider based on a local
* database, the block will be momentary, but in a real app you
* should use android.content.AsyncQueryHandler or
* android.os.AsyncTask.
*/
Cursor cursor = activity.managedQuery(uri, // The URI that gets
// multiple
// notes from
// the provider.
NotesEditorFragment.PROJECTION, // A projection that returns
// the note ID and
// note
// content for each note.
null, // No "where" clause selection criteria.
null, // No "where" clause selection values.
null // Use the default sort order (modification date,
// descending)
);
// Or Honeycomb will crash
activity.stopManagingCursor(cursor);
return cursor;
}
public void onDeleteAction() {
int num = notesToDelete.size();
if (onDeleteListener != null) {
for (int pos : notesToDelete) {
Log.d(TAG, "Deleting key: " + pos);
}
onDeleteListener.onModalDelete(notesToDelete);
}
Toast.makeText(
activity,
getResources().getQuantityString(R.plurals.notedeleted_msg,
num, num), Toast.LENGTH_SHORT).show();
mode.finish();
}
}
@TargetApi(14)
private class ModeCallbackICS extends ModeCallbackHC {
protected ShareActionProvider actionProvider;
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
super.onItemCheckedStateChanged(mode, position, id, checked);
if (actionProvider != null) {
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
}
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
Log.d("modeCallBack", "onCreateActionMode " + mode);
this.textToShare.clear();
this.notesToDelete.clear();
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.list_select_menu, menu);
// mode.setTitle(getResources().getQuantityString(R.plurals.mode_choose,
// 1, 1));
this.mode = mode;
// Set file with share history to the provider and set the share
// intent.
android.view.MenuItem actionItem = menu
.findItem(R.id.modal_item_share_action_provider_action_bar);
actionProvider = (ShareActionProvider) actionItem
.getActionProvider();
actionProvider
.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
// Note that you can set/change the intent any time,
// say when the user has selected an image.
actionProvider
.setShareIntent(createShareIntent(buildTextToShare()));
return true;
}
public ModeCallbackICS(NotesListFragment list) {
super(list);
}
}
@Override
public void onModalDelete(Collection<Integer> positions) {
Log.d(TAG, "onModalDelete");
if (positions.contains(mActivatedPosition)) {
Log.d(TAG, "onModalDelete contained setting id invalid");
// idInvalid = true;
} else {
// We must recalculate the positions index of the current note
// This is always done when content changes
}
HashSet<Long> ids = new HashSet<Long>();
for (int pos : positions) {
Log.d(TAG, "onModalDelete pos: " + pos);
ids.add(mSectionAdapter.getItemId(pos));
}
((MainActivity) activity).onMultiDelete(ids, mCurId);
}
private boolean shouldDisplaySections(String sorting) {
if (mCurListId == MainActivity.ALL_NOTES_ID) {
return true;
} else if (sorting.equals(MainPrefs.DUEDATESORT)
|| sorting.equals(MainPrefs.MODIFIEDSORT)) {
return true;
} else {
return false;
}
}
private void refreshList(Bundle args) {
// We might need to construct a new adapter
final String sorting = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
if (shouldDisplaySections(sorting)) {
if (mSectionAdapter == null || !mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity, null);
// mSectionAdapter.changeState(sorting);
setListAdapter(mSectionAdapter);
}
} else if (mSectionAdapter == null || mSectionAdapter.isSectioned()) {
// Destroy section loaders
destroyActiveLoaders();
mSectionAdapter = new SectionAdapter(activity,
getThemedAdapter(null));
setListAdapter(mSectionAdapter);
}
if (mSectionAdapter.isSectioned()) {
// If sort date, fire sorting loaders
// If mod date, fire modded loaders
if (mCurListId == MainActivity.ALL_NOTES_ID
&& PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(MainPrefs.KEY_LISTHEADERS, true)) {
destroyNonListNameLoaders();
activeLoaders.add(LOADER_LISTNAMES);
getLoaderManager().restartLoader(LOADER_LISTNAMES, args, this);
} else if (sorting.equals(MainPrefs.DUEDATESORT)) {
Log.d("listproto", "refreshing sectioned date list");
destroyNonDateLoaders();
activeLoaders.add(LOADER_DATEFUTURE);
activeLoaders.add(LOADER_DATENONE);
activeLoaders.add(LOADER_DATEOVERDUE);
activeLoaders.add(LOADER_DATETODAY);
activeLoaders.add(LOADER_DATETOMORROW);
activeLoaders.add(LOADER_DATEWEEK);
activeLoaders.add(LOADER_DATECOMPLETED);
getLoaderManager().restartLoader(LOADER_DATEFUTURE, args, this);
getLoaderManager().restartLoader(LOADER_DATENONE, args, this);
getLoaderManager()
.restartLoader(LOADER_DATEOVERDUE, args, this);
getLoaderManager().restartLoader(LOADER_DATETODAY, args, this);
getLoaderManager().restartLoader(LOADER_DATETOMORROW, args,
this);
getLoaderManager().restartLoader(LOADER_DATEWEEK, args, this);
getLoaderManager().restartLoader(LOADER_DATECOMPLETED, args,
this);
} else if (sorting.equals(MainPrefs.MODIFIEDSORT)) {
Log.d("listproto", "refreshing sectioned mod list");
destroyNonModLoaders();
activeLoaders.add(LOADER_MODPAST);
activeLoaders.add(LOADER_MODTODAY);
activeLoaders.add(LOADER_MODWEEK);
activeLoaders.add(LOADER_MODYESTERDAY);
getLoaderManager().restartLoader(LOADER_MODPAST, args, this);
getLoaderManager().restartLoader(LOADER_MODTODAY, args, this);
getLoaderManager().restartLoader(LOADER_MODWEEK, args, this);
getLoaderManager().restartLoader(LOADER_MODYESTERDAY, args,
this);
}
} else {
destroyNonRegularLoaders();
Log.d("listproto", "refreshing normal list");
activeLoaders.add(LOADER_REGULARLIST);
getLoaderManager().restartLoader(LOADER_REGULARLIST, args, this);
}
}
private void destroyActiveLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
private void destroyListLoaders() {
for (Integer id : activeLoaders.toArray(new Integer[activeLoaders
.size()])) {
if (id > -1) {
activeLoaders.remove(id);
getLoaderManager().destroyLoader(id);
}
}
}
private void destroyModLoaders() {
activeLoaders.remove(LOADER_MODPAST);
getLoaderManager().destroyLoader(LOADER_MODPAST);
activeLoaders.remove(LOADER_MODWEEK);
getLoaderManager().destroyLoader(LOADER_MODWEEK);
activeLoaders.remove(LOADER_MODYESTERDAY);
getLoaderManager().destroyLoader(LOADER_MODYESTERDAY);
activeLoaders.remove(LOADER_MODTODAY);
getLoaderManager().destroyLoader(LOADER_MODTODAY);
}
private void destroyDateLoaders() {
activeLoaders.remove(LOADER_DATECOMPLETED);
getLoaderManager().destroyLoader(LOADER_DATECOMPLETED);
activeLoaders.remove(LOADER_DATEFUTURE);
getLoaderManager().destroyLoader(LOADER_DATEFUTURE);
activeLoaders.remove(LOADER_DATENONE);
getLoaderManager().destroyLoader(LOADER_DATENONE);
activeLoaders.remove(LOADER_DATEOVERDUE);
getLoaderManager().destroyLoader(LOADER_DATEOVERDUE);
activeLoaders.remove(LOADER_DATETODAY);
getLoaderManager().destroyLoader(LOADER_DATETODAY);
activeLoaders.remove(LOADER_DATETOMORROW);
getLoaderManager().destroyLoader(LOADER_DATETOMORROW);
activeLoaders.remove(LOADER_DATEWEEK);
getLoaderManager().destroyLoader(LOADER_DATEWEEK);
}
private void destroyListNameLoaders() {
activeLoaders.remove(LOADER_LISTNAMES);
getLoaderManager().destroyLoader(LOADER_LISTNAMES);
}
private void destroyRegularLoaders() {
activeLoaders.remove(LOADER_REGULARLIST);
getLoaderManager().destroyLoader(LOADER_REGULARLIST);
}
private void destroyNonDateLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonListNameLoaders() {
destroyDateLoaders();
destroyModLoaders();
destroyRegularLoaders();
}
private void destroyNonModLoaders() {
destroyListNameLoaders();
destroyDateLoaders();
destroyListLoaders();
destroyRegularLoaders();
}
private void destroyNonRegularLoaders() {
destroyListNameLoaders();
destroyModLoaders();
destroyListLoaders();
destroyDateLoaders();
}
private CursorLoader getAllNotesLoader(long listId) {
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Get current sort order or assemble the default one.
String sortChoice = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE, "");
String sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
if (MainPrefs.DUEDATESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
} else if (MainPrefs.TITLESORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.ALPHABETIC_SORT_TYPE;
} else if (MainPrefs.MODIFIEDSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
} else if (MainPrefs.POSSUBSORT.equals(sortChoice)) {
sortOrder = NotePad.Notes.POSSUBSORT_SORT_TYPE;
}
NotesListFragment.sortType = sortOrder;
sortOrder += " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
if (listId == MainActivity.ALL_NOTES_ID) {
return new CursorLoader(activity, baseUri, PROJECTION, null, null,
sortOrder);
} else {
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_LIST + " IS ?",
new String[] { Long.toString(listId) }, sortOrder);
}
}
private CursorLoader getSearchNotesLoader() {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
Uri baseUri = NotePad.Notes.CONTENT_VISIBLE_URI;
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
// Get current sort order or assemble the default one.
String sortOrder = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_TYPE,
NotePad.Notes.DEFAULT_SORT_TYPE)
+ " "
+ PreferenceManager.getDefaultSharedPreferences(activity)
.getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
// include title field in search
return new CursorLoader(activity, baseUri, PROJECTION,
NotePad.Notes.COLUMN_NAME_NOTE + " LIKE ?" + " OR "
+ NotePad.Notes.COLUMN_NAME_TITLE + " LIKE ?",
new String[] { "%" + currentQuery + "%",
"%" + currentQuery + "%" }, sortOrder);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader");
if (args != null) {
/*
* if (args.containsKey(SHOULD_OPEN_NOTE) &&
* args.getBoolean(SHOULD_OPEN_NOTE)) { autoOpenNote = true; }
*/
}
if (currentQuery != null && !currentQuery.isEmpty()) {
return getSearchNotesLoader();
} else {
// Important that these are in the correct order!
switch (id) {
case LOADER_DATEFUTURE:
case LOADER_DATENONE:
case LOADER_DATEOVERDUE:
case LOADER_DATETODAY:
case LOADER_DATETOMORROW:
case LOADER_DATEWEEK:
case LOADER_DATECOMPLETED:
return getDateLoader(id, mCurListId);
case LOADER_MODPAST:
case LOADER_MODTODAY:
case LOADER_MODWEEK:
case LOADER_MODYESTERDAY:
return getModLoader(id, mCurListId);
case LOADER_REGULARLIST:
Log.d("listproto", "Getting cursor normal list: " + mCurListId);
// Regular lists
return getAllNotesLoader(mCurListId);
case LOADER_LISTNAMES:
Log.d("listproto", "Getting cursor for list names");
// Section names
return getSectionNameLoader();
default:
Log.d("listproto", "Getting cursor for individual list: " + id);
// Individual lists. ID is actually be the list id
return getAllNotesLoader(id);
}
}
}
private CursorLoader getSectionNameLoader() {
// first check SharedPreferences for what the appropriate loader would
// be
// list names, due date, modification
return new CursorLoader(activity, NotePad.Lists.CONTENT_URI,
new String[] { NotePad.Lists._ID,
NotePad.Lists.COLUMN_NAME_TITLE },
NotePad.Lists.COLUMN_NAME_DELETED + " IS NOT 1", null,
NotePad.Lists.SORT_ORDER);
}
private CursorLoader getDateLoader(int id, long listId) {
Log.d("listproto", "getting date loader");
String sortOrder = NotePad.Notes.DUEDATE_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
if (dateComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
dateComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.date_header_overdue),
"0");
put(activity
.getString(R.string.date_header_today),
"1");
put(activity
.getString(R.string.date_header_tomorrow),
"2");
put(activity
.getString(R.string.date_header_7days),
"3");
put(activity
.getString(R.string.date_header_future),
"4");
put(activity
.getString(R.string.date_header_none),
"5");
put(activity
.getString(R.string.date_header_completed),
"6");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
String[] vars = null;
String where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ? AND ";
switch (id) {
case LOADER_DATEFUTURE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") >= ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateEightDay() };
break;
case LOADER_DATEOVERDUE:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETODAY:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateToday() };
break;
case LOADER_DATETOMORROW:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + ") IS ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow() };
break;
case LOADER_DATEWEEK:
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT NULL AND ";
where += NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NOT '' AND ";
where += "date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") > ? AND date(" + NotePad.Notes.COLUMN_NAME_DUE_DATE
+ ") < ?";
vars = new String[] {
activity.getString(R.string.gtask_status_uncompleted),
TimeHelper.dateTomorrow(), TimeHelper.dateEightDay() };
break;
case LOADER_DATECOMPLETED:
where = NotePad.Notes.COLUMN_NAME_GTASKS_STATUS + " IS ?";
vars = new String[] { activity
.getString(R.string.gtask_status_completed) };
break;
case LOADER_DATENONE:
default:
where += "(" + NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS NULL OR "
+ NotePad.Notes.COLUMN_NAME_DUE_DATE + " IS '')";
vars = new String[] { activity
.getString(R.string.gtask_status_uncompleted) };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private CursorLoader getModLoader(int id, long listId) {
Log.d("listproto", "getting mod loader");
String sortOrder = NotePad.Notes.MODIFICATION_SORT_TYPE;
NotesListFragment.sortType = sortOrder;
final String ordering = PreferenceManager.getDefaultSharedPreferences(
activity).getString(MainPrefs.KEY_SORT_ORDER,
NotePad.Notes.DEFAULT_SORT_ORDERING);
sortOrder += " " + ordering;
String[] vars = null;
String where = "";
if (modComparator == null) {
// Create the comparator
// Doing it here because I need the context
// to fetch strings
modComparator = new Comparator<String>() {
@SuppressWarnings("serial")
private final Map<String, String> orderMap = Collections
.unmodifiableMap(new HashMap<String, String>() {
{
put(activity
.getString(R.string.mod_header_today),
"0");
put(activity
.getString(R.string.mod_header_yesterday),
"1");
put(activity
.getString(R.string.mod_header_thisweek),
"2");
put(activity
.getString(R.string.mod_header_earlier),
"3");
}
});
public int compare(String object1, String object2) {
// -1 if object 1 is first, 0 equal, 1 otherwise
final String m1 = orderMap.get(object1);
final String m2 = orderMap.get(object2);
if (m1 == null)
return 1;
if (m2 == null)
return -1;
if (ordering.equals(NotePad.Notes.ASCENDING_SORT_ORDERING))
return m1.compareTo(m2);
else
return m2.compareTo(m1);
};
};
}
switch (id) {
case LOADER_MODTODAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " > ?";
vars = new String[] { TimeHelper.milliTodayStart() };
break;
case LOADER_MODYESTERDAY:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milliYesterdayStart(),
TimeHelper.milliTodayStart() };
break;
case LOADER_MODWEEK:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " >= ? AND ";
where += NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo(),
TimeHelper.milliYesterdayStart() };
break;
case LOADER_MODPAST:
default:
where = NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " < ?";
vars = new String[] { TimeHelper.milli7DaysAgo() };
break;
}
// And only for current list
if (listId != MainActivity.ALL_NOTES_ID) {
where = NotePad.Notes.COLUMN_NAME_LIST + " IS ? AND (" + where
+ ")";
String[] nvars = new String[1 + vars.length];
nvars[0] = Long.toString(listId);
for (int i = 0; i < vars.length; i++) {
nvars[i + 1] = vars[i];
}
vars = nvars;
}
return new CursorLoader(activity, NotePad.Notes.CONTENT_VISIBLE_URI,
PROJECTION, where, vars, sortOrder);
}
private void addSectionToAdapter(String sectionname, Cursor data,
Comparator<String> comp) {
addSectionToAdapter(-1, sectionname, data, comp);
}
private void addSectionToAdapter(long sectionId, String sectionname,
Cursor data, Comparator<String> comp) {
// Make sure an adapter exists
SimpleCursorAdapter adapter = mSectionAdapter.sections.get(sectionname);
if (adapter == null) {
adapter = getThemedAdapter(null);
if (sectionId > -1)
mSectionAdapter.addSection(sectionId, sectionname, adapter,
comp);
else
mSectionAdapter.addSection(sectionname, adapter, comp);
}
adapter.swapCursor(data);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
Log.d(TAG, "onLoadFinished");
Log.d("listproto", "loader id: " + loader.getId());
Log.d("listproto", "Current list " + mCurListId);
long listid;
String sectionname;
switch (loader.getId()) {
case LOADER_REGULARLIST:
if (!mSectionAdapter.isSectioned()) {
mSectionAdapter.swapCursor(data);
} else
Log.d("listproto",
"That's odd... List id invalid: " + loader.getId());
break;
case LOADER_LISTNAMES:
// Section names and starts loaders for individual sections
Log.d("listproto", "List names");
while (data != null && data.moveToNext()) {
listid = data.getLong(data.getColumnIndex(NotePad.Lists._ID));
sectionname = data.getString(data
.getColumnIndex(NotePad.Lists.COLUMN_NAME_TITLE));
Log.d("listproto", "Adding " + sectionname + " to headers");
listNames.put(listid, sectionname);
// Start loader for this list
Log.d("listproto", "Starting loader for " + sectionname
+ " id " + listid);
activeLoaders.add((int) listid);
getLoaderManager().restartLoader((int) listid, null, this);
}
break;
case LOADER_DATEFUTURE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_future);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATECOMPLETED:
Log.d("listproto", "got completed cursor");
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_completed);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATENONE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_none);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEOVERDUE:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_overdue);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETODAY:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_today);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATETOMORROW:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_tomorrow);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_DATEWEEK:
mSectionAdapter.changeState(SECTION_STATE_DATE);
sectionname = activity.getString(R.string.date_header_7days);
addSectionToAdapter(sectionname, data, dateComparator);
break;
case LOADER_MODPAST:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_earlier);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODTODAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_today);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODWEEK:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_thisweek);
addSectionToAdapter(sectionname, data, modComparator);
break;
case LOADER_MODYESTERDAY:
mSectionAdapter.changeState(SECTION_STATE_MOD);
sectionname = activity.getString(R.string.mod_header_yesterday);
addSectionToAdapter(sectionname, data, modComparator);
break;
default:
mSectionAdapter.changeState(SECTION_STATE_LISTS);
// Individual lists have ids that are positive
if (loader.getId() >= 0) {
Log.d("listproto", "Sublists");
// Sublists
listid = loader.getId();
sectionname = listNames.get(listid);
Log.d("listproto", "Loader finished for list id: "
+ sectionname);
addSectionToAdapter(listid, sectionname, data, alphaComparator);
}
break;
}
// The list should now be shown.
if (getView() != null) {
if (this.getListAdapter().getCount() > 0) {
Log.d(TAG, "showing list");
getView().findViewById(R.id.listContainer).setVisibility(
View.VISIBLE);
getView().findViewById(R.id.hintContainer).setVisibility(
View.GONE);
} else {
Log.d(TAG, "no notes, hiding list");
getView().findViewById(R.id.listContainer).setVisibility(
View.GONE);
getView().findViewById(R.id.hintContainer).setVisibility(
View.VISIBLE);
}
}
// Reselect current note in list, if possible
// This happens in delete
/*
* if (idInvalid) { idInvalid = false; // Note is invalid, so
* recalculate a valid position and index
* reCalculateValidValuesAfterDelete(); reSelectId(); //if
* (activity.getCurrentContent().equals( //
* DualLayoutActivity.CONTENTVIEW.DUAL)) //autoOpenNote = true; } else {
*/
reSelectId();
// }
// If a note was created, it will be set in this variable
if (newNoteIdToSelect > -1) {
setActivatedPosition(showNote(getPosOfId(newNoteIdToSelect)));
newNoteIdToSelect = -1; // Should only be set to anything else on
// create
}
// Open first note if this is first start
// or if one was opened previously
/*
* else if (autoOpenNote && false) { autoOpenNote = false;
* showFirstBestNote(); } else { reSelectId(); }
*/
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
Log.d(TAG, "onLoaderReset");
if (mSectionAdapter.isSectioned()) {
// Sections
for (SimpleCursorAdapter adapter : mSectionAdapter.sections
.values()) {
adapter.swapCursor(null);
}
mSectionAdapter.headers.clear();
mSectionAdapter.sections.clear();
} else {
// Single list
mSectionAdapter.swapCursor(null);
}
}
/**
* Re list notes when sorting changes
*
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
try {
if (activity == null || activity.isFinishing()) {
Log.d(TAG, "isFinishing, should not update");
// Setting the summary now would crash it with
// IllegalStateException since we are not attached to a view
} else {
if (MainPrefs.KEY_SORT_TYPE.equals(key)
|| MainPrefs.KEY_SORT_ORDER.equals(key)) {
// rebuild comparators during refresh
dateComparator = modComparator = null;
refreshList(null);
}
}
} catch (IllegalStateException e) {
// This is just in case the "isFinishing" wouldn't be enough
// The isFinishing will try to prevent us from doing something
// stupid
// This catch prevents the app from crashing if we do something
// stupid
Log.d(TAG, "Exception was caught: " + e.getMessage());
}
}
}
|
diff --git a/src/nl/astraeus/persistence/SimpleList.java b/src/nl/astraeus/persistence/SimpleList.java
index a9805a8..4c6a628 100644
--- a/src/nl/astraeus/persistence/SimpleList.java
+++ b/src/nl/astraeus/persistence/SimpleList.java
@@ -1,258 +1,260 @@
package nl.astraeus.persistence;
import java.io.Serializable;
import java.util.*;
/**
* SimpleList
* <p/>
* User: rnentjes
* Date: 7/27/11
* Time: 2:52 PM
*/
public class SimpleList<M extends SimpleModel> implements java.util.List<M>, Serializable {
public static final long serialVersionUID = 1L;
private Class<? extends SimpleModel> cls;
private java.util.List<Long> list = new LinkedList<Long>();
private transient Map<Long, M> incoming;
public SimpleList(Class<? extends SimpleModel> cls) {
this.cls = cls;
}
public Map<Long, M> getIncoming() {
if (incoming == null) {
incoming = new HashMap<Long, M>();
}
return incoming;
}
public void clearIncoming() {
getIncoming().clear();
}
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public boolean contains(Object o) {
if (o instanceof SimpleModel) {
return list.contains(((SimpleModel)o).getId());
} else {
return list.contains(o);
}
}
public java.util.List<Long> getIdList() {
return list;
}
public Class<? extends SimpleModel> getType() {
return cls;
}
public Iterator<M> iterator() {
return new Iterator<M>() {
Iterator<Long> it = list.iterator();
M next = null;
public boolean hasNext() {
while (next == null && it.hasNext()) {
long id = it.next();
- next = incoming.get(id);
+ if (incoming != null) {
+ next = incoming.get(id);
+ }
if (next == null) {
next = (M) SimpleStore.get().getModelMap(cls).get(id);
}
}
return (next != null);
}
public M next() {
M result = next;
next = null;
while (it.hasNext() && next == null) {
Long nextId = it.next();
next = getIncoming().get(nextId);
if (next == null) {
next = (M) SimpleStore.get().find(cls, nextId);
}
}
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public Object[] toArray() {
throw new IllegalStateException("Not implemented yet.");
}
public <T> T[] toArray(T[] a) {
throw new IllegalStateException("Not implemented yet.");
}
public boolean add(M m) {
//SimpleStore.get().assertIsStored(m);
getIncoming().put(m.getId(), m);
return list.add(m.getId());
}
// used by SimplePersistence to copy this list,
// using this function will avoid the entity to be added to the incoming list
public boolean add(long id) {
//SimpleStore.get().assertIsStored(m);
return list.add(id);
}
public boolean remove(Object o) {
getIncoming().remove(((M)o).getId());
return list.remove(((M)o).getId());
}
public boolean containsAll(Collection<?> c) {
throw new IllegalStateException("Not implemented yet.");
}
public boolean addAll(Collection<? extends M> c) {
boolean result = true;
for (M m : c) {
result = result && add(m);
}
return result;
}
public boolean addAll(int index, Collection<? extends M> c) {
for (M m : c) {
add(index, m);
}
return true;
}
public boolean removeAll(Collection<?> c) {
for (Object m : c) {
remove(m);
}
return true;
}
private java.util.List<Long> getLongList(Collection<? extends M> c) {
java.util.List<Long> result = new LinkedList<Long>();
for (M m : c) {
result.add(m.getId());
}
return result;
}
public boolean retainAll(Collection<?> c) {
return list.retainAll(getLongList((Collection<? extends M>) c));
}
public void clear() {
getIncoming().clear();
list.clear();
}
public M get(int index) {
Long id = list.get(index);
M result = getIncoming().get(id);
if (result == null) {
result = (M) SimpleStore.get().find(cls, id);
}
return result;
}
public M set(int index, M element) {
M result = get(index);
getIncoming().put(element.getId(), element);
list.set(index, element.getId());
return result;
}
public void add(int index, M element) {
getIncoming().put(element.getId(), element);
list.add(index, element.getId());
}
public M remove(int index) {
Long id = list.remove(index);
M result = getIncoming().get(id);
if (result == null) {
result = (M) SimpleStore.get().find(cls, id);
}
return result;
}
public int indexOf(Object o) {
return list.indexOf(((M)o).getId());
}
public int lastIndexOf(Object o) {
return list.lastIndexOf(((M) o).getId());
}
public ListIterator<M> listIterator() {
throw new IllegalStateException("Not implemented yet.");
}
public ListIterator<M> listIterator(int index) {
throw new IllegalStateException("Not implemented yet.");
}
public java.util.List<M> subList(int fromIndex, int toIndex) {
throw new IllegalStateException("Not implemented yet.");
}
public String toString() {
StringBuilder result = new StringBuilder();
if (list.isEmpty()) {
result.append("empty");
} else {
for (int i = 0; i < 10 && this.list.size() > i; i++) {
if (i > 0) {
result.append(", ");
}
result.append(this.list.get(i));
}
if (this.list.size() > 10) {
result.append(", <" + (this.list.size() - 10) + " more>");
}
}
return result.toString();
}
}
| true | true | public Iterator<M> iterator() {
return new Iterator<M>() {
Iterator<Long> it = list.iterator();
M next = null;
public boolean hasNext() {
while (next == null && it.hasNext()) {
long id = it.next();
next = incoming.get(id);
if (next == null) {
next = (M) SimpleStore.get().getModelMap(cls).get(id);
}
}
return (next != null);
}
public M next() {
M result = next;
next = null;
while (it.hasNext() && next == null) {
Long nextId = it.next();
next = getIncoming().get(nextId);
if (next == null) {
next = (M) SimpleStore.get().find(cls, nextId);
}
}
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
| public Iterator<M> iterator() {
return new Iterator<M>() {
Iterator<Long> it = list.iterator();
M next = null;
public boolean hasNext() {
while (next == null && it.hasNext()) {
long id = it.next();
if (incoming != null) {
next = incoming.get(id);
}
if (next == null) {
next = (M) SimpleStore.get().getModelMap(cls).get(id);
}
}
return (next != null);
}
public M next() {
M result = next;
next = null;
while (it.hasNext() && next == null) {
Long nextId = it.next();
next = getIncoming().get(nextId);
if (next == null) {
next = (M) SimpleStore.get().find(cls, nextId);
}
}
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
|
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/FtpCheck.java b/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/FtpCheck.java
index 175688c..bd5d507 100644
--- a/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/FtpCheck.java
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/FtpCheck.java
@@ -1,94 +1,94 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.libcheck;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* Basic check for sftp
*/
public class FtpCheck
{
public static void main(String args[]) throws Exception
{
if (args.length < 3)
{
throw new IllegalArgumentException("Usage: FtpCheck user pass host dir");
}
String user = args[0];
String pass = args[1];
String host = args[2];
String dir = null;
if (args.length == 4)
{
dir = args[3];
}
FTPClient client = new FTPClient();
client.connect(host);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
throw new IllegalArgumentException("cant connect: " + reply);
}
if (!client.login(user, pass))
{
throw new IllegalArgumentException("login failed");
}
client.enterLocalPassiveMode();
OutputStream os = client.storeFileStream(dir + "/test.txt");
if (os == null)
{
throw new IllegalStateException(client.getReplyString());
}
os.write("test".getBytes());
os.close();
client.completePendingCommand();
if (dir != null)
{
if (!client.changeWorkingDirectory(dir))
{
throw new IllegalArgumentException("change dir to '" + dir + "' failed");
}
}
- System.err.println("System: " + client.getSystemName());
+ System.err.println("System: " + client.getSystemType());
FTPFile[] files = client.listFiles();
for (int i = 0; i < files.length; i++)
{
FTPFile file = files[i];
if (file == null)
{
System.err.println("#" + i + ": " + null);
}
else
{
System.err.println("#" + i + ": " + file.getRawListing());
System.err.println("#" + i + ": " + file.toString());
System.err.println("\t name:" + file.getName() + " type:" + file.getType());
}
}
client.disconnect();
}
}
| true | true | public static void main(String args[]) throws Exception
{
if (args.length < 3)
{
throw new IllegalArgumentException("Usage: FtpCheck user pass host dir");
}
String user = args[0];
String pass = args[1];
String host = args[2];
String dir = null;
if (args.length == 4)
{
dir = args[3];
}
FTPClient client = new FTPClient();
client.connect(host);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
throw new IllegalArgumentException("cant connect: " + reply);
}
if (!client.login(user, pass))
{
throw new IllegalArgumentException("login failed");
}
client.enterLocalPassiveMode();
OutputStream os = client.storeFileStream(dir + "/test.txt");
if (os == null)
{
throw new IllegalStateException(client.getReplyString());
}
os.write("test".getBytes());
os.close();
client.completePendingCommand();
if (dir != null)
{
if (!client.changeWorkingDirectory(dir))
{
throw new IllegalArgumentException("change dir to '" + dir + "' failed");
}
}
System.err.println("System: " + client.getSystemName());
FTPFile[] files = client.listFiles();
for (int i = 0; i < files.length; i++)
{
FTPFile file = files[i];
if (file == null)
{
System.err.println("#" + i + ": " + null);
}
else
{
System.err.println("#" + i + ": " + file.getRawListing());
System.err.println("#" + i + ": " + file.toString());
System.err.println("\t name:" + file.getName() + " type:" + file.getType());
}
}
client.disconnect();
}
| public static void main(String args[]) throws Exception
{
if (args.length < 3)
{
throw new IllegalArgumentException("Usage: FtpCheck user pass host dir");
}
String user = args[0];
String pass = args[1];
String host = args[2];
String dir = null;
if (args.length == 4)
{
dir = args[3];
}
FTPClient client = new FTPClient();
client.connect(host);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
throw new IllegalArgumentException("cant connect: " + reply);
}
if (!client.login(user, pass))
{
throw new IllegalArgumentException("login failed");
}
client.enterLocalPassiveMode();
OutputStream os = client.storeFileStream(dir + "/test.txt");
if (os == null)
{
throw new IllegalStateException(client.getReplyString());
}
os.write("test".getBytes());
os.close();
client.completePendingCommand();
if (dir != null)
{
if (!client.changeWorkingDirectory(dir))
{
throw new IllegalArgumentException("change dir to '" + dir + "' failed");
}
}
System.err.println("System: " + client.getSystemType());
FTPFile[] files = client.listFiles();
for (int i = 0; i < files.length; i++)
{
FTPFile file = files[i];
if (file == null)
{
System.err.println("#" + i + ": " + null);
}
else
{
System.err.println("#" + i + ": " + file.getRawListing());
System.err.println("#" + i + ": " + file.toString());
System.err.println("\t name:" + file.getName() + " type:" + file.getType());
}
}
client.disconnect();
}
|
diff --git a/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java b/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
index 222eddb..566916a 100644
--- a/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
+++ b/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
@@ -1,226 +1,225 @@
/*
* Copyright (C) 2010 Mirko Weber, Felix Bechstein
*
* This file is part of WebSMS.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; If not, see <http://www.gnu.org/licenses/>.
*/
package de.ub0r.android.websms.connector.sipgate;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import org.xmlrpc.android.XMLRPCFault;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import de.ub0r.android.websms.connector.common.Connector;
import de.ub0r.android.websms.connector.common.ConnectorCommand;
import de.ub0r.android.websms.connector.common.ConnectorSpec;
import de.ub0r.android.websms.connector.common.Utils;
import de.ub0r.android.websms.connector.common.WebSMSException;
import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec;
/**
* AsyncTask to manage XMLRPC-Calls to sipgate.de remote-API.
*
* @author Mirko Weber
*/
public class ConnectorSipgate extends Connector {
/** Tag for output. */
private static final String TAG = "WebSMS.Sipg";
/** Preferences intent action. */
private static final String PREFS_INTENT_ACTION = "de.ub0r.android."
+ "websms.connectors.sipgate.PREFS";
/** Sipgate.de API URL. */
private static final String SIPGATE_URL = "https://"
+ "samurai.sipgate.net/RPC2";
/** Sipfate.de TEAM-API URL. */
private static final String SIPGATE_TEAM_URL = "https://"
+ "api.sipgate.net/RPC2";
/**
* {@inheritDoc}
*/
@Override
public final ConnectorSpec initSpec(final Context context) {
final String name = context.getString(R.string.connector_sipgate_name);
ConnectorSpec c = new ConnectorSpec(TAG, name);
c.setAuthor(// .
context.getString(R.string.connector_sipgate_author));
c.setBalance(null);
c.setPrefsIntent(PREFS_INTENT_ACTION);
c.setPrefsTitle(context
.getString(R.string.connector_sipgate_preferences));
c.setCapabilities(ConnectorSpec.CAPABILITIES_UPDATE
| ConnectorSpec.CAPABILITIES_SEND);
c.addSubConnector(TAG, c.getName(),
SubConnectorSpec.FEATURE_MULTIRECIPIENTS);
return c;
}
/**
* {@inheritDoc}
*/
@Override
public final ConnectorSpec updateSpec(final Context context,
final ConnectorSpec connectorSpec) {
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(context);
if (p.getBoolean(Preferences.PREFS_ENABLE_SIPGATE, false)) {
if (p.getString(Preferences.PREFS_USER_SIPGATE, "").length() > 0
&& p.getString(Preferences.PREFS_PASSWORD_SIPGATE, "") // .
.length() > 0) {
connectorSpec.setReady();
} else {
connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED);
}
} else {
connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE);
}
return connectorSpec;
}
/**
* {@inheritDoc}
*/
@Override
protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
for (String t : command.getRecipients()) {
if (t != null && t.length() > 1) {
- // TODO: force international number?
- // FIXME: this is broken
+ // FIXME: force international number
final String u = "sip:"
+ Utils.getRecipientsNumber(t)
.replaceAll("\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
if (command.getDefSender().length() > 6) {
String localUri = "sip:"
+ command.getDefSender().replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
params.put("Content", command.getText());
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
protected final void doUpdate(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doUpdate()");
Map<String, Object> back = null;
try {
XMLRPCClient client = this.init(context);
back = (Map<String, Object>) client.call("samurai.BalanceGet");
Log.d(TAG, back.toString());
if (back.get("StatusCode").equals(
new Integer(Utils.HTTP_SERVICE_OK))) {
final String b = String.format("%.2f \u20AC",
((Double) ((Map<String, Object>) back
.get("CurrentBalance"))
.get("TotalIncludingVat")));
this.getSpec(context).setBalance(b);
}
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
/**
* Sets up and instance of {@link XMLRPCClient}.
*
* @param context
* {@link Context}
* @return the initialized {@link XMLRPCClient}
* @throws XMLRPCException
* XMLRPCException
*/
private XMLRPCClient init(final Context context) throws XMLRPCException {
Log.d(TAG, "init()");
final String version = context.getString(R.string.app_version);
final String vendor = context
.getString(R.string.connector_sipgate_author);
XMLRPCClient client = null;
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(context);
if (p.getBoolean(Preferences.PREFS_ENABLE_SIPGATE_TEAM, false)) {
client = new XMLRPCClient(SIPGATE_TEAM_URL);
} else {
client = new XMLRPCClient(SIPGATE_URL);
}
client.setBasicAuthentication(p.getString(
Preferences.PREFS_USER_SIPGATE, ""), p.getString(
Preferences.PREFS_PASSWORD_SIPGATE, ""));
Object back;
try {
Hashtable<String, String> ident = new Hashtable<String, String>();
ident.put("ClientName", TAG);
ident.put("ClientVersion", version);
ident.put("ClientVendor", vendor);
back = client.call("samurai.ClientIdentify", ident);
Log.d(TAG, back.toString());
return client;
} catch (XMLRPCException e) {
Log.e(TAG, "XMLRPCExceptin in init()", e);
throw e;
}
}
}
| true | true | protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
for (String t : command.getRecipients()) {
if (t != null && t.length() > 1) {
// TODO: force international number?
// FIXME: this is broken
final String u = "sip:"
+ Utils.getRecipientsNumber(t)
.replaceAll("\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
if (command.getDefSender().length() > 6) {
String localUri = "sip:"
+ command.getDefSender().replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
params.put("Content", command.getText());
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
| protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
for (String t : command.getRecipients()) {
if (t != null && t.length() > 1) {
// FIXME: force international number
final String u = "sip:"
+ Utils.getRecipientsNumber(t)
.replaceAll("\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
if (command.getDefSender().length() > 6) {
String localUri = "sip:"
+ command.getDefSender().replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
params.put("Content", command.getText());
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
|
diff --git a/src/main/java/rinde/evo4mas/gendreau06/Gendreau06Evaluator.java b/src/main/java/rinde/evo4mas/gendreau06/Gendreau06Evaluator.java
index b481a54..59e2ae1 100644
--- a/src/main/java/rinde/evo4mas/gendreau06/Gendreau06Evaluator.java
+++ b/src/main/java/rinde/evo4mas/gendreau06/Gendreau06Evaluator.java
@@ -1,197 +1,197 @@
/**
*
*/
package rinde.evo4mas.gendreau06;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static java.util.Collections.unmodifiableList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.jppf.client.JPPFJob;
import org.jppf.task.storage.DataProvider;
import org.jppf.task.storage.MemoryMapDataProvider;
import rinde.ecj.GPBaseNode;
import rinde.ecj.GPEvaluator;
import rinde.ecj.GPProgram;
import rinde.ecj.GPProgramParser;
import rinde.ecj.Heuristic;
import rinde.evo4mas.common.ExperimentUtil;
import rinde.evo4mas.common.ResultDTO;
import rinde.evo4mas.gendreau06.GSimulationTask.SolutionType;
import ec.EvolutionState;
import ec.gp.GPIndividual;
import ec.gp.GPTree;
import ec.util.Parameter;
/**
* @author Rinde van Lon <[email protected]>
*
*/
public class Gendreau06Evaluator extends GPEvaluator<GSimulationTask, ResultDTO, Heuristic<GendreauContext>> {
private static final long serialVersionUID = 5944679648563955812L;
static List<List<String>> folds = ExperimentUtil.createFolds("files/scenarios/gendreau06/", 5, "");
protected List<String> trainSet;
protected List<String> testSet;
protected int numScenariosPerGeneration;
protected int numScenariosAtLastGeneration;
protected SolutionType solutionType;
private final Map<String, String> scenarioCache;
public final static String P_SOLUTION_VARIANT = "solution-variant";
public final static String P_TEST_SET_DIR = "test-set-dir";
public final static String P_TRAIN_SET_DIR = "train-set-dir";
public final static String P_NUM_SCENARIOS_PER_GENERATION = "num-scenarios-per-generation";
public final static String P_NUM_SCENARIOS_AT_LAST_GENERATION = "num-scenarios-at-last-generation";
public Gendreau06Evaluator() {
scenarioCache = newHashMap();
}
@Override
public void setup(final EvolutionState state, final Parameter base) {
super.setup(state, base);
final String testSetDir = state.parameters.getString(base.push(P_TEST_SET_DIR), null);
checkArgument(testSetDir != null && new File(testSetDir).isDirectory(), "A valid test set directory should be specified, "
+ base.push(P_TEST_SET_DIR) + "=" + testSetDir);
final String trainSetDir = state.parameters.getString(base.push(P_TRAIN_SET_DIR), null);
checkArgument(trainSetDir != null && new File(trainSetDir).isDirectory(), "A valid train set directory should be specified, "
+ base.push(P_TRAIN_SET_DIR) + "=" + trainSetDir);
testSet = unmodifiableList(ExperimentUtil.getFilesFromDir(testSetDir, "_240_24"));
trainSet = unmodifiableList(ExperimentUtil.getFilesFromDir(trainSetDir, "_240_24"));
System.out.println("test: " + removeDirPrefix(testSet) + "\ntrain: " + removeDirPrefix(trainSet));
final String sv = state.parameters.getString(base.push(P_SOLUTION_VARIANT), null);
- checkArgument(SolutionType.hasValue(sv), base.push(P_TRAIN_SET_DIR)
+ checkArgument(SolutionType.hasValue(sv), base.push(P_SOLUTION_VARIANT)
+ " should be assigned one of the following values: " + Arrays.toString(SolutionType.values()));
solutionType = SolutionType.valueOf(sv);
try {
for (final String s : testSet) {
scenarioCache.put(s, ExperimentUtil.textFileToString(s));
}
for (final String s : trainSet) {
scenarioCache.put(s, ExperimentUtil.textFileToString(s));
}
} catch (final FileNotFoundException e) {
throw new RuntimeException(e);
} catch (final IOException e) {
throw new RuntimeException(e);
}
numScenariosPerGeneration = state.parameters.getInt(base.push(P_NUM_SCENARIOS_PER_GENERATION), null, 0);
checkArgument(numScenariosPerGeneration > 0, "Number of scenarios per generation must be defined, found "
+ base.push(P_NUM_SCENARIOS_PER_GENERATION) + "="
+ (numScenariosPerGeneration == -1 ? "undefined" : numScenariosPerGeneration));
numScenariosAtLastGeneration = state.parameters.getInt(base.push(P_NUM_SCENARIOS_AT_LAST_GENERATION), null, 0);
checkArgument(numScenariosAtLastGeneration > 0, "Number of scenarios at last generation must be defined, found "
+ base.push(P_NUM_SCENARIOS_AT_LAST_GENERATION)
+ "="
+ (numScenariosAtLastGeneration == -1 ? "undefined" : numScenariosAtLastGeneration));
}
List<String> getCurrentScenarios(EvolutionState state) {
final List<String> list = newArrayList();
final int numScens = state.generation == state.numGenerations - 1 ? numScenariosAtLastGeneration
: numScenariosPerGeneration;
for (int i = 0; i < numScens; i++) {
list.add(trainSet.get((state.generation * numScenariosPerGeneration + i) % trainSet.size()));
}
return list;
}
@Override
public void evaluatePopulation(EvolutionState state) {
System.out.println(removeDirPrefix(getCurrentScenarios(state)));
super.evaluatePopulation(state);
}
List<String> removeDirPrefix(List<String> files) {
final List<String> names = newArrayList();
for (final String f : files) {
names.add(f.substring(f.lastIndexOf('/') + 1));
}
return names;
}
Collection<ResultDTO> experimentOnTestSet(GPIndividual ind) {
final GPProgram<GendreauContext> heuristic = GPProgramParser
.convertToGPProgram((GPBaseNode<GendreauContext>) ind.trees[0].child);
final DataProvider dataProvider = new MemoryMapDataProvider();
final JPPFJob job = new JPPFJob(dataProvider);
job.setBlocking(true);
job.setName("Evaluation on test set");
final List<GSimulationTask> list = newArrayList();
final List<String> scenarios = testSet;
for (final String s : scenarios) {
try {
dataProvider.setValue(s, scenarioCache.get(s));
} catch (final Exception e) {
throw new RuntimeException(e);
}
final int numVehicles = s.contains("_450_") ? 20 : 10;
list.add(new GSimulationTask(s, heuristic.clone(), numVehicles, -1, solutionType));
}
try {
for (final GSimulationTask j : list) {
if (compStrategy == ComputationStrategy.LOCAL) {
j.setDataProvider(dataProvider);
}
job.addTask(j);
}
final Collection<ResultDTO> results = compute(job);
return results;
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected Collection<GSimulationTask> createComputationJobs(DataProvider dataProvider, GPTree[] trees,
EvolutionState state) {
final GPProgram<GendreauContext> heuristic = GPProgramParser
.convertToGPProgram((GPBaseNode<GendreauContext>) trees[0].child);
final List<GSimulationTask> list = newArrayList();
final List<String> scenarios = getCurrentScenarios(state);
for (final String s : scenarios) {
try {
dataProvider.setValue(s, scenarioCache.get(s));
} catch (final Exception e) {
throw new RuntimeException(e);
}
final int numVehicles = s.contains("_450_") ? 20 : 10;
list.add(new GSimulationTask(s, heuristic.clone(), numVehicles, 60000, SolutionType.AUCTION));
}
return list;
}
@Override
protected int expectedNumberOfResultsPerGPIndividual(EvolutionState state) {
return state.generation == state.numGenerations - 1 ? numScenariosAtLastGeneration : numScenariosPerGeneration;
}
}
| true | true | public void setup(final EvolutionState state, final Parameter base) {
super.setup(state, base);
final String testSetDir = state.parameters.getString(base.push(P_TEST_SET_DIR), null);
checkArgument(testSetDir != null && new File(testSetDir).isDirectory(), "A valid test set directory should be specified, "
+ base.push(P_TEST_SET_DIR) + "=" + testSetDir);
final String trainSetDir = state.parameters.getString(base.push(P_TRAIN_SET_DIR), null);
checkArgument(trainSetDir != null && new File(trainSetDir).isDirectory(), "A valid train set directory should be specified, "
+ base.push(P_TRAIN_SET_DIR) + "=" + trainSetDir);
testSet = unmodifiableList(ExperimentUtil.getFilesFromDir(testSetDir, "_240_24"));
trainSet = unmodifiableList(ExperimentUtil.getFilesFromDir(trainSetDir, "_240_24"));
System.out.println("test: " + removeDirPrefix(testSet) + "\ntrain: " + removeDirPrefix(trainSet));
final String sv = state.parameters.getString(base.push(P_SOLUTION_VARIANT), null);
checkArgument(SolutionType.hasValue(sv), base.push(P_TRAIN_SET_DIR)
+ " should be assigned one of the following values: " + Arrays.toString(SolutionType.values()));
solutionType = SolutionType.valueOf(sv);
try {
for (final String s : testSet) {
scenarioCache.put(s, ExperimentUtil.textFileToString(s));
}
for (final String s : trainSet) {
scenarioCache.put(s, ExperimentUtil.textFileToString(s));
}
} catch (final FileNotFoundException e) {
throw new RuntimeException(e);
} catch (final IOException e) {
throw new RuntimeException(e);
}
numScenariosPerGeneration = state.parameters.getInt(base.push(P_NUM_SCENARIOS_PER_GENERATION), null, 0);
checkArgument(numScenariosPerGeneration > 0, "Number of scenarios per generation must be defined, found "
+ base.push(P_NUM_SCENARIOS_PER_GENERATION) + "="
+ (numScenariosPerGeneration == -1 ? "undefined" : numScenariosPerGeneration));
numScenariosAtLastGeneration = state.parameters.getInt(base.push(P_NUM_SCENARIOS_AT_LAST_GENERATION), null, 0);
checkArgument(numScenariosAtLastGeneration > 0, "Number of scenarios at last generation must be defined, found "
+ base.push(P_NUM_SCENARIOS_AT_LAST_GENERATION)
+ "="
+ (numScenariosAtLastGeneration == -1 ? "undefined" : numScenariosAtLastGeneration));
}
| public void setup(final EvolutionState state, final Parameter base) {
super.setup(state, base);
final String testSetDir = state.parameters.getString(base.push(P_TEST_SET_DIR), null);
checkArgument(testSetDir != null && new File(testSetDir).isDirectory(), "A valid test set directory should be specified, "
+ base.push(P_TEST_SET_DIR) + "=" + testSetDir);
final String trainSetDir = state.parameters.getString(base.push(P_TRAIN_SET_DIR), null);
checkArgument(trainSetDir != null && new File(trainSetDir).isDirectory(), "A valid train set directory should be specified, "
+ base.push(P_TRAIN_SET_DIR) + "=" + trainSetDir);
testSet = unmodifiableList(ExperimentUtil.getFilesFromDir(testSetDir, "_240_24"));
trainSet = unmodifiableList(ExperimentUtil.getFilesFromDir(trainSetDir, "_240_24"));
System.out.println("test: " + removeDirPrefix(testSet) + "\ntrain: " + removeDirPrefix(trainSet));
final String sv = state.parameters.getString(base.push(P_SOLUTION_VARIANT), null);
checkArgument(SolutionType.hasValue(sv), base.push(P_SOLUTION_VARIANT)
+ " should be assigned one of the following values: " + Arrays.toString(SolutionType.values()));
solutionType = SolutionType.valueOf(sv);
try {
for (final String s : testSet) {
scenarioCache.put(s, ExperimentUtil.textFileToString(s));
}
for (final String s : trainSet) {
scenarioCache.put(s, ExperimentUtil.textFileToString(s));
}
} catch (final FileNotFoundException e) {
throw new RuntimeException(e);
} catch (final IOException e) {
throw new RuntimeException(e);
}
numScenariosPerGeneration = state.parameters.getInt(base.push(P_NUM_SCENARIOS_PER_GENERATION), null, 0);
checkArgument(numScenariosPerGeneration > 0, "Number of scenarios per generation must be defined, found "
+ base.push(P_NUM_SCENARIOS_PER_GENERATION) + "="
+ (numScenariosPerGeneration == -1 ? "undefined" : numScenariosPerGeneration));
numScenariosAtLastGeneration = state.parameters.getInt(base.push(P_NUM_SCENARIOS_AT_LAST_GENERATION), null, 0);
checkArgument(numScenariosAtLastGeneration > 0, "Number of scenarios at last generation must be defined, found "
+ base.push(P_NUM_SCENARIOS_AT_LAST_GENERATION)
+ "="
+ (numScenariosAtLastGeneration == -1 ? "undefined" : numScenariosAtLastGeneration));
}
|
diff --git a/src/java/org/apache/ftpserver/command/AUTH.java b/src/java/org/apache/ftpserver/command/AUTH.java
index 08f819fc..b88fdb15 100644
--- a/src/java/org/apache/ftpserver/command/AUTH.java
+++ b/src/java/org/apache/ftpserver/command/AUTH.java
@@ -1,93 +1,94 @@
// $Id$
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ftpserver.command;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.ftpserver.FtpRequestImpl;
import org.apache.ftpserver.FtpWriter;
import org.apache.ftpserver.RequestHandler;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.interfaces.ICommand;
import org.apache.ftpserver.interfaces.IFtpConfig;
/**
* This server supports explicit SSL support.
*
* @author <a href="mailto:[email protected]">Rana Bhattacharyya</a>
*/
public
class AUTH implements ICommand {
/**
* Execute command
*/
public void execute(RequestHandler handler,
FtpRequestImpl request,
FtpWriter out) throws IOException, FtpException {
// reset state variables
request.resetState();
// argument check
if(!request.hasArgument()) {
out.send(501, "AUTH", null);
return;
}
// check SSL configuration
IFtpConfig fconfig = handler.getConfig();
Log log = fconfig.getLogFactory().getInstance(getClass());
if(fconfig.getSocketFactory().getSSL() == null) {
out.send(431, "AUTH", null);
+ return;
}
// check parameter
String authType = request.getArgument().toUpperCase();
if(authType.equals("SSL")) {
out.send(234, "AUTH.SSL", null);
try {
handler.createSecureSocket("SSL");
}
catch(FtpException ex) {
throw ex;
}
catch(Exception ex) {
log.warn("AUTH.execute()", ex);
throw new FtpException("AUTH.execute()", ex);
}
}
else if(authType.equals("TLS")) {
out.send(234, "AUTH.TLS", null);
try {
handler.createSecureSocket("TLS");
}
catch(FtpException ex) {
throw ex;
}
catch(Exception ex) {
log.warn("AUTH.execute()", ex);
throw new FtpException("AUTH.execute()", ex);
}
}
else {
out.send(502, "AUTH", null);
}
}
}
| true | true | public void execute(RequestHandler handler,
FtpRequestImpl request,
FtpWriter out) throws IOException, FtpException {
// reset state variables
request.resetState();
// argument check
if(!request.hasArgument()) {
out.send(501, "AUTH", null);
return;
}
// check SSL configuration
IFtpConfig fconfig = handler.getConfig();
Log log = fconfig.getLogFactory().getInstance(getClass());
if(fconfig.getSocketFactory().getSSL() == null) {
out.send(431, "AUTH", null);
}
// check parameter
String authType = request.getArgument().toUpperCase();
if(authType.equals("SSL")) {
out.send(234, "AUTH.SSL", null);
try {
handler.createSecureSocket("SSL");
}
catch(FtpException ex) {
throw ex;
}
catch(Exception ex) {
log.warn("AUTH.execute()", ex);
throw new FtpException("AUTH.execute()", ex);
}
}
else if(authType.equals("TLS")) {
out.send(234, "AUTH.TLS", null);
try {
handler.createSecureSocket("TLS");
}
catch(FtpException ex) {
throw ex;
}
catch(Exception ex) {
log.warn("AUTH.execute()", ex);
throw new FtpException("AUTH.execute()", ex);
}
}
else {
out.send(502, "AUTH", null);
}
}
| public void execute(RequestHandler handler,
FtpRequestImpl request,
FtpWriter out) throws IOException, FtpException {
// reset state variables
request.resetState();
// argument check
if(!request.hasArgument()) {
out.send(501, "AUTH", null);
return;
}
// check SSL configuration
IFtpConfig fconfig = handler.getConfig();
Log log = fconfig.getLogFactory().getInstance(getClass());
if(fconfig.getSocketFactory().getSSL() == null) {
out.send(431, "AUTH", null);
return;
}
// check parameter
String authType = request.getArgument().toUpperCase();
if(authType.equals("SSL")) {
out.send(234, "AUTH.SSL", null);
try {
handler.createSecureSocket("SSL");
}
catch(FtpException ex) {
throw ex;
}
catch(Exception ex) {
log.warn("AUTH.execute()", ex);
throw new FtpException("AUTH.execute()", ex);
}
}
else if(authType.equals("TLS")) {
out.send(234, "AUTH.TLS", null);
try {
handler.createSecureSocket("TLS");
}
catch(FtpException ex) {
throw ex;
}
catch(Exception ex) {
log.warn("AUTH.execute()", ex);
throw new FtpException("AUTH.execute()", ex);
}
}
else {
out.send(502, "AUTH", null);
}
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipProtocolHandler.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipProtocolHandler.java
index 47c3999fd..475321b1d 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipProtocolHandler.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipProtocolHandler.java
@@ -1,605 +1,617 @@
/*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.startup;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.sip.ListeningPoint;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import net.java.stun4j.StunAddress;
import net.java.stun4j.client.NetworkConfigurationDiscoveryProcess;
import net.java.stun4j.client.StunDiscoveryReport;
import org.apache.coyote.Adapter;
import org.apache.coyote.ProtocolHandler;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.modeler.Registry;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.SipConnector;
import org.mobicents.servlet.sip.core.ExtendedListeningPoint;
import org.mobicents.servlet.sip.core.SipApplicationDispatcher;
/**
* This is the sip protocol handler that will get called upon creation of the
* tomcat connector defined in the server.xml.<br/> To use a sip connector, one
* need to specify a new connector in server.xml with
* org.mobicents.servlet.sip.startup.SipProtocolHandler as the value for the
* protocol attribute.<br/>
*
* Some of the fields (representing the sip stack propeties) get populated
* automatically by the container.<br/>
*
* @author Jean Deruelle
*
*/
public class SipProtocolHandler implements ProtocolHandler, MBeanRegistration {
public static final String IS_SIP_CONNECTOR = "isSipConnector";
// the logger
private static final Logger logger = Logger.getLogger(SipProtocolHandler.class.getName());
// *
protected ObjectName tpOname = null;
// *
protected ObjectName rgOname = null;
/**
* The random port number generator that we use in getRandomPortNumer()
*/
private static Random portNumberGenerator = new Random();
private Adapter adapter = null;
private Map<String, Object> attributes = new HashMap<String, Object>();
private SipStack sipStack;
/*
* the extended listening point with global ip address and port for it
*/
public ExtendedListeningPoint extendedListeningPoint;
// defining sip stack properties
private Properties sipStackProperties;
private boolean started = false;
private SipConnector sipConnector;
public SipProtocolHandler() {
sipConnector = new SipConnector();
}
public SipProtocolHandler(SipConnector connector) {
sipConnector = connector;
}
/**
* {@inheritDoc}
*/
public void destroy() throws Exception {
if(logger.isDebugEnabled()) {
logger.debug("Stopping a sip protocol handler");
}
//Jboss specific unloading case
SipApplicationDispatcher sipApplicationDispatcher = (SipApplicationDispatcher)
getAttribute(SipApplicationDispatcher.class.getSimpleName());
if(sipApplicationDispatcher != null && extendedListeningPoint != null) {
if(logger.isDebugEnabled()) {
logger.debug("Removing the Sip Application Dispatcher as a sip listener for listening point " + extendedListeningPoint);
}
extendedListeningPoint.getSipProvider().removeSipListener(sipApplicationDispatcher);
sipApplicationDispatcher.getSipNetworkInterfaceManager().removeExtendedListeningPoint(extendedListeningPoint);
}
// removing listening point and sip provider
if(sipStack != null) {
if(extendedListeningPoint != null) {
if(extendedListeningPoint.getSipProvider().getListeningPoints().length == 1) {
sipStack.deleteSipProvider(extendedListeningPoint.getSipProvider());
if(logger.isDebugEnabled()) {
logger.debug("Removing the sip provider");
}
} else {
if(logger.isDebugEnabled()) {
logger.debug("Removing the following Listening Point " + extendedListeningPoint + " from the sip provider");
}
extendedListeningPoint.getSipProvider().removeListeningPoint(extendedListeningPoint.getListeningPoint());
}
if(logger.isDebugEnabled()) {
logger.debug("Removing the following Listening Point " + extendedListeningPoint);
}
sipStack.deleteListeningPoint(extendedListeningPoint.getListeningPoint());
extendedListeningPoint = null;
}
}
if (tpOname != null)
Registry.getRegistry(null, null).unregisterComponent(tpOname);
if (rgOname != null)
Registry.getRegistry(null, null).unregisterComponent(rgOname);
setStarted(false);
sipStack = null;
}
public Adapter getAdapter() {
return adapter;
}
/**
* {@inheritDoc}
*/
public Object getAttribute(String attribute) {
return attributes.get(attribute);
}
/**
* {@inheritDoc}
*/
public Iterator getAttributeNames() {
return attributes.keySet().iterator();
}
/**
* {@inheritDoc}
*/
public void init() throws Exception {
setAttribute(IS_SIP_CONNECTOR,Boolean.TRUE);
}
public void pause() throws Exception {
//This is optionnal, no implementation there
}
public void resume() throws Exception {
// This is optionnal, no implementation there
}
public void setAdapter(Adapter adapter) {
this.adapter = adapter;
}
/**
* {@inheritDoc}
*/
public void setAttribute(String arg0, Object arg1) {
attributes.put(arg0, arg1);
}
public void start() throws Exception {
if(logger.isDebugEnabled()) {
logger.debug("Starting a sip protocol handler");
}
+ Integer portFromConfig = sipConnector.getPort();
+ String set = System.getProperty("jboss.service.binding.set");
+ int setIncrememt = 0;
+ if(set != null) {
+ int setNumber = set.charAt(set.length() - 1) - '0';
+ if(setNumber>0 && setNumber<10) {
+ setIncrememt = (setNumber) * 100; // don't attempt to compute if the port set is custom outside that range
+ }
+ logger.info("Computed port increment for MSS SIP ports is " + setIncrememt + " from " + set);
+ }
+ portFromConfig += setIncrememt;
+ sipConnector.setPort(portFromConfig);
final String ipAddress = sipConnector.getIpAddress();
final int port = sipConnector.getPort();
final String signalingTransport = sipConnector.getTransport();
try {
//checking the external ip address if stun enabled
String globalIpAddress = null;
int globalPort = -1;
boolean useStun = sipConnector.isUseStun();
if (useStun) {
if(InetAddress.getByName(ipAddress).isLoopbackAddress()) {
logger.warn("The Ip address provided is the loopback address, stun won't be enabled for it");
} else {
//chooses stun port randomly
DatagramSocket randomSocket = initRandomPortSocket();
int randomPort = randomSocket.getLocalPort();
randomSocket.disconnect();
randomSocket.close();
randomSocket = null;
StunAddress localStunAddress = new StunAddress(ipAddress,
randomPort);
StunAddress serverStunAddress = new StunAddress(
sipConnector.getStunServerAddress(), sipConnector.getStunServerPort());
NetworkConfigurationDiscoveryProcess addressDiscovery = new NetworkConfigurationDiscoveryProcess(
localStunAddress, serverStunAddress);
addressDiscovery.start();
StunDiscoveryReport report = addressDiscovery
.determineAddress();
if(report.getPublicAddress() != null) {
globalIpAddress = report.getPublicAddress().getSocketAddress().getAddress().getHostAddress();
globalPort = report.getPublicAddress().getPort();
//TODO set a timer to retry the binding and provide a callback to update the global ip address and port
} else {
useStun = false;
logger.error("Stun discovery failed to find a valid public ip address, disabling stun !");
}
logger.info("Stun report = " + report);
addressDiscovery.shutDown();
}
}
ListeningPoint listeningPoint = sipStack.createListeningPoint(ipAddress,
port, signalingTransport);
if(useStun) {
// TODO: (ISSUE-CONFUSION) Check what is the confusion here, why not use the globalport. It ends up putting the local port everywhere
// listeningPoint.setSentBy(globalIpAddress + ":" + globalPort);
listeningPoint.setSentBy(globalIpAddress + ":" + port);
}
boolean createSipProvider = false;
SipProvider sipProvider = null;
if(sipStack.getSipProviders().hasNext()) {
sipProvider = (SipProvider) sipStack.getSipProviders().next();
for (ListeningPoint listeningPointTemp : sipProvider.getListeningPoints()) {
if(!(listeningPointTemp.getIPAddress().equalsIgnoreCase(listeningPoint.getIPAddress()) && listeningPointTemp.getPort() == listeningPoint.getPort())) {
createSipProvider = true;
break;
}
}
} else {
createSipProvider = true;
}
if(createSipProvider) {
sipProvider = sipStack.createSipProvider(listeningPoint);
} else {
sipProvider.addListeningPoint(listeningPoint);
}
//creating the extended listening point
extendedListeningPoint = new ExtendedListeningPoint(sipProvider, listeningPoint, sipConnector);
extendedListeningPoint.setUseStaticAddress(false);
extendedListeningPoint.setGlobalIpAddress(globalIpAddress);
extendedListeningPoint.setGlobalPort(globalPort);
//TODO add it as a listener for global ip address changes if STUN rediscover a new addess at some point
//made the sip stack and the extended listening Point available to the service implementation
setAttribute(SipStack.class.getSimpleName(), sipStack);
setAttribute(ExtendedListeningPoint.class.getSimpleName(), extendedListeningPoint);
SipApplicationDispatcher sipApplicationDispatcher = (SipApplicationDispatcher)
getAttribute(SipApplicationDispatcher.class.getSimpleName());
//Jboss specific loading case
if(sipApplicationDispatcher != null) {
// Let's add it to hostnames, so that IP load balancer appears as localhost. Otherwise requestst addressed there will
// get forwarded and especially in case of failover this might be severe error.
if(sipConnector.getStaticServerAddress() != null) {
sipApplicationDispatcher.addHostName(sipConnector.getStaticServerAddress() + ":" + sipConnector.getStaticServerPort());
if(logger.isDebugEnabled()) {
logger.debug("Adding hostname for IP load balancer " + sipConnector.getStaticServerAddress());
}
}
if(logger.isDebugEnabled()) {
logger.debug("Adding the Sip Application Dispatcher as a sip listener for connector listening on port " + port);
}
sipProvider.addSipListener(sipApplicationDispatcher);
sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint);
}
logger.info("Sip Connector started on ip address : " + ipAddress
+ ",port " + port + ", transport " + signalingTransport + ", useStun " + useStun + ", stunAddress " + sipConnector.getStunServerAddress() + ", stunPort : " + sipConnector.getStaticServerPort());
if (this.domain != null) {
// try {
// tpOname = new ObjectName
// (domain + ":" + "type=ThreadPool,name=" + getName());
// Registry.getRegistry(null, null)
// .registerComponent(endpoint, tpOname, null );
// } catch (Exception e) {
// logger.error("Can't register endpoint");
// }
rgOname=new ObjectName
(domain + ":type=GlobalRequestProcessor,name=" + getName());
Registry.getRegistry(null, null).registerComponent
( sipStack, rgOname, null );
}
setStarted(true);
} catch (Exception ex) {
logger.error(
"A problem occured while setting up SIP Connector " + ipAddress + ":" + port + "/" + signalingTransport + "-- check server.xml for tomcat. ", ex);
} finally {
if(!isStarted()) {
destroy();
}
}
}
/**
* Initializes and binds a socket that on a random port number. The method
* would try to bind on a random port and retry 5 times until a free port
* is found.
*
* @return the socket that we have initialized on a randomport number.
*/
private DatagramSocket initRandomPortSocket() {
int bindRetries = 5;
int currentlyTriedPort =
getRandomPortNumber(JainSipUtils.MIN_PORT_NUMBER, JainSipUtils.MAX_PORT_NUMBER);
DatagramSocket resultSocket = null;
//we'll first try to bind to a random port. if this fails we'll try
//again (bindRetries times in all) until we find a free local port.
for (int i = 0; i < bindRetries; i++) {
try {
resultSocket = new DatagramSocket(currentlyTriedPort);
//we succeeded - break so that we don't try to bind again
break;
}
catch (SocketException exc) {
if (exc.getMessage().indexOf("Address already in use") == -1) {
logger.fatal("An exception occurred while trying to create"
+ "a local host discovery socket.", exc);
return null;
}
//port seems to be taken. try another one.
logger.debug("Port " + currentlyTriedPort + " seems in use.");
currentlyTriedPort =
getRandomPortNumber(JainSipUtils.MIN_PORT_NUMBER, JainSipUtils.MAX_PORT_NUMBER);
logger.debug("Retrying bind on port " + currentlyTriedPort);
}
}
return resultSocket;
}
/**
* Returns a random local port number, greater than min and lower than max.
*
* @param min the minimum allowed value for the returned port number.
* @param max the maximum allowed value for the returned port number.
*
* @return a random int located between greater than min and lower than max.
*/
public static int getRandomPortNumber(int min, int max) {
return portNumberGenerator.nextInt(max - min) + min;
}
/**
* @return the signalingTransport
*/
public String getSignalingTransport() {
return sipConnector.getTransport();
}
/**
* @param signalingTransport
* the signalingTransport to set
* @throws Exception
*/
public void setSignalingTransport(String transport) throws Exception {
sipConnector.setTransport(transport);
if(isStarted()) {
destroy();
start();
}
}
/**
* @return the port
*/
public int getPort() {
return sipConnector.getPort();
}
/**
* @param port
* the port to set
* @throws Exception
*/
public void setPort(int port) throws Exception {
sipConnector.setPort(port);
if(isStarted()) {
destroy();
start();
}
}
public void setIpAddress(String ipAddress) throws Exception {
sipConnector.setIpAddress(ipAddress);
if(isStarted()) {
destroy();
start();
}
}
public String getIpAddress() {
return sipConnector.getIpAddress();
}
/**
* @return the stunServerAddress
*/
public String getStunServerAddress() {
return sipConnector.getStunServerAddress();
}
/**
* @param stunServerAddress the stunServerAddress to set
*/
public void setStunServerAddress(String stunServerAddress) {
sipConnector.setStunServerAddress(stunServerAddress);
}
/**
* @return the stunServerPort
*/
public int getStunServerPort() {
return sipConnector.getStunServerPort();
}
/**
* @param stunServerPort the stunServerPort to set
*/
public void setStunServerPort(int stunServerPort) {
sipConnector.setStunServerPort(stunServerPort);
}
/**
* @return the useStun
*/
public boolean isUseStun() {
return sipConnector.isUseStun();
}
/**
* @param useStun the useStun to set
*/
public void setUseStun(boolean useStun) {
sipConnector.setUseStun(useStun);
}
public String getStaticServerAddress() {
return sipConnector.getStaticServerAddress();
}
public void setStaticServerAddress(String staticServerAddress) {
sipConnector.setStaticServerAddress(staticServerAddress);
}
public int getStaticServerPort() {
return sipConnector.getStaticServerPort();
}
public void setStaticServerPort(int staticServerPort) {
sipConnector.setStaticServerPort(staticServerPort);
}
public boolean isUseStaticAddress() {
return sipConnector.isUseStaticAddress();
}
public void setUseStaticAddress(boolean useStaticAddress) {
sipConnector.setUseStaticAddress(useStaticAddress);
}
public InetAddress getAddress() {
try {
return InetAddress.getByName(sipConnector.getIpAddress());
} catch (UnknownHostException e) {
logger.error("unexpected exception while getting the ipaddress of the sip protocol handler", e);
return null;
}
}
public void setAddress(InetAddress ia) {
sipConnector.setIpAddress(ia.getHostAddress());
}
public String getTransport() {
return sipConnector.getTransport();
}
/**
* @return the sipStackProperties
*/
public Properties getSipStackProperties() {
return sipStackProperties;
}
/**
* @param sipStackProperties the sipStackProperties to set
*/
public void setSipStackProperties(Properties sipStackProperties) {
this.sipStackProperties = sipStackProperties;
}
/**
* @param sipConnector the sipConnector to set
*/
public void setSipConnector(SipConnector sipConnector) {
this.sipConnector = sipConnector;
}
/**
* @return the sipConnector
*/
public SipConnector getSipConnector() {
return sipConnector;
}
public String getName() {
String encodedAddr = "";
if (getAddress() != null) {
encodedAddr = "" + getAddress();
if (encodedAddr.startsWith("/"))
encodedAddr = encodedAddr.substring(1);
encodedAddr = URLEncoder.encode(encodedAddr) + "-";
}
return ("sip-" + getTransport() + "-" + encodedAddr + getPort());
}
// -------------------- JMX related methods --------------------
// *
protected String domain;
protected ObjectName oname;
protected MBeanServer mserver;
public ObjectName getObjectName() {
return oname;
}
public String getDomain() {
return domain;
}
public ObjectName preRegister(MBeanServer server,
ObjectName name) throws Exception {
oname=name;
mserver=server;
domain=name.getDomain();
return name;
}
public void postRegister(Boolean registrationDone) {
}
public void preDeregister() throws Exception {
}
public void postDeregister() {
}
/**
* @param started the started to set
*/
public void setStarted(boolean started) {
this.started = started;
}
/**
* @return the started
*/
public boolean isStarted() {
return started;
}
public void setSipStack(SipStack sipStack) {
this.sipStack = sipStack;
}
}
| true | true | public void start() throws Exception {
if(logger.isDebugEnabled()) {
logger.debug("Starting a sip protocol handler");
}
final String ipAddress = sipConnector.getIpAddress();
final int port = sipConnector.getPort();
final String signalingTransport = sipConnector.getTransport();
try {
//checking the external ip address if stun enabled
String globalIpAddress = null;
int globalPort = -1;
boolean useStun = sipConnector.isUseStun();
if (useStun) {
if(InetAddress.getByName(ipAddress).isLoopbackAddress()) {
logger.warn("The Ip address provided is the loopback address, stun won't be enabled for it");
} else {
//chooses stun port randomly
DatagramSocket randomSocket = initRandomPortSocket();
int randomPort = randomSocket.getLocalPort();
randomSocket.disconnect();
randomSocket.close();
randomSocket = null;
StunAddress localStunAddress = new StunAddress(ipAddress,
randomPort);
StunAddress serverStunAddress = new StunAddress(
sipConnector.getStunServerAddress(), sipConnector.getStunServerPort());
NetworkConfigurationDiscoveryProcess addressDiscovery = new NetworkConfigurationDiscoveryProcess(
localStunAddress, serverStunAddress);
addressDiscovery.start();
StunDiscoveryReport report = addressDiscovery
.determineAddress();
if(report.getPublicAddress() != null) {
globalIpAddress = report.getPublicAddress().getSocketAddress().getAddress().getHostAddress();
globalPort = report.getPublicAddress().getPort();
//TODO set a timer to retry the binding and provide a callback to update the global ip address and port
} else {
useStun = false;
logger.error("Stun discovery failed to find a valid public ip address, disabling stun !");
}
logger.info("Stun report = " + report);
addressDiscovery.shutDown();
}
}
ListeningPoint listeningPoint = sipStack.createListeningPoint(ipAddress,
port, signalingTransport);
if(useStun) {
// TODO: (ISSUE-CONFUSION) Check what is the confusion here, why not use the globalport. It ends up putting the local port everywhere
// listeningPoint.setSentBy(globalIpAddress + ":" + globalPort);
listeningPoint.setSentBy(globalIpAddress + ":" + port);
}
boolean createSipProvider = false;
SipProvider sipProvider = null;
if(sipStack.getSipProviders().hasNext()) {
sipProvider = (SipProvider) sipStack.getSipProviders().next();
for (ListeningPoint listeningPointTemp : sipProvider.getListeningPoints()) {
if(!(listeningPointTemp.getIPAddress().equalsIgnoreCase(listeningPoint.getIPAddress()) && listeningPointTemp.getPort() == listeningPoint.getPort())) {
createSipProvider = true;
break;
}
}
} else {
createSipProvider = true;
}
if(createSipProvider) {
sipProvider = sipStack.createSipProvider(listeningPoint);
} else {
sipProvider.addListeningPoint(listeningPoint);
}
//creating the extended listening point
extendedListeningPoint = new ExtendedListeningPoint(sipProvider, listeningPoint, sipConnector);
extendedListeningPoint.setUseStaticAddress(false);
extendedListeningPoint.setGlobalIpAddress(globalIpAddress);
extendedListeningPoint.setGlobalPort(globalPort);
//TODO add it as a listener for global ip address changes if STUN rediscover a new addess at some point
//made the sip stack and the extended listening Point available to the service implementation
setAttribute(SipStack.class.getSimpleName(), sipStack);
setAttribute(ExtendedListeningPoint.class.getSimpleName(), extendedListeningPoint);
SipApplicationDispatcher sipApplicationDispatcher = (SipApplicationDispatcher)
getAttribute(SipApplicationDispatcher.class.getSimpleName());
//Jboss specific loading case
if(sipApplicationDispatcher != null) {
// Let's add it to hostnames, so that IP load balancer appears as localhost. Otherwise requestst addressed there will
// get forwarded and especially in case of failover this might be severe error.
if(sipConnector.getStaticServerAddress() != null) {
sipApplicationDispatcher.addHostName(sipConnector.getStaticServerAddress() + ":" + sipConnector.getStaticServerPort());
if(logger.isDebugEnabled()) {
logger.debug("Adding hostname for IP load balancer " + sipConnector.getStaticServerAddress());
}
}
if(logger.isDebugEnabled()) {
logger.debug("Adding the Sip Application Dispatcher as a sip listener for connector listening on port " + port);
}
sipProvider.addSipListener(sipApplicationDispatcher);
sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint);
}
logger.info("Sip Connector started on ip address : " + ipAddress
+ ",port " + port + ", transport " + signalingTransport + ", useStun " + useStun + ", stunAddress " + sipConnector.getStunServerAddress() + ", stunPort : " + sipConnector.getStaticServerPort());
if (this.domain != null) {
// try {
// tpOname = new ObjectName
// (domain + ":" + "type=ThreadPool,name=" + getName());
// Registry.getRegistry(null, null)
// .registerComponent(endpoint, tpOname, null );
// } catch (Exception e) {
// logger.error("Can't register endpoint");
// }
rgOname=new ObjectName
(domain + ":type=GlobalRequestProcessor,name=" + getName());
Registry.getRegistry(null, null).registerComponent
( sipStack, rgOname, null );
}
setStarted(true);
} catch (Exception ex) {
logger.error(
"A problem occured while setting up SIP Connector " + ipAddress + ":" + port + "/" + signalingTransport + "-- check server.xml for tomcat. ", ex);
} finally {
if(!isStarted()) {
destroy();
}
}
}
| public void start() throws Exception {
if(logger.isDebugEnabled()) {
logger.debug("Starting a sip protocol handler");
}
Integer portFromConfig = sipConnector.getPort();
String set = System.getProperty("jboss.service.binding.set");
int setIncrememt = 0;
if(set != null) {
int setNumber = set.charAt(set.length() - 1) - '0';
if(setNumber>0 && setNumber<10) {
setIncrememt = (setNumber) * 100; // don't attempt to compute if the port set is custom outside that range
}
logger.info("Computed port increment for MSS SIP ports is " + setIncrememt + " from " + set);
}
portFromConfig += setIncrememt;
sipConnector.setPort(portFromConfig);
final String ipAddress = sipConnector.getIpAddress();
final int port = sipConnector.getPort();
final String signalingTransport = sipConnector.getTransport();
try {
//checking the external ip address if stun enabled
String globalIpAddress = null;
int globalPort = -1;
boolean useStun = sipConnector.isUseStun();
if (useStun) {
if(InetAddress.getByName(ipAddress).isLoopbackAddress()) {
logger.warn("The Ip address provided is the loopback address, stun won't be enabled for it");
} else {
//chooses stun port randomly
DatagramSocket randomSocket = initRandomPortSocket();
int randomPort = randomSocket.getLocalPort();
randomSocket.disconnect();
randomSocket.close();
randomSocket = null;
StunAddress localStunAddress = new StunAddress(ipAddress,
randomPort);
StunAddress serverStunAddress = new StunAddress(
sipConnector.getStunServerAddress(), sipConnector.getStunServerPort());
NetworkConfigurationDiscoveryProcess addressDiscovery = new NetworkConfigurationDiscoveryProcess(
localStunAddress, serverStunAddress);
addressDiscovery.start();
StunDiscoveryReport report = addressDiscovery
.determineAddress();
if(report.getPublicAddress() != null) {
globalIpAddress = report.getPublicAddress().getSocketAddress().getAddress().getHostAddress();
globalPort = report.getPublicAddress().getPort();
//TODO set a timer to retry the binding and provide a callback to update the global ip address and port
} else {
useStun = false;
logger.error("Stun discovery failed to find a valid public ip address, disabling stun !");
}
logger.info("Stun report = " + report);
addressDiscovery.shutDown();
}
}
ListeningPoint listeningPoint = sipStack.createListeningPoint(ipAddress,
port, signalingTransport);
if(useStun) {
// TODO: (ISSUE-CONFUSION) Check what is the confusion here, why not use the globalport. It ends up putting the local port everywhere
// listeningPoint.setSentBy(globalIpAddress + ":" + globalPort);
listeningPoint.setSentBy(globalIpAddress + ":" + port);
}
boolean createSipProvider = false;
SipProvider sipProvider = null;
if(sipStack.getSipProviders().hasNext()) {
sipProvider = (SipProvider) sipStack.getSipProviders().next();
for (ListeningPoint listeningPointTemp : sipProvider.getListeningPoints()) {
if(!(listeningPointTemp.getIPAddress().equalsIgnoreCase(listeningPoint.getIPAddress()) && listeningPointTemp.getPort() == listeningPoint.getPort())) {
createSipProvider = true;
break;
}
}
} else {
createSipProvider = true;
}
if(createSipProvider) {
sipProvider = sipStack.createSipProvider(listeningPoint);
} else {
sipProvider.addListeningPoint(listeningPoint);
}
//creating the extended listening point
extendedListeningPoint = new ExtendedListeningPoint(sipProvider, listeningPoint, sipConnector);
extendedListeningPoint.setUseStaticAddress(false);
extendedListeningPoint.setGlobalIpAddress(globalIpAddress);
extendedListeningPoint.setGlobalPort(globalPort);
//TODO add it as a listener for global ip address changes if STUN rediscover a new addess at some point
//made the sip stack and the extended listening Point available to the service implementation
setAttribute(SipStack.class.getSimpleName(), sipStack);
setAttribute(ExtendedListeningPoint.class.getSimpleName(), extendedListeningPoint);
SipApplicationDispatcher sipApplicationDispatcher = (SipApplicationDispatcher)
getAttribute(SipApplicationDispatcher.class.getSimpleName());
//Jboss specific loading case
if(sipApplicationDispatcher != null) {
// Let's add it to hostnames, so that IP load balancer appears as localhost. Otherwise requestst addressed there will
// get forwarded and especially in case of failover this might be severe error.
if(sipConnector.getStaticServerAddress() != null) {
sipApplicationDispatcher.addHostName(sipConnector.getStaticServerAddress() + ":" + sipConnector.getStaticServerPort());
if(logger.isDebugEnabled()) {
logger.debug("Adding hostname for IP load balancer " + sipConnector.getStaticServerAddress());
}
}
if(logger.isDebugEnabled()) {
logger.debug("Adding the Sip Application Dispatcher as a sip listener for connector listening on port " + port);
}
sipProvider.addSipListener(sipApplicationDispatcher);
sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint);
}
logger.info("Sip Connector started on ip address : " + ipAddress
+ ",port " + port + ", transport " + signalingTransport + ", useStun " + useStun + ", stunAddress " + sipConnector.getStunServerAddress() + ", stunPort : " + sipConnector.getStaticServerPort());
if (this.domain != null) {
// try {
// tpOname = new ObjectName
// (domain + ":" + "type=ThreadPool,name=" + getName());
// Registry.getRegistry(null, null)
// .registerComponent(endpoint, tpOname, null );
// } catch (Exception e) {
// logger.error("Can't register endpoint");
// }
rgOname=new ObjectName
(domain + ":type=GlobalRequestProcessor,name=" + getName());
Registry.getRegistry(null, null).registerComponent
( sipStack, rgOname, null );
}
setStarted(true);
} catch (Exception ex) {
logger.error(
"A problem occured while setting up SIP Connector " + ipAddress + ":" + port + "/" + signalingTransport + "-- check server.xml for tomcat. ", ex);
} finally {
if(!isStarted()) {
destroy();
}
}
}
|
diff --git a/src/org/mozilla/javascript/ScriptableObject.java b/src/org/mozilla/javascript/ScriptableObject.java
index da9b29fd..094fbd60 100644
--- a/src/org/mozilla/javascript/ScriptableObject.java
+++ b/src/org/mozilla/javascript/ScriptableObject.java
@@ -1,2414 +1,2414 @@
/* -*- 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
* Steve Weiss
*
* 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 ***** */
// API class
package org.mozilla.javascript;
import java.lang.reflect.*;
import java.util.Hashtable;
import java.io.*;
import org.mozilla.javascript.debug.DebuggableObject;
/**
* This is the default implementation of the Scriptable interface. This
* class provides convenient default behavior that makes it easier to
* define host objects.
* <p>
* Various properties and methods of JavaScript objects can be conveniently
* defined using methods of ScriptableObject.
* <p>
* Classes extending ScriptableObject must define the getClassName method.
*
* @see org.mozilla.javascript.Scriptable
* @author Norris Boyd
*/
public abstract class ScriptableObject implements Scriptable, Serializable,
DebuggableObject,
ConstProperties
{
/**
* The empty property attribute.
*
* Used by getAttributes() and setAttributes().
*
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int EMPTY = 0x00;
/**
* Property attribute indicating assignment to this property is ignored.
*
* @see org.mozilla.javascript.ScriptableObject
* #put(String, Scriptable, Object)
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int READONLY = 0x01;
/**
* Property attribute indicating property is not enumerated.
*
* Only enumerated properties will be returned by getIds().
*
* @see org.mozilla.javascript.ScriptableObject#getIds()
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int DONTENUM = 0x02;
/**
* Property attribute indicating property cannot be deleted.
*
* @see org.mozilla.javascript.ScriptableObject#delete(String)
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int PERMANENT = 0x04;
/**
* Property attribute indicating that this is a const property that has not
* been assigned yet. The first 'const' assignment to the property will
* clear this bit.
*/
public static final int UNINITIALIZED_CONST = 0x08;
public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST;
/**
* The prototype of this object.
*/
private Scriptable prototypeObject;
/**
* The parent scope of this object.
*/
private Scriptable parentScopeObject;
private static final Slot REMOVED = new Slot(null, 0, READONLY);
static {
REMOVED.wasDeleted = 1;
}
private transient Slot[] slots;
// If count >= 0, it gives number of keys or if count < 0,
// it indicates sealed object where ~count gives number of keys
private int count;
// cache; may be removed for smaller memory footprint
private transient Slot lastAccess = REMOVED;
// associated values are not serialized
private transient volatile Hashtable associatedValues;
private static final int SLOT_QUERY = 1;
private static final int SLOT_MODIFY = 2;
private static final int SLOT_REMOVE = 3;
private static final int SLOT_MODIFY_GETTER_SETTER = 4;
private static final int SLOT_MODIFY_CONST = 5;
private static class Slot implements Serializable
{
static final long serialVersionUID = -3539051633409902634L;
String name; // This can change due to caching
int indexOrHash;
private volatile short attributes;
transient volatile byte wasDeleted;
volatile Object value;
Slot(String name, int indexOrHash, int attributes)
{
this.name = name;
this.indexOrHash = indexOrHash;
this.attributes = (short)attributes;
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (name != null) {
indexOrHash = name.hashCode();
}
}
final int getAttributes()
{
return attributes;
}
final synchronized void setAttributes(int value)
{
checkValidAttributes(value);
attributes = (short)value;
}
final void checkNotReadonly()
{
if ((attributes & READONLY) != 0) {
String str = (name != null ? name
: Integer.toString(indexOrHash));
throw Context.reportRuntimeError1("msg.modify.readonly", str);
}
}
}
private static final class GetterSlot extends Slot
{
static final long serialVersionUID = -4900574849788797588L;
Object getter;
Object setter;
GetterSlot(String name, int indexOrHash, int attributes)
{
super(name, indexOrHash, attributes);
}
}
static void checkValidAttributes(int attributes)
{
final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST;
if ((attributes & ~mask) != 0) {
throw new IllegalArgumentException(String.valueOf(attributes));
}
}
public ScriptableObject()
{
}
public ScriptableObject(Scriptable scope, Scriptable prototype)
{
if (scope == null)
throw new IllegalArgumentException();
parentScopeObject = scope;
prototypeObject = prototype;
}
/**
* Return the name of the class.
*
* This is typically the same name as the constructor.
* Classes extending ScriptableObject must implement this abstract
* method.
*/
public abstract String getClassName();
/**
* Returns true if the named property is defined.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
public boolean has(String name, Scriptable start)
{
return null != getSlot(name, 0, SLOT_QUERY);
}
/**
* Returns true if the property index is defined.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
public boolean has(int index, Scriptable start)
{
return null != getSlot(null, index, SLOT_QUERY);
}
/**
* Returns the value of the named property or NOT_FOUND.
*
* If the property was created using defineProperty, the
* appropriate getter method is called.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
public Object get(String name, Scriptable start)
{
return getImpl(name, 0, start);
}
/**
* Returns the value of the indexed property or NOT_FOUND.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
public Object get(int index, Scriptable start)
{
return getImpl(null, index, start);
}
/**
* Sets the value of the named property, creating it if need be.
*
* If the property was created using defineProperty, the
* appropriate setter method is called. <p>
*
* If the property's attributes include READONLY, no action is
* taken.
* This method will actually set the property in the start
* object.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void put(String name, Scriptable start, Object value)
{
if (putImpl(name, 0, start, value, EMPTY))
return;
if (start == this) throw Kit.codeBug();
start.put(name, start, value);
}
/**
* Sets the value of the indexed property, creating it if need be.
*
* @param index the numeric index for the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void put(int index, Scriptable start, Object value)
{
if (putImpl(null, index, start, value, EMPTY))
return;
if (start == this) throw Kit.codeBug();
start.put(index, start, value);
}
/**
* Removes a named property from the object.
*
* If the property is not found, or it has the PERMANENT attribute,
* no action is taken.
*
* @param name the name of the property
*/
public void delete(String name)
{
checkNotSealed(name, 0);
accessSlot(name, 0, SLOT_REMOVE);
}
/**
* Removes the indexed property from the object.
*
* If the property is not found, or it has the PERMANENT attribute,
* no action is taken.
*
* @param index the numeric index for the property
*/
public void delete(int index)
{
checkNotSealed(null, index);
accessSlot(null, index, SLOT_REMOVE);
}
/**
* Sets the value of the named const property, creating it if need be.
*
* If the property was created using defineProperty, the
* appropriate setter method is called. <p>
*
* If the property's attributes include READONLY, no action is
* taken.
* This method will actually set the property in the start
* object.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void putConst(String name, Scriptable start, Object value)
{
if (putImpl(name, 0, start, value, READONLY))
return;
if (start == this) throw Kit.codeBug();
if (start instanceof ConstProperties)
((ConstProperties)start).putConst(name, start, value);
else
start.put(name, start, value);
}
public void defineConst(String name, Scriptable start)
{
if (putImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST))
return;
if (start == this) throw Kit.codeBug();
if (start instanceof ConstProperties)
((ConstProperties)start).defineConst(name, start);
}
/**
* Returns true if the named property is defined as a const on this object.
* @param name
* @return true if the named property is defined as a const, false
* otherwise.
*/
public boolean isConst(String name)
{
Slot slot = getSlot(name, 0, SLOT_QUERY);
if (slot == null) {
return false;
}
return (slot.getAttributes() & (PERMANENT|READONLY)) ==
(PERMANENT|READONLY);
}
/**
* @deprecated Use {@link #getAttributes(String name)}. The engine always
* ignored the start argument.
*/
public final int getAttributes(String name, Scriptable start)
{
return getAttributes(name);
}
/**
* @deprecated Use {@link #getAttributes(int index)}. The engine always
* ignored the start argument.
*/
public final int getAttributes(int index, Scriptable start)
{
return getAttributes(index);
}
/**
* @deprecated Use {@link #setAttributes(String name, int attributes)}.
* The engine always ignored the start argument.
*/
public final void setAttributes(String name, Scriptable start,
int attributes)
{
setAttributes(name, attributes);
}
/**
* @deprecated Use {@link #setAttributes(int index, int attributes)}.
* The engine always ignored the start argument.
*/
public void setAttributes(int index, Scriptable start,
int attributes)
{
setAttributes(index, attributes);
}
/**
* Get the attributes of a named property.
*
* The property is specified by <code>name</code>
* as defined for <code>has</code>.<p>
*
* @param name the identifier for the property
* @return the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public int getAttributes(String name)
{
return findAttributeSlot(name, 0, SLOT_QUERY).getAttributes();
}
/**
* Get the attributes of an indexed property.
*
* @param index the numeric index for the property
* @exception EvaluatorException if the named property is not found
* is not found
* @return the bitset of attributes
* @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public int getAttributes(int index)
{
return findAttributeSlot(null, index, SLOT_QUERY).getAttributes();
}
/**
* Set the attributes of a named property.
*
* The property is specified by <code>name</code>
* as defined for <code>has</code>.<p>
*
* The possible attributes are READONLY, DONTENUM,
* and PERMANENT. Combinations of attributes
* are expressed by the bitwise OR of attributes.
* EMPTY is the state of no attributes set. Any unused
* bits are reserved for future use.
*
* @param name the name of the property
* @param attributes the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public void setAttributes(String name, int attributes)
{
checkNotSealed(name, 0);
findAttributeSlot(name, 0, SLOT_MODIFY).setAttributes(attributes);
}
/**
* Set the attributes of an indexed property.
*
* @param index the numeric index for the property
* @param attributes the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public void setAttributes(int index, int attributes)
{
checkNotSealed(null, index);
findAttributeSlot(null, index, SLOT_MODIFY).setAttributes(attributes);
}
/**
* XXX: write docs.
*/
public void setGetterOrSetter(String name, int index,
Callable getterOrSeter, boolean isSetter)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
checkNotSealed(name, index);
GetterSlot gslot = (GetterSlot)getSlot(name, index,
SLOT_MODIFY_GETTER_SETTER);
gslot.checkNotReadonly();
if (isSetter) {
gslot.setter = getterOrSeter;
} else {
gslot.getter = getterOrSeter;
}
gslot.value = Undefined.instance;
}
/**
* Get the getter or setter for a given property. Used by __lookupGetter__
* and __lookupSetter__.
*
* @param name Name of the object. If nonnull, index must be 0.
* @param index Index of the object. If nonzero, name must be null.
* @param isSetter If true, return the setter, otherwise return the getter.
* @exception IllegalArgumentException if both name and index are nonnull
* and nonzero respectively.
* @return Null if the property does not exist. Otherwise returns either
* the getter or the setter for the property, depending on
* the value of isSetter (may be undefined if unset).
*/
public Object getGetterOrSetter(String name, int index, boolean isSetter)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
Slot slot = getSlot(name, index, SLOT_QUERY);
if (slot == null)
return null;
if (slot instanceof GetterSlot) {
GetterSlot gslot = (GetterSlot)slot;
if (isSetter) {
return gslot.setter;
} else {
return gslot.getter;
}
} else
return Undefined.instance;
}
void addLazilyInitializedValue(String name, int index,
LazilyLoadedCtor init, int attributes)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
checkNotSealed(name, index);
GetterSlot gslot = (GetterSlot)getSlot(name, index,
SLOT_MODIFY_GETTER_SETTER);
gslot.setAttributes(attributes);
gslot.getter = null;
gslot.setter = null;
gslot.value = init;
}
/**
* Returns the prototype of the object.
*/
public Scriptable getPrototype()
{
return prototypeObject;
}
/**
* Sets the prototype of the object.
*/
public void setPrototype(Scriptable m)
{
prototypeObject = m;
}
/**
* Returns the parent (enclosing) scope of the object.
*/
public Scriptable getParentScope()
{
return parentScopeObject;
}
/**
* Sets the parent (enclosing) scope of the object.
*/
public void setParentScope(Scriptable m)
{
parentScopeObject = m;
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>Any properties with the attribute DONTENUM are not listed. <p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
public Object[] getIds() {
return getIds(false);
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>All properties, even those with attribute DONTENUM, are listed. <p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
public Object[] getAllIds() {
return getIds(true);
}
/**
* Implements the [[DefaultValue]] internal method.
*
* <p>Note that the toPrimitive conversion is a no-op for
* every type other than Object, for which [[DefaultValue]]
* is called. See ECMA 9.1.<p>
*
* A <code>hint</code> of null means "no hint".
*
* @param typeHint the type hint
* @return the default value for the object
*
* See ECMA 8.6.2.6.
*/
public Object getDefaultValue(Class typeHint)
{
return getDefaultValue(this, typeHint);
}
public static Object getDefaultValue(Scriptable object, Class typeHint)
{
Context cx = null;
for (int i=0; i < 2; i++) {
boolean tryToString;
if (typeHint == ScriptRuntime.StringClass) {
tryToString = (i == 0);
} else {
tryToString = (i == 1);
}
String methodName;
Object[] args;
if (tryToString) {
methodName = "toString";
args = ScriptRuntime.emptyArgs;
} else {
methodName = "valueOf";
args = new Object[1];
String hint;
if (typeHint == null) {
hint = "undefined";
} else if (typeHint == ScriptRuntime.StringClass) {
hint = "string";
} else if (typeHint == ScriptRuntime.ScriptableClass) {
hint = "object";
} else if (typeHint == ScriptRuntime.FunctionClass) {
hint = "function";
} else if (typeHint == ScriptRuntime.BooleanClass
|| typeHint == Boolean.TYPE)
{
hint = "boolean";
} else if (typeHint == ScriptRuntime.NumberClass ||
typeHint == ScriptRuntime.ByteClass ||
typeHint == Byte.TYPE ||
typeHint == ScriptRuntime.ShortClass ||
typeHint == Short.TYPE ||
typeHint == ScriptRuntime.IntegerClass ||
typeHint == Integer.TYPE ||
typeHint == ScriptRuntime.FloatClass ||
typeHint == Float.TYPE ||
typeHint == ScriptRuntime.DoubleClass ||
typeHint == Double.TYPE)
{
hint = "number";
} else {
throw Context.reportRuntimeError1(
"msg.invalid.type", typeHint.toString());
}
args[0] = hint;
}
Object v = getProperty(object, methodName);
if (!(v instanceof Function))
continue;
Function fun = (Function) v;
if (cx == null)
cx = Context.getContext();
v = fun.call(cx, fun.getParentScope(), object, args);
if (v != null) {
if (!(v instanceof Scriptable)) {
return v;
}
if (typeHint == ScriptRuntime.ScriptableClass
|| typeHint == ScriptRuntime.FunctionClass)
{
return v;
}
if (tryToString && v instanceof Wrapper) {
// Let a wrapped java.lang.String pass for a primitive
// string.
Object u = ((Wrapper)v).unwrap();
if (u instanceof String)
return u;
}
}
}
// fall through to error
String arg = (typeHint == null) ? "undefined" : typeHint.getName();
throw ScriptRuntime.typeError1("msg.default.value", arg);
}
/**
* Implements the instanceof operator.
*
* <p>This operator has been proposed to ECMA.
*
* @param instance The value that appeared on the LHS of the instanceof
* operator
* @return true if "this" appears in value's prototype chain
*
*/
public boolean hasInstance(Scriptable instance) {
// Default for JS objects (other than Function) is to do prototype
// chasing. This will be overridden in NativeFunction and non-JS
// objects.
return ScriptRuntime.jsDelegatesTo(instance, this);
}
/**
* Custom <tt>==</tt> operator.
* Must return {@link Scriptable#NOT_FOUND} if this object does not
* have custom equality operator for the given value,
* <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>,
* <tt>Boolean.FALSE</tt> if this object is not equivalent to
* <tt>value</tt>.
* <p>
* The default implementation returns Boolean.TRUE
* if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise.
* It indicates that by default custom equality is available only if
* <tt>value</tt> is <tt>this</tt> in which case true is returned.
*/
protected Object equivalentValues(Object value)
{
return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND;
}
/**
* Defines JavaScript objects from a Java class that implements Scriptable.
*
* If the given class has a method
* <pre>
* static void init(Context cx, Scriptable scope, boolean sealed);</pre>
*
* or its compatibility form
* <pre>
* static void init(Scriptable scope);</pre>
*
* then it is invoked and no further initialization is done.<p>
*
* However, if no such a method is found, then the class's constructors and
* methods are used to initialize a class in the following manner.<p>
*
* First, the zero-parameter constructor of the class is called to
* create the prototype. If no such constructor exists,
* a {@link EvaluatorException} is thrown. <p>
*
* Next, all methods are scanned for special prefixes that indicate that they
* have special meaning for defining JavaScript objects.
* These special prefixes are
* <ul>
* <li><code>jsFunction_</code> for a JavaScript function
* <li><code>jsStaticFunction_</code> for a JavaScript function that
* is a property of the constructor
* <li><code>jsGet_</code> for a getter of a JavaScript property
* <li><code>jsSet_</code> for a setter of a JavaScript property
* <li><code>jsConstructor</code> for a JavaScript function that
* is the constructor
* </ul><p>
*
* If the method's name begins with "jsFunction_", a JavaScript function
* is created with a name formed from the rest of the Java method name
* following "jsFunction_". So a Java method named "jsFunction_foo" will
* define a JavaScript method "foo". Calling this JavaScript function
* will cause the Java method to be called. The parameters of the method
* must be of number and types as defined by the FunctionObject class.
* The JavaScript function is then added as a property
* of the prototype. <p>
*
* If the method's name begins with "jsStaticFunction_", it is handled
* similarly except that the resulting JavaScript function is added as a
* property of the constructor object. The Java method must be static.
*
* If the method's name begins with "jsGet_" or "jsSet_", the method is
* considered to define a property. Accesses to the defined property
* will result in calls to these getter and setter methods. If no
* setter is defined, the property is defined as READONLY.<p>
*
* If the method's name is "jsConstructor", the method is
* considered to define the body of the constructor. Only one
* method of this name may be defined.
* If no method is found that can serve as constructor, a Java
* constructor will be selected to serve as the JavaScript
* constructor in the following manner. If the class has only one
* Java constructor, that constructor is used to define
* the JavaScript constructor. If the the class has two constructors,
* one must be the zero-argument constructor (otherwise an
* {@link EvaluatorException} would have already been thrown
* when the prototype was to be created). In this case
* the Java constructor with one or more parameters will be used
* to define the JavaScript constructor. If the class has three
* or more constructors, an {@link EvaluatorException}
* will be thrown.<p>
*
* Finally, if there is a method
* <pre>
* static void finishInit(Scriptable scope, FunctionObject constructor,
* Scriptable prototype)</pre>
*
* it will be called to finish any initialization. The <code>scope</code>
* argument will be passed, along with the newly created constructor and
* the newly created prototype.<p>
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties.
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @see org.mozilla.javascript.Function
* @see org.mozilla.javascript.FunctionObject
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject
* #defineProperty(String, Class, int)
*/
public static void defineClass(Scriptable scope, Class clazz)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
defineClass(scope, clazz, false, false);
}
/**
* Defines JavaScript objects from a Java class, optionally
* allowing sealing.
*
* Similar to <code>defineClass(Scriptable scope, Class clazz)</code>
* except that sealing is allowed. An object that is sealed cannot have
* properties added or removed. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties. The class must implement Scriptable.
* @param sealed Whether or not to create sealed standard objects that
* cannot be modified.
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @since 1.4R3
*/
public static void defineClass(Scriptable scope, Class clazz,
boolean sealed)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
defineClass(scope, clazz, sealed, false);
}
/**
* Defines JavaScript objects from a Java class, optionally
* allowing sealing and mapping of Java inheritance to JavaScript
* prototype-based inheritance.
*
* Similar to <code>defineClass(Scriptable scope, Class clazz)</code>
* except that sealing and inheritance mapping are allowed. An object
* that is sealed cannot have properties added or removed. Note that
* sealing is not allowed in the current ECMA/ISO language specification,
* but is likely for the next version.
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties. The class must implement Scriptable.
* @param sealed Whether or not to create sealed standard objects that
* cannot be modified.
* @param mapInheritance Whether or not to map Java inheritance to
* JavaScript prototype-based inheritance.
* @return the class name for the prototype of the specified class
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @since 1.6R2
*/
public static String defineClass(Scriptable scope, Class clazz,
boolean sealed, boolean mapInheritance)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
BaseFunction ctor = buildClassCtor(scope, clazz, sealed,
mapInheritance);
if (ctor == null)
return null;
String name = ctor.getClassPrototype().getClassName();
defineProperty(scope, name, ctor, ScriptableObject.DONTENUM);
return name;
}
static BaseFunction buildClassCtor(Scriptable scope, Class clazz,
boolean sealed,
boolean mapInheritance)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
Method[] methods = FunctionObject.getMethodList(clazz);
for (int i=0; i < methods.length; i++) {
Method method = methods[i];
if (!method.getName().equals("init"))
continue;
Class[] parmTypes = method.getParameterTypes();
if (parmTypes.length == 3 &&
parmTypes[0] == ScriptRuntime.ContextClass &&
parmTypes[1] == ScriptRuntime.ScriptableClass &&
parmTypes[2] == Boolean.TYPE &&
Modifier.isStatic(method.getModifiers()))
{
Object args[] = { Context.getContext(), scope,
sealed ? Boolean.TRUE : Boolean.FALSE };
method.invoke(null, args);
return null;
}
if (parmTypes.length == 1 &&
parmTypes[0] == ScriptRuntime.ScriptableClass &&
Modifier.isStatic(method.getModifiers()))
{
Object args[] = { scope };
method.invoke(null, args);
return null;
}
}
// If we got here, there isn't an "init" method with the right
// parameter types.
Constructor[] ctors = clazz.getConstructors();
Constructor protoCtor = null;
for (int i=0; i < ctors.length; i++) {
if (ctors[i].getParameterTypes().length == 0) {
protoCtor = ctors[i];
break;
}
}
if (protoCtor == null) {
throw Context.reportRuntimeError1(
"msg.zero.arg.ctor", clazz.getName());
}
Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs);
String className = proto.getClassName();
// Set the prototype's prototype, trying to map Java inheritance to JS
// prototype-based inheritance if requested to do so.
Scriptable superProto = null;
if (mapInheritance) {
Class superClass = clazz.getSuperclass();
if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass)
&& !Modifier.isAbstract(superClass.getModifiers())) {
String name = ScriptableObject.defineClass(scope, superClass, sealed, mapInheritance);
if (name != null) {
superProto = ScriptableObject.getClassPrototype(scope, name);
}
}
}
if (superProto == null) {
superProto = ScriptableObject.getObjectPrototype(scope);
}
proto.setPrototype(superProto);
// Find out whether there are any methods that begin with
// "js". If so, then only methods that begin with special
// prefixes will be defined as JavaScript entities.
final String functionPrefix = "jsFunction_";
final String staticFunctionPrefix = "jsStaticFunction_";
final String getterPrefix = "jsGet_";
final String setterPrefix = "jsSet_";
final String ctorName = "jsConstructor";
Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName);
if (ctorMember == null) {
if (ctors.length == 1) {
ctorMember = ctors[0];
} else if (ctors.length == 2) {
if (ctors[0].getParameterTypes().length == 0)
ctorMember = ctors[1];
else if (ctors[1].getParameterTypes().length == 0)
ctorMember = ctors[0];
}
if (ctorMember == null) {
throw Context.reportRuntimeError1(
"msg.ctor.multiple.parms", clazz.getName());
}
}
FunctionObject ctor = new FunctionObject(className, ctorMember, scope);
if (ctor.isVarArgsMethod()) {
throw Context.reportRuntimeError1
("msg.varargs.ctor", ctorMember.getName());
}
ctor.initAsConstructor(scope, proto);
Method finishInit = null;
for (int i=0; i < methods.length; i++) {
if (methods[i] == ctorMember) {
continue;
}
String name = methods[i].getName();
if (name.equals("finishInit")) {
Class[] parmTypes = methods[i].getParameterTypes();
if (parmTypes.length == 3 &&
parmTypes[0] == ScriptRuntime.ScriptableClass &&
parmTypes[1] == FunctionObject.class &&
parmTypes[2] == ScriptRuntime.ScriptableClass &&
Modifier.isStatic(methods[i].getModifiers()))
{
finishInit = methods[i];
continue;
}
}
// ignore any compiler generated methods.
if (name.indexOf('$') != -1)
continue;
if (name.equals(ctorName))
continue;
String prefix = null;
if (name.startsWith(functionPrefix)) {
prefix = functionPrefix;
} else if (name.startsWith(staticFunctionPrefix)) {
prefix = staticFunctionPrefix;
if (!Modifier.isStatic(methods[i].getModifiers())) {
throw Context.reportRuntimeError(
"jsStaticFunction must be used with static method.");
}
} else if (name.startsWith(getterPrefix)) {
prefix = getterPrefix;
} else if (name.startsWith(setterPrefix)) {
prefix = setterPrefix;
} else {
continue;
}
name = name.substring(prefix.length());
if (prefix == setterPrefix)
continue; // deal with set when we see get
if (prefix == getterPrefix) {
if (!(proto instanceof ScriptableObject)) {
throw Context.reportRuntimeError2(
"msg.extend.scriptable",
proto.getClass().toString(), name);
}
Method setter = FunctionObject.findSingleMethod(
methods,
setterPrefix + name);
int attr = ScriptableObject.PERMANENT |
ScriptableObject.DONTENUM |
(setter != null ? 0
: ScriptableObject.READONLY);
((ScriptableObject) proto).defineProperty(name, null,
methods[i], setter,
attr);
continue;
}
FunctionObject f = new FunctionObject(name, methods[i], proto);
if (f.isVarArgsConstructor()) {
throw Context.reportRuntimeError1
("msg.varargs.fun", ctorMember.getName());
}
Scriptable dest = prefix == staticFunctionPrefix
? ctor
: proto;
defineProperty(dest, name, f, DONTENUM);
if (sealed) {
f.sealObject();
}
}
// Call user code to complete initialization if necessary.
if (finishInit != null) {
Object[] finishArgs = { scope, ctor, proto };
finishInit.invoke(null, finishArgs);
}
// Seal the object if necessary.
if (sealed) {
ctor.sealObject();
if (proto instanceof ScriptableObject) {
((ScriptableObject) proto).sealObject();
}
}
return ctor;
}
/**
* Define a JavaScript property.
*
* Creates the property with an initial value and sets its attributes.
*
* @param propertyName the name of the property to define.
* @param value the initial value of the property
* @param attributes the attributes of the JavaScript property
* @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
*/
public void defineProperty(String propertyName, Object value,
int attributes)
{
checkNotSealed(propertyName, 0);
put(propertyName, this, value);
setAttributes(propertyName, attributes);
}
/**
* Utility method to add properties to arbitrary Scriptable object.
* If destination is instance of ScriptableObject, calls
* defineProperty there, otherwise calls put in destination
* ignoring attributes
*/
public static void defineProperty(Scriptable destination,
String propertyName, Object value,
int attributes)
{
if (!(destination instanceof ScriptableObject)) {
destination.put(propertyName, destination, value);
return;
}
ScriptableObject so = (ScriptableObject)destination;
so.defineProperty(propertyName, value, attributes);
}
/**
* Utility method to add properties to arbitrary Scriptable object.
* If destination is instance of ScriptableObject, calls
* defineProperty there, otherwise calls put in destination
* ignoring attributes
*/
public static void defineConstProperty(Scriptable destination,
String propertyName)
{
if (destination instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)destination;
cp.defineConst(propertyName, destination);
} else
defineProperty(destination, propertyName, Undefined.instance, CONST);
}
/**
* Define a JavaScript property with getter and setter side effects.
*
* If the setter is not found, the attribute READONLY is added to
* the given attributes. <p>
*
* The getter must be a method with zero parameters, and the setter, if
* found, must be a method with one parameter.<p>
*
* @param propertyName the name of the property to define. This name
* also affects the name of the setter and getter
* to search for. If the propertyId is "foo", then
* <code>clazz</code> will be searched for "getFoo"
* and "setFoo" methods.
* @param clazz the Java class to search for the getter and setter
* @param attributes the attributes of the JavaScript property
* @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
*/
public void defineProperty(String propertyName, Class clazz,
int attributes)
{
int length = propertyName.length();
if (length == 0) throw new IllegalArgumentException();
char[] buf = new char[3 + length];
propertyName.getChars(0, length, buf, 3);
buf[3] = Character.toUpperCase(buf[3]);
buf[0] = 'g';
buf[1] = 'e';
buf[2] = 't';
String getterName = new String(buf);
buf[0] = 's';
String setterName = new String(buf);
Method[] methods = FunctionObject.getMethodList(clazz);
Method getter = FunctionObject.findSingleMethod(methods, getterName);
Method setter = FunctionObject.findSingleMethod(methods, setterName);
if (setter == null)
attributes |= ScriptableObject.READONLY;
defineProperty(propertyName, null, getter,
setter == null ? null : setter, attributes);
}
/**
* Define a JavaScript property.
*
* Use this method only if you wish to define getters and setters for
* a given property in a ScriptableObject. To create a property without
* special getter or setter side effects, use
* <code>defineProperty(String,int)</code>.
*
* If <code>setter</code> is null, the attribute READONLY is added to
* the given attributes.<p>
*
* Several forms of getters or setters are allowed. In all cases the
* type of the value parameter can be any one of the following types:
* Object, String, boolean, Scriptable, byte, short, int, long, float,
* or double. The runtime will perform appropriate conversions based
* upon the type of the parameter (see description in FunctionObject).
* The first forms are nonstatic methods of the class referred to
* by 'this':
* <pre>
* Object getFoo();
* void setFoo(SomeType value);</pre>
* Next are static methods that may be of any class; the object whose
* property is being accessed is passed in as an extra argument:
* <pre>
* static Object getFoo(Scriptable obj);
* static void setFoo(Scriptable obj, SomeType value);</pre>
* Finally, it is possible to delegate to another object entirely using
* the <code>delegateTo</code> parameter. In this case the methods are
* nonstatic methods of the class delegated to, and the object whose
* property is being accessed is passed in as an extra argument:
* <pre>
* Object getFoo(Scriptable obj);
* void setFoo(Scriptable obj, SomeType value);</pre>
*
* @param propertyName the name of the property to define.
* @param delegateTo an object to call the getter and setter methods on,
* or null, depending on the form used above.
* @param getter the method to invoke to get the value of the property
* @param setter the method to invoke to set the value of the property
* @param attributes the attributes of the JavaScript property
*/
public void defineProperty(String propertyName, Object delegateTo,
Method getter, Method setter, int attributes)
{
MemberBox getterBox = null;
if (getter != null) {
getterBox = new MemberBox(getter);
boolean delegatedForm;
if (!Modifier.isStatic(getter.getModifiers())) {
delegatedForm = (delegateTo != null);
getterBox.delegateTo = delegateTo;
} else {
delegatedForm = true;
// Ignore delegateTo for static getter but store
// non-null delegateTo indicator.
getterBox.delegateTo = Void.TYPE;
}
String errorId = null;
Class[] parmTypes = getter.getParameterTypes();
if (parmTypes.length == 0) {
if (delegatedForm) {
errorId = "msg.obj.getter.parms";
}
} else if (parmTypes.length == 1) {
Object argType = parmTypes[0];
// Allow ScriptableObject for compatibility
if (!(argType == ScriptRuntime.ScriptableClass ||
argType == ScriptRuntime.ScriptableObjectClass))
{
errorId = "msg.bad.getter.parms";
} else if (!delegatedForm) {
errorId = "msg.bad.getter.parms";
}
} else {
errorId = "msg.bad.getter.parms";
}
if (errorId != null) {
throw Context.reportRuntimeError1(errorId, getter.toString());
}
}
MemberBox setterBox = null;
if (setter != null) {
if (setter.getReturnType() != Void.TYPE)
throw Context.reportRuntimeError1("msg.setter.return",
setter.toString());
setterBox = new MemberBox(setter);
boolean delegatedForm;
if (!Modifier.isStatic(setter.getModifiers())) {
delegatedForm = (delegateTo != null);
setterBox.delegateTo = delegateTo;
} else {
delegatedForm = true;
// Ignore delegateTo for static setter but store
// non-null delegateTo indicator.
setterBox.delegateTo = Void.TYPE;
}
String errorId = null;
Class[] parmTypes = setter.getParameterTypes();
if (parmTypes.length == 1) {
if (delegatedForm) {
errorId = "msg.setter2.expected";
}
} else if (parmTypes.length == 2) {
Object argType = parmTypes[0];
// Allow ScriptableObject for compatibility
if (!(argType == ScriptRuntime.ScriptableClass ||
argType == ScriptRuntime.ScriptableObjectClass))
{
errorId = "msg.setter2.parms";
} else if (!delegatedForm) {
errorId = "msg.setter1.parms";
}
} else {
errorId = "msg.setter.parms";
}
if (errorId != null) {
throw Context.reportRuntimeError1(errorId, setter.toString());
}
}
GetterSlot gslot = (GetterSlot)getSlot(propertyName, 0,
SLOT_MODIFY_GETTER_SETTER);
gslot.setAttributes(attributes);
gslot.getter = getterBox;
gslot.setter = setterBox;
}
/**
* Search for names in a class, adding the resulting methods
* as properties.
*
* <p> Uses reflection to find the methods of the given names. Then
* FunctionObjects are constructed from the methods found, and
* are added to this object as properties with the given names.
*
* @param names the names of the Methods to add as function properties
* @param clazz the class to search for the Methods
* @param attributes the attributes of the new properties
* @see org.mozilla.javascript.FunctionObject
*/
public void defineFunctionProperties(String[] names, Class clazz,
int attributes)
{
Method[] methods = FunctionObject.getMethodList(clazz);
for (int i=0; i < names.length; i++) {
String name = names[i];
Method m = FunctionObject.findSingleMethod(methods, name);
if (m == null) {
throw Context.reportRuntimeError2(
"msg.method.not.found", name, clazz.getName());
}
FunctionObject f = new FunctionObject(name, m, this);
defineProperty(name, f, attributes);
}
}
/**
* Get the Object.prototype property.
* See ECMA 15.2.4.
*/
public static Scriptable getObjectPrototype(Scriptable scope) {
return getClassPrototype(scope, "Object");
}
/**
* Get the Function.prototype property.
* See ECMA 15.3.4.
*/
public static Scriptable getFunctionPrototype(Scriptable scope) {
return getClassPrototype(scope, "Function");
}
/**
* Get the prototype for the named class.
*
* For example, <code>getClassPrototype(s, "Date")</code> will first
* walk up the parent chain to find the outermost scope, then will
* search that scope for the Date constructor, and then will
* return Date.prototype. If any of the lookups fail, or
* the prototype is not a JavaScript object, then null will
* be returned.
*
* @param scope an object in the scope chain
* @param className the name of the constructor
* @return the prototype for the named class, or null if it
* cannot be found.
*/
public static Scriptable getClassPrototype(Scriptable scope,
String className)
{
scope = getTopLevelScope(scope);
Object ctor = getProperty(scope, className);
Object proto;
if (ctor instanceof BaseFunction) {
proto = ((BaseFunction)ctor).getPrototypeProperty();
} else if (ctor instanceof Scriptable) {
Scriptable ctorObj = (Scriptable)ctor;
proto = ctorObj.get("prototype", ctorObj);
} else {
return null;
}
if (proto instanceof Scriptable) {
return (Scriptable)proto;
}
return null;
}
/**
* Get the global scope.
*
* <p>Walks the parent scope chain to find an object with a null
* parent scope (the global object).
*
* @param obj a JavaScript object
* @return the corresponding global scope
*/
public static Scriptable getTopLevelScope(Scriptable obj)
{
for (;;) {
Scriptable parent = obj.getParentScope();
if (parent == null) {
return obj;
}
obj = parent;
}
}
/**
* Seal this object.
*
* A sealed object may not have properties added or removed. Once
* an object is sealed it may not be unsealed.
*
* @since 1.4R3
*/
public synchronized void sealObject() {
if (count >= 0) {
count = ~count;
}
}
/**
* Return true if this object is sealed.
*
* It is an error to attempt to add or remove properties to
* a sealed object.
*
* @return true if sealed, false otherwise.
* @since 1.4R3
*/
public final boolean isSealed() {
return count < 0;
}
private void checkNotSealed(String name, int index)
{
if (!isSealed())
return;
String str = (name != null) ? name : Integer.toString(index);
throw Context.reportRuntimeError1("msg.modify.sealed", str);
}
/**
* Gets a named property from an object or any object in its prototype chain.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param obj a JavaScript object
* @param name a property name
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* <code>Scriptable.NOT_FOUND</code> if not found
* @since 1.5R2
*/
public static Object getProperty(Scriptable obj, String name)
{
Scriptable start = obj;
Object result;
do {
result = obj.get(name, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* Gets an indexed property from an object or any object in its prototype chain.
* <p>
* Searches the prototype chain for a property with integral index
* <code>index</code>. Note that if you wish to look for properties with numerical
* but non-integral indicies, you should use getProperty(Scriptable,String) with
* the string value of the index.
* <p>
* @param obj a JavaScript object
* @param index an integral index
* @return the value of a property with index <code>index</code> found in
* <code>obj</code> or any object in its prototype chain, or
* <code>Scriptable.NOT_FOUND</code> if not found
* @since 1.5R2
*/
public static Object getProperty(Scriptable obj, int index)
{
Scriptable start = obj;
Object result;
do {
result = obj.get(index, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* Returns whether a named property is defined in an object or any object
* in its prototype chain.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param obj a JavaScript object
* @param name a property name
* @return the true if property was found
* @since 1.5R2
*/
public static boolean hasProperty(Scriptable obj, String name)
{
return null != getBase(obj, name);
}
/**
* If hasProperty(obj, name) would return true, then if the property that
* was found is compatible with the new property, this method just returns.
* If the property is not compatible, then an exception is thrown.
*
* A property redefinition is incompatible if the first definition was a
* const declaration or if this one is. They are compatible only if neither
* was const.
*/
public static void redefineProperty(Scriptable obj, String name,
boolean isConst)
{
Scriptable base = getBase(obj, name);
if (base == null)
return;
if (base instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)base;
if (cp.isConst(name))
throw Context.reportRuntimeError1("msg.const.redecl", name);
}
if (isConst)
throw Context.reportRuntimeError1("msg.var.redecl", name);
}
/**
* Returns whether an indexed property is defined in an object or any object
* in its prototype chain.
* <p>
* Searches the prototype chain for a property with index <code>index</code>.
* <p>
* @param obj a JavaScript object
* @param index a property index
* @return the true if property was found
* @since 1.5R2
*/
public static boolean hasProperty(Scriptable obj, int index)
{
return null != getBase(obj, index);
}
/**
* Puts a named property in an object or in an object in its prototype chain.
* <p>
* Searches for the named property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(String, Scriptable, Object)} on the
* prototype passing <code>obj</code> as the <code>start</code> argument.
* This allows the prototype to veto the property setting in case the
* prototype defines the property with [[ReadOnly]] attribute. If the
* property is not found, it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param name a property name
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
base.put(name, obj, value);
}
/**
* Puts a named property in an object or in an object in its prototype chain.
* <p>
* Searches for the named property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(String, Scriptable, Object)} on the
* prototype passing <code>obj</code> as the <code>start</code> argument.
* This allows the prototype to veto the property setting in case the
* prototype defines the property with [[ReadOnly]] attribute. If the
* property is not found, it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param name a property name
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putConstProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
if (base instanceof ConstProperties)
((ConstProperties)base).putConst(name, obj, value);
}
/**
* Puts an indexed property in an object or in an object in its prototype chain.
* <p>
* Searches for the indexed property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(int, Scriptable, Object)} on the prototype
* passing <code>obj</code> as the <code>start</code> argument. This allows
* the prototype to veto the property setting in case the prototype defines
* the property with [[ReadOnly]] attribute. If the property is not found,
* it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param index a property index
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putProperty(Scriptable obj, int index, Object value)
{
Scriptable base = getBase(obj, index);
if (base == null)
base = obj;
base.put(index, obj, value);
}
/**
* Removes the property from an object or its prototype chain.
* <p>
* Searches for a property with <code>name</code> in obj or
* its prototype chain. If it is found, the object's delete
* method is called.
* @param obj a JavaScript object
* @param name a property name
* @return true if the property doesn't exist or was successfully removed
* @since 1.5R2
*/
public static boolean deleteProperty(Scriptable obj, String name)
{
Scriptable base = getBase(obj, name);
if (base == null)
return true;
base.delete(name);
return !base.has(name, obj);
}
/**
* Removes the property from an object or its prototype chain.
* <p>
* Searches for a property with <code>index</code> in obj or
* its prototype chain. If it is found, the object's delete
* method is called.
* @param obj a JavaScript object
* @param index a property index
* @return true if the property doesn't exist or was successfully removed
* @since 1.5R2
*/
public static boolean deleteProperty(Scriptable obj, int index)
{
Scriptable base = getBase(obj, index);
if (base == null)
return true;
base.delete(index);
return !base.has(index, obj);
}
/**
* Returns an array of all ids from an object and its prototypes.
* <p>
* @param obj a JavaScript object
* @return an array of all ids from all object in the prototype chain.
* If a given id occurs multiple times in the prototype chain,
* it will occur only once in this list.
* @since 1.5R2
*/
public static Object[] getPropertyIds(Scriptable obj)
{
if (obj == null) {
return ScriptRuntime.emptyArgs;
}
Object[] result = obj.getIds();
ObjToIntMap map = null;
for (;;) {
obj = obj.getPrototype();
if (obj == null) {
break;
}
Object[] ids = obj.getIds();
if (ids.length == 0) {
continue;
}
if (map == null) {
if (result.length == 0) {
result = ids;
continue;
}
map = new ObjToIntMap(result.length + ids.length);
for (int i = 0; i != result.length; ++i) {
map.intern(result[i]);
}
result = null; // Allow to GC the result
}
for (int i = 0; i != ids.length; ++i) {
map.intern(ids[i]);
}
}
if (map != null) {
result = map.getKeys();
}
return result;
}
/**
* Call a method of an object.
* @param obj the JavaScript object
* @param methodName the name of the function property
* @param args the arguments for the call
*
* @see Context#getCurrentContext()
*/
public static Object callMethod(Scriptable obj, String methodName,
Object[] args)
{
return callMethod(null, obj, methodName, args);
}
/**
* Call a method of an object.
* @param cx the Context object associated with the current thread.
* @param obj the JavaScript object
* @param methodName the name of the function property
* @param args the arguments for the call
*/
public static Object callMethod(Context cx, Scriptable obj,
String methodName,
Object[] args)
{
Object funObj = getProperty(obj, methodName);
if (!(funObj instanceof Function)) {
throw ScriptRuntime.notFunctionError(obj, methodName);
}
Function fun = (Function)funObj;
// XXX: What should be the scope when calling funObj?
// The following favor scope stored in the object on the assumption
// that is more useful especially under dynamic scope setup.
// An alternative is to check for dynamic scope flag
// and use ScriptableObject.getTopLevelScope(fun) if the flag is not
// set. But that require access to Context and messy code
// so for now it is not checked.
Scriptable scope = ScriptableObject.getTopLevelScope(obj);
if (cx != null) {
return fun.call(cx, scope, obj, args);
} else {
return Context.call(null, fun, scope, obj, args);
}
}
private static Scriptable getBase(Scriptable obj, String name)
{
do {
if (obj.has(name, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
private static Scriptable getBase(Scriptable obj, int index)
{
do {
if (obj.has(index, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
/**
* Get arbitrary application-specific value associated with this object.
* @param key key object to select particular value.
* @see #associateValue(Object key, Object value)
*/
public final Object getAssociatedValue(Object key)
{
Hashtable h = associatedValues;
if (h == null)
return null;
return h.get(key);
}
/**
* Get arbitrary application-specific value associated with the top scope
* of the given scope.
* The method first calls {@link #getTopLevelScope(Scriptable scope)}
* and then searches the prototype chain of the top scope for the first
* object containing the associated value with the given key.
*
* @param scope the starting scope.
* @param key key object to select particular value.
* @see #getAssociatedValue(Object key)
*/
public static Object getTopScopeValue(Scriptable scope, Object key)
{
scope = ScriptableObject.getTopLevelScope(scope);
for (;;) {
if (scope instanceof ScriptableObject) {
ScriptableObject so = (ScriptableObject)scope;
Object value = so.getAssociatedValue(key);
if (value != null) {
return value;
}
}
scope = scope.getPrototype();
if (scope == null) {
return null;
}
}
}
/**
* Associate arbitrary application-specific value with this object.
* Value can only be associated with the given object and key only once.
* The method ignores any subsequent attempts to change the already
* associated value.
* <p> The associated values are not serilized.
* @param key key object to select particular value.
* @param value the value to associate
* @return the passed value if the method is called first time for the
* given key or old value for any subsequent calls.
* @see #getAssociatedValue(Object key)
*/
public final Object associateValue(Object key, Object value)
{
if (value == null) throw new IllegalArgumentException();
Hashtable h = associatedValues;
if (h == null) {
synchronized (this) {
h = associatedValues;
if (h == null) {
h = new Hashtable();
associatedValues = h;
}
}
}
return Kit.initHash(h, key, value);
}
private Object getImpl(String name, int index, Scriptable start)
{
Slot slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return Scriptable.NOT_FOUND;
}
if (!(slot instanceof GetterSlot)) {
return slot.value;
}
Object getterObj = ((GetterSlot)slot).getter;
if (getterObj != null) {
if (getterObj instanceof MemberBox) {
MemberBox nativeGetter = (MemberBox)getterObj;
Object getterThis;
Object[] args;
if (nativeGetter.delegateTo == null) {
getterThis = start;
args = ScriptRuntime.emptyArgs;
} else {
getterThis = nativeGetter.delegateTo;
args = new Object[] { start };
}
return nativeGetter.invoke(getterThis, args);
} else {
Callable f = (Callable)getterObj;
Context cx = Context.getContext();
return f.call(cx, ScriptRuntime.getTopCallScope(cx), start,
ScriptRuntime.emptyArgs);
}
}
Object value = slot.value;
if (value instanceof LazilyLoadedCtor) {
LazilyLoadedCtor initializer = (LazilyLoadedCtor)value;
try {
initializer.init();
} finally {
value = initializer.getValue();
slot.value = value;
}
}
return value;
}
/**
*
* @param name
* @param index
* @param start
* @param value
* @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means
* defineConstProperty. READONLY means const initialization expression.
* @return false if this != start and no slot was found. true if this == start
* or this != start and a READONLY slot was found.
*/
private boolean putImpl(String name, int index, Scriptable start,
Object value, int constFlag)
{
Slot slot;
if (this != start) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return false;
}
} else {
checkNotSealed(name, index);
// either const hoisted declaration or initialization
if (constFlag != EMPTY) {
slot = getSlot(name, index, SLOT_MODIFY_CONST);
int attr = slot.getAttributes();
if ((attr & READONLY) == 0)
throw Context.reportRuntimeError1("msg.var.redecl", name);
if ((attr & UNINITIALIZED_CONST) != 0) {
slot.value = value;
// clear the bit on const initialization
if (constFlag != UNINITIALIZED_CONST)
slot.setAttributes(attr & ~UNINITIALIZED_CONST);
}
return true;
}
slot = getSlot(name, index, SLOT_MODIFY);
}
if ((slot.getAttributes() & READONLY) != 0)
return true;
if (slot instanceof GetterSlot) {
Object setterObj = ((GetterSlot)slot).setter;
if (setterObj != null) {
Context cx = Context.getContext();
if (setterObj instanceof MemberBox) {
MemberBox nativeSetter = (MemberBox)setterObj;
Class pTypes[] = nativeSetter.argTypes;
// XXX: cache tag since it is already calculated in
// defineProperty ?
Class valueType = pTypes[pTypes.length - 1];
int tag = FunctionObject.getTypeTag(valueType);
Object actualArg = FunctionObject.convertArg(cx, start,
value, tag);
Object setterThis;
Object[] args;
if (nativeSetter.delegateTo == null) {
setterThis = start;
args = new Object[] { actualArg };
} else {
setterThis = nativeSetter.delegateTo;
args = new Object[] { start, actualArg };
}
nativeSetter.invoke(setterThis, args);
} else {
Callable f = (Callable)setterObj;
f.call(cx, ScriptRuntime.getTopCallScope(cx), start,
new Object[] { value });
}
return true;
}
}
if (this == start) {
slot.value = value;
return true;
} else {
return false;
}
}
private Slot findAttributeSlot(String name, int index, int accessType)
{
Slot slot = getSlot(name, index, accessType);
if (slot == null) {
String str = (name != null ? name : Integer.toString(index));
throw Context.reportRuntimeError1("msg.prop.not.found", str);
}
return slot;
}
/**
* Locate the slot with given name or index.
*
* @param name property name or null if slot holds spare array index.
* @param index index or 0 if slot holds property name.
*/
private Slot getSlot(String name, int index, int accessType)
{
Slot slot;
// Query last access cache and check that it was not deleted.
lastAccessCheck:
{
slot = lastAccess;
if (name != null) {
if (name != slot.name)
break lastAccessCheck;
// No String.equals here as successful slot search update
// name object with fresh reference of the same string.
} else {
if (slot.name != null || index != slot.indexOrHash)
break lastAccessCheck;
}
if (slot.wasDeleted != 0)
break lastAccessCheck;
if (accessType == SLOT_MODIFY_GETTER_SETTER &&
!(slot instanceof GetterSlot))
break lastAccessCheck;
return slot;
}
slot = accessSlot(name, index, accessType);
if (slot != null) {
// Update the cache
lastAccess = slot;
}
return slot;
}
private Slot accessSlot(String name, int index, int accessType)
{
int indexOrHash = (name != null ? name.hashCode() : index);
if (accessType == SLOT_QUERY ||
accessType == SLOT_MODIFY ||
accessType == SLOT_MODIFY_CONST ||
accessType == SLOT_MODIFY_GETTER_SETTER)
{
// Check the hashtable without using synchronization
Slot[] slotsLocalRef = slots; // Get stable local reference
if (slotsLocalRef == null) {
if (accessType == SLOT_QUERY)
return null;
} else {
int tableSize = slotsLocalRef.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
Slot slot;
for (int i = start;;) {
slot = slotsLocalRef[i];
if (slot == null)
break;
String sname = slot.name;
if (sname != null) {
// Name slot which can not be REMOVED
if (sname == name)
break;
if (name != null && indexOrHash == slot.indexOrHash) {
if (name.equals(sname)) {
- // This will eleminate String.equals when
+ // This will avoid calling String.equals when
// slot is accessed with same string object
// next time.
slot.name = name;
break;
}
}
} else if (name == null &&
indexOrHash == slot.indexOrHash) {
// Match for index slot which can coincide with REMOVED
if (slot != REMOVED)
break;
}
if (++i == tableSize)
i = 0;
// slotsLocalRef should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if (accessType == SLOT_QUERY) {
return slot;
} else if (accessType == SLOT_MODIFY) {
if (slot != null)
return slot;
} else if (accessType == SLOT_MODIFY_GETTER_SETTER) {
if (slot instanceof GetterSlot)
return slot;
} else if (accessType == SLOT_MODIFY_CONST) {
if (slot != null)
return slot;
} else {
Kit.codeBug();
}
}
// A new slot has to be inserted or the old has to be replaced
// by GetterSlot. Time to synchronize.
synchronized (this) {
// Refresh local ref if another thread triggered grow
slotsLocalRef = slots;
int insertPos;
if (count == 0) {
// Always throw away old slots if any on empty insert
slotsLocalRef = new Slot[5];
slots = slotsLocalRef;
insertPos = getKnownAbsentPos(slotsLocalRef, indexOrHash);
} else {
int tableSize = slotsLocalRef.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
int firstDeleted = -1;
Slot slot;
for (int i = start;;) {
slot = slotsLocalRef[i];
if (slot == null) {
insertPos = (firstDeleted < 0 ? i : firstDeleted);
break;
}
if (slot == REMOVED) {
if (firstDeleted < 0)
firstDeleted = i;
}
if (slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
insertPos = i;
break;
}
if (++i == tableSize)
i = 0;
// slots should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if (slot != null) {
// Another thread just added a slot with same
// name/index before this one entered synchronized
// block. This is a race in application code and
// probably indicates bug there. But for the hashtable
// implementation it is harmless with the only
// complication is the need to replace the added slot
// if we need GetterSlot and the old one is not.
if (accessType == SLOT_MODIFY_GETTER_SETTER &&
!(slot instanceof GetterSlot))
{
GetterSlot newSlot;
newSlot = new GetterSlot(name, indexOrHash,
slot.getAttributes());
newSlot.value = slot.value;
slotsLocalRef[insertPos] = newSlot;
slot.wasDeleted = (byte)1;
if (slot == lastAccess) {
lastAccess = REMOVED;
}
slot = newSlot;
} else if (accessType == SLOT_MODIFY_CONST) {
return null;
}
return slot;
}
// Check if the table is not too full before inserting.
if (4 * (count + 1) > 3 * slotsLocalRef.length) {
slotsLocalRef = new Slot[slotsLocalRef.length * 2 + 1];
copyTable(slots, slotsLocalRef, count);
slots = slotsLocalRef;
insertPos = getKnownAbsentPos(slotsLocalRef,
indexOrHash);
}
}
Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER
? new GetterSlot(name, indexOrHash, 0)
: new Slot(name, indexOrHash, 0));
if (accessType == SLOT_MODIFY_CONST)
newSlot.setAttributes(CONST);
++count;
slotsLocalRef[insertPos] = newSlot;
return newSlot;
}
} else if (accessType == SLOT_REMOVE) {
synchronized (this) {
Slot[] slotsLocalRef = slots;
if (count != 0) {
int tableSize = slots.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
Slot slot;
int i = start;
for (;;) {
slot = slotsLocalRef[i];
if (slot == null)
return null;
if (slot != REMOVED &&
slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
break;
}
if (++i == tableSize)
i = 0;
// slots should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if ((slot.getAttributes() & PERMANENT) == 0) {
count--;
if (count != 0) {
slotsLocalRef[i] = REMOVED;
} else {
// With no slots mark with null.
slotsLocalRef[i] = null;
}
// Mark the slot as removed to handle a case when
// another thread manages to put just removed slot
// into lastAccess cache.
slot.wasDeleted = (byte)1;
if (slot == lastAccess) {
lastAccess = REMOVED;
}
}
}
}
return null;
} else {
throw Kit.codeBug();
}
}
private static int getSearchStartIndex(int tableSize, int indexOrHash)
{
return (indexOrHash & 0x7fffffff) % tableSize;
}
// Must be inside synchronized (this)
private static void copyTable(Slot[] slots, Slot[] newSlots, int count)
{
if (count == 0) throw Kit.codeBug();
int i = slots.length;
for (;;) {
--i;
Slot slot = slots[i];
if (slot != null && slot != REMOVED) {
int insertPos = getKnownAbsentPos(newSlots, slot.indexOrHash);
newSlots[insertPos] = slot;
if (--count == 0)
break;
}
}
}
/**
* Add slot with keys that are known to absent from the table.
* This is an optimization to use when inserting into empty table,
* after table growth or during desirialization.
*/
private static int getKnownAbsentPos(Slot[] slots, int indexOrHash)
{
int tableSize = slots.length;
int i = getSearchStartIndex(tableSize, indexOrHash);
while (slots[i] != null) {
if (++i == tableSize)
i = 0;
}
return i;
}
Object[] getIds(boolean getAll) {
Slot[] s = slots;
Object[] a = ScriptRuntime.emptyArgs;
if (s == null)
return a;
int c = 0;
for (int i=0; i < s.length; i++) {
Slot slot = s[i];
if (slot == null || slot == REMOVED)
continue;
if (getAll || (slot.getAttributes() & DONTENUM) == 0) {
if (c == 0)
a = new Object[s.length - i];
a[c++] = (slot.name != null ? (Object) slot.name
: new Integer(slot.indexOrHash));
}
}
if (c == a.length)
return a;
Object[] result = new Object[c];
System.arraycopy(a, 0, result, 0, c);
return result;
}
private synchronized void writeObject(ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
int objectsCount = count;
if (objectsCount < 0) {
// "this" was sealed
objectsCount = ~objectsCount;
}
if (objectsCount == 0) {
out.writeInt(0);
} else {
out.writeInt(slots.length);
for (int i = 0; ; ++i) {
Slot slot = slots[i];
if (slot != null && slot != REMOVED) {
out.writeObject(slot);
if (--objectsCount == 0)
break;
}
}
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
lastAccess = REMOVED;
int tableSize = in.readInt();
if (tableSize != 0) {
slots = new Slot[tableSize];
int objectsCount = count;
if (objectsCount < 0) {
// "this" was sealed
objectsCount = ~objectsCount;
}
for (int i = 0; i != objectsCount; ++i) {
Slot slot = (Slot)in.readObject();
slots[getKnownAbsentPos(slots, slot.indexOrHash)] = slot;
}
}
}
}
| true | true | private Slot accessSlot(String name, int index, int accessType)
{
int indexOrHash = (name != null ? name.hashCode() : index);
if (accessType == SLOT_QUERY ||
accessType == SLOT_MODIFY ||
accessType == SLOT_MODIFY_CONST ||
accessType == SLOT_MODIFY_GETTER_SETTER)
{
// Check the hashtable without using synchronization
Slot[] slotsLocalRef = slots; // Get stable local reference
if (slotsLocalRef == null) {
if (accessType == SLOT_QUERY)
return null;
} else {
int tableSize = slotsLocalRef.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
Slot slot;
for (int i = start;;) {
slot = slotsLocalRef[i];
if (slot == null)
break;
String sname = slot.name;
if (sname != null) {
// Name slot which can not be REMOVED
if (sname == name)
break;
if (name != null && indexOrHash == slot.indexOrHash) {
if (name.equals(sname)) {
// This will eleminate String.equals when
// slot is accessed with same string object
// next time.
slot.name = name;
break;
}
}
} else if (name == null &&
indexOrHash == slot.indexOrHash) {
// Match for index slot which can coincide with REMOVED
if (slot != REMOVED)
break;
}
if (++i == tableSize)
i = 0;
// slotsLocalRef should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if (accessType == SLOT_QUERY) {
return slot;
} else if (accessType == SLOT_MODIFY) {
if (slot != null)
return slot;
} else if (accessType == SLOT_MODIFY_GETTER_SETTER) {
if (slot instanceof GetterSlot)
return slot;
} else if (accessType == SLOT_MODIFY_CONST) {
if (slot != null)
return slot;
} else {
Kit.codeBug();
}
}
// A new slot has to be inserted or the old has to be replaced
// by GetterSlot. Time to synchronize.
synchronized (this) {
// Refresh local ref if another thread triggered grow
slotsLocalRef = slots;
int insertPos;
if (count == 0) {
// Always throw away old slots if any on empty insert
slotsLocalRef = new Slot[5];
slots = slotsLocalRef;
insertPos = getKnownAbsentPos(slotsLocalRef, indexOrHash);
} else {
int tableSize = slotsLocalRef.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
int firstDeleted = -1;
Slot slot;
for (int i = start;;) {
slot = slotsLocalRef[i];
if (slot == null) {
insertPos = (firstDeleted < 0 ? i : firstDeleted);
break;
}
if (slot == REMOVED) {
if (firstDeleted < 0)
firstDeleted = i;
}
if (slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
insertPos = i;
break;
}
if (++i == tableSize)
i = 0;
// slots should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if (slot != null) {
// Another thread just added a slot with same
// name/index before this one entered synchronized
// block. This is a race in application code and
// probably indicates bug there. But for the hashtable
// implementation it is harmless with the only
// complication is the need to replace the added slot
// if we need GetterSlot and the old one is not.
if (accessType == SLOT_MODIFY_GETTER_SETTER &&
!(slot instanceof GetterSlot))
{
GetterSlot newSlot;
newSlot = new GetterSlot(name, indexOrHash,
slot.getAttributes());
newSlot.value = slot.value;
slotsLocalRef[insertPos] = newSlot;
slot.wasDeleted = (byte)1;
if (slot == lastAccess) {
lastAccess = REMOVED;
}
slot = newSlot;
} else if (accessType == SLOT_MODIFY_CONST) {
return null;
}
return slot;
}
// Check if the table is not too full before inserting.
if (4 * (count + 1) > 3 * slotsLocalRef.length) {
slotsLocalRef = new Slot[slotsLocalRef.length * 2 + 1];
copyTable(slots, slotsLocalRef, count);
slots = slotsLocalRef;
insertPos = getKnownAbsentPos(slotsLocalRef,
indexOrHash);
}
}
Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER
? new GetterSlot(name, indexOrHash, 0)
: new Slot(name, indexOrHash, 0));
if (accessType == SLOT_MODIFY_CONST)
newSlot.setAttributes(CONST);
++count;
slotsLocalRef[insertPos] = newSlot;
return newSlot;
}
} else if (accessType == SLOT_REMOVE) {
synchronized (this) {
Slot[] slotsLocalRef = slots;
if (count != 0) {
int tableSize = slots.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
Slot slot;
int i = start;
for (;;) {
slot = slotsLocalRef[i];
if (slot == null)
return null;
if (slot != REMOVED &&
slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
break;
}
if (++i == tableSize)
i = 0;
// slots should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if ((slot.getAttributes() & PERMANENT) == 0) {
count--;
if (count != 0) {
slotsLocalRef[i] = REMOVED;
} else {
// With no slots mark with null.
slotsLocalRef[i] = null;
}
// Mark the slot as removed to handle a case when
// another thread manages to put just removed slot
// into lastAccess cache.
slot.wasDeleted = (byte)1;
if (slot == lastAccess) {
lastAccess = REMOVED;
}
}
}
}
return null;
} else {
throw Kit.codeBug();
}
}
| private Slot accessSlot(String name, int index, int accessType)
{
int indexOrHash = (name != null ? name.hashCode() : index);
if (accessType == SLOT_QUERY ||
accessType == SLOT_MODIFY ||
accessType == SLOT_MODIFY_CONST ||
accessType == SLOT_MODIFY_GETTER_SETTER)
{
// Check the hashtable without using synchronization
Slot[] slotsLocalRef = slots; // Get stable local reference
if (slotsLocalRef == null) {
if (accessType == SLOT_QUERY)
return null;
} else {
int tableSize = slotsLocalRef.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
Slot slot;
for (int i = start;;) {
slot = slotsLocalRef[i];
if (slot == null)
break;
String sname = slot.name;
if (sname != null) {
// Name slot which can not be REMOVED
if (sname == name)
break;
if (name != null && indexOrHash == slot.indexOrHash) {
if (name.equals(sname)) {
// This will avoid calling String.equals when
// slot is accessed with same string object
// next time.
slot.name = name;
break;
}
}
} else if (name == null &&
indexOrHash == slot.indexOrHash) {
// Match for index slot which can coincide with REMOVED
if (slot != REMOVED)
break;
}
if (++i == tableSize)
i = 0;
// slotsLocalRef should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if (accessType == SLOT_QUERY) {
return slot;
} else if (accessType == SLOT_MODIFY) {
if (slot != null)
return slot;
} else if (accessType == SLOT_MODIFY_GETTER_SETTER) {
if (slot instanceof GetterSlot)
return slot;
} else if (accessType == SLOT_MODIFY_CONST) {
if (slot != null)
return slot;
} else {
Kit.codeBug();
}
}
// A new slot has to be inserted or the old has to be replaced
// by GetterSlot. Time to synchronize.
synchronized (this) {
// Refresh local ref if another thread triggered grow
slotsLocalRef = slots;
int insertPos;
if (count == 0) {
// Always throw away old slots if any on empty insert
slotsLocalRef = new Slot[5];
slots = slotsLocalRef;
insertPos = getKnownAbsentPos(slotsLocalRef, indexOrHash);
} else {
int tableSize = slotsLocalRef.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
int firstDeleted = -1;
Slot slot;
for (int i = start;;) {
slot = slotsLocalRef[i];
if (slot == null) {
insertPos = (firstDeleted < 0 ? i : firstDeleted);
break;
}
if (slot == REMOVED) {
if (firstDeleted < 0)
firstDeleted = i;
}
if (slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
insertPos = i;
break;
}
if (++i == tableSize)
i = 0;
// slots should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if (slot != null) {
// Another thread just added a slot with same
// name/index before this one entered synchronized
// block. This is a race in application code and
// probably indicates bug there. But for the hashtable
// implementation it is harmless with the only
// complication is the need to replace the added slot
// if we need GetterSlot and the old one is not.
if (accessType == SLOT_MODIFY_GETTER_SETTER &&
!(slot instanceof GetterSlot))
{
GetterSlot newSlot;
newSlot = new GetterSlot(name, indexOrHash,
slot.getAttributes());
newSlot.value = slot.value;
slotsLocalRef[insertPos] = newSlot;
slot.wasDeleted = (byte)1;
if (slot == lastAccess) {
lastAccess = REMOVED;
}
slot = newSlot;
} else if (accessType == SLOT_MODIFY_CONST) {
return null;
}
return slot;
}
// Check if the table is not too full before inserting.
if (4 * (count + 1) > 3 * slotsLocalRef.length) {
slotsLocalRef = new Slot[slotsLocalRef.length * 2 + 1];
copyTable(slots, slotsLocalRef, count);
slots = slotsLocalRef;
insertPos = getKnownAbsentPos(slotsLocalRef,
indexOrHash);
}
}
Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER
? new GetterSlot(name, indexOrHash, 0)
: new Slot(name, indexOrHash, 0));
if (accessType == SLOT_MODIFY_CONST)
newSlot.setAttributes(CONST);
++count;
slotsLocalRef[insertPos] = newSlot;
return newSlot;
}
} else if (accessType == SLOT_REMOVE) {
synchronized (this) {
Slot[] slotsLocalRef = slots;
if (count != 0) {
int tableSize = slots.length;
int start = getSearchStartIndex(tableSize, indexOrHash);
Slot slot;
int i = start;
for (;;) {
slot = slotsLocalRef[i];
if (slot == null)
return null;
if (slot != REMOVED &&
slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
break;
}
if (++i == tableSize)
i = 0;
// slots should never be full or bug in grow code
if (i == start)
throw Kit.codeBug();
}
if ((slot.getAttributes() & PERMANENT) == 0) {
count--;
if (count != 0) {
slotsLocalRef[i] = REMOVED;
} else {
// With no slots mark with null.
slotsLocalRef[i] = null;
}
// Mark the slot as removed to handle a case when
// another thread manages to put just removed slot
// into lastAccess cache.
slot.wasDeleted = (byte)1;
if (slot == lastAccess) {
lastAccess = REMOVED;
}
}
}
}
return null;
} else {
throw Kit.codeBug();
}
}
|
diff --git a/src/net/sf/freecol/client/gui/panel/MapEditorTransformPanel.java b/src/net/sf/freecol/client/gui/panel/MapEditorTransformPanel.java
index 2a35d0fae..5c85b3a71 100644
--- a/src/net/sf/freecol/client/gui/panel/MapEditorTransformPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/MapEditorTransformPanel.java
@@ -1,294 +1,295 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.panel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.MapEditorController;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.Map.Direction;
import net.sf.freecol.common.model.ResourceType;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileItemContainer;
import net.sf.freecol.common.model.TileImprovement;
import net.sf.freecol.common.model.TileType;
import net.sf.freecol.server.generator.River;
import net.sf.freecol.server.generator.RiverSection;
/**
* A panel for choosing the current <code>MapTransform</code>.
*
* <br><br>
*
* This panel is only used when running in
* {@link FreeColClient#isMapEditor() map editor mode}.
*
* @see MapEditorController#getMapTransform()
* @see MapTransform
*/
public final class MapEditorTransformPanel extends FreeColPanel {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(MapEditorTransformPanel.class.getName());
private final FreeColClient freeColClient;
private final ImageLibrary library;
private final JPanel listPanel;
private ButtonGroup group;
/**
* The constructor that will add the items to this panel.
* @param parent The parent of this panel.
*/
public MapEditorTransformPanel(Canvas parent) {
super(new BorderLayout());
this.freeColClient = parent.getClient();
this.library = parent.getGUI().getImageLibrary();
listPanel = new JPanel(new GridLayout(2, 0));
group = new ButtonGroup();
buildList();
JScrollPane sl = new JScrollPane(listPanel,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sl.getViewport().setOpaque(false);
add(sl);
}
/**
* Builds the buttons for all the terrains.
*/
private void buildList() {
List<TileType> tileList = FreeCol.getSpecification().getTileTypeList();
for (TileType type : tileList) {
buildButton(library.getScaledTerrainImage(type, 1f),
type.getName(), new TileTypeTransform(type));
}
buildButton(library.getRiverImage(10), Messages.message("minorRiver"),
new RiverTransform(TileImprovement.SMALL_RIVER));
buildButton(library.getRiverImage(20), Messages.message("majorRiver"),
new RiverTransform(TileImprovement.LARGE_RIVER));
buildButton(library.getBonusImage(FreeCol.getSpecification().getResourceTypeList().get(0)),
Messages.message("editor.resource"), new ResourceTransform());
buildButton(library.getMiscImage(ImageLibrary.LOST_CITY_RUMOUR),
Messages.message("model.message.LOST_CITY_RUMOUR"), new LostCityRumourTransform());
}
/**
* Builds the button for the given terrain.
*
* @param image an <code>Image</code> value
* @param text a <code>String</code> value
* @param mt a <code>MapTransform</code> value
*/
private void buildButton(Image image, String text, final MapTransform mt) {
Image scaledImage = library.scaleImage(image, 0.5f);
JPanel descriptionPanel = new JPanel(new BorderLayout());
descriptionPanel.add(new JLabel(new ImageIcon(image)), BorderLayout.CENTER);
descriptionPanel.add(new JLabel(text, JLabel.CENTER), BorderLayout.SOUTH);
descriptionPanel.setBackground(Color.RED);
mt.setDescriptionPanel(descriptionPanel);
ImageIcon icon = new ImageIcon(scaledImage);
final JButton button = new JButton(icon);
button.setToolTipText(text);
button.setOpaque(false);
group.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
freeColClient.getMapEditorController().setMapTransform(mt);
}
});
button.setBorder(null);
listPanel.add(button);
}
/**
* Represents a transformation that can be applied to
* a <code>Tile</code>.
*
* @see #transform(Tile)
*/
public abstract class MapTransform {
/**
* A panel with information about this transformation.
*/
private JPanel descriptionPanel = null;
/**
* Applies this transformation to the given tile.
* @param t The <code>Tile</code> to be transformed,
*/
public abstract void transform(Tile t);
/**
* A panel with information about this transformation.
* This panel is currently displayed on the
* {@link InfoPanel} when selected, but might be
* used elsewhere as well.
*
* @return The panel or <code>null</code> if no panel
* has been set.
*/
public JPanel getDescriptionPanel() {
return descriptionPanel;
}
/**
* Sets a panel that can be used for describing this
* transformation to the user.
*
* @param descriptionPanel The panel.
* @see #setDescriptionPanel(JPanel)
*/
public void setDescriptionPanel(JPanel descriptionPanel) {
this.descriptionPanel = descriptionPanel;
}
}
private class TileTypeTransform extends MapTransform {
private TileType tileType;
private TileTypeTransform(TileType tileType) {
this.tileType = tileType;
}
public void transform(Tile t) {
t.setType(tileType);
t.setLostCityRumour(false);
}
}
private class RiverTransform extends MapTransform {
private int magnitude;
private RiverTransform(int magnitude) {
this.magnitude = magnitude;
}
public void transform(Tile tile) {
if (tile.getType().canHaveRiver()) {
TileItemContainer tic = tile.getTileItemContainer();
if (tic == null) {
- tile.setTileItemContainer(new TileItemContainer(tile.getGame(), tile));
+ tic = new TileItemContainer(tile.getGame(), tile);
+ tile.setTileItemContainer(tic);
}
int oldMagnitude = TileImprovement.NO_RIVER;
if (tic.hasRiver()) {
oldMagnitude = tic.getRiver().getMagnitude();
}
if (magnitude != oldMagnitude) {
tic.addRiver(magnitude, tic.getRiverStyle());
RiverSection mysection = new RiverSection(tic.getRiverStyle());
// for each neighboring tile
for (Direction direction : River.directions) {
Tile t = tile.getMap().getNeighbourOrNull(direction, tile);
if (t == null) {
continue;
}
TileImprovement otherRiver = t.getRiver();
if (!t.isLand() && otherRiver == null) {
// add a virtual river in the ocean/lake tile
// just for the purpose of drawing the river mouth
otherRiver = new TileImprovement(tile.getGame(), tile, FreeCol.getSpecification()
.getTileImprovementType("model.improvement.River"));
otherRiver.setMagnitude(tile.getRiver().getMagnitude());
}
if (otherRiver != null) {
// update the other tile river branch
Direction otherDirection = direction.getReverseDirection();
RiverSection oppositesection = new RiverSection(otherRiver.getStyle());
oppositesection.setBranch(otherDirection, tile.getRiver().getMagnitude());
otherRiver.setStyle(oppositesection.encodeStyle());
// update the current tile river branch
mysection.setBranch(direction, tile.getRiver().getMagnitude());
}
// else the neighbor tile doesn't have a river, nothing to do
}
tile.getRiver().setStyle(mysection.encodeStyle());
}
}
}
}
/**
* Adds, Removes or Cycles through the available resources for this Tile
* Cycles through the ResourceTypeList and picks the next valid, or removes if end of list
*/
private class ResourceTransform extends MapTransform {
public void transform(Tile t) {
TileType tileType = t.getType();
List<ResourceType> resList = tileType.getResourceTypeList();
// Check if there is a resource already
if (t.hasResource()) {
// Get the index for this Resource in the resList
int index = resList.indexOf(t.getTileItemContainer().getResource().getType());
ResourceType resType = null;
if (++index < resList.size()) {
// Valid resource after this one, otherwise remain null
resType = resList.get(index);
}
t.setResource(resType);
} else {
if (resList.size() > 0) {
// Take first valid in ResourceList
t.setResource(resList.get(0));
}
}
}
}
private class LostCityRumourTransform extends MapTransform {
public void transform(Tile t) {
t.setLostCityRumour(true);
}
}
}
| true | true | public void transform(Tile tile) {
if (tile.getType().canHaveRiver()) {
TileItemContainer tic = tile.getTileItemContainer();
if (tic == null) {
tile.setTileItemContainer(new TileItemContainer(tile.getGame(), tile));
}
int oldMagnitude = TileImprovement.NO_RIVER;
if (tic.hasRiver()) {
oldMagnitude = tic.getRiver().getMagnitude();
}
if (magnitude != oldMagnitude) {
tic.addRiver(magnitude, tic.getRiverStyle());
RiverSection mysection = new RiverSection(tic.getRiverStyle());
// for each neighboring tile
for (Direction direction : River.directions) {
Tile t = tile.getMap().getNeighbourOrNull(direction, tile);
if (t == null) {
continue;
}
TileImprovement otherRiver = t.getRiver();
if (!t.isLand() && otherRiver == null) {
// add a virtual river in the ocean/lake tile
// just for the purpose of drawing the river mouth
otherRiver = new TileImprovement(tile.getGame(), tile, FreeCol.getSpecification()
.getTileImprovementType("model.improvement.River"));
otherRiver.setMagnitude(tile.getRiver().getMagnitude());
}
if (otherRiver != null) {
// update the other tile river branch
Direction otherDirection = direction.getReverseDirection();
RiverSection oppositesection = new RiverSection(otherRiver.getStyle());
oppositesection.setBranch(otherDirection, tile.getRiver().getMagnitude());
otherRiver.setStyle(oppositesection.encodeStyle());
// update the current tile river branch
mysection.setBranch(direction, tile.getRiver().getMagnitude());
}
// else the neighbor tile doesn't have a river, nothing to do
}
tile.getRiver().setStyle(mysection.encodeStyle());
}
}
}
| public void transform(Tile tile) {
if (tile.getType().canHaveRiver()) {
TileItemContainer tic = tile.getTileItemContainer();
if (tic == null) {
tic = new TileItemContainer(tile.getGame(), tile);
tile.setTileItemContainer(tic);
}
int oldMagnitude = TileImprovement.NO_RIVER;
if (tic.hasRiver()) {
oldMagnitude = tic.getRiver().getMagnitude();
}
if (magnitude != oldMagnitude) {
tic.addRiver(magnitude, tic.getRiverStyle());
RiverSection mysection = new RiverSection(tic.getRiverStyle());
// for each neighboring tile
for (Direction direction : River.directions) {
Tile t = tile.getMap().getNeighbourOrNull(direction, tile);
if (t == null) {
continue;
}
TileImprovement otherRiver = t.getRiver();
if (!t.isLand() && otherRiver == null) {
// add a virtual river in the ocean/lake tile
// just for the purpose of drawing the river mouth
otherRiver = new TileImprovement(tile.getGame(), tile, FreeCol.getSpecification()
.getTileImprovementType("model.improvement.River"));
otherRiver.setMagnitude(tile.getRiver().getMagnitude());
}
if (otherRiver != null) {
// update the other tile river branch
Direction otherDirection = direction.getReverseDirection();
RiverSection oppositesection = new RiverSection(otherRiver.getStyle());
oppositesection.setBranch(otherDirection, tile.getRiver().getMagnitude());
otherRiver.setStyle(oppositesection.encodeStyle());
// update the current tile river branch
mysection.setBranch(direction, tile.getRiver().getMagnitude());
}
// else the neighbor tile doesn't have a river, nothing to do
}
tile.getRiver().setStyle(mysection.encodeStyle());
}
}
}
|
diff --git a/src/com/modcrafting/ultrabans/commands/Fine.java b/src/com/modcrafting/ultrabans/commands/Fine.java
index 3342917..5159d0a 100644
--- a/src/com/modcrafting/ultrabans/commands/Fine.java
+++ b/src/com/modcrafting/ultrabans/commands/Fine.java
@@ -1,145 +1,147 @@
package com.modcrafting.ultrabans.commands;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import com.modcrafting.ultrabans.UltraBan;
import com.nijikokun.bukkit.Permissions.Permissions;
public class Fine implements CommandExecutor{
public net.milkbowl.vault.economy.Economy economy = null;
public static final Logger log = Logger.getLogger("Minecraft");
UltraBan plugin;
public Fine(UltraBan ultraBan) {
this.plugin = ultraBan;
}
public boolean autoComplete;
public String expandName(String p) {
int m = 0;
String Result = "";
for (int n = 0; n < plugin.getServer().getOnlinePlayers().length; n++) {
String str = plugin.getServer().getOnlinePlayers()[n].getName();
if (str.matches("(?i).*" + p + ".*")) {
m++;
Result = str;
if(m==2) {
return null;
}
}
if (str.equalsIgnoreCase(p))
return str;
}
if (m == 1)
return Result;
if (m > 1) {
return null;
}
if (m < 1) {
return p;
}
return p;
}
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
String perms = "ultraban.fine";
if (sender instanceof Player){
player = (Player)sender;
//new permissions test before reconstruct
if (Permissions.Security.permission(player, perms)){
auth = true;
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = args[0];
if(autoComplete) p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
boolean broadcast = true;
String amt = args[1]; //set string amount to argument
//Going loud
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
amt = combineSplit(2, args, " ");
}else{
amt = combineSplit(1, args, " ");
}
}
if(victim != null){
if(!broadcast){ //If silent wake his ass up
String fineMsg = config.getString("messages.fineMsgVictim", "You have been fined by %admin% in the amount of %amt%!");
String idoit = victim.getName();
fineMsg = fineMsg.replaceAll("%admin%", admin);
+ fineMsg = fineMsg.replaceAll("%amt%", amt);
fineMsg = fineMsg.replaceAll("%victim%", idoit);
sender.sendMessage(formatMessage(":S:" + fineMsg));
victim.sendMessage(formatMessage(fineMsg));
}
if(setupEconomy()){
double bal = economy.getBalance(p);
double amtd = Double.valueOf(amt.trim());
if(amtd > bal){
economy.withdrawPlayer(victim.getName(), bal);
}else{
economy.withdrawPlayer(victim.getName(), amtd);
}
}
log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + ".");
plugin.db.addPlayer(p, amt, admin, 0, 4);
if(broadcast){
String idoit = victim.getName();
String fineMsgAll = config.getString("messages.fineMsgBroadcast", "%victim% was fined by %admin% in the amount of %amt%!!");
fineMsgAll = fineMsgAll.replaceAll("%admin%", admin);
+ fineMsgAll = fineMsgAll.replaceAll("%amt%", amt);
fineMsgAll = fineMsgAll.replaceAll("%victim%", idoit);
plugin.getServer().broadcastMessage(formatMessage(fineMsgAll));
return true;
}
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
public String combineSplit(int startIndex, String[] string, String seperator) {
StringBuilder builder = new StringBuilder();
for (int i = startIndex; i < string.length; i++) {
builder.append(string[i]);
builder.append(seperator);
}
builder.deleteCharAt(builder.length() - seperator.length()); // remove
return builder.toString();
}
public boolean setupEconomy(){
RegisteredServiceProvider<net.milkbowl.vault.economy.Economy> economyProvider = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
return (economy != null);
}
public String formatMessage(String str){
String funnyChar = new Character((char) 167).toString();
str = str.replaceAll("&", funnyChar);
return str;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
String perms = "ultraban.fine";
if (sender instanceof Player){
player = (Player)sender;
//new permissions test before reconstruct
if (Permissions.Security.permission(player, perms)){
auth = true;
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = args[0];
if(autoComplete) p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
boolean broadcast = true;
String amt = args[1]; //set string amount to argument
//Going loud
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
amt = combineSplit(2, args, " ");
}else{
amt = combineSplit(1, args, " ");
}
}
if(victim != null){
if(!broadcast){ //If silent wake his ass up
String fineMsg = config.getString("messages.fineMsgVictim", "You have been fined by %admin% in the amount of %amt%!");
String idoit = victim.getName();
fineMsg = fineMsg.replaceAll("%admin%", admin);
fineMsg = fineMsg.replaceAll("%victim%", idoit);
sender.sendMessage(formatMessage(":S:" + fineMsg));
victim.sendMessage(formatMessage(fineMsg));
}
if(setupEconomy()){
double bal = economy.getBalance(p);
double amtd = Double.valueOf(amt.trim());
if(amtd > bal){
economy.withdrawPlayer(victim.getName(), bal);
}else{
economy.withdrawPlayer(victim.getName(), amtd);
}
}
log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + ".");
plugin.db.addPlayer(p, amt, admin, 0, 4);
if(broadcast){
String idoit = victim.getName();
String fineMsgAll = config.getString("messages.fineMsgBroadcast", "%victim% was fined by %admin% in the amount of %amt%!!");
fineMsgAll = fineMsgAll.replaceAll("%admin%", admin);
fineMsgAll = fineMsgAll.replaceAll("%victim%", idoit);
plugin.getServer().broadcastMessage(formatMessage(fineMsgAll));
return true;
}
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
String perms = "ultraban.fine";
if (sender instanceof Player){
player = (Player)sender;
//new permissions test before reconstruct
if (Permissions.Security.permission(player, perms)){
auth = true;
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = args[0];
if(autoComplete) p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
boolean broadcast = true;
String amt = args[1]; //set string amount to argument
//Going loud
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
amt = combineSplit(2, args, " ");
}else{
amt = combineSplit(1, args, " ");
}
}
if(victim != null){
if(!broadcast){ //If silent wake his ass up
String fineMsg = config.getString("messages.fineMsgVictim", "You have been fined by %admin% in the amount of %amt%!");
String idoit = victim.getName();
fineMsg = fineMsg.replaceAll("%admin%", admin);
fineMsg = fineMsg.replaceAll("%amt%", amt);
fineMsg = fineMsg.replaceAll("%victim%", idoit);
sender.sendMessage(formatMessage(":S:" + fineMsg));
victim.sendMessage(formatMessage(fineMsg));
}
if(setupEconomy()){
double bal = economy.getBalance(p);
double amtd = Double.valueOf(amt.trim());
if(amtd > bal){
economy.withdrawPlayer(victim.getName(), bal);
}else{
economy.withdrawPlayer(victim.getName(), amtd);
}
}
log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + ".");
plugin.db.addPlayer(p, amt, admin, 0, 4);
if(broadcast){
String idoit = victim.getName();
String fineMsgAll = config.getString("messages.fineMsgBroadcast", "%victim% was fined by %admin% in the amount of %amt%!!");
fineMsgAll = fineMsgAll.replaceAll("%admin%", admin);
fineMsgAll = fineMsgAll.replaceAll("%amt%", amt);
fineMsgAll = fineMsgAll.replaceAll("%victim%", idoit);
plugin.getServer().broadcastMessage(formatMessage(fineMsgAll));
return true;
}
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
|
diff --git a/src/org/proofpad/Acl2Parser.java b/src/org/proofpad/Acl2Parser.java
index 7300c85..5c0b384 100644
--- a/src/org/proofpad/Acl2Parser.java
+++ b/src/org/proofpad/Acl2Parser.java
@@ -1,684 +1,684 @@
package org.proofpad;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.*;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rsyntaxtextarea.parser.*;
public class Acl2Parser extends AbstractParser {
private static Logger logger = Logger.getLogger(Acl2Parser.class.toString());
public static class CacheKey implements Serializable {
private static final long serialVersionUID = -4201796432147755450L;
private File book;
private long mtime;
public CacheKey(File book, long mtime) {
this.book = book;
this.mtime = mtime;
}
@Override
public int hashCode() {
return book.hashCode() ^ Long.valueOf(mtime).hashCode();
}
@Override
public boolean equals(Object other) {
return (other instanceof CacheKey &&
((CacheKey) other).book.equals(this.book) &&
((CacheKey) other).mtime == this.mtime);
}
}
private static class Range implements Serializable {
private static final long serialVersionUID = 3510110011135344206L;
public final int lower;
public final int upper;
private Range(int both) {
upper = lower = both;
}
private Range(int lower, int upper) {
this.lower = lower;
this.upper = upper;
}
}
static class CacheSets implements Serializable {
private static final long serialVersionUID = -2233827686979689741L;
public Set<String> functions;
public Set<String> macros;
public Set<String> constants;
}
public Set<String> functions;
public Set<String> macros;
public Set<String> constants;
public File workingDir;
private Map<CacheKey, CacheSets> cache = Main.cache.getBookCache();
private File acl2Dir;
public Acl2Parser(File workingDir, File acl2Dir) {
this(null, workingDir, acl2Dir);
}
public Acl2Parser(CodePane codePane, File workingDir, File acl2Dir) {
this.workingDir = workingDir;
this.acl2Dir = acl2Dir;
}
private static Map<String, Range> paramCounts = new HashMap<String, Range>();
static {
paramCounts.put("-", new Range(1, 2));
paramCounts.put("/", new Range(1, 2));
paramCounts.put("/=", new Range(2, 2));
paramCounts.put("1+", new Range(1, 1));
paramCounts.put("1-", new Range(1, 1));
paramCounts.put("<=", new Range(2, 2));
paramCounts.put(">", new Range(2, 2));
paramCounts.put(">=", new Range(2, 2));
paramCounts.put("abs", new Range(1, 1));
paramCounts.put("acl2-numberp", new Range(1, 1));
paramCounts.put("acons", new Range(3, 3));
paramCounts.put("add-to-set-eq", new Range(2, 2));
paramCounts.put("add-to-set-eql", new Range(2, 2));
paramCounts.put("add-to-set-equal", new Range(2, 2));
paramCounts.put("alistp", new Range(1, 1));
paramCounts.put("alpha-char-p", new Range(1, 1));
paramCounts.put("alphorder", new Range(2, 2));
paramCounts.put("ash", new Range(2, 2));
paramCounts.put("assert$", new Range(2, 2));
paramCounts.put("assoc-eq", new Range(2, 2));
paramCounts.put("assoc-equal", new Range(2, 2));
paramCounts.put("assoc-keyword", new Range(2, 2));
paramCounts.put("atom", new Range(1, 1));
paramCounts.put("atom-listp", new Range(1, 1));
paramCounts.put("binary-*", new Range(2, 2));
paramCounts.put("binary-+", new Range(2, 2));
paramCounts.put("binary-append", new Range(2, 2));
paramCounts.put("boole$", new Range(3, 3));
paramCounts.put("booleanp", new Range(1, 1));
paramCounts.put("butlast", new Range(2, 2));
paramCounts.put("caaaar", new Range(1, 1));
paramCounts.put("caaadr", new Range(1, 1));
paramCounts.put("caaar", new Range(1, 1));
paramCounts.put("caadar", new Range(1, 1));
paramCounts.put("caaddr", new Range(1, 1));
paramCounts.put("caadr", new Range(1, 1));
paramCounts.put("caar", new Range(1, 1));
paramCounts.put("cadaar", new Range(1, 1));
paramCounts.put("cadadr", new Range(1, 1));
paramCounts.put("cadar", new Range(1, 1));
paramCounts.put("caddar", new Range(1, 1));
paramCounts.put("cadddr", new Range(1, 1));
paramCounts.put("caddr", new Range(1, 1));
paramCounts.put("cadr", new Range(1, 1));
paramCounts.put("car", new Range(1, 1));
paramCounts.put("cdaaar", new Range(1, 1));
paramCounts.put("cdaadr", new Range(1, 1));
paramCounts.put("cdaar", new Range(1, 1));
paramCounts.put("cdadar", new Range(1, 1));
paramCounts.put("cdaddr", new Range(1, 1));
paramCounts.put("cdadr", new Range(1, 1));
paramCounts.put("cdar", new Range(1, 1));
paramCounts.put("cddaar", new Range(1, 1));
paramCounts.put("cddadr", new Range(1, 1));
paramCounts.put("cddar", new Range(1, 1));
paramCounts.put("cdddar", new Range(1, 1));
paramCounts.put("cddddr", new Range(1, 1));
paramCounts.put("cdddr", new Range(1, 1));
paramCounts.put("cddr", new Range(1, 1));
paramCounts.put("cdr", new Range(1, 1));
paramCounts.put("ceiling", new Range(2, 2));
paramCounts.put("char", new Range(2, 2));
paramCounts.put("char-code", new Range(1, 1));
paramCounts.put("char-downcase", new Range(1, 1));
paramCounts.put("char-equal", new Range(2, 2));
paramCounts.put("char-upcase", new Range(1, 1));
paramCounts.put("char<", new Range(2, 2));
paramCounts.put("char<=", new Range(2, 2));
paramCounts.put("char>", new Range(2, 2));
paramCounts.put("char>=", new Range(2, 2));
paramCounts.put("character-alistp", new Range(1, 1));
paramCounts.put("character-listp", new Range(1, 1));
paramCounts.put("characterp", new Range(1, 1));
paramCounts.put("code-char", new Range(1, 1));
paramCounts.put("coerce", new Range(2, 2));
paramCounts.put("comp", new Range(1, 1));
paramCounts.put("comp-gcl", new Range(1, 1));
paramCounts.put("complex", new Range(2, 2));
paramCounts.put("complex-rationalp", new Range(1, 1));
paramCounts.put("complex/complex-rationalp", new Range(1, 1));
paramCounts.put("conjugate", new Range(1, 1));
paramCounts.put("cons", new Range(2, 2));
paramCounts.put("consp", new Range(1, 1));
paramCounts.put("cpu-core-count", new Range(1, 1));
paramCounts.put("delete-assoc-eq", new Range(2, 2));
paramCounts.put("denominator", new Range(1, 1));
paramCounts.put("digit-char-p", new Range(1, 2));
paramCounts.put("digit-to-char", new Range(1, 1));
paramCounts.put("ec-call", new Range(1, 1));
paramCounts.put("eighth", new Range(1, 1));
paramCounts.put("endp", new Range(1, 1));
paramCounts.put("eq", new Range(2, 2));
paramCounts.put("eql", new Range(2, 2));
paramCounts.put("eqlable-alistp", new Range(1, 1));
paramCounts.put("eqlable-listp", new Range(1, 1));
paramCounts.put("eqlablep", new Range(1, 1));
paramCounts.put("equal", new Range(2, 2));
paramCounts.put("error1", new Range(4, 4));
paramCounts.put("evenp", new Range(1, 1));
paramCounts.put("explode-nonnegative-integer", new Range(3, 5));
paramCounts.put("expt", new Range(2, 2));
paramCounts.put("fifth", new Range(1, 1));
paramCounts.put("first", new Range(1, 1));
paramCounts.put("fix", new Range(1, 1));
paramCounts.put("fix-true-list", new Range(1, 1));
paramCounts.put("floor", new Range(2, 2));
paramCounts.put("fms", new Range(5, 5));
paramCounts.put("fms!", new Range(5, 5));
paramCounts.put("fmt", new Range(5, 5));
paramCounts.put("fmt!", new Range(5, 5));
paramCounts.put("fmt1", new Range(6, 6));
paramCounts.put("fmt1!", new Range(6, 6));
paramCounts.put("fourth", new Range(1, 1));
paramCounts.put("get-output-stream-string$", new Range(2, 4));
paramCounts.put("getenv$", new Range(2, 2));
paramCounts.put("getprop", new Range(5, 5));
paramCounts.put("good-atom-listp", new Range(1, 1));
paramCounts.put("hard-error", new Range(3, 3));
paramCounts.put("identity", new Range(1, 1));
paramCounts.put("if", new Range(3, 3));
paramCounts.put("iff", new Range(2, 2));
paramCounts.put("ifix", new Range(1, 1));
paramCounts.put("illegal", new Range(3, 3));
paramCounts.put("imagpart", new Range(1, 1));
paramCounts.put("implies", new Range(2, 2));
paramCounts.put("improper-consp", new Range(1, 1));
paramCounts.put("int=", new Range(2, 2));
paramCounts.put("integer-length", new Range(1, 1));
paramCounts.put("integer-listp", new Range(1, 1));
paramCounts.put("integerp", new Range(1, 1));
paramCounts.put("intern", new Range(2, 2));
paramCounts.put("intern$", new Range(2, 2));
paramCounts.put("intern-in-package-of-symbol", new Range(2, 5));
paramCounts.put("intersectp-eq", new Range(2, 2));
paramCounts.put("intersectp-equal", new Range(2, 2));
paramCounts.put("keywordp", new Range(1, 1));
paramCounts.put("kwote", new Range(1, 1));
paramCounts.put("kwote-lst", new Range(1, 1));
paramCounts.put("last", new Range(1, 1));
paramCounts.put("len", new Range(1, 1));
paramCounts.put("length", new Range(1, 1));
paramCounts.put("lexorder", new Range(2, 2));
paramCounts.put("listp", new Range(1, 1));
paramCounts.put("logandc1", new Range(2, 2));
paramCounts.put("logandc2", new Range(2, 2));
paramCounts.put("logbitp", new Range(2, 2));
paramCounts.put("logcount", new Range(1, 1));
paramCounts.put("lognand", new Range(2, 2));
paramCounts.put("lognor", new Range(2, 2));
paramCounts.put("lognot", new Range(1, 1));
paramCounts.put("logorc1", new Range(2, 2));
paramCounts.put("logorc2", new Range(2, 2));
paramCounts.put("logtest", new Range(2, 2));
paramCounts.put("lower-case-p", new Range(1, 1));
paramCounts.put("make-ord", new Range(3, 3));
paramCounts.put("max", new Range(2, 2));
paramCounts.put("mbe1", new Range(2, 2));
paramCounts.put("mbt", new Range(1, 1));
paramCounts.put("member-eq", new Range(2, 2));
paramCounts.put("member-equal", new Range(2, 2));
paramCounts.put("min", new Range(2, 2));
paramCounts.put("minusp", new Range(1, 1));
paramCounts.put("mod", new Range(2, 2));
paramCounts.put("mod-expt", new Range(3, 3));
paramCounts.put("must-be-equal", new Range(2, 2));
paramCounts.put("mv-list", new Range(2, 2));
paramCounts.put("mv-nth", new Range(2, 2));
paramCounts.put("natp", new Range(1, 1));
paramCounts.put("nfix", new Range(1, 1));
paramCounts.put("ninth", new Range(1, 1));
paramCounts.put("no-duplicatesp-eq", new Range(1, 1));
paramCounts.put("nonnegative-integer-quotient", new Range(2, 4));
paramCounts.put("not", new Range(1, 1));
paramCounts.put("nth", new Range(2, 2));
paramCounts.put("nthcdr", new Range(2, 2));
paramCounts.put("null", new Range(1, 1));
paramCounts.put("numerator", new Range(1, 1));
paramCounts.put("o-finp", new Range(1, 1));
paramCounts.put("o-first-coeff", new Range(1, 1));
paramCounts.put("o-first-expt", new Range(1, 1));
paramCounts.put("o-infp", new Range(1, 1));
paramCounts.put("o-p", new Range(1, 1));
paramCounts.put("o-rst", new Range(1, 1));
paramCounts.put("o<", new Range(2, 2));
paramCounts.put("o<=", new Range(2, 2));
paramCounts.put("o>", new Range(2, 2));
paramCounts.put("o>=", new Range(2, 2));
paramCounts.put("oddp", new Range(1, 1));
paramCounts.put("pairlis$", new Range(2, 2));
paramCounts.put("peek-char$", new Range(2, 2));
paramCounts.put("pkg-imports", new Range(1, 1));
paramCounts.put("pkg-witness", new Range(1, 1));
paramCounts.put("plusp", new Range(1, 1));
paramCounts.put("position-eq", new Range(2, 2));
paramCounts.put("position-equal", new Range(2, 2));
paramCounts.put("posp", new Range(1, 1));
paramCounts.put("print-object$", new Range(3, 3));
paramCounts.put("prog2$", new Range(2, 2));
paramCounts.put("proofs-co", new Range(1, 1));
paramCounts.put("proper-consp", new Range(1, 1));
paramCounts.put("put-assoc-eq", new Range(3, 3));
paramCounts.put("put-assoc-eql", new Range(3, 3));
paramCounts.put("put-assoc-equal", new Range(3, 3));
paramCounts.put("putprop", new Range(4, 4));
paramCounts.put("r-eqlable-alistp", new Range(1, 1));
paramCounts.put("r-symbol-alistp", new Range(1, 1));
paramCounts.put("random$", new Range(2, 2));
paramCounts.put("rassoc-eq", new Range(2, 2));
paramCounts.put("rassoc-equal", new Range(2, 2));
paramCounts.put("rational-listp", new Range(1, 1));
paramCounts.put("rationalp", new Range(1, 1));
paramCounts.put("read-byte$", new Range(2, 2));
paramCounts.put("read-char$", new Range(2, 2));
paramCounts.put("read-object", new Range(2, 2));
paramCounts.put("real/rationalp", new Range(1, 1));
paramCounts.put("realfix", new Range(1, 1));
paramCounts.put("realpart", new Range(1, 1));
paramCounts.put("rem", new Range(2, 2));
paramCounts.put("remove-duplicates-eq", new Range(1, 1));
paramCounts.put("remove-duplicates-equal", new Range(1, 6));
paramCounts.put("remove-eq", new Range(2, 2));
paramCounts.put("remove-equal", new Range(2, 2));
paramCounts.put("remove1-eq", new Range(2, 2));
paramCounts.put("remove1-equal", new Range(2, 2));
paramCounts.put("rest", new Range(1, 1));
paramCounts.put("return-last", new Range(3, 3));
paramCounts.put("revappend", new Range(2, 2));
paramCounts.put("reverse", new Range(1, 1));
paramCounts.put("rfix", new Range(1, 1));
paramCounts.put("round", new Range(2, 2));
paramCounts.put("second", new Range(1, 1));
paramCounts.put("set-difference-eq", new Range(2, 2));
paramCounts.put("setenv$", new Range(2, 2));
paramCounts.put("seventh", new Range(1, 1));
paramCounts.put("signum", new Range(1, 1));
paramCounts.put("sixth", new Range(1, 1));
paramCounts.put("standard-char-p", new Range(1, 1));
paramCounts.put("string", new Range(1, 1));
paramCounts.put("string-append", new Range(2, 2));
paramCounts.put("string-downcase", new Range(1, 1));
paramCounts.put("string-equal", new Range(2, 2));
paramCounts.put("string-listp", new Range(1, 1));
paramCounts.put("string-upcase", new Range(1, 1));
paramCounts.put("string<", new Range(2, 2));
paramCounts.put("string<=", new Range(2, 2));
paramCounts.put("string>", new Range(2, 2));
paramCounts.put("string>=", new Range(2, 2));
paramCounts.put("stringp", new Range(1, 1));
paramCounts.put("strip-cars", new Range(1, 1));
paramCounts.put("strip-cdrs", new Range(1, 1));
paramCounts.put("sublis", new Range(2, 2));
paramCounts.put("subseq", new Range(3, 3));
paramCounts.put("subsetp-eq", new Range(2, 2));
paramCounts.put("subsetp-equal", new Range(2, 2));
paramCounts.put("subst", new Range(3, 3));
paramCounts.put("substitute", new Range(3, 3));
paramCounts.put("symbol-<", new Range(2, 2));
paramCounts.put("symbol-alistp", new Range(1, 1));
paramCounts.put("symbol-listp", new Range(1, 1));
paramCounts.put("symbol-name", new Range(1, 1));
paramCounts.put("symbolp", new Range(1, 1));
paramCounts.put("sys-call-status", new Range(1, 1));
paramCounts.put("take", new Range(2, 2));
paramCounts.put("tenth", new Range(1, 1));
paramCounts.put("the", new Range(2, 2));
paramCounts.put("third", new Range(1, 1));
paramCounts.put("true-list-listp", new Range(1, 1));
paramCounts.put("true-listp", new Range(1, 1));
paramCounts.put("truncate", new Range(2, 2));
paramCounts.put("unary--", new Range(1, 1));
paramCounts.put("unary-/", new Range(1, 1));
paramCounts.put("union-equal", new Range(2, 2));
paramCounts.put("update-nth", new Range(3, 3));
paramCounts.put("upper-case-p", new Range(1, 1));
paramCounts.put("with-live-state", new Range(1, 1));
paramCounts.put("write-byte$", new Range(3, 3));
paramCounts.put("xor", new Range(2, 2));
paramCounts.put("zerop", new Range(1, 1));
paramCounts.put("zip", new Range(1, 1));
paramCounts.put("zp", new Range(1, 1));
paramCounts.put("zpf", new Range(1, 1));
paramCounts.put("comp", new Range(1, 1));
paramCounts.put("defconst", new Range(2, 3));
paramCounts.put("defdoc", new Range(2, 2));
paramCounts.put("defpkg", new Range(2, 5));
paramCounts.put("defproxy", new Range(4, 4));
paramCounts.put("local", new Range(1, 1));
paramCounts.put("remove-custom-keyword-hint", new Range(1, 1));
paramCounts.put("set-body", new Range(2, 2));
paramCounts.put("show-custom-keyword-hint-expansion", new Range(1, 1));
paramCounts.put("table", new Range(1, 5));
paramCounts.put("unmemoize", new Range(1, 1));
paramCounts.put("add-binop", new Range(2, 2));
paramCounts.put("add-dive-into-macro", new Range(2, 2));
paramCounts.put("add-include-book-dir", new Range(2, 2));
paramCounts.put("add-macro-alias", new Range(2, 2));
paramCounts.put("add-nth-alias", new Range(2, 2));
paramCounts.put("binop-table", new Range(1, 1));
paramCounts.put("delete-include-book-dir", new Range(1, 1));
paramCounts.put("remove-binop", new Range(1, 1));
paramCounts.put("remove-default-hints", new Range(1, 1));
paramCounts.put("remove-default-hints!", new Range(1, 1));
paramCounts.put("remove-dive-into-macro", new Range(1, 1));
paramCounts.put("remove-macro-alias", new Range(1, 1));
paramCounts.put("remove-nth-alias", new Range(1, 1));
paramCounts.put("remove-override-hints", new Range(1, 1));
paramCounts.put("remove-override-hints!", new Range(1, 1));
paramCounts.put("set-backchain-limit", new Range(1, 1));
paramCounts.put("set-bogus-defun-hints-ok", new Range(1, 1));
paramCounts.put("set-bogus-mutual-recursion-ok", new Range(1, 1));
paramCounts.put("set-case-split-limitations", new Range(1, 1));
paramCounts.put("set-checkpoint-summary-limit", new Range(1, 1));
paramCounts.put("set-compile-fns", new Range(1, 1));
paramCounts.put("set-debugger-enable", new Range(1, 1));
paramCounts.put("set-default-backchain-limit", new Range(1, 1));
paramCounts.put("set-default-hints", new Range(1, 1));
paramCounts.put("set-default-hints!", new Range(1, 1));
paramCounts.put("set-deferred-ttag-notes", new Range(2, 6));
paramCounts.put("set-enforce-redundancy", new Range(1, 1));
paramCounts.put("set-gag-mode", new Range(1, 1));
paramCounts.put("set-guard-checking", new Range(1, 1));
paramCounts.put("set-ignore-doc-string-error", new Range(1, 1));
paramCounts.put("set-ignore-ok", new Range(1, 1));
paramCounts.put("set-inhibit-output-lst", new Range(1, 1));
paramCounts.put("set-inhibited-summary-types", new Range(1, 1));
paramCounts.put("set-invisible-fns-table", new Range(1, 1));
paramCounts.put("set-irrelevant-formals-ok", new Range(1, 1));
paramCounts.put("set-ld-keyword-aliases", new Range(2, 6));
paramCounts.put("set-ld-redefinition-action", new Range(2, 5));
paramCounts.put("set-ld-skip-proofs", new Range(2, 2));
paramCounts.put("set-let*-abstraction", new Range(1, 1));
paramCounts.put("set-let*-abstractionp", new Range(1, 1));
paramCounts.put("set-match-free-default", new Range(1, 1));
paramCounts.put("set-match-free-error", new Range(1, 1));
paramCounts.put("set-measure-function", new Range(1, 1));
paramCounts.put("set-non-linear", new Range(1, 1));
paramCounts.put("set-non-linearp", new Range(1, 1));
paramCounts.put("set-nu-rewriter-mode", new Range(1, 1));
paramCounts.put("set-override-hints", new Range(1, 1));
paramCounts.put("set-override-hints!", new Range(1, 1));
paramCounts.put("set-print-clause-ids", new Range(1, 1));
paramCounts.put("set-prover-step-limit", new Range(1, 1));
paramCounts.put("set-raw-mode", new Range(1, 1));
paramCounts.put("set-raw-proof-format", new Range(1, 1));
paramCounts.put("set-rewrite-stack-limit", new Range(1, 1));
paramCounts.put("set-ruler-extenders", new Range(1, 1));
paramCounts.put("set-rw-cache-state", new Range(1, 1));
paramCounts.put("set-rw-cache-state!", new Range(1, 1));
paramCounts.put("set-saved-output", new Range(2, 2));
paramCounts.put("set-state-ok", new Range(1, 1));
paramCounts.put("set-tainted-ok", new Range(1, 1));
paramCounts.put("set-tainted-okp", new Range(1, 1));
paramCounts.put("set-verify-guards-eagerness", new Range(1, 1));
paramCounts.put("set-waterfall-parallelism", new Range(1, 2));
paramCounts.put("set-waterfall-printing", new Range(1, 1));
paramCounts.put("set-well-founded-relation", new Range(1, 1));
paramCounts.put("set-write-acl2x", new Range(2, 2));
paramCounts.put("with-guard-checking", new Range(2, 2));
}
public class ParseToken {
public int offset;
public int line;
public String name;
public List<String> params = new ArrayList<String>();
public Set<String> vars = new HashSet<String>();
}
public class Acl2ParserNotice extends DefaultParserNotice {
public Acl2ParserNotice(Acl2Parser parser, String msg, int line, int offs, int len, int level) {
super(parser, msg, line, offs, len);
//System.out.println("ERROR on line " + line + ": " + msg);
setLevel(level);
}
public Acl2ParserNotice(Acl2Parser parser, String msg,
ParseToken top, int end) {
this(parser, msg, top.line, top.offset, end - top.offset, ERROR);
}
public Acl2ParserNotice(Acl2Parser parser, String msg, int line,
Token token, int level) {
this(parser, msg, line, token.offset, token.textCount, level);
}
public Color getColor() {
if (getLevel() == ERROR) {
return Color.RED;
} else if (getLevel() == INFO) {
return null;
} else {
return null;
}
}
@Override
public boolean getShowInEditor() {
return getLevel() != INFO;
}
}
@Override
public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
- "declare", "include-book", "defproperty"
+ "declare", "include-book", "defproperty", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
if (!s.empty() && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
functions.add(token.getLexeme().toLowerCase());
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
macros.add(token.getLexeme());
} else if (top.name.equals("defconst") && top.params.size() == 1) {
constants.add(token.getLexeme());
String constName = token.getLexeme();
if (!constName.startsWith("*") || !constName.endsWith("*")) {
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = (parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1));
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (s.empty()) {
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top != null && top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(acl2Dir, "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(acl2Dir, "dracula");
} else {
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
// TODO: Progress indicator.
bookCache = parseBook(book, acl2Dir, cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
result.addNotice(new Acl2ParserNotice(this, "File could not be found", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (!s.empty() && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
result.addNotice(new Acl2ParserNotice(this, "<html><b>" +
htmlEncode(top.name) + "</b> is undefined.</html>",
line, token, ParserNotice.ERROR));
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">Cmd+? for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() + " is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
return result;
}
public static CacheSets parseBook(File book, File acl2Dir, Map<CacheKey, CacheSets> cache) throws FileNotFoundException,
BadLocationException {
CacheSets bookCache;
Scanner bookScanner = new Scanner(book);
bookScanner.useDelimiter("\\Z");
String bookContents = bookScanner.next();
logger.info("PARSING: " + book);
book.lastModified();
Acl2Parser bookParser = new Acl2Parser(book.getParentFile(), acl2Dir);
bookParser.cache = cache;
RSyntaxDocument bookDoc = new IdeDocument(null);
bookDoc.insertString(0, bookContents, null);
bookParser.parse(bookDoc, null);
bookCache = new CacheSets();
bookCache.functions = bookParser.functions;
bookCache.constants = bookParser.constants;
bookCache.macros = bookParser.macros;
return bookCache;
}
private String htmlEncode(String name) {
return name.replace("&", "&").replace("<", "<").replace(">", ">");
}
}
| true | true | public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defproperty"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
if (!s.empty() && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
functions.add(token.getLexeme().toLowerCase());
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
macros.add(token.getLexeme());
} else if (top.name.equals("defconst") && top.params.size() == 1) {
constants.add(token.getLexeme());
String constName = token.getLexeme();
if (!constName.startsWith("*") || !constName.endsWith("*")) {
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = (parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1));
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (s.empty()) {
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top != null && top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(acl2Dir, "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(acl2Dir, "dracula");
} else {
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
// TODO: Progress indicator.
bookCache = parseBook(book, acl2Dir, cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
result.addNotice(new Acl2ParserNotice(this, "File could not be found", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (!s.empty() && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
result.addNotice(new Acl2ParserNotice(this, "<html><b>" +
htmlEncode(top.name) + "</b> is undefined.</html>",
line, token, ParserNotice.ERROR));
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">Cmd+? for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() + " is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
return result;
}
| public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defproperty", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
if (!s.empty() && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
functions.add(token.getLexeme().toLowerCase());
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
macros.add(token.getLexeme());
} else if (top.name.equals("defconst") && top.params.size() == 1) {
constants.add(token.getLexeme());
String constName = token.getLexeme();
if (!constName.startsWith("*") || !constName.endsWith("*")) {
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = (parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1));
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (s.empty()) {
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top != null && top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(acl2Dir, "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(acl2Dir, "dracula");
} else {
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
// TODO: Progress indicator.
bookCache = parseBook(book, acl2Dir, cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
result.addNotice(new Acl2ParserNotice(this, "File could not be found", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (!s.empty() && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
result.addNotice(new Acl2ParserNotice(this, "<html><b>" +
htmlEncode(top.name) + "</b> is undefined.</html>",
line, token, ParserNotice.ERROR));
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">Cmd+? for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() + " is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
return result;
}
|
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/ui/listeners/SubtitleSpinnerOnItemSelectedListener.java b/serenity-app/src/main/java/us/nineworlds/serenity/ui/listeners/SubtitleSpinnerOnItemSelectedListener.java
index 2e98580c..907f4e81 100644
--- a/serenity-app/src/main/java/us/nineworlds/serenity/ui/listeners/SubtitleSpinnerOnItemSelectedListener.java
+++ b/serenity-app/src/main/java/us/nineworlds/serenity/ui/listeners/SubtitleSpinnerOnItemSelectedListener.java
@@ -1,92 +1,92 @@
/**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* 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 us.nineworlds.serenity.ui.listeners;
import us.nineworlds.serenity.core.model.VideoContentInfo;
import us.nineworlds.serenity.core.model.impl.Subtitle;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* @author dcarver
*
*/
public class SubtitleSpinnerOnItemSelectedListener implements
OnItemSelectedListener {
private VideoContentInfo video;
private boolean firstSelection = true;
private static SharedPreferences preferences;
public SubtitleSpinnerOnItemSelectedListener(VideoContentInfo video,
Context context) {
this.video = video;
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Subtitle subtitle = null;
if (firstSelection) {
boolean automaticallySelectSubtitle = preferences.getBoolean(
"automatic_subtitle_selection", false);
if (automaticallySelectSubtitle) {
String languageCode = preferences.getString(
"preferred_subtitle_language", "");
if (languageCode != "") {
for (int i = 0; i < parent.getAdapter().getCount(); i++) {
subtitle = (Subtitle) parent.getItemAtPosition(i);
if (languageCode.equals(subtitle.getLanguageCode())) {
parent.setSelection(i);
continue;
}
}
- firstSelection = false;
}
}
+ firstSelection = false;
} else {
subtitle = (Subtitle) parent.getItemAtPosition(position);
}
video.setSubtitle(subtitle);
}
/*
* (non-Javadoc)
*
* @see
* android.widget.AdapterView.OnItemSelectedListener#onNothingSelected(android
* .widget.AdapterView)
*/
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
| false | true | public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Subtitle subtitle = null;
if (firstSelection) {
boolean automaticallySelectSubtitle = preferences.getBoolean(
"automatic_subtitle_selection", false);
if (automaticallySelectSubtitle) {
String languageCode = preferences.getString(
"preferred_subtitle_language", "");
if (languageCode != "") {
for (int i = 0; i < parent.getAdapter().getCount(); i++) {
subtitle = (Subtitle) parent.getItemAtPosition(i);
if (languageCode.equals(subtitle.getLanguageCode())) {
parent.setSelection(i);
continue;
}
}
firstSelection = false;
}
}
} else {
subtitle = (Subtitle) parent.getItemAtPosition(position);
}
video.setSubtitle(subtitle);
}
| public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Subtitle subtitle = null;
if (firstSelection) {
boolean automaticallySelectSubtitle = preferences.getBoolean(
"automatic_subtitle_selection", false);
if (automaticallySelectSubtitle) {
String languageCode = preferences.getString(
"preferred_subtitle_language", "");
if (languageCode != "") {
for (int i = 0; i < parent.getAdapter().getCount(); i++) {
subtitle = (Subtitle) parent.getItemAtPosition(i);
if (languageCode.equals(subtitle.getLanguageCode())) {
parent.setSelection(i);
continue;
}
}
}
}
firstSelection = false;
} else {
subtitle = (Subtitle) parent.getItemAtPosition(position);
}
video.setSubtitle(subtitle);
}
|
diff --git a/pipe-gui/src/test/java/pipe/actions/type/AnnotationActionTest.java b/pipe-gui/src/test/java/pipe/actions/type/AnnotationActionTest.java
index e96a9ee8..ffb722b4 100644
--- a/pipe-gui/src/test/java/pipe/actions/type/AnnotationActionTest.java
+++ b/pipe-gui/src/test/java/pipe/actions/type/AnnotationActionTest.java
@@ -1,68 +1,68 @@
package pipe.actions.type;
import matchers.component.HasAnnotationFields;
import matchers.component.HasMultiple;
import org.junit.Before;
import org.junit.Test;
import pipe.controllers.PetriNetController;
import pipe.gui.Constants;
import pipe.historyActions.AddPetriNetObject;
import pipe.historyActions.HistoryManager;
import pipe.models.component.annotation.Annotation;
import pipe.models.petrinet.PetriNet;
import java.awt.*;
import java.awt.event.MouseEvent;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.*;
public class AnnotationActionTest {
private PetriNetController mockController;
private HistoryManager mockHistory;
private PetriNet mockNet;
private AnnotationAction action;
@Before
public void setUp() {
action = new AnnotationAction("Annotation", Constants.ANNOTATION, "Add an annotation", "N");
mockController = mock(PetriNetController.class);
mockNet = mock(PetriNet.class);
when(mockController.getPetriNet()).thenReturn(mockNet);
mockHistory = mock(HistoryManager.class);
when(mockController.getHistoryManager()).thenReturn(mockHistory);
}
@Test
public void createsAnnotationOnClick() {
Point point = new Point(10, 20);
MouseEvent mockEvent = mock(MouseEvent.class);
when(mockEvent.getClickCount()).thenReturn(1);
when(mockEvent.getPoint()).thenReturn(point);
action.doAction(mockEvent, mockController);
verify(mockNet).addAnnotaiton(
- argThat(new HasMultiple<Annotation>(new HasAnnotationFields("", 10, 20, 50, 50))));
+ argThat(new HasMultiple<Annotation>(new HasAnnotationFields("Enter text here", 10, 20, 100, 50))));
}
@Test
public void createsUndoOnClickAction() {
Point point = new Point(10, 20);
MouseEvent mockEvent = mock(MouseEvent.class);
when(mockEvent.getClickCount()).thenReturn(1);
when(mockEvent.getPoint()).thenReturn(point);
action.doAction(mockEvent, mockController);
verify(mockHistory).addNewEdit(any(AddPetriNetObject.class));
}
}
| true | true | public void createsAnnotationOnClick() {
Point point = new Point(10, 20);
MouseEvent mockEvent = mock(MouseEvent.class);
when(mockEvent.getClickCount()).thenReturn(1);
when(mockEvent.getPoint()).thenReturn(point);
action.doAction(mockEvent, mockController);
verify(mockNet).addAnnotaiton(
argThat(new HasMultiple<Annotation>(new HasAnnotationFields("", 10, 20, 50, 50))));
}
| public void createsAnnotationOnClick() {
Point point = new Point(10, 20);
MouseEvent mockEvent = mock(MouseEvent.class);
when(mockEvent.getClickCount()).thenReturn(1);
when(mockEvent.getPoint()).thenReturn(point);
action.doAction(mockEvent, mockController);
verify(mockNet).addAnnotaiton(
argThat(new HasMultiple<Annotation>(new HasAnnotationFields("Enter text here", 10, 20, 100, 50))));
}
|
diff --git a/merger/src/main/java/com/metamx/druid/merger/worker/executor/ExecutorMain.java b/merger/src/main/java/com/metamx/druid/merger/worker/executor/ExecutorMain.java
index b55060b3f1..f495aad646 100644
--- a/merger/src/main/java/com/metamx/druid/merger/worker/executor/ExecutorMain.java
+++ b/merger/src/main/java/com/metamx/druid/merger/worker/executor/ExecutorMain.java
@@ -1,73 +1,73 @@
/*
* Druid - a distributed column store.
* Copyright (C) 2012 Metamarkets Group Inc.
*
* 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 com.metamx.druid.merger.worker.executor;
import com.metamx.common.lifecycle.Lifecycle;
import com.metamx.common.logger.Logger;
import com.metamx.druid.log.LogLevelAdjuster;
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
/**
*/
public class ExecutorMain
{
private static final Logger log = new Logger(ExecutorMain.class);
public static void main(String[] args) throws Exception
{
LogLevelAdjuster.register();
- if (args.length != 3) {
+ if (args.length != 2) {
log.info("Usage: ExecutorMain <task.json> <status.json>");
System.exit(2);
}
Iterator<String> arguments = Arrays.asList(args).iterator();
final String taskJsonFile = arguments.next();
final String statusJsonFile = arguments.next();
final ExecutorNode node = ExecutorNode.builder()
.build(
System.getProperty("druid.executor.nodeType", "indexer-executor"),
new ExecutorLifecycleFactory(
new File(taskJsonFile),
new File(statusJsonFile),
System.in
)
);
final Lifecycle lifecycle = new Lifecycle();
lifecycle.addManagedInstance(node);
try {
lifecycle.start();
node.join();
lifecycle.stop();
}
catch (Throwable t) {
log.info(t, "Throwable caught at startup, committing seppuku");
System.exit(2);
}
}
}
| true | true | public static void main(String[] args) throws Exception
{
LogLevelAdjuster.register();
if (args.length != 3) {
log.info("Usage: ExecutorMain <task.json> <status.json>");
System.exit(2);
}
Iterator<String> arguments = Arrays.asList(args).iterator();
final String taskJsonFile = arguments.next();
final String statusJsonFile = arguments.next();
final ExecutorNode node = ExecutorNode.builder()
.build(
System.getProperty("druid.executor.nodeType", "indexer-executor"),
new ExecutorLifecycleFactory(
new File(taskJsonFile),
new File(statusJsonFile),
System.in
)
);
final Lifecycle lifecycle = new Lifecycle();
lifecycle.addManagedInstance(node);
try {
lifecycle.start();
node.join();
lifecycle.stop();
}
catch (Throwable t) {
log.info(t, "Throwable caught at startup, committing seppuku");
System.exit(2);
}
}
| public static void main(String[] args) throws Exception
{
LogLevelAdjuster.register();
if (args.length != 2) {
log.info("Usage: ExecutorMain <task.json> <status.json>");
System.exit(2);
}
Iterator<String> arguments = Arrays.asList(args).iterator();
final String taskJsonFile = arguments.next();
final String statusJsonFile = arguments.next();
final ExecutorNode node = ExecutorNode.builder()
.build(
System.getProperty("druid.executor.nodeType", "indexer-executor"),
new ExecutorLifecycleFactory(
new File(taskJsonFile),
new File(statusJsonFile),
System.in
)
);
final Lifecycle lifecycle = new Lifecycle();
lifecycle.addManagedInstance(node);
try {
lifecycle.start();
node.join();
lifecycle.stop();
}
catch (Throwable t) {
log.info(t, "Throwable caught at startup, committing seppuku");
System.exit(2);
}
}
|
diff --git a/src/com/titanium/ebaybottom/controller/PrivateMessage.java b/src/com/titanium/ebaybottom/controller/PrivateMessage.java
index 0ed94e7..eab987c 100644
--- a/src/com/titanium/ebaybottom/controller/PrivateMessage.java
+++ b/src/com/titanium/ebaybottom/controller/PrivateMessage.java
@@ -1,178 +1,178 @@
package com.titanium.ebaybottom.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringEscapeUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.titanium.ebaybottom.model.Item;
import com.titanium.ebaybottom.model.Pair;
import com.titanium.ebaybottom.selenium.WebWindow;
import com.titanium.ebaybottom.selenium.WebdriverHelper;
import com.titanium.ebaybottom.ui.TextIO;
import com.titanium.ebaybottom.ui.UI;
public class PrivateMessage {
private static final String ITEM_MESSAGE_BASE = "http://contact.ebay.com/ws/eBayISAPI.dll?ShowSellerFAQ&";
private static final String PERSONAL_MESSAGE_BASE = "http://contact.ebay.com/ws/eBayISAPI.dll?ContactUserNextGen&recipient=";
private static final String CAPTCHA_ID = "tokenText";
private static final String PRIVATEMESSAGE_TITLE_ID = "qusetOther_cnt_cnt";
private static final String PRIVATEMESSAGE_BODY_ID = "msg_cnt_cnt";
public static List<Item> items = new ArrayList<>();
public static List<Pair<String, String>> messages = new ArrayList<>();
private static WebDriver driver;
public static void addToMessageQue(Item selectedItem,
Pair<String, String> msg) {
UI.printDebug("MSG QUEUE ADD:" + selectedItem.toString() + " " + msg);
items.add(selectedItem);
messages.add(msg);
}
public static void sendMessagesInQueue(
Pair<String, String> selectedUserAccount) {
UI.printUI("Starting private message sending setup...");
// if (driver == null)
driver = Network.logIn(selectedUserAccount);
for (int i = 0; i < items.size(); i++) {
Item selectedItem = items.get(i);
Pair<String, String> selectedMessage = messages.get(i);
- if (!driver.getCurrentUrl().contains(
- "contact.ebay.com/ws/eBayISAPI.dll?")) {
- driver.get(composeMessageUrl(selectedItem));
- } else {
+// if (!driver.getCurrentUrl().contains(
+// "contact.ebay.com/ws/eBayISAPI.dll?")) {
+// driver.get(composeMessageUrl(selectedItem));
+// } else {
new WebWindow(driver, composeMessageUrl(selectedItem));
- }
+// }
// select other
// <input type="radio" style="margin-top:0px;margin-top:-2px\9;"
// name="cat" value="5" id="Other">
WebElement radio = WebdriverHelper.findElementById(driver, "Other");
if (radio != null && !radio.isSelected())
radio.click();
// continue button
// <input type="submit" value="Continue" class="btn btn-m btn-prim"
// style="width:109px;height:33px">
WebElement continueBtn = WebdriverHelper.findElementById(driver,
"continueBtnDiv");
if (continueBtn != null)
continueBtn.submit();
// title
// <input id="qusetOther_cnt_cnt" class="gryFnt" type="text"
// name="qusetOther_cnt_cnt" size="50" maxlength="32" value=""
// style="display: inline;">
// if (findElementById(driver, "qusetOther_cnt_cnt") != null)
// findElementById(driver, "qusetOther_cnt_cnt").sendKeys(
// selectedMessage.getKey());
if (WebdriverHelper
.findElementById(driver, PRIVATEMESSAGE_TITLE_ID) != null) {
WebdriverHelper.setInstantKeys(driver, PRIVATEMESSAGE_TITLE_ID,
selectedMessage.getKey());
WebdriverHelper
.findElementById(driver, PRIVATEMESSAGE_TITLE_ID)
.click();
}
// message
// <textarea id="msg_cnt_cnt" class="gryFnt"
// defval="Enter your question here..." name="msg_cnt_cnt" cols="70"
// rows="5" style="display: inline;"></textarea>
// if (findElementById(driver, "msg_cnt_cnt") != null)
// findElementById(driver, "msg_cnt_cnt").sendKeys(
// selectedMessage.getValue());
if (findMessageBodyTextbox() != null) {
WebdriverHelper.setInstantKeys(
driver,
PRIVATEMESSAGE_BODY_ID,
selectedMessage.getValue().replace(
Config.PERSONAL_MESSAGE_ADDON, ""));
findMessageBodyTextbox().click();
}
// captcha highlight
if (findCaptchaTextbox() != null) {
findCaptchaTextbox().click();
// onresume website highlight captcha HACK
injectJavascriptOnResumeHighlightCaptchaTextbox();
} else {
// captcha is used to determine if we are able to send messages
// or not, if captcha doesn't exist, then message sending is not
// allowed and we have to redirect user to send personal message
// page
String username = selectedItem.getSellerInfo().get(0)
.getSellerUserName().get(0);
driver.get(PERSONAL_MESSAGE_BASE + username);
String messageAddonFinal = Config.personalMessageAddon
+ " Nr. " + selectedItem.getItemId().get(0) + " "
+ selectedItem.getTitle().get(0) + ".";
String finalMEssage = selectedMessage.getValue().replace(
Config.PERSONAL_MESSAGE_ADDON, messageAddonFinal);
if (findMessageBodyTextbox() != null) {
WebdriverHelper.setInstantKeys(driver,
PRIVATEMESSAGE_BODY_ID, finalMEssage);
findMessageBodyTextbox().click();
}
// captcha highlight
if (findCaptchaTextbox() != null) {
findCaptchaTextbox().click();
injectJavascriptOnResumeHighlightCaptchaTextbox();
}
}
}
UI.printUI("Message sending setup finished");
}
private static WebElement findMessageBodyTextbox() {
return WebdriverHelper.findElementById(driver, PRIVATEMESSAGE_BODY_ID);
}
private static WebElement findCaptchaTextbox() {
return WebdriverHelper.findElementById(driver, CAPTCHA_ID);
}
private static void injectJavascriptOnResumeHighlightCaptchaTextbox() {
JavascriptExecutor js2 = (JavascriptExecutor) driver;
String onFocusFocus = "var s = document.createElement('script'); s.type = 'text/javascript'; "
+ "var code = 'window.onfocus = function () {document.getElementById(\"tokenText\").focus();}';"
+ "try {s.appendChild(document.createTextNode(code)); document.body.appendChild(s); } catch (e) {s.text = code; document.body.appendChild(s);}";
js2.executeScript(onFocusFocus);
}
private static String composeMessageUrl(Item i) {
String s = String
.format(ITEM_MESSAGE_BASE
+ "iid=%s&requested=%s&redirect=0&ssPageName=PageSellerM2MFAQ_VI",
i.getItemId().get(0), i.getSellerInfo().get(0)
.getSellerUserName().get(0));
UI.printDebug("MSG URL: " + s);
return s;
}
}
| false | true | public static void sendMessagesInQueue(
Pair<String, String> selectedUserAccount) {
UI.printUI("Starting private message sending setup...");
// if (driver == null)
driver = Network.logIn(selectedUserAccount);
for (int i = 0; i < items.size(); i++) {
Item selectedItem = items.get(i);
Pair<String, String> selectedMessage = messages.get(i);
if (!driver.getCurrentUrl().contains(
"contact.ebay.com/ws/eBayISAPI.dll?")) {
driver.get(composeMessageUrl(selectedItem));
} else {
new WebWindow(driver, composeMessageUrl(selectedItem));
}
// select other
// <input type="radio" style="margin-top:0px;margin-top:-2px\9;"
// name="cat" value="5" id="Other">
WebElement radio = WebdriverHelper.findElementById(driver, "Other");
if (radio != null && !radio.isSelected())
radio.click();
// continue button
// <input type="submit" value="Continue" class="btn btn-m btn-prim"
// style="width:109px;height:33px">
WebElement continueBtn = WebdriverHelper.findElementById(driver,
"continueBtnDiv");
if (continueBtn != null)
continueBtn.submit();
// title
// <input id="qusetOther_cnt_cnt" class="gryFnt" type="text"
// name="qusetOther_cnt_cnt" size="50" maxlength="32" value=""
// style="display: inline;">
// if (findElementById(driver, "qusetOther_cnt_cnt") != null)
// findElementById(driver, "qusetOther_cnt_cnt").sendKeys(
// selectedMessage.getKey());
if (WebdriverHelper
.findElementById(driver, PRIVATEMESSAGE_TITLE_ID) != null) {
WebdriverHelper.setInstantKeys(driver, PRIVATEMESSAGE_TITLE_ID,
selectedMessage.getKey());
WebdriverHelper
.findElementById(driver, PRIVATEMESSAGE_TITLE_ID)
.click();
}
// message
// <textarea id="msg_cnt_cnt" class="gryFnt"
// defval="Enter your question here..." name="msg_cnt_cnt" cols="70"
// rows="5" style="display: inline;"></textarea>
// if (findElementById(driver, "msg_cnt_cnt") != null)
// findElementById(driver, "msg_cnt_cnt").sendKeys(
// selectedMessage.getValue());
if (findMessageBodyTextbox() != null) {
WebdriverHelper.setInstantKeys(
driver,
PRIVATEMESSAGE_BODY_ID,
selectedMessage.getValue().replace(
Config.PERSONAL_MESSAGE_ADDON, ""));
findMessageBodyTextbox().click();
}
// captcha highlight
if (findCaptchaTextbox() != null) {
findCaptchaTextbox().click();
// onresume website highlight captcha HACK
injectJavascriptOnResumeHighlightCaptchaTextbox();
} else {
// captcha is used to determine if we are able to send messages
// or not, if captcha doesn't exist, then message sending is not
// allowed and we have to redirect user to send personal message
// page
String username = selectedItem.getSellerInfo().get(0)
.getSellerUserName().get(0);
driver.get(PERSONAL_MESSAGE_BASE + username);
String messageAddonFinal = Config.personalMessageAddon
+ " Nr. " + selectedItem.getItemId().get(0) + " "
+ selectedItem.getTitle().get(0) + ".";
String finalMEssage = selectedMessage.getValue().replace(
Config.PERSONAL_MESSAGE_ADDON, messageAddonFinal);
if (findMessageBodyTextbox() != null) {
WebdriverHelper.setInstantKeys(driver,
PRIVATEMESSAGE_BODY_ID, finalMEssage);
findMessageBodyTextbox().click();
}
// captcha highlight
if (findCaptchaTextbox() != null) {
findCaptchaTextbox().click();
injectJavascriptOnResumeHighlightCaptchaTextbox();
}
}
}
UI.printUI("Message sending setup finished");
}
| public static void sendMessagesInQueue(
Pair<String, String> selectedUserAccount) {
UI.printUI("Starting private message sending setup...");
// if (driver == null)
driver = Network.logIn(selectedUserAccount);
for (int i = 0; i < items.size(); i++) {
Item selectedItem = items.get(i);
Pair<String, String> selectedMessage = messages.get(i);
// if (!driver.getCurrentUrl().contains(
// "contact.ebay.com/ws/eBayISAPI.dll?")) {
// driver.get(composeMessageUrl(selectedItem));
// } else {
new WebWindow(driver, composeMessageUrl(selectedItem));
// }
// select other
// <input type="radio" style="margin-top:0px;margin-top:-2px\9;"
// name="cat" value="5" id="Other">
WebElement radio = WebdriverHelper.findElementById(driver, "Other");
if (radio != null && !radio.isSelected())
radio.click();
// continue button
// <input type="submit" value="Continue" class="btn btn-m btn-prim"
// style="width:109px;height:33px">
WebElement continueBtn = WebdriverHelper.findElementById(driver,
"continueBtnDiv");
if (continueBtn != null)
continueBtn.submit();
// title
// <input id="qusetOther_cnt_cnt" class="gryFnt" type="text"
// name="qusetOther_cnt_cnt" size="50" maxlength="32" value=""
// style="display: inline;">
// if (findElementById(driver, "qusetOther_cnt_cnt") != null)
// findElementById(driver, "qusetOther_cnt_cnt").sendKeys(
// selectedMessage.getKey());
if (WebdriverHelper
.findElementById(driver, PRIVATEMESSAGE_TITLE_ID) != null) {
WebdriverHelper.setInstantKeys(driver, PRIVATEMESSAGE_TITLE_ID,
selectedMessage.getKey());
WebdriverHelper
.findElementById(driver, PRIVATEMESSAGE_TITLE_ID)
.click();
}
// message
// <textarea id="msg_cnt_cnt" class="gryFnt"
// defval="Enter your question here..." name="msg_cnt_cnt" cols="70"
// rows="5" style="display: inline;"></textarea>
// if (findElementById(driver, "msg_cnt_cnt") != null)
// findElementById(driver, "msg_cnt_cnt").sendKeys(
// selectedMessage.getValue());
if (findMessageBodyTextbox() != null) {
WebdriverHelper.setInstantKeys(
driver,
PRIVATEMESSAGE_BODY_ID,
selectedMessage.getValue().replace(
Config.PERSONAL_MESSAGE_ADDON, ""));
findMessageBodyTextbox().click();
}
// captcha highlight
if (findCaptchaTextbox() != null) {
findCaptchaTextbox().click();
// onresume website highlight captcha HACK
injectJavascriptOnResumeHighlightCaptchaTextbox();
} else {
// captcha is used to determine if we are able to send messages
// or not, if captcha doesn't exist, then message sending is not
// allowed and we have to redirect user to send personal message
// page
String username = selectedItem.getSellerInfo().get(0)
.getSellerUserName().get(0);
driver.get(PERSONAL_MESSAGE_BASE + username);
String messageAddonFinal = Config.personalMessageAddon
+ " Nr. " + selectedItem.getItemId().get(0) + " "
+ selectedItem.getTitle().get(0) + ".";
String finalMEssage = selectedMessage.getValue().replace(
Config.PERSONAL_MESSAGE_ADDON, messageAddonFinal);
if (findMessageBodyTextbox() != null) {
WebdriverHelper.setInstantKeys(driver,
PRIVATEMESSAGE_BODY_ID, finalMEssage);
findMessageBodyTextbox().click();
}
// captcha highlight
if (findCaptchaTextbox() != null) {
findCaptchaTextbox().click();
injectJavascriptOnResumeHighlightCaptchaTextbox();
}
}
}
UI.printUI("Message sending setup finished");
}
|
diff --git a/tests/src/cgeo/geocaching/files/SimpleDirChooserUITest.java b/tests/src/cgeo/geocaching/files/SimpleDirChooserUITest.java
index 1fe473ca2..b1a464948 100644
--- a/tests/src/cgeo/geocaching/files/SimpleDirChooserUITest.java
+++ b/tests/src/cgeo/geocaching/files/SimpleDirChooserUITest.java
@@ -1,61 +1,62 @@
package cgeo.geocaching.files;
import com.jayway.android.robotium.solo.Solo;
import android.annotation.TargetApi;
import android.os.Build;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.CheckBox;
import java.util.ArrayList;
@TargetApi(Build.VERSION_CODES.FROYO)
public class SimpleDirChooserUITest extends ActivityInstrumentationTestCase2<SimpleDirChooser> {
private Solo solo;
public SimpleDirChooserUITest() {
super(SimpleDirChooser.class);
}
@Override
public void setUp() throws Exception {
solo = new Solo(getInstrumentation(), getActivity());
}
public void testSingleSelection() throws InterruptedException {
final ArrayList<CheckBox> boxes = solo.getCurrentCheckBoxes();
final int lastIndex = boxes.size() - 1;
assertChecked("Newly opened activity", 0);
solo.scrollToBottom();
solo.clickOnCheckBox(lastIndex);
assertTrue(solo.getCurrentCheckBoxes().get(lastIndex).isChecked());
assertFalse(solo.getCurrentCheckBoxes().get(0).isChecked());
assertChecked("Clicked last checkbox", 1);
solo.scrollUp();
Thread.sleep(20);
solo.scrollToBottom();
+ Thread.sleep(20);
assertChecked("Refreshing last checkbox", 1);
solo.scrollToTop();
solo.clickOnCheckBox(0);
assertChecked("Clicked first checkbox", 1);
assertTrue(solo.getCurrentCheckBoxes().get(0).isChecked());
}
private void assertChecked(String message, int expectedChecked) {
int checked = 0;
final ArrayList<CheckBox> boxes = solo.getCurrentCheckBoxes();
assertNotNull("Could not get checkboxes", boxes);
assertTrue("There are no checkboxes", boxes.size() > 1);
for (CheckBox checkBox : boxes) {
if (checkBox.isChecked()) {
checked++;
}
}
assertEquals(message, expectedChecked, checked);
}
}
| true | true | public void testSingleSelection() throws InterruptedException {
final ArrayList<CheckBox> boxes = solo.getCurrentCheckBoxes();
final int lastIndex = boxes.size() - 1;
assertChecked("Newly opened activity", 0);
solo.scrollToBottom();
solo.clickOnCheckBox(lastIndex);
assertTrue(solo.getCurrentCheckBoxes().get(lastIndex).isChecked());
assertFalse(solo.getCurrentCheckBoxes().get(0).isChecked());
assertChecked("Clicked last checkbox", 1);
solo.scrollUp();
Thread.sleep(20);
solo.scrollToBottom();
assertChecked("Refreshing last checkbox", 1);
solo.scrollToTop();
solo.clickOnCheckBox(0);
assertChecked("Clicked first checkbox", 1);
assertTrue(solo.getCurrentCheckBoxes().get(0).isChecked());
}
| public void testSingleSelection() throws InterruptedException {
final ArrayList<CheckBox> boxes = solo.getCurrentCheckBoxes();
final int lastIndex = boxes.size() - 1;
assertChecked("Newly opened activity", 0);
solo.scrollToBottom();
solo.clickOnCheckBox(lastIndex);
assertTrue(solo.getCurrentCheckBoxes().get(lastIndex).isChecked());
assertFalse(solo.getCurrentCheckBoxes().get(0).isChecked());
assertChecked("Clicked last checkbox", 1);
solo.scrollUp();
Thread.sleep(20);
solo.scrollToBottom();
Thread.sleep(20);
assertChecked("Refreshing last checkbox", 1);
solo.scrollToTop();
solo.clickOnCheckBox(0);
assertChecked("Clicked first checkbox", 1);
assertTrue(solo.getCurrentCheckBoxes().get(0).isChecked());
}
|
diff --git a/common/cpw/mods/fml/common/modloader/ModLoaderConnectionHandler.java b/common/cpw/mods/fml/common/modloader/ModLoaderConnectionHandler.java
index 22df7691..f3eadd90 100644
--- a/common/cpw/mods/fml/common/modloader/ModLoaderConnectionHandler.java
+++ b/common/cpw/mods/fml/common/modloader/ModLoaderConnectionHandler.java
@@ -1,61 +1,61 @@
package cpw.mods.fml.common.modloader;
import net.minecraft.server.MinecraftServer;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.NetHandler;
import net.minecraft.src.NetLoginHandler;
import net.minecraft.src.INetworkManager;
import net.minecraft.src.Packet1Login;
import cpw.mods.fml.common.network.IConnectionHandler;
import cpw.mods.fml.common.network.Player;
public class ModLoaderConnectionHandler implements IConnectionHandler
{
private BaseModProxy mod;
public ModLoaderConnectionHandler(BaseModProxy mod)
{
this.mod = mod;
}
@Override
public void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager)
{
mod.onClientLogin((EntityPlayer)player);
}
@Override
public String connectionReceived(NetLoginHandler netHandler, INetworkManager manager)
{
return null;
}
@Override
public void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager)
{
ModLoaderHelper.sidedHelper.clientConnectionOpened(netClientHandler, manager, mod);
}
@Override
public void connectionClosed(INetworkManager manager)
{
- if (!ModLoaderHelper.sidedHelper.clientConnectionClosed(manager, mod))
+ if (ModLoaderHelper.sidedHelper==null || !ModLoaderHelper.sidedHelper.clientConnectionClosed(manager, mod))
{
mod.serverDisconnect();
mod.onClientLogout(manager);
}
}
@Override
public void clientLoggedIn(NetHandler nh, INetworkManager manager, Packet1Login login)
{
mod.serverConnect(nh);
}
@Override
public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager)
{
ModLoaderHelper.sidedHelper.clientConnectionOpened(netClientHandler, manager, mod);
}
}
| true | true | public void connectionClosed(INetworkManager manager)
{
if (!ModLoaderHelper.sidedHelper.clientConnectionClosed(manager, mod))
{
mod.serverDisconnect();
mod.onClientLogout(manager);
}
}
| public void connectionClosed(INetworkManager manager)
{
if (ModLoaderHelper.sidedHelper==null || !ModLoaderHelper.sidedHelper.clientConnectionClosed(manager, mod))
{
mod.serverDisconnect();
mod.onClientLogout(manager);
}
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/osgi/OSGiScriptEngineManager.java b/hazelcast/src/main/java/com/hazelcast/osgi/OSGiScriptEngineManager.java
index f33cd0a157..37ee653509 100644
--- a/hazelcast/src/main/java/com/hazelcast/osgi/OSGiScriptEngineManager.java
+++ b/hazelcast/src/main/java/com/hazelcast/osgi/OSGiScriptEngineManager.java
@@ -1,310 +1,310 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.osgi;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class acts as a delegate for all the available ScriptEngineManagers. Unluckily, the standard did not
* define it as an interface, so we need to extend it to allow polymorphism. However, no calls to super are used.
* It wraps all available ScriptEngineManagers in the OSGi ServicePlatform into a merged ScriptEngineManager.
* <p/>
* Internally, what this class does is creating ScriptEngineManagers for each bundle
* that contains a ScriptEngineFactory and includes a META-INF/services/javax.script.ScriptEngineFactory file.
* It assumes that the file contains a list of @link ScriptEngineFactory classes. For each bundle, it creates a
* ScriptEngineManager, then merges them. @link ScriptEngineFactory objects are wrapped
* into @link OSGiScriptEngineFactory objects to deal with problems of context class loader:
* Those scripting engines that rely on the ContextClassloader for finding resources need to use this wrapper
* and the @link OSGiScriptFactory. Mainly, jruby does.
* <p/>
* Note that even if no context classloader issues arose, it would still be needed to search manually for the
* factories and either use them directly (losing the mimeType/extension/shortName mechanisms for finding engines
* or manually registering them) or still use this class, which would be smarter. In the latter case,
* it would only be needed to remove the hack that temporarily sets the context classloader to the appropriate,
* bundle-related, class loader.
* <p/>
* Caveats:
* <ul><li>
* All factories are wrapped with an {@link OSGiScriptEngineFactory}. As Engines are not wrapped,
* calls like
* <code>
* ScriptEngineManager osgiManager=new OSGiScriptEngineManager(context);<br>
* ScriptEngine engine=osgiManager.getEngineByName("ruby");
* ScriptEngineFactory factory=engine.getFactory() //this does not return the OSGiFactory wrapper
* factory.getScriptEngine(); //this might fail, as it does not use OSGiScriptEngineFactory wrapper
* </code>
* might result in unexpected errors. Future versions may wrap the ScriptEngine with a OSGiScriptEngine to solve this
* issue, but for the moment it is not needed.
* </li>
*/
/*
Imported from Apache Felix project.
http://svn.apache.org/repos/asf/felix/trunk/mishell/src/main/java/org/apache/felix/mishell/OSGiScriptEngineManager.java
*/
public class OSGiScriptEngineManager extends ScriptEngineManager {
private final ILogger logger = Logger.getLogger(getClass());
private Bindings bindings;
private Map<ScriptEngineManager, ClassLoader> classLoaders;
private BundleContext context;
public OSGiScriptEngineManager(BundleContext context) {
this.context = context;
bindings = new SimpleBindings();
this.classLoaders = findManagers(context);
}
/**
* This method is the only one that is visible and not part of the ScriptEngineManager class.
* Its purpose is to find new managers that weren't available before, but keeping the globalScope bindings
* set.
* If you want to clean the bindings you can either get a fresh instance of OSGiScriptManager or
* setting up a new bindings object.
* This can be done with:
* <code>
* ScriptEngineManager manager=new OSGiScriptEngineManager(context);
* (...)//do stuff
* osgiManager=(OSGiScriptEngineManager)manager;//cast to ease reading
* osgiManager.reloadManagers();
* <p/>
* manager.setBindings(new OSGiBindings());//or you can use your own bindings implementation
* <p/>
* </code>
*/
public void reloadManagers() {
this.classLoaders = findManagers(context);
}
@Override
public Object get(String key) {
return bindings.get(key);
}
@Override
public Bindings getBindings() {
return bindings;
}
/**
* Follows the same behavior of @link javax.script.ScriptEngineManager#setBindings(Bindings)
* This means that the same bindings are applied to all the underlying managers.
*
* @param bindings
*/
@Override
public void setBindings(Bindings bindings) {
this.bindings = bindings;
for (ScriptEngineManager manager : classLoaders.keySet()) {
manager.setBindings(bindings);
}
}
@Override
public ScriptEngine getEngineByExtension(String extension) {
//TODO this is a hack to deal with context class loader issues
ScriptEngine engine = null;
for (ScriptEngineManager manager : classLoaders.keySet()) {
Thread currentThread = Thread.currentThread();
ClassLoader old = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(classLoaders.get(manager));
engine = manager.getEngineByExtension(extension);
currentThread.setContextClassLoader(old);
if (engine != null) {
break;
}
}
return engine;
}
@Override
public ScriptEngine getEngineByMimeType(String mimeType) {
//TODO this is a hack to deal with context class loader issues
ScriptEngine engine = null;
for (ScriptEngineManager manager : classLoaders.keySet()) {
Thread currentThread = Thread.currentThread();
ClassLoader old = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(classLoaders.get(manager));
engine = manager.getEngineByMimeType(mimeType);
currentThread.setContextClassLoader(old);
if (engine != null) {
break;
}
}
return engine;
}
@Override
public ScriptEngine getEngineByName(String shortName) {
//TODO this is a hack to deal with context class loader issues
for (ScriptEngineManager manager : classLoaders.keySet()) {
Thread currentThread = Thread.currentThread();
ClassLoader old = currentThread.getContextClassLoader();
ClassLoader contextClassLoader = classLoaders.get(manager);
currentThread.setContextClassLoader(contextClassLoader);
ScriptEngine engine = manager.getEngineByName(shortName);
currentThread.setContextClassLoader(old);
if (engine != null) {
OSGiScriptEngineFactory factory = new OSGiScriptEngineFactory(engine.getFactory(), contextClassLoader);
return new OSGiScriptEngine(engine, factory);
}
}
return null;
}
@Override
public List<ScriptEngineFactory> getEngineFactories() {
List<ScriptEngineFactory> osgiFactories = new ArrayList<ScriptEngineFactory>();
for (ScriptEngineManager engineManager : classLoaders.keySet()) {
for (ScriptEngineFactory factory : engineManager.getEngineFactories()) {
OSGiScriptEngineFactory scriptEngineFactory
= new OSGiScriptEngineFactory(factory, classLoaders.get(engineManager));
osgiFactories.add(scriptEngineFactory);
}
}
return osgiFactories;
}
@Override
public void put(String key, Object value) {
bindings.put(key, value);
}
@Override
public void registerEngineExtension(String extension, ScriptEngineFactory factory) {
for (ScriptEngineManager engineManager : classLoaders.keySet()) {
engineManager.registerEngineExtension(extension, factory);
}
}
@Override
public void registerEngineMimeType(String type, ScriptEngineFactory factory) {
for (ScriptEngineManager engineManager : classLoaders.keySet()) {
engineManager.registerEngineMimeType(type, factory);
}
}
@Override
public void registerEngineName(String name, ScriptEngineFactory factory) {
for (ScriptEngineManager engineManager : classLoaders.keySet()) {
engineManager.registerEngineName(name, factory);
}
}
private Map<ScriptEngineManager, ClassLoader> findManagers(BundleContext context) {
Map<ScriptEngineManager, ClassLoader> managers = new HashMap<ScriptEngineManager, ClassLoader>();
try {
for (String factoryName : findFactoryCandidates(context)) {
ClassLoader factoryClassLoader = loadScriptEngineFactoryClassLoader(factoryName);
if (factoryClassLoader == null) {
continue;
}
createScriptEngineManager(managers, factoryName, factoryClassLoader);
}
return managers;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
private ClassLoader loadScriptEngineFactoryClassLoader(String factoryName) {
//We do not really need the class, but we need the classloader
try {
return Class.forName(factoryName).getClassLoader();
} catch (ClassNotFoundException cnfe) {
// may fail if script implementation is not in environment
logger.warning("Found ScriptEngineFactory candidate for "
+ factoryName + ", but cannot load class! -> " + cnfe);
if (logger.isFinestEnabled()) {
logger.finest(cnfe);
}
return null;
}
}
private void createScriptEngineManager(Map<ScriptEngineManager, ClassLoader> managers, String factoryName,
ClassLoader factoryLoader) {
try {
ScriptEngineManager manager = new ScriptEngineManager(factoryLoader);
manager.setBindings(bindings);
managers.put(manager, factoryLoader);
} catch (Exception e) {
// may fail if script implementation is not in environment
logger.warning("Found ScriptEngineFactory candidate for " + factoryName
+ ", but could not load ScripEngineManager! -> " + e);
if (logger.isFinestEnabled()) {
logger.finest(e);
}
}
}
/**
* Iterates through all bundles to get the available @link ScriptEngineFactory classes
*
* @return the names of the available ScriptEngineFactory classes
* @throws IOException
*/
private List<String> findFactoryCandidates(BundleContext context) throws IOException {
Bundle[] bundles = context.getBundles();
List<String> factoryCandidates = new ArrayList<String>();
for (Bundle bundle : bundles) {
if (bundle.getSymbolicName().equals("system.bundle")) {
continue;
}
Enumeration urls = bundle.findEntries("META-INF/services", "javax.script.ScriptEngineFactory", false);
if (urls == null) {
continue;
}
while (urls.hasMoreElements()) {
URL u = (URL) urls.nextElement();
BufferedReader reader = new BufferedReader(
- new InputStreamReader(u.openStream()));
+ new InputStreamReader(u.openStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.startsWith("#") && line.length() > 0) {
factoryCandidates.add(line);
}
}
reader.close();
}
}
//add java built in JavaScript ScriptEngineFactory's
factoryCandidates.add("com.sun.script.javascript.RhinoScriptEngineFactory");
return factoryCandidates;
}
}
| true | true | private List<String> findFactoryCandidates(BundleContext context) throws IOException {
Bundle[] bundles = context.getBundles();
List<String> factoryCandidates = new ArrayList<String>();
for (Bundle bundle : bundles) {
if (bundle.getSymbolicName().equals("system.bundle")) {
continue;
}
Enumeration urls = bundle.findEntries("META-INF/services", "javax.script.ScriptEngineFactory", false);
if (urls == null) {
continue;
}
while (urls.hasMoreElements()) {
URL u = (URL) urls.nextElement();
BufferedReader reader = new BufferedReader(
new InputStreamReader(u.openStream()));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.startsWith("#") && line.length() > 0) {
factoryCandidates.add(line);
}
}
reader.close();
}
}
//add java built in JavaScript ScriptEngineFactory's
factoryCandidates.add("com.sun.script.javascript.RhinoScriptEngineFactory");
return factoryCandidates;
}
| private List<String> findFactoryCandidates(BundleContext context) throws IOException {
Bundle[] bundles = context.getBundles();
List<String> factoryCandidates = new ArrayList<String>();
for (Bundle bundle : bundles) {
if (bundle.getSymbolicName().equals("system.bundle")) {
continue;
}
Enumeration urls = bundle.findEntries("META-INF/services", "javax.script.ScriptEngineFactory", false);
if (urls == null) {
continue;
}
while (urls.hasMoreElements()) {
URL u = (URL) urls.nextElement();
BufferedReader reader = new BufferedReader(
new InputStreamReader(u.openStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.startsWith("#") && line.length() > 0) {
factoryCandidates.add(line);
}
}
reader.close();
}
}
//add java built in JavaScript ScriptEngineFactory's
factoryCandidates.add("com.sun.script.javascript.RhinoScriptEngineFactory");
return factoryCandidates;
}
|
diff --git a/src/main/java/org/klco/email2html/OutputWriter.java b/src/main/java/org/klco/email2html/OutputWriter.java
index 2fadd5d..ba00b13 100644
--- a/src/main/java/org/klco/email2html/OutputWriter.java
+++ b/src/main/java/org/klco/email2html/OutputWriter.java
@@ -1,455 +1,455 @@
/*
* Copyright (C) 2012 Dan Klco
*
* 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 org.klco.email2html;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.CRC32;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.mail.MessagingException;
import javax.mail.Part;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.filters.Canvas;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.ToolManager;
import org.klco.email2html.models.Email2HTMLConfiguration;
import org.klco.email2html.models.EmailMessage;
import org.klco.email2html.plugin.Rendition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class for writing output from the email messages to the filesystem.
*
* @author dklco
*/
public class OutputWriter {
/** The Constant FILE_DATE_FORMAT. */
private static final SimpleDateFormat FILE_DATE_FORMAT = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
/** The Constant log. */
private static final Logger log = LoggerFactory
.getLogger(OutputWriter.class);
/**
* A set of the downloaded attachment checksums, can ensure each attachment
* is only downloaded once
*/
private Set<Long> attachmentChecksums = new HashSet<Long>();
/**
* A flag for excluding duplicates, loaded from the configuration
*/
private boolean excludeDuplicates;
/**
* The list of 'index' file templates.
*/
private List<Template> indexTemplates = new ArrayList<Template>();
/** The output dir. */
private File outputDir;
/**
* The image renditions to create
*/
private Rendition[] renditions;
/** The template. */
private Template template;
/**
* The velocity tool manager.
*/
private ToolManager velocityToolManager;
/**
* Constructs a new OutputWriter.
*
* @param config
* the current configuration
*/
public OutputWriter(Email2HTMLConfiguration config) {
log.trace("HTMLWriter");
outputDir = new File(config.getOutputDir());
log.info("Using output directory {}", outputDir.getAbsolutePath());
if (!outputDir.exists()) {
log.info("Creating ouput directory");
outputDir.mkdirs();
}
log.debug("Initializing templating engine");
Velocity.setProperty("file.resource.loader.path",
config.getTemplateDir());
Velocity.init();
log.info("Initializing template {}", config.getMessageTemplateName());
template = Velocity.getTemplate(config.getMessageTemplateName());
log.info("Initializing index templates from: {}",
config.getIndexTemplateNames());
for (String templateName : config.getIndexTemplateNames().split("\\,")) {
log.debug("Initializing index template from: {}", templateName);
indexTemplates.add(Velocity.getTemplate(templateName));
}
log.debug("Loading Velocity tools");
velocityToolManager = new ToolManager();
velocityToolManager.configure("velocity-tools.xml");
this.renditions = config.getRenditions();
this.excludeDuplicates = config.isExcludeDuplicates();
}
/**
* Adds the attachment to the EmailMessage. Call this method when the email
* content has most likely already been loaded.
*
* @param containingMessage
* the Email Message to add the attachment to
* @param part
* the content of the attachment
* @throws IOException
* @throws MessagingException
*/
public void addAttachment(EmailMessage containingMessage, Part part)
throws IOException, MessagingException {
log.trace("addAttachment");
File attachmentFolder = new File(outputDir.getAbsolutePath()
+ File.separator
+ FILE_DATE_FORMAT.format(containingMessage.getSentDate()));
File attachmentFile = new File(attachmentFolder, part.getFileName());
boolean addAttachment = true;
boolean writeAttachment = false;
if (!attachmentFolder.exists() || !attachmentFile.exists()) {
log.warn("Attachment or folder missing, writing attachment {}",
attachmentFile.getName());
writeAttachment = true;
}
if (!writeAttachment
&& part.getContentType().toLowerCase().startsWith("image")) {
for (Rendition rendition : renditions) {
File renditionFile = new File(attachmentFolder,
rendition.getName() + "-" + part.getFileName());
if (!renditionFile.exists()) {
log.warn("Rendition {} missing, writing attachment {}",
renditionFile.getName(), attachmentFile.getName());
writeAttachment = true;
break;
}
}
}
if (writeAttachment) {
addAttachment = writeAttachment(containingMessage, part);
} else {
if (this.excludeDuplicates) {
log.debug("Computing checksum");
InputStream is = null;
try {
CRC32 checksum = new CRC32();
is = new BufferedInputStream(new FileInputStream(
attachmentFile));
for (int read = is.read(); read != -1; read = is.read()) {
checksum.update(read);
}
long value = checksum.getValue();
if (attachmentChecksums.contains(value)) {
addAttachment = false;
} else {
attachmentChecksums.add(checksum.getValue());
}
} finally {
IOUtils.closeQuietly(is);
}
}
}
if (addAttachment) {
containingMessage.getAttachments().add(attachmentFile);
} else {
log.debug("Attachment is a duplicate, not adding as message attachment");
}
}
/**
* Checks to see if a file exists for the specified message.
*
* @param emailMessage
* the message to check
* @return true if a file exists, false otherwise
*/
public boolean fileExists(EmailMessage emailMessage) {
File messageFile = new File(outputDir.getAbsolutePath()
+ File.separator
+ FILE_DATE_FORMAT.format(emailMessage.getSentDate()) + ".html");
return messageFile.exists();
}
/**
* Writes the attachment contained in the body part to a file.
*
* @param containingMessage
* the message this body part is contained within
* @param part
* the part containing the attachment
* @return the file that was created/written to
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws MessagingException
* the messaging exception
*/
public boolean writeAttachment(EmailMessage containingMessage, Part part)
throws IOException, MessagingException {
log.trace("writeAttachment");
File attachmentFolder;
File attachmentFile;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = null;
try {
in = part.getInputStream();
IOUtils.copy(part.getInputStream(), baos);
if (this.excludeDuplicates) {
log.debug("Computing checksum");
CRC32 checksum = new CRC32();
checksum.update(baos.toByteArray());
long value = checksum.getValue();
if (this.attachmentChecksums.contains(value)) {
log.info("Skipping duplicate attachment: {}",
part.getFileName());
return false;
} else {
attachmentChecksums.add(value);
}
}
attachmentFolder = new File(outputDir.getAbsolutePath()
+ File.separator
+ FILE_DATE_FORMAT.format(containingMessage.getSentDate()));
if (!attachmentFolder.exists()) {
log.debug("Creating attachment folder");
attachmentFolder.mkdirs();
}
attachmentFile = new File(attachmentFolder, part.getFileName());
log.debug("Writing attachment file: {}",
attachmentFile.getAbsolutePath());
if (!attachmentFile.exists()) {
attachmentFile.createNewFile();
}
OutputStream os = null;
InputStream is = null;
try {
log.debug("Writing to file");
os = new FileOutputStream(attachmentFile);
is = new ByteArrayInputStream(baos.toByteArray());
IOUtils.copy(is, os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
log.debug("Attachement saved");
} finally {
IOUtils.closeQuietly(baos);
IOUtils.closeQuietly(in);
}
if (part.getContentType().toLowerCase().startsWith("image")) {
log.debug("Creating renditions");
String contentType = part.getContentType().substring(0,
part.getContentType().indexOf(";"));
log.debug("Creating renditions of type: " + contentType);
for (Rendition rendition : renditions) {
File renditionFile = new File(attachmentFolder,
rendition.getName() + "-" + part.getFileName());
try {
if (!renditionFile.exists()) {
renditionFile.createNewFile();
}
log.debug("Creating rendition file: {}",
renditionFile.getAbsolutePath());
if (rendition.getFill()) {
log.debug("Adding fill");
Thumbnails
.of(attachmentFile)
.size(rendition.getWidth(),
rendition.getHeight())
.addFilter(
new Canvas(rendition.getWidth(),
rendition.getHeight(),
Positions.CENTER, Color.WHITE))
.toFile(renditionFile);
} else {
Thumbnails
.of(part.getInputStream())
.size(rendition.getWidth(),
rendition.getHeight())
.toFile(renditionFile);
}
log.debug("Rendition created");
} catch (Throwable t) {
log.warn("Exception creating rendition: " + rendition, t);
try {
BufferedImage img = ImageIO.read(attachmentFile);
if (rendition.getHeight() > img.getHeight(null)
|| img.getHeight(null) == -1) {
img = (BufferedImage) img.getScaledInstance(-1,
rendition.getHeight(), Image.SCALE_SMOOTH);
}
if (rendition.getWidth() > img.getWidth(null)
|| img.getWidth(null) == -1) {
img = (BufferedImage) img.getScaledInstance(rendition.getWidth(),
-1, Image.SCALE_SMOOTH);
}
ImageIO.write(img, "image/"
+ renditionFile.getName().split("\\.")[1],
new FileImageOutputStream(renditionFile));
- } catch (Exception e) {
- log.warn("Exception creating placeholder rendition", e);
+ } catch (Throwable th) {
+ log.warn("Exception creating backup rendition", th);
}
}
}
}
return true;
}
/**
* Writes the message to a html file. The name of the HTML file is generated
* from the date of the message.
*
* @param emailMessage
* the message to save to a file
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void writeHTML(EmailMessage emailMessage) throws IOException {
log.trace("writeHTML");
log.debug("Initializing templating context");
VelocityContext context = new VelocityContext(
velocityToolManager.createContext());
context.put("emailMessage", emailMessage);
File messageFile = new File(outputDir.getAbsolutePath()
+ File.separator
+ FILE_DATE_FORMAT.format(emailMessage.getSentDate()) + ".html");
log.debug("Writing message to file {}", messageFile.getAbsolutePath());
writeHTML(messageFile, context, template);
}
/**
* Writes the content from the merging of the context and template to the
* specified file.
*
* @param messageFile
* the file to save the contents
* @param context
* the context containing all of the properties to save
* @param template
* the velocity template to use
* @throws IOException
*/
private void writeHTML(File messageFile, VelocityContext context,
Template template) throws IOException {
log.trace("writeHTML");
if (!messageFile.exists()) {
log.debug("Creating message file");
messageFile.createNewFile();
}
log.debug("Merging message into template");
StringWriter sw = new StringWriter();
template.merge(context, sw);
log.debug("Writing contents to file");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(messageFile);
IOUtils.copy(
new ByteArrayInputStream(sw.toString().getBytes("UTF-8")),
fos);
} finally {
IOUtils.closeQuietly(fos);
}
}
/**
* Writes the index file to the filesystem
*
* @param messages
* the messages for the index file to be generated from.
* @throws IOException
*/
public void writeIndex(List<EmailMessage> messages) throws IOException {
log.trace("writeHTML");
log.debug("Initializing templating context");
VelocityContext context = new VelocityContext(
velocityToolManager.createContext());
context.put("messages", messages);
for (Template indexTemplate : indexTemplates) {
String fileName = indexTemplate.getName().substring(0,
indexTemplate.getName().indexOf(".vm"));
File messageFile = new File(outputDir.getAbsolutePath()
+ File.separator + fileName);
log.debug("Writing index to file {}", messageFile.getAbsolutePath());
writeHTML(messageFile, context, indexTemplate);
}
}
}
| true | true | public boolean writeAttachment(EmailMessage containingMessage, Part part)
throws IOException, MessagingException {
log.trace("writeAttachment");
File attachmentFolder;
File attachmentFile;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = null;
try {
in = part.getInputStream();
IOUtils.copy(part.getInputStream(), baos);
if (this.excludeDuplicates) {
log.debug("Computing checksum");
CRC32 checksum = new CRC32();
checksum.update(baos.toByteArray());
long value = checksum.getValue();
if (this.attachmentChecksums.contains(value)) {
log.info("Skipping duplicate attachment: {}",
part.getFileName());
return false;
} else {
attachmentChecksums.add(value);
}
}
attachmentFolder = new File(outputDir.getAbsolutePath()
+ File.separator
+ FILE_DATE_FORMAT.format(containingMessage.getSentDate()));
if (!attachmentFolder.exists()) {
log.debug("Creating attachment folder");
attachmentFolder.mkdirs();
}
attachmentFile = new File(attachmentFolder, part.getFileName());
log.debug("Writing attachment file: {}",
attachmentFile.getAbsolutePath());
if (!attachmentFile.exists()) {
attachmentFile.createNewFile();
}
OutputStream os = null;
InputStream is = null;
try {
log.debug("Writing to file");
os = new FileOutputStream(attachmentFile);
is = new ByteArrayInputStream(baos.toByteArray());
IOUtils.copy(is, os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
log.debug("Attachement saved");
} finally {
IOUtils.closeQuietly(baos);
IOUtils.closeQuietly(in);
}
if (part.getContentType().toLowerCase().startsWith("image")) {
log.debug("Creating renditions");
String contentType = part.getContentType().substring(0,
part.getContentType().indexOf(";"));
log.debug("Creating renditions of type: " + contentType);
for (Rendition rendition : renditions) {
File renditionFile = new File(attachmentFolder,
rendition.getName() + "-" + part.getFileName());
try {
if (!renditionFile.exists()) {
renditionFile.createNewFile();
}
log.debug("Creating rendition file: {}",
renditionFile.getAbsolutePath());
if (rendition.getFill()) {
log.debug("Adding fill");
Thumbnails
.of(attachmentFile)
.size(rendition.getWidth(),
rendition.getHeight())
.addFilter(
new Canvas(rendition.getWidth(),
rendition.getHeight(),
Positions.CENTER, Color.WHITE))
.toFile(renditionFile);
} else {
Thumbnails
.of(part.getInputStream())
.size(rendition.getWidth(),
rendition.getHeight())
.toFile(renditionFile);
}
log.debug("Rendition created");
} catch (Throwable t) {
log.warn("Exception creating rendition: " + rendition, t);
try {
BufferedImage img = ImageIO.read(attachmentFile);
if (rendition.getHeight() > img.getHeight(null)
|| img.getHeight(null) == -1) {
img = (BufferedImage) img.getScaledInstance(-1,
rendition.getHeight(), Image.SCALE_SMOOTH);
}
if (rendition.getWidth() > img.getWidth(null)
|| img.getWidth(null) == -1) {
img = (BufferedImage) img.getScaledInstance(rendition.getWidth(),
-1, Image.SCALE_SMOOTH);
}
ImageIO.write(img, "image/"
+ renditionFile.getName().split("\\.")[1],
new FileImageOutputStream(renditionFile));
} catch (Exception e) {
log.warn("Exception creating placeholder rendition", e);
}
}
}
}
return true;
}
| public boolean writeAttachment(EmailMessage containingMessage, Part part)
throws IOException, MessagingException {
log.trace("writeAttachment");
File attachmentFolder;
File attachmentFile;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = null;
try {
in = part.getInputStream();
IOUtils.copy(part.getInputStream(), baos);
if (this.excludeDuplicates) {
log.debug("Computing checksum");
CRC32 checksum = new CRC32();
checksum.update(baos.toByteArray());
long value = checksum.getValue();
if (this.attachmentChecksums.contains(value)) {
log.info("Skipping duplicate attachment: {}",
part.getFileName());
return false;
} else {
attachmentChecksums.add(value);
}
}
attachmentFolder = new File(outputDir.getAbsolutePath()
+ File.separator
+ FILE_DATE_FORMAT.format(containingMessage.getSentDate()));
if (!attachmentFolder.exists()) {
log.debug("Creating attachment folder");
attachmentFolder.mkdirs();
}
attachmentFile = new File(attachmentFolder, part.getFileName());
log.debug("Writing attachment file: {}",
attachmentFile.getAbsolutePath());
if (!attachmentFile.exists()) {
attachmentFile.createNewFile();
}
OutputStream os = null;
InputStream is = null;
try {
log.debug("Writing to file");
os = new FileOutputStream(attachmentFile);
is = new ByteArrayInputStream(baos.toByteArray());
IOUtils.copy(is, os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
log.debug("Attachement saved");
} finally {
IOUtils.closeQuietly(baos);
IOUtils.closeQuietly(in);
}
if (part.getContentType().toLowerCase().startsWith("image")) {
log.debug("Creating renditions");
String contentType = part.getContentType().substring(0,
part.getContentType().indexOf(";"));
log.debug("Creating renditions of type: " + contentType);
for (Rendition rendition : renditions) {
File renditionFile = new File(attachmentFolder,
rendition.getName() + "-" + part.getFileName());
try {
if (!renditionFile.exists()) {
renditionFile.createNewFile();
}
log.debug("Creating rendition file: {}",
renditionFile.getAbsolutePath());
if (rendition.getFill()) {
log.debug("Adding fill");
Thumbnails
.of(attachmentFile)
.size(rendition.getWidth(),
rendition.getHeight())
.addFilter(
new Canvas(rendition.getWidth(),
rendition.getHeight(),
Positions.CENTER, Color.WHITE))
.toFile(renditionFile);
} else {
Thumbnails
.of(part.getInputStream())
.size(rendition.getWidth(),
rendition.getHeight())
.toFile(renditionFile);
}
log.debug("Rendition created");
} catch (Throwable t) {
log.warn("Exception creating rendition: " + rendition, t);
try {
BufferedImage img = ImageIO.read(attachmentFile);
if (rendition.getHeight() > img.getHeight(null)
|| img.getHeight(null) == -1) {
img = (BufferedImage) img.getScaledInstance(-1,
rendition.getHeight(), Image.SCALE_SMOOTH);
}
if (rendition.getWidth() > img.getWidth(null)
|| img.getWidth(null) == -1) {
img = (BufferedImage) img.getScaledInstance(rendition.getWidth(),
-1, Image.SCALE_SMOOTH);
}
ImageIO.write(img, "image/"
+ renditionFile.getName().split("\\.")[1],
new FileImageOutputStream(renditionFile));
} catch (Throwable th) {
log.warn("Exception creating backup rendition", th);
}
}
}
}
return true;
}
|
diff --git a/src/ramirez57/CLIShop/Main.java b/src/ramirez57/CLIShop/Main.java
index 9c3cfbb..52df66a 100644
--- a/src/ramirez57/CLIShop/Main.java
+++ b/src/ramirez57/CLIShop/Main.java
@@ -1,302 +1,304 @@
package ramirez57.CLIShop;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener {
Server mc;
PluginManager pluginmgr;
Logger log;
Economy economy;
Player player;
String string;
File salesFile;
FileConfiguration sales;
File configFile;
FileConfiguration config;
Material material;
ItemStack itemstack;
List<String> stringlist;
public void onEnable() {
mc = this.getServer();
log = this.getLogger();
pluginmgr = this.getServer().getPluginManager();
if(!setupEcon()) {
log.info("Problem depending vault. Disabling...");
pluginmgr.disablePlugin(this);
return;
}
salesFile = new File(this.getDataFolder(), "SALES");
sales = YamlConfiguration.loadConfiguration(salesFile);
configFile = new File(this.getDataFolder(), "config.yml");
config = this.getConfig();
config.options().copyDefaults(true);
savesales();
saveconfig();
}
public void onDisable() {
}
public void reload() {
config = YamlConfiguration.loadConfiguration(configFile);
sales = YamlConfiguration.loadConfiguration(salesFile);
return;
}
public void savesales() {
try {
sales.save(salesFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
public void saveconfig() {
try {
config.save(configFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equalsIgnoreCase("cshop")){
if(isplayer(sender)) {
player = (Player)sender;
if(args.length > 0) {
if(args[0].equalsIgnoreCase("help")) {
sender.sendMessage(ChatColor.GOLD + "/cshop help" + ChatColor.GRAY + " - Display help information");
sender.sendMessage(ChatColor.GOLD + "/cshop sell " + ChatColor.GRAY + "- Sell amount of item for cost per one");
sender.sendMessage(ChatColor.GOLD + "/cshop sell hand " + ChatColor.GRAY + "- Sell amount of what is in your hand for cost per one");
sender.sendMessage(ChatColor.GOLD + "/cshop buy " + ChatColor.GRAY + "- Buy the amount of item from player");
sender.sendMessage(ChatColor.GOLD + "/cshop list <page> <item> " + ChatColor.GRAY + "- Show the CLIShop market");
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Type a command for further help on syntax.");
return true;
}
if(args[0].equalsIgnoreCase("sell")) {
if(args.length > 3) {
try {Integer.parseInt(args[2]);} catch(NumberFormatException e) {player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");return true;}
try {Double.parseDouble(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");return true;}
if(Double.parseDouble(args[3]) > config.getDouble("price_limit")) {
player.sendMessage(ChatColor.RED + "You may not set a price that high.");
player.sendMessage(ChatColor.RED + "Price limit is " + String.valueOf(config.getDouble("price_limit")));
return true;
}
if(Double.parseDouble(args[3]) < 0) {
player.sendMessage(ChatColor.RED + "You must set a price 0 or higher.");
return true;
}
if(!args[1].equalsIgnoreCase("hand")) {
if(Material.matchMaterial(args[1]) == null) {
sender.sendMessage("What is " + args[1] + "?");
return true;
}
} else {
args[1] = player.getItemInHand().getType().toString();
}
material = Material.matchMaterial(args[1]);
if(Integer.parseInt(args[2]) <= 0 || material == Material.AIR) {
player.sendMessage(ChatColor.RED + "Stop trying to sell nothing.");
return true;
}
if(!player.getInventory().contains(material, Integer.parseInt(args[2]))) {
sender.sendMessage("You do not have at least " + args[2] + " of " + args[1]);
return true;
} else {
int eax,ebx;
eax = Integer.parseInt(args[2]);
while(eax > 0) {
ebx = player.getInventory().first(material);
itemstack = player.getInventory().getItem(ebx);
if(itemstack.getDurability() > 0 && !config.getBoolean("sell_damaged_items")) {
player.sendMessage(ChatColor.RED + "You cannot sell damaged items.");
return true;
}
if(itemstack.getAmount() <= eax) {
eax -= itemstack.getAmount();
itemstack.setAmount(0);
player.getInventory().setItem(ebx, itemstack);
} else {
itemstack.setAmount(itemstack.getAmount()-eax);
player.getInventory().setItem(ebx, itemstack);
eax = 0;
}
}
string = material.toString() +"."+player.getName().toUpperCase() + ".";
sales.set(string + "amount", sales.getInt(string + "amount", 0) + Integer.parseInt(args[2]));
sales.set(string + "durability", itemstack.getDurability());
sales.set(string + "cost", Double.parseDouble(args[3]));
stringlist = sales.getStringList(material.toString() + ".sellers");if(!stringlist.contains(player.getName().toUpperCase())) stringlist.add(player.getName().toUpperCase());
sales.set(material.toString() + ".sellers", stringlist);
savesales();
player.sendMessage(ChatColor.GREEN + "Put item (" + args[1] + " x " + args[2] + ") on the market for " + args[3] + " " + economy.currencyNamePlural() + " per one.");
mc.broadcastMessage(ChatColor.BLUE + player.getName() + ChatColor.GREEN +" is now selling " + ChatColor.YELLOW + args[2] + " " + Material.matchMaterial(args[1]).toString() + ChatColor.GREEN + " for " + ChatColor.RED + args[3] + " " + economy.currencyNamePlural() + " per one.");
return true;
}
} else {
player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");
return true;
}
}
if(args[0].equalsIgnoreCase("buy")) {
if(args.length > 3) {
try{Integer.parseInt(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cshop buy [player] [item] [amount]");return true;}
material = Material.matchMaterial(args[2]);
if(material == null) {
player.sendMessage("What is " + args[2] + "?");
return true;
}
String szsale = material.toString() + "." + args[1].toUpperCase() + ".";
int eax = Integer.parseInt(args[3]);
if(sales.getInt(szsale + "amount",0) > 0) {
if(sales.getInt(szsale + "amount",0) >= eax) {
double cost = sales.getDouble(szsale + "cost") * Integer.parseInt(args[3]);
String name = player.getName();
if(economy.getBalance(name) >= cost) {
economy.withdrawPlayer(name, cost);
economy.depositPlayer(args[1], cost);
- if(mc.getPlayer(args[1]).isOnline()) {
- mc.getPlayer(args[1]).sendMessage(ChatColor.GREEN + name + " has bought " + args[3] + " of your " + args[2] + "(" + cost + " " + economy.currencyNamePlural() + ")");
+ if(mc.getPlayer(args[1]) != null) {
+ if(mc.getPlayer(args[1]).isOnline()) {
+ mc.getPlayer(args[1]).sendMessage(ChatColor.GREEN + name + " has bought " + args[3] + " of your " + args[2] + "(" + cost + " " + economy.currencyNamePlural() + ")");
+ }
}
} else if(name.equalsIgnoreCase(args[1])) {
player.sendMessage(ChatColor.GREEN + "Taking item off the market...");
} else {
player.sendMessage(ChatColor.RED + "You do not have enough " + economy.currencyNamePlural());
player.sendMessage(ChatColor.RED + String.valueOf(cost) + " " + economy.currencyNamePlural() + " is required.");
return true;
}
itemstack = new ItemStack(material,Integer.parseInt(args[3]),Short.parseShort(sales.getString(szsale + "durability","0")));
Iterator<ItemStack> i_stacks = player.getInventory().addItem(itemstack).values().iterator();
while(i_stacks.hasNext()) {
player.getWorld().dropItem(player.getLocation(), i_stacks.next()); //drop any items that couldn't fit
player.sendMessage(ChatColor.YELLOW + "Some items could not fit. They were dropped at your location.");
}
if(sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]) <= 0) {
sales.set(szsale + "amount", null);
sales.set(szsale + "durability", null); //sold out
sales.set(szsale + "cost", null);
sales.set(material.toString() + "." + args[1].toUpperCase(), null);
stringlist = sales.getStringList(material.toString() + ".sellers");stringlist.remove(args[1].toUpperCase());
sales.set(material.toString() + ".sellers", stringlist);
} else {
sales.set(szsale + "amount", sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]));
}
savesales();
player.sendMessage(ChatColor.GREEN + "Received item.");
return true;
} else {
player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling that many " + args[2]);
player.sendMessage(ChatColor.RED + args[1] + " is selling " + String.valueOf(sales.getInt(string + "amount",0)) + " " + args[2]);
return true;
}
} else {
player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling any " + args[2]);
return true;
}
} else {
player.sendMessage("/cshop buy [player] [item] [amount]");
return true;
}
}
if(args[0].equalsIgnoreCase("list")) {
int page = 1;
String filter;
if(args.length >= 2) {
try{page=Integer.valueOf(args[1]);} catch(NumberFormatException e) {player.sendMessage(ChatColor.RED + "That page number is invalid.");return true;}
}
if(args.length >= 3) filter = Material.matchMaterial(args[2]).toString(); else filter = "NONE";
int lineend = 11 * page;
int linestart = lineend-10;
int lines = 1;
player.sendMessage(ChatColor.RED + "|-----Page " + String.valueOf(page) + "-----|");
if(config.getBoolean("shorthand")) { //The check is done first so it can process faster later.
for(Material mat : Material.values()) {
if(mat.toString().equals(filter) || filter.equals("NONE")) {
List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers");
for(Object seller : sellers.toArray()) {
if(lines >= linestart && lines <= lineend) {
- player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + ": " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " each.");
+ player.sendMessage(ChatColor.BLUE + String.valueOf(seller) + ChatColor.RED + ": " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " each.");
}
lines++;
}
}
}
} else {
for(Material mat : Material.values()) {
if(mat.toString().equals(filter) || filter.equals("NONE")) {
List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers");
for(Object seller : sellers.toArray()) {
if(lines >= linestart && lines <= lineend) {
- player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + " is selling " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " per one.");
+ player.sendMessage(ChatColor.BLUE + String.valueOf(seller) + ChatColor.RED + " is selling " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " per one.");
}
lines++;
}
}
}
}
player.sendMessage(ChatColor.RED + "Type " + ChatColor.YELLOW + "/cshop list " + String.valueOf(page+1) + ChatColor.RED + " to see the next page");
return true;
}
} else {
return false;
}
} else {
sender.sendMessage("Only players can use this command.");
return true;
}
}
if(cmd.getName().equalsIgnoreCase("cshopadmin")) {
if(args.length > 0) {
if(args[0].equalsIgnoreCase("reload")) {
reload();
sender.sendMessage(ChatColor.GREEN + "Configuration reloaded.");
return true;
}
}
}
return false;
}
public boolean isplayer(CommandSender _sender) {
return _sender instanceof Player;
}
public boolean setupEcon() {
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
return (economy != null);
}
public boolean sell(String playername, ItemStack item, double cost) {
return true;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equalsIgnoreCase("cshop")){
if(isplayer(sender)) {
player = (Player)sender;
if(args.length > 0) {
if(args[0].equalsIgnoreCase("help")) {
sender.sendMessage(ChatColor.GOLD + "/cshop help" + ChatColor.GRAY + " - Display help information");
sender.sendMessage(ChatColor.GOLD + "/cshop sell " + ChatColor.GRAY + "- Sell amount of item for cost per one");
sender.sendMessage(ChatColor.GOLD + "/cshop sell hand " + ChatColor.GRAY + "- Sell amount of what is in your hand for cost per one");
sender.sendMessage(ChatColor.GOLD + "/cshop buy " + ChatColor.GRAY + "- Buy the amount of item from player");
sender.sendMessage(ChatColor.GOLD + "/cshop list <page> <item> " + ChatColor.GRAY + "- Show the CLIShop market");
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Type a command for further help on syntax.");
return true;
}
if(args[0].equalsIgnoreCase("sell")) {
if(args.length > 3) {
try {Integer.parseInt(args[2]);} catch(NumberFormatException e) {player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");return true;}
try {Double.parseDouble(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");return true;}
if(Double.parseDouble(args[3]) > config.getDouble("price_limit")) {
player.sendMessage(ChatColor.RED + "You may not set a price that high.");
player.sendMessage(ChatColor.RED + "Price limit is " + String.valueOf(config.getDouble("price_limit")));
return true;
}
if(Double.parseDouble(args[3]) < 0) {
player.sendMessage(ChatColor.RED + "You must set a price 0 or higher.");
return true;
}
if(!args[1].equalsIgnoreCase("hand")) {
if(Material.matchMaterial(args[1]) == null) {
sender.sendMessage("What is " + args[1] + "?");
return true;
}
} else {
args[1] = player.getItemInHand().getType().toString();
}
material = Material.matchMaterial(args[1]);
if(Integer.parseInt(args[2]) <= 0 || material == Material.AIR) {
player.sendMessage(ChatColor.RED + "Stop trying to sell nothing.");
return true;
}
if(!player.getInventory().contains(material, Integer.parseInt(args[2]))) {
sender.sendMessage("You do not have at least " + args[2] + " of " + args[1]);
return true;
} else {
int eax,ebx;
eax = Integer.parseInt(args[2]);
while(eax > 0) {
ebx = player.getInventory().first(material);
itemstack = player.getInventory().getItem(ebx);
if(itemstack.getDurability() > 0 && !config.getBoolean("sell_damaged_items")) {
player.sendMessage(ChatColor.RED + "You cannot sell damaged items.");
return true;
}
if(itemstack.getAmount() <= eax) {
eax -= itemstack.getAmount();
itemstack.setAmount(0);
player.getInventory().setItem(ebx, itemstack);
} else {
itemstack.setAmount(itemstack.getAmount()-eax);
player.getInventory().setItem(ebx, itemstack);
eax = 0;
}
}
string = material.toString() +"."+player.getName().toUpperCase() + ".";
sales.set(string + "amount", sales.getInt(string + "amount", 0) + Integer.parseInt(args[2]));
sales.set(string + "durability", itemstack.getDurability());
sales.set(string + "cost", Double.parseDouble(args[3]));
stringlist = sales.getStringList(material.toString() + ".sellers");if(!stringlist.contains(player.getName().toUpperCase())) stringlist.add(player.getName().toUpperCase());
sales.set(material.toString() + ".sellers", stringlist);
savesales();
player.sendMessage(ChatColor.GREEN + "Put item (" + args[1] + " x " + args[2] + ") on the market for " + args[3] + " " + economy.currencyNamePlural() + " per one.");
mc.broadcastMessage(ChatColor.BLUE + player.getName() + ChatColor.GREEN +" is now selling " + ChatColor.YELLOW + args[2] + " " + Material.matchMaterial(args[1]).toString() + ChatColor.GREEN + " for " + ChatColor.RED + args[3] + " " + economy.currencyNamePlural() + " per one.");
return true;
}
} else {
player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");
return true;
}
}
if(args[0].equalsIgnoreCase("buy")) {
if(args.length > 3) {
try{Integer.parseInt(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cshop buy [player] [item] [amount]");return true;}
material = Material.matchMaterial(args[2]);
if(material == null) {
player.sendMessage("What is " + args[2] + "?");
return true;
}
String szsale = material.toString() + "." + args[1].toUpperCase() + ".";
int eax = Integer.parseInt(args[3]);
if(sales.getInt(szsale + "amount",0) > 0) {
if(sales.getInt(szsale + "amount",0) >= eax) {
double cost = sales.getDouble(szsale + "cost") * Integer.parseInt(args[3]);
String name = player.getName();
if(economy.getBalance(name) >= cost) {
economy.withdrawPlayer(name, cost);
economy.depositPlayer(args[1], cost);
if(mc.getPlayer(args[1]).isOnline()) {
mc.getPlayer(args[1]).sendMessage(ChatColor.GREEN + name + " has bought " + args[3] + " of your " + args[2] + "(" + cost + " " + economy.currencyNamePlural() + ")");
}
} else if(name.equalsIgnoreCase(args[1])) {
player.sendMessage(ChatColor.GREEN + "Taking item off the market...");
} else {
player.sendMessage(ChatColor.RED + "You do not have enough " + economy.currencyNamePlural());
player.sendMessage(ChatColor.RED + String.valueOf(cost) + " " + economy.currencyNamePlural() + " is required.");
return true;
}
itemstack = new ItemStack(material,Integer.parseInt(args[3]),Short.parseShort(sales.getString(szsale + "durability","0")));
Iterator<ItemStack> i_stacks = player.getInventory().addItem(itemstack).values().iterator();
while(i_stacks.hasNext()) {
player.getWorld().dropItem(player.getLocation(), i_stacks.next()); //drop any items that couldn't fit
player.sendMessage(ChatColor.YELLOW + "Some items could not fit. They were dropped at your location.");
}
if(sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]) <= 0) {
sales.set(szsale + "amount", null);
sales.set(szsale + "durability", null); //sold out
sales.set(szsale + "cost", null);
sales.set(material.toString() + "." + args[1].toUpperCase(), null);
stringlist = sales.getStringList(material.toString() + ".sellers");stringlist.remove(args[1].toUpperCase());
sales.set(material.toString() + ".sellers", stringlist);
} else {
sales.set(szsale + "amount", sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]));
}
savesales();
player.sendMessage(ChatColor.GREEN + "Received item.");
return true;
} else {
player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling that many " + args[2]);
player.sendMessage(ChatColor.RED + args[1] + " is selling " + String.valueOf(sales.getInt(string + "amount",0)) + " " + args[2]);
return true;
}
} else {
player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling any " + args[2]);
return true;
}
} else {
player.sendMessage("/cshop buy [player] [item] [amount]");
return true;
}
}
if(args[0].equalsIgnoreCase("list")) {
int page = 1;
String filter;
if(args.length >= 2) {
try{page=Integer.valueOf(args[1]);} catch(NumberFormatException e) {player.sendMessage(ChatColor.RED + "That page number is invalid.");return true;}
}
if(args.length >= 3) filter = Material.matchMaterial(args[2]).toString(); else filter = "NONE";
int lineend = 11 * page;
int linestart = lineend-10;
int lines = 1;
player.sendMessage(ChatColor.RED + "|-----Page " + String.valueOf(page) + "-----|");
if(config.getBoolean("shorthand")) { //The check is done first so it can process faster later.
for(Material mat : Material.values()) {
if(mat.toString().equals(filter) || filter.equals("NONE")) {
List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers");
for(Object seller : sellers.toArray()) {
if(lines >= linestart && lines <= lineend) {
player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + ": " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " each.");
}
lines++;
}
}
}
} else {
for(Material mat : Material.values()) {
if(mat.toString().equals(filter) || filter.equals("NONE")) {
List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers");
for(Object seller : sellers.toArray()) {
if(lines >= linestart && lines <= lineend) {
player.sendMessage(ChatColor.BLUE + mc.getPlayer(String.valueOf(seller)).getName() + ChatColor.RED + " is selling " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " per one.");
}
lines++;
}
}
}
}
player.sendMessage(ChatColor.RED + "Type " + ChatColor.YELLOW + "/cshop list " + String.valueOf(page+1) + ChatColor.RED + " to see the next page");
return true;
}
} else {
return false;
}
} else {
sender.sendMessage("Only players can use this command.");
return true;
}
}
if(cmd.getName().equalsIgnoreCase("cshopadmin")) {
if(args.length > 0) {
if(args[0].equalsIgnoreCase("reload")) {
reload();
sender.sendMessage(ChatColor.GREEN + "Configuration reloaded.");
return true;
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equalsIgnoreCase("cshop")){
if(isplayer(sender)) {
player = (Player)sender;
if(args.length > 0) {
if(args[0].equalsIgnoreCase("help")) {
sender.sendMessage(ChatColor.GOLD + "/cshop help" + ChatColor.GRAY + " - Display help information");
sender.sendMessage(ChatColor.GOLD + "/cshop sell " + ChatColor.GRAY + "- Sell amount of item for cost per one");
sender.sendMessage(ChatColor.GOLD + "/cshop sell hand " + ChatColor.GRAY + "- Sell amount of what is in your hand for cost per one");
sender.sendMessage(ChatColor.GOLD + "/cshop buy " + ChatColor.GRAY + "- Buy the amount of item from player");
sender.sendMessage(ChatColor.GOLD + "/cshop list <page> <item> " + ChatColor.GRAY + "- Show the CLIShop market");
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Type a command for further help on syntax.");
return true;
}
if(args[0].equalsIgnoreCase("sell")) {
if(args.length > 3) {
try {Integer.parseInt(args[2]);} catch(NumberFormatException e) {player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");return true;}
try {Double.parseDouble(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");return true;}
if(Double.parseDouble(args[3]) > config.getDouble("price_limit")) {
player.sendMessage(ChatColor.RED + "You may not set a price that high.");
player.sendMessage(ChatColor.RED + "Price limit is " + String.valueOf(config.getDouble("price_limit")));
return true;
}
if(Double.parseDouble(args[3]) < 0) {
player.sendMessage(ChatColor.RED + "You must set a price 0 or higher.");
return true;
}
if(!args[1].equalsIgnoreCase("hand")) {
if(Material.matchMaterial(args[1]) == null) {
sender.sendMessage("What is " + args[1] + "?");
return true;
}
} else {
args[1] = player.getItemInHand().getType().toString();
}
material = Material.matchMaterial(args[1]);
if(Integer.parseInt(args[2]) <= 0 || material == Material.AIR) {
player.sendMessage(ChatColor.RED + "Stop trying to sell nothing.");
return true;
}
if(!player.getInventory().contains(material, Integer.parseInt(args[2]))) {
sender.sendMessage("You do not have at least " + args[2] + " of " + args[1]);
return true;
} else {
int eax,ebx;
eax = Integer.parseInt(args[2]);
while(eax > 0) {
ebx = player.getInventory().first(material);
itemstack = player.getInventory().getItem(ebx);
if(itemstack.getDurability() > 0 && !config.getBoolean("sell_damaged_items")) {
player.sendMessage(ChatColor.RED + "You cannot sell damaged items.");
return true;
}
if(itemstack.getAmount() <= eax) {
eax -= itemstack.getAmount();
itemstack.setAmount(0);
player.getInventory().setItem(ebx, itemstack);
} else {
itemstack.setAmount(itemstack.getAmount()-eax);
player.getInventory().setItem(ebx, itemstack);
eax = 0;
}
}
string = material.toString() +"."+player.getName().toUpperCase() + ".";
sales.set(string + "amount", sales.getInt(string + "amount", 0) + Integer.parseInt(args[2]));
sales.set(string + "durability", itemstack.getDurability());
sales.set(string + "cost", Double.parseDouble(args[3]));
stringlist = sales.getStringList(material.toString() + ".sellers");if(!stringlist.contains(player.getName().toUpperCase())) stringlist.add(player.getName().toUpperCase());
sales.set(material.toString() + ".sellers", stringlist);
savesales();
player.sendMessage(ChatColor.GREEN + "Put item (" + args[1] + " x " + args[2] + ") on the market for " + args[3] + " " + economy.currencyNamePlural() + " per one.");
mc.broadcastMessage(ChatColor.BLUE + player.getName() + ChatColor.GREEN +" is now selling " + ChatColor.YELLOW + args[2] + " " + Material.matchMaterial(args[1]).toString() + ChatColor.GREEN + " for " + ChatColor.RED + args[3] + " " + economy.currencyNamePlural() + " per one.");
return true;
}
} else {
player.sendMessage("/cshop sell [item] [amount] [cost_per_one]");
return true;
}
}
if(args[0].equalsIgnoreCase("buy")) {
if(args.length > 3) {
try{Integer.parseInt(args[3]);} catch(NumberFormatException e) {player.sendMessage("/cshop buy [player] [item] [amount]");return true;}
material = Material.matchMaterial(args[2]);
if(material == null) {
player.sendMessage("What is " + args[2] + "?");
return true;
}
String szsale = material.toString() + "." + args[1].toUpperCase() + ".";
int eax = Integer.parseInt(args[3]);
if(sales.getInt(szsale + "amount",0) > 0) {
if(sales.getInt(szsale + "amount",0) >= eax) {
double cost = sales.getDouble(szsale + "cost") * Integer.parseInt(args[3]);
String name = player.getName();
if(economy.getBalance(name) >= cost) {
economy.withdrawPlayer(name, cost);
economy.depositPlayer(args[1], cost);
if(mc.getPlayer(args[1]) != null) {
if(mc.getPlayer(args[1]).isOnline()) {
mc.getPlayer(args[1]).sendMessage(ChatColor.GREEN + name + " has bought " + args[3] + " of your " + args[2] + "(" + cost + " " + economy.currencyNamePlural() + ")");
}
}
} else if(name.equalsIgnoreCase(args[1])) {
player.sendMessage(ChatColor.GREEN + "Taking item off the market...");
} else {
player.sendMessage(ChatColor.RED + "You do not have enough " + economy.currencyNamePlural());
player.sendMessage(ChatColor.RED + String.valueOf(cost) + " " + economy.currencyNamePlural() + " is required.");
return true;
}
itemstack = new ItemStack(material,Integer.parseInt(args[3]),Short.parseShort(sales.getString(szsale + "durability","0")));
Iterator<ItemStack> i_stacks = player.getInventory().addItem(itemstack).values().iterator();
while(i_stacks.hasNext()) {
player.getWorld().dropItem(player.getLocation(), i_stacks.next()); //drop any items that couldn't fit
player.sendMessage(ChatColor.YELLOW + "Some items could not fit. They were dropped at your location.");
}
if(sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]) <= 0) {
sales.set(szsale + "amount", null);
sales.set(szsale + "durability", null); //sold out
sales.set(szsale + "cost", null);
sales.set(material.toString() + "." + args[1].toUpperCase(), null);
stringlist = sales.getStringList(material.toString() + ".sellers");stringlist.remove(args[1].toUpperCase());
sales.set(material.toString() + ".sellers", stringlist);
} else {
sales.set(szsale + "amount", sales.getInt(szsale + "amount",0)-Integer.parseInt(args[3]));
}
savesales();
player.sendMessage(ChatColor.GREEN + "Received item.");
return true;
} else {
player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling that many " + args[2]);
player.sendMessage(ChatColor.RED + args[1] + " is selling " + String.valueOf(sales.getInt(string + "amount",0)) + " " + args[2]);
return true;
}
} else {
player.sendMessage(ChatColor.RED + "Player " + args[1] + " is not selling any " + args[2]);
return true;
}
} else {
player.sendMessage("/cshop buy [player] [item] [amount]");
return true;
}
}
if(args[0].equalsIgnoreCase("list")) {
int page = 1;
String filter;
if(args.length >= 2) {
try{page=Integer.valueOf(args[1]);} catch(NumberFormatException e) {player.sendMessage(ChatColor.RED + "That page number is invalid.");return true;}
}
if(args.length >= 3) filter = Material.matchMaterial(args[2]).toString(); else filter = "NONE";
int lineend = 11 * page;
int linestart = lineend-10;
int lines = 1;
player.sendMessage(ChatColor.RED + "|-----Page " + String.valueOf(page) + "-----|");
if(config.getBoolean("shorthand")) { //The check is done first so it can process faster later.
for(Material mat : Material.values()) {
if(mat.toString().equals(filter) || filter.equals("NONE")) {
List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers");
for(Object seller : sellers.toArray()) {
if(lines >= linestart && lines <= lineend) {
player.sendMessage(ChatColor.BLUE + String.valueOf(seller) + ChatColor.RED + ": " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " each.");
}
lines++;
}
}
}
} else {
for(Material mat : Material.values()) {
if(mat.toString().equals(filter) || filter.equals("NONE")) {
List<String> sellers = sales.getStringList(mat.toString() + "." + "sellers");
for(Object seller : sellers.toArray()) {
if(lines >= linestart && lines <= lineend) {
player.sendMessage(ChatColor.BLUE + String.valueOf(seller) + ChatColor.RED + " is selling " + ChatColor.YELLOW + String.valueOf(sales.getInt(mat.toString() + "." + seller + ".amount")) + " " + mat.toString() + ChatColor.RED + " for " + ChatColor.GREEN + String.valueOf(sales.getDouble(mat.toString() + "." + seller + ".cost")) + " " + economy.currencyNamePlural() + " per one.");
}
lines++;
}
}
}
}
player.sendMessage(ChatColor.RED + "Type " + ChatColor.YELLOW + "/cshop list " + String.valueOf(page+1) + ChatColor.RED + " to see the next page");
return true;
}
} else {
return false;
}
} else {
sender.sendMessage("Only players can use this command.");
return true;
}
}
if(cmd.getName().equalsIgnoreCase("cshopadmin")) {
if(args.length > 0) {
if(args[0].equalsIgnoreCase("reload")) {
reload();
sender.sendMessage(ChatColor.GREEN + "Configuration reloaded.");
return true;
}
}
}
return false;
}
|
diff --git a/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/TestVersion.java b/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/TestVersion.java
index f2ef03805a..5e23b7ad1c 100644
--- a/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/TestVersion.java
+++ b/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/TestVersion.java
@@ -1,41 +1,41 @@
/**
* Copyright (C) 2009-2012 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.tests;
import junit.framework.TestCase;
import org.bonitasoft.studio.diagram.custom.commands.NewDiagramCommandHandler;
import org.bonitasoft.studio.model.process.MainProcess;
import org.bonitasoft.studio.model.process.diagram.part.ProcessDiagramEditor;
import org.eclipse.ui.PlatformUI;
/**
* @author Mickael Istria
*
*/
public class TestVersion extends TestCase {
public void testNewProcessVersionMatchesProduct() throws Exception {
- String version = "6.0.1";//TO BE MODIFIED AT EACH RELEASE
+ String version = "6.1.0";//TO BE MODIFIED AT EACH RELEASE
NewDiagramCommandHandler command = new NewDiagramCommandHandler();
command.execute(null);
ProcessDiagramEditor editor = (ProcessDiagramEditor)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
String bonitaVersion = ((MainProcess)editor.getDiagramEditPart().resolveSemanticElement()).getBonitaVersion();
assertEquals("New Process Version <" + bonitaVersion + "> does not match product version <" + version + ">", version, bonitaVersion);
}
}
| true | true | public void testNewProcessVersionMatchesProduct() throws Exception {
String version = "6.0.1";//TO BE MODIFIED AT EACH RELEASE
NewDiagramCommandHandler command = new NewDiagramCommandHandler();
command.execute(null);
ProcessDiagramEditor editor = (ProcessDiagramEditor)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
String bonitaVersion = ((MainProcess)editor.getDiagramEditPart().resolveSemanticElement()).getBonitaVersion();
assertEquals("New Process Version <" + bonitaVersion + "> does not match product version <" + version + ">", version, bonitaVersion);
}
| public void testNewProcessVersionMatchesProduct() throws Exception {
String version = "6.1.0";//TO BE MODIFIED AT EACH RELEASE
NewDiagramCommandHandler command = new NewDiagramCommandHandler();
command.execute(null);
ProcessDiagramEditor editor = (ProcessDiagramEditor)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
String bonitaVersion = ((MainProcess)editor.getDiagramEditPart().resolveSemanticElement()).getBonitaVersion();
assertEquals("New Process Version <" + bonitaVersion + "> does not match product version <" + version + ">", version, bonitaVersion);
}
|
diff --git a/jabox-persistence/src/main/java/org/jabox/environment/Environment.java b/jabox-persistence/src/main/java/org/jabox/environment/Environment.java
index fa7bf434..50dd3d8a 100644
--- a/jabox-persistence/src/main/java/org/jabox/environment/Environment.java
+++ b/jabox-persistence/src/main/java/org/jabox/environment/Environment.java
@@ -1,97 +1,98 @@
/*
* Jabox Open Source Version
* Copyright (C) 2009-2010 Dimitris Kapanidis
*
* This file is part of Jabox
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package org.jabox.environment;
import java.io.File;
public class Environment {
private static final String JABOX_ENV = "JABOX_HOME";
private static final String JABOX_PROPERTY = "JABOX_HOME";
private static final String HUDSON_ENV = "HUDSON_HOME";
private static final String HUDSON_PROPERTY = "HUDSON_HOME";
private static final String HUDSON_DIR = ".hudson";
private static final String CUSTOM_MAVEN_DIR = ".m2";
public static String getBaseDir() {
return getHomeDir();
}
public static File getBaseDirFile() {
return new File(getBaseDir());
}
public static File getCustomMavenHomeDir() {
File m2Dir = new File(getBaseDirFile(), CUSTOM_MAVEN_DIR);
if (!m2Dir.exists()) {
m2Dir.mkdirs();
}
return m2Dir;
}
public static String getHudsonHomeDir() {
String env = System.getenv(HUDSON_ENV);
String property = System.getProperty(HUDSON_PROPERTY);
if (env != null) {
return env;
} else if (property != null) {
return property;
} else {
return Environment.getBaseDir() + HUDSON_DIR;
}
}
public static File getTmpDirFile() {
File tmpDir = new File(getBaseDirFile(), "tmp");
if (!tmpDir.exists()) {
tmpDir.mkdirs();
}
return tmpDir;
}
protected static String getHomeDir() {
String env = System.getenv(JABOX_ENV);
String property = System.getProperty(JABOX_PROPERTY);
if (env != null) {
- return env + File.separatorChar;
+ return new File(env).getAbsolutePath() + File.separator;
} else if (property != null) {
- return property + File.separatorChar;
+ return new File(property).getAbsolutePath() + File.separator;
}
- String homeDir = System.getProperty("user.home") + File.separatorChar
- + ".jabox" + File.separatorChar;
+ String homeDir = new File(System.getProperty("user.home"), ".jabox")
+ .getAbsolutePath()
+ + File.separator;
System.setProperty(JABOX_PROPERTY, homeDir);
return homeDir;
}
public static void configureEnvironmentVariables() {
configBaseDir(HUDSON_ENV, HUDSON_PROPERTY, HUDSON_DIR);
configBaseDir("ARTIFACTORY_HOME", "artifactory.home", ".artifactory/");
configBaseDir("NEXUS_HOME", "plexus.nexus-work", ".nexus/");
}
private static void configBaseDir(final String env, final String property,
final String subdir) {
if (System.getenv(env) == null && System.getProperty(property) == null) {
System.setProperty(property, Environment.getBaseDir() + subdir);
}
}
}
| false | true | protected static String getHomeDir() {
String env = System.getenv(JABOX_ENV);
String property = System.getProperty(JABOX_PROPERTY);
if (env != null) {
return env + File.separatorChar;
} else if (property != null) {
return property + File.separatorChar;
}
String homeDir = System.getProperty("user.home") + File.separatorChar
+ ".jabox" + File.separatorChar;
System.setProperty(JABOX_PROPERTY, homeDir);
return homeDir;
}
| protected static String getHomeDir() {
String env = System.getenv(JABOX_ENV);
String property = System.getProperty(JABOX_PROPERTY);
if (env != null) {
return new File(env).getAbsolutePath() + File.separator;
} else if (property != null) {
return new File(property).getAbsolutePath() + File.separator;
}
String homeDir = new File(System.getProperty("user.home"), ".jabox")
.getAbsolutePath()
+ File.separator;
System.setProperty(JABOX_PROPERTY, homeDir);
return homeDir;
}
|
diff --git a/src/gwtbootstrap3/src/main/java/com/svenjacobs/gwtbootstrap3/client/ui/PageHeader.java b/src/gwtbootstrap3/src/main/java/com/svenjacobs/gwtbootstrap3/client/ui/PageHeader.java
index a020d45..690c5dc 100644
--- a/src/gwtbootstrap3/src/main/java/com/svenjacobs/gwtbootstrap3/client/ui/PageHeader.java
+++ b/src/gwtbootstrap3/src/main/java/com/svenjacobs/gwtbootstrap3/client/ui/PageHeader.java
@@ -1,94 +1,94 @@
package com.svenjacobs.gwtbootstrap3.client.ui;
/*
* #%L
* GwtBootstrap3
* %%
* Copyright (C) 2013 Sven Jacobs
* %%
* 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.
* #L%
*/
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget;
import com.svenjacobs.gwtbootstrap3.client.ui.base.mixin.IdMixin;
import com.svenjacobs.gwtbootstrap3.client.ui.constants.Styles;
/**
* Page header with optional subtext
* <p/>
* <h3>UiBinder example</h3>
* <pre>{@code
* <b:PageHeader subText="Some subtext">Page header title</b:PageHeader>
* }</pre>
*
* @author Sven Jacobs
*/
public class PageHeader extends Widget implements HasText, HasId {
private final IdMixin idMixin = new IdMixin(this);
private String heading;
private String subText;
public PageHeader() {
setElement(DOM.createDiv());
setStyleName(Styles.PAGE_HEADER);
}
public void setSubText(final String subText) {
this.subText = subText;
render();
}
@Override
public void setText(final String text) {
this.heading = text;
render();
}
@Override
public String getText() {
return heading;
}
@Override
public void setId(final String id) {
idMixin.setId(id);
}
@Override
public String getId() {
return idMixin.getId();
}
private void render() {
final SafeHtmlBuilder builder = new SafeHtmlBuilder();
builder.appendHtmlConstant("<h1>");
builder.appendEscaped(heading == null ? "" : heading);
if (subText != null && !subText.isEmpty()) {
builder.appendEscaped(" ");
builder.appendHtmlConstant("<small>");
builder.appendEscaped(subText);
builder.appendHtmlConstant("</small>");
}
builder.appendHtmlConstant("</h1>");
- getElement().setInnerHTML(builder.toSafeHtml().asString());
+ getElement().setInnerSafeHtml(builder.toSafeHtml());
}
}
| true | true | private void render() {
final SafeHtmlBuilder builder = new SafeHtmlBuilder();
builder.appendHtmlConstant("<h1>");
builder.appendEscaped(heading == null ? "" : heading);
if (subText != null && !subText.isEmpty()) {
builder.appendEscaped(" ");
builder.appendHtmlConstant("<small>");
builder.appendEscaped(subText);
builder.appendHtmlConstant("</small>");
}
builder.appendHtmlConstant("</h1>");
getElement().setInnerHTML(builder.toSafeHtml().asString());
}
| private void render() {
final SafeHtmlBuilder builder = new SafeHtmlBuilder();
builder.appendHtmlConstant("<h1>");
builder.appendEscaped(heading == null ? "" : heading);
if (subText != null && !subText.isEmpty()) {
builder.appendEscaped(" ");
builder.appendHtmlConstant("<small>");
builder.appendEscaped(subText);
builder.appendHtmlConstant("</small>");
}
builder.appendHtmlConstant("</h1>");
getElement().setInnerSafeHtml(builder.toSafeHtml());
}
|
diff --git a/crypto/test/src/org/bouncycastle/sasn1/test/ParseTest.java b/crypto/test/src/org/bouncycastle/sasn1/test/ParseTest.java
index d61aa189..d63858ab 100644
--- a/crypto/test/src/org/bouncycastle/sasn1/test/ParseTest.java
+++ b/crypto/test/src/org/bouncycastle/sasn1/test/ParseTest.java
@@ -1,300 +1,300 @@
package org.bouncycastle.sasn1.test;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
import org.bouncycastle.sasn1.Asn1InputStream;
import org.bouncycastle.sasn1.Asn1OctetString;
import org.bouncycastle.sasn1.Asn1Sequence;
import org.bouncycastle.sasn1.BerTag;
import org.bouncycastle.sasn1.cms.ContentInfoParser;
import org.bouncycastle.sasn1.cms.EncryptedContentInfoParser;
import org.bouncycastle.sasn1.cms.EnvelopedDataParser;
import org.bouncycastle.util.encoders.Base64;
public class ParseTest
extends TestCase
{
private static byte[] classCastTest = Base64.decode(
"MIIXqAYJKoZIhvcNAQcDoIIXmTCCF5UCAQAxggG1MIIBsQIBADCBmDCBkDEL"
+ "MAkGA1UEBhMCVVMxETAPBgNVBAgTCE1pY2hpZ2FuMQ0wCwYDVQQHEwRUcm95"
+ "MQwwCgYDVQQKEwNFRFMxGTAXBgNVBAsTEEVMSVQgRW5naW5lZXJpbmcxJDAi"
+ "BgkqhkiG9w0BCQEWFUVsaXQuU2VydmljZXNAZWRzLmNvbTEQMA4GA1UEAxMH"
+ "RURTRUxJVAIDD6FBMA0GCSqGSIb3DQEBAQUABIIBAGh04C2SyEnH9J2Va18w"
+ "3vdp5L7immD5h5CDZFgdgHln5QBzT7hodXMVHmyGnycsWnAjYqpsil96H3xQ"
+ "A6+9a7yB6TYSLTNv8zhL2qU3IrfdmUJyxxfsFJlWFO1MlRmu9xEAW5CeauXs"
+ "RurQCT+C5tLc5uytbvw0Jqbz+Qp1+eaRbfvyhWFGkO/BYZ89hVL9Yl1sg/Ls"
+ "mA5jwTj2AvHkAwis+F33ZhYlto2QDvbPsUa0cldnX8+1Pz4QzKMHmfUbFD2D"
+ "ngaYN1tDlmezCsYFQmNx1th1SaQtTefvPr+qaqRsm8KEXlWbJQXmIfdyi0zY"
+ "qiwztEtO81hXZYkKqc5fKMMwghXVBgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcE"
+ "CEq3cLLWVds9gIIVsAAik3al6Nn5pr7r0mSy9Ki3vEeCBcV9EzEG44BvNHNA"
+ "WyEsqQsdSxuF7h1/DJAMuZFwCbGflaRGx/1L94zrmtpeuH501lzPMvvZCmpj"
+ "KrOF8e1B4MVQ5TfQTdUVyRnbcDa6E4V1ZZIdAI7BgDeJttS4+L6btquXfxUg"
+ "ttPYQkevF7MdShYNnfLkY4vUMDOp3+iVzrOlq0elM95dfSA7OdBavgDJbz/7"
+ "mro3AFTytnWjGz8TUos+oUujTk9/kHOn4cEAIm0hHrNhPS5qoj3QnNduNrad"
+ "rLpGtcYyNlHIsYCsvPMxwoHmIw+r9xQQRjjzmVYzidn+cNOt0FmLs6YE8ds4"
+ "wvHRO9S69TgKPHRgk2bihgHqII9lF9qIzfG40YwJLHzGoEwVO1O0+wn8j2EP"
+ "O9I/Q3vreCH+5VbpUD2NGTwsMwZ3YlUesurLwse/YICxmgdN5Ro4DeQJSa9M"
+ "iJnRFYWRq+58cKgr+L11mNc9nApZBShlpPP7pdNqWOafStIEjo+dsY/J+iyS"
+ "6WLlUvNt/12qF4NAgZMb3FvRQ9PrMe87lqSRnHcpLWHcFjuKbMKCBvcdWGWI"
+ "R7JR8UNzUvoLGGAUI9Ck+yTq4QtfgtL5MLmdBGxSKzgs44Mmek+LnrFx+e9n"
+ "pkrdDf2gM/m7E50FnLYqzUjctKYGLNYpXQorq9MJx6TB20CHXcqOOoQqesXa"
+ "9jL9PIOtBQy1Ow5Bh4SP07nTFWFSMI/Wt4ZvNvWJj3ecA9KjMOA9EXWUDS/H"
+ "k9iCb2EEMo7fe5mhoyxMxPO+EIa1sEC9A1+rDACKPQCHOLI0uPmsdo0AEECC"
+ "QLgOQkcwQlkHexOyHiOOtBxehtGZ1eBQQZ+31DF+RRU6WvS6grg58eS4gGOQ"
+ "bd7CS9yYebvAQkz61J8KprWdtZuG1gBGma12wKMuQuC6RuWlKsj+rPMvaQCt"
+ "8mucGbkElPGZVhdyD8/BvpSCNbgRwb6iSiw4EECovu4P4GFJaMGUYEuCA711"
+ "itEieYc1QqS6ULjb3LFL/RcwSw0fGdjnt6B2nHckC2VsYKU1NwU7j0R1Omb4"
+ "y5AvSgpuWjTXWnHnE9Ey0B+KP5ERZA+jJGiwYz48ynYlvQFSbBm4I6nh/DuI"
+ "dWB2dLNxWuhdfzafBGtEHhLHzjW3WQwwRZsKesgHLrrj9hBUObodl1uvqvZN"
+ "AjMOj8DrqbGOhAClj1t4S1Zk1ZekuMjsuoxEL+/lgtbT+056ES0k3A/LnpRb"
+ "uxA1ZBr26Im+GVFzEcsV0hB4vNujSwStTTZH5jX5rMyi085yJfnikcLYUn9N"
+ "apl+srhpIZlDJPw7IHaw8tsqXKDxF7MozIXo8B45CKv5Am+BMrIemCMX/ehu"
+ "PODICl98Ur8tNAn1L+m0nj7H3c8HW2vNuBLEI3SEHHgm2Ij3IY5pyyeVUaWC"
+ "pumhy8Ru5dj3fZcfKgYuJBQxWMf+UqPsf4iUK3923pouJ1cQ8XU8gOXIRrtX"
+ "e41d/yR+UAZXSig6SITLw+wLtvitSvtxvjcUSUOI9CYTovKyuz1PQKiaLsV5"
+ "4CoJhMQ5uRlVFS3H829I2d2gLRpSp6pNWeIZO2NMBxPYf2qcSHyHqQjR7xP2"
+ "ZTg7U3OO6dZHORfXxzAnW2ExavBIYQmZh1gLn5jSS4wXFPXyvnJAsF4s5wed"
+ "YHsyAqM/ek0n2Oo/zAh7UcP2vcb9FOoeRK8qC9HjTciS6WbjskRN0ft4T69G"
+ "+1RsH8/edBxo2LZeA48BSCXDXOlBZJBsOptzYJD8HSZONPnef0jn23lk0fkU"
+ "C3BjJu2ubFChctRvJniTko4klpidkHwuJgrTnL4er8rG3RfiiEHn/d5era15"
+ "E1cekdVYWqwQOObOd4v+0gZSJgI48TBc5Qdy8F6wIU38DR2pn/5uNthNDgXk"
+ "NcV9a2gOE3DoLe8CEIPMihqYMPY8NuSp97eHB2YhKpjP7qX9TUMoOdE2Iat2"
+ "klNxadJt6JTFeiBPL6R9RHAD5sVBrkrl0S+oYtgF92f9WHVwAXU7zP6IgM4x"
+ "hhzeJT07yyIp44mKd//F+7ntbgQjZ/iLbHh0mtOlUmzkFsDR0UNSXEQoourZ"
+ "EY4A62HXj0DMqEQbik6QwEF7FKuwZX2opdOyVKH9MzJxNfDLd5dc8wAc8bCX"
+ "jcCx5/GzHx2S5DndWQEVhp2hOQYuoJS3r6QCYFaHtDPKnFHS2PBFyFWL+2UK"
+ "c0WsvVaHYqYKnksmxse9I9oU75kx5O05DZCThPX6h8J8MHRuxU9tcuuleIUQ"
+ "XY8On+JeEtLSUZgp+Z7ITLuagf6yuKQpaR396MlDii/449/dvBiXAXeduyO1"
+ "QzSkQCh37fdasqGL3mP0ssMcxM/qpOwQsx3gMtwiHQRi1oQE1QHb8qZHDE4m"
+ "I5afQJ9O/H/m/EVlGUSn2yYOsPlZrWuI3BBZKoRzRq1lZOQDtOh18BE3tWmX"
+ "viGIAxajam0i2Ce3h2U7vNwtiePRNEgPmQ7RwTTv0U6X8qqkjeYskiF4Cv9G"
+ "nrB0WreC19ih5psEWLIkCYKTr+OhQuRrtv7RcyUi9QSneh7BjcvRjlGB6joA"
+ "F6J4Y6ENAA/nzOZJ699VkljTi59bbNJYlONpQhOeRTu8M/wExkIJz7yR9DTY"
+ "bY4/JdbdHNFf5DSDmYAHaFLmdnnfuRy+tC9CGGJvlcLVv5LMFJQGt2Wi15p8"
+ "lctx7sL6yNCi7OakWbEOCvGPOxY7ejnvOjVK/Krx1T+dAXNUqrsDZmvmakOP"
+ "We+P4Di1GqcyLVOTP8wNCkuAUoN0JFoBHy336/Xnae91KlY4DciPMpEOIpPN"
+ "oB+3h6CozV7IWX5Wh3rhfC25nyGJshIBUS6cMXAsswQI8rOylMlGaekNcSU4"
+ "gNKNDZAK5jNkS0Z/ziIrElSvMNTfYbnx3gCkY0pV18uadmchXihVT11Bt77O"
+ "8KCKHycR39WYFIRO09wvGv6P42CRBFTdQbWFtkSwRiH8l6x39Z7pIkDFxokT"
+ "Dp6Htkj3ywfQXNbFgRXZUXqgD1gZVFDFx920hcJnuu65CKz6pEL6X0XUwNPg"
+ "vtraA2nj4wjVB/y+Cxc+1FgzeELB4CAmWO1OfRVLjYe7WEe/X5DPT6p8HBkB"
+ "5mWuv+iQ3e37e1Lrsjt2frRYQWoOSP5Lv7c8tZiNfuIp07IYnJKBWZLTqNf9"
+ "60uiY93ssE0gr3mfYOj+fSbbjy6NgAenT7NRZmFCjFwAfmapIV0hJoqnquaN"
+ "jj5KKOP72hp+Zr9l8cEcvIhG/BbkY3kYbx3JJ9lnujBVr69PphHQTdw67CNB"
+ "mDkH7y3bvZ+YaDY0vdKOJif9YwW2qoALXKgVBu1T2BONbCTIUTOzrKhWEvW8"
+ "D6x03JsWrMMqOKeoyomf1iMt4dIOjp7yGl/lQ3iserzzLsAzR699W2+PWrAT"
+ "5vLgklJPX/Fb3Tojbsc074lBq669WZe3xzlj85hFcBmoLPPyBE91BLhEwlGC"
+ "+lWmwFOENLFGZE0mGoRN+KYxwqfA2N6H8TWoz6m0oPUW4uQvy9sGtYTSyQO9"
+ "6ZwVNT3ndlFrP5p2atdEFVc5aO5FsK8/Fenwez06B2wv9cE9QTVpFrnJkKtF"
+ "SaPCZkignj64XN7cHbk7Ys6nC3WIrTCcj1UOyp5ihuMS9eL9vosYADsmrR6M"
+ "uqqeqHsf2+6U1sO1JBkDYtLzoaILTJoqg9/eH7cTA0T0mEfxVos9kAzk5nVN"
+ "nVOKFrCGVIbOStpYlWP6wyykIKVkssfO6D42D5Im0zmgUwgNEkB+Vxvs8bEs"
+ "l1wPuB2YPRDCEvwM3A5d5vTKhPtKMECIcDxpdwkD5RmLt+iaYN6oSFzyeeU0"
+ "YvXBQzq8gfpqJu/lP8cFsjEJ0qCKdDHVTAAeWE6s5XpIzXt5cEWa5JK7Us+I"
+ "VbSmri4z0sVwSpuopXmhLqLlNWLGXRDyTjZSGGJbguczXCq5XJ2E3E4WGYd6"
+ "mUWhnP5H7gfW7ILOUN8HLbwOWon8A6xZlMQssL/1PaP3nL8ukvOqzbIBCZQY"
+ "nrIYGowGKDU83zhO6IOgO8RIVQBJsdjXbN0FyV/sFCs5Sf5WyPlXw/dUAXIA"
+ "cQiVKM3GiVeAg/q8f5nfrr8+OD4TGMVtUVYujfJocDEtdjxBuyFz3aUaKj0F"
+ "r9DM3ozAxgWcEvl2CUqJLPHH+AWn5kM7bDyQ2sTIUf5M6hdeick09hwrmXRF"
+ "NdIoUpn7rZORh0h2VX3XytLj2ERmvv/jPVC97VKU916n1QeMJLprjIsp7GsH"
+ "KieC1RCKEfg4i9uHoIyHo/VgnKrnTOGX/ksj2ArMhviUJ0yjDDx5jo/k5wLn"
+ "Rew2+bhiQdghRSriUMkubFh7TN901yl1kF2BBP5PHbpgfTP6R7qfl8ZEwzzO"
+ "elHe7t7SvI7ff5LkwDvUXSEIrHPGajYvBNZsgro+4Sx5rmaE0QSXACG228OQ"
+ "Qaju8qWqA2UaPhcHSPHO/u7ad/r8kHceu0dYnSFNe1p5v9Tjux0Yn6y1c+xf"
+ "V1cu3plCwzW3Byw14PH9ATmi8KJpZQaJOqTxn+zD9TvOa93blK/9b5KDY1QM"
+ "1s70+VOq0lEMI6Ch3QhFbXaslpgMUJLgvEa5fz3GhmD6+BRHkqjjwlLdwmyR"
+ "qbr4v6o+vnJKucoUmzvDT8ZH9nH2WCtiiEtQaLNU2vsJ4kZvEy0CEajOrqUF"
+ "d8qgEAHgh9it5oiyGBB2X/52notXWOi6OMKgWlxxKHPTJDvEVcQ4zZUverII"
+ "4vYrveRXdiDodggfrafziDrA/0eEKWpcZj7fDBYjUBazwjrsn5VIWfwP2AUE"
+ "wNn+xR81/so8Nl7EDBeoRXttyH7stbZYdRnkPK025CQug9RLzfhEAgjdgQYw"
+ "uG+z0IuyctJW1Q1E8YSOpWEFcOK5okQkLFUfB63sO1M2LS0dDHzmdZriCfIE"
+ "F+9aPMzojaHg3OQmZD7MiIjioV6w43bzVmtMRG22weZIYH/Sh3lDRZn13AS9"
+ "YV6L7hbFtKKYrie79SldtYazYT8FTSNml/+Qv2TvYTjVwYwHpm7t479u+MLh"
+ "LxMRVsVeJeSxjgufHmiLk7yYJajNyS2j9Kx/fmXmJbWZNcerrfLP+q+b594Y"
+ "1TGWr8E6ZTh9I1gU2JR7WYl/hB2/eT6sgSYHTPyGSxTEvEHP242lmjkiHY94"
+ "CfiTMDu281gIsnAskl05aeCBkj2M5S0BWCxy7bpVAVFf5nhf74EFIBOtHaJl"
+ "/8psz1kGVF3TzgYHkZXpUjVX/mJX8FG0R8HN7g/xK73HSvqeamr4qVz3Kmm/"
+ "kMtYRbZre7E1D10qh/ksNYnOkYBcG4P2JyjZ5q+8CQNungz2/b0Glg5LztNz"
+ "hUgG27xDOUraJXjkkZl/GOh0eTqhfLHXC/TfyoEAQOPcA59MKqvroFC5Js0Q"
+ "sTgqm2lWzaLNz+PEXpJHuSifHFXaYIkLUJs+8X5711+0M03y8iP4jZeEOrjI"
+ "l9t3ZYbazwsI3hBIke2hGprw4m3ZmSvQ22g+N6+hnitnDALMsZThesjb6aJd"
+ "XOwhjLkWRD4nQN594o6ZRrfv4bFEPTp4ev8l6diouKlXSFFnVqz7AZw3Pe53"
+ "BvIsoh66zHBpZhauPV/s/uLb5x6Z8sU2OK6AoJ7b8R9V/AT7zvonBi/XQNw3"
+ "nwkwGnTS9Mh7PFnGHLJWTKKlYXrSpNviR1vPxqHMO6b+Lki10d/YMY0vHQrY"
+ "P6oSVkA6RIKsepHWo11+rV838+2NRrdedCe91foUmOs+eoWQnwmTy2CTZmQ5"
+ "b7/TTcau9ewimZAqI+MtDWcmWoZfgibZmnIITGcduNOJDRn+aLt9dz+zr1qA"
+ "HxlLXCOyBPdtfx6eo4Jon+fVte37i3HmxHk+8ZGMMSS9hJbLQEkA59b4E+7L"
+ "GI3JZjvEkhizB4n/aFeG7KT7K3x072DMbHLZ7VgsXQ1VDDmcZmizFwgyNqKy"
+ "hKCKxU+I2O10IMtiZUpEzV1Pw7hD5Kv/eFCsJFPXOJ2j3KP6qPtX5IYki1qH"
+ "Juo5C5uGKtqNc6OzkXsvNUfBz5sJkEYl0WfitSSo4ARyshFUNh2hGxNxUVKM"
+ "2opOcuHSxBgwUSmVprym50C305zdHulBXv3mLzGjvRstE9qfkQ8qVJYLQEkL"
+ "1Yn7E92ex71YsC8JhNNMy0/YZwMkiFrqyaFd/LrblWpBbGumhe4reCJ4K3mk"
+ "lFGEsICcMoe+zU1+QuLlz/bQ+UtvClHUe8hTyIjfY04Fwo2vbdSc1U/SHho5"
+ "thQy+lOZ/HijzCmfWK3aTqYMdwCUTCsoxri2N8vyD/K2kbMLQWUfUlBQfDOK"
+ "VrksBoSfcluNVaO56uEUw3enPhhJghfNlJnpr5gUcrAMES53DfkjNr0dCsfM"
+ "JOY2ZfQEwwYey1c4W1MNNMoegSTg4aXzjVc0xDgKa7RGbtRmVNbOxIhUNAVi"
+ "thQV3Qujoz1ehDt2GyLpjGjHSpQo3WlIU4OUqJaQfF6EH+3khFqUmp1LT7Iq"
+ "zH3ydYsoCDjvdXSSEY3hLcZVijUJqoaNWBLb/LF8OG5qTjsM2gLgy2vgO/lM"
+ "NsqkHnWTtDimoaRRjZBlYLhdzf6QlfLi7RPmmRriiAOM0nXmylF5xBPHQLoz"
+ "LO9lXYIfNbVJVqQsV43z52MvEQCqPNpGqjB+Au/PZalYHbosiVOQLgTB9hTI"
+ "sGutSXXeLnf5rftCFvWyL3n5DgURzDFLibrbyVGGKAk166bK1RyVP9XZJonr"
+ "hPYELk4KawCysJJSmC0E8sSsuXpfd6PPDru6nCV1EdXKR7DybS7NVHCktiPR"
+ "4B4y8O/AgfJX8sb6LuxmjaINtUKEJ1+O88Gb69uy6b/Kpu2ri/SUBaNNw4Sn"
+ "/tuaD+jxroL7RlZmt9ME/saNKn9OmLuggd6IUKAL4Ifsx9i7+JKcYuP8Cjdf"
+ "Rx6U6H4qkEwwYGXnZYqF3jxplyOfqA2Vpvp4rnf8mST6dRLKk49IhKGTzwZr"
+ "4za/RZhyl6lyoRAFDrVs1b+tj6RYZk0QnK3dLiN1MFYojLyz5Uvi5KlSyFw9"
+ "trsvXyfyWdyRmJqo1fT7OUe0ImJW2RN3v/qs1k+EXizgb7DW4Rc2goDsCGrZ"
+ "ZdMwuAdpRnyg9WNtmWwp4XXeb66u3hJHr4RwMd5oyKFB1GsmzZF7aOhSIb2B"
+ "t3coNXo/Y+WpEj9fD7/snq7I1lS2+3Jrnna1048O7N4b5S4b5TtEcCBILP1C"
+ "SRvaHyZhBtJpoH6UyimKfabXi08ksrcHmbs1+HRvn+3pl0bHcdeBIQS/wjk1"
+ "TVEDtaP+K9zkJxaExtoa45QvqowxtcKtMftNoznF45LvwriXEDV9jCXvKMcO"
+ "nxG5aQ//fbnn4j4q1wsKXxn61wuLUW5Nrg9fIhX7nTNAAooETO7bMUeOWjig"
+ "2S1nscmtwaV+Sumyz/XUhvWynwE0AXveLrA8Gxfx");
private static byte[] derExpTest = Base64.decode(
"MIIS6AYJKoZIhvcNAQcDoIIS2TCCEtUCAQAxggG1MIIBsQIBADCBmDCBkDEL"
+ "MAkGA1UEBhMCVVMxETAPBgNVBAgTCE1pY2hpZ2FuMQ0wCwYDVQQHEwRUcm95"
+ "MQwwCgYDVQQKEwNFRFMxGTAXBgNVBAsTEEVMSVQgRW5naW5lZXJpbmcxJDAi"
+ "BgkqhkiG9w0BCQEWFUVsaXQuU2VydmljZXNAZWRzLmNvbTEQMA4GA1UEAxMH"
+ "RURTRUxJVAIDD6FBMA0GCSqGSIb3DQEBAQUABIIBAGsRYK/jP1YujirddAMl"
+ "ATysfLCwd0eZhENohVqLiMleH25Dnwf+tBaH4a9hyW+7VrWw/LC6ILPVbKpo"
+ "oLBAOical40cw6C3zulajc4gM3AlE2KEeAWtI+bgPMXhumqiWDb4byX/APYk"
+ "53Gk7WXF6Xs4hj3tmrHSJxCUOsTdHKUJYvOqjwKGARPQDjP0EUbVJezeAwBA"
+ "RMlJ/qBVLBj2UW28n5oJZm3oaSaU93Uc6GPVIk43IWrmEUcWVPiMfUtUCwcX"
+ "tRNtHuQ9os++rmdNBiuB5p+vtUeA45KWnTUtkwJXvrzE6Sf9AUH/p8uOvvZJ"
+ "3yt9LhPxcZukGIVvcQnBxLswghEVBgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcE"
+ "CGObmTycubs2gIIQ8AKUC8ciGPxa3sFJ1EPeX/nRwYGNAarlpVnG+07NITL2"
+ "pUzqZSgsYh5JiKd8TptQBZNdebzNmCvjrVv5s9PaescGcypL7FNVPEubh0w/"
+ "8h9rTACqUpF5yRgfcgpAGeK29F1hyZ1WaIH43avUCaDnrZcOKB7wc1ats1aQ"
+ "TSDLImyFn4KjSo5k0Ec/xSoWnfg391vebp8eOsyHZhFMffFtKQMaayZNHJ7Q"
+ "BzG3r/ysUbkgI5x+0bX0QfZjEIs7yuV5Wt8DxMTueCm3RQ+HkR4lNdTBkM4V"
+ "qozCqC1SjcAF5YHB0WFkGouEPGgTlmyvLqR2xerEXVZn9YwSnT48kOde3oGt"
+ "EAYyg0yHbNbL0sp6LDM7upRmrgWwxf0BR6lP4wyWdv/XSLatEB7twSNiPBJ4"
+ "PJ+QagK08yQJ84UB7YpMTudKsaUs7zW76eA7KkW3TndfDYGdhbmZ5wxNl+5x"
+ "yPZc/jcQHW7vplMfWglUVxnzibNW12th0QXSB57Mzk8v1Rvc/HLGvAOJZG/S"
+ "N12FZOxbUrMIHGi3kXsmfWznVyq92X4P9tuDDD7sxkSGsyUAm/UJIZ3KsXhV"
+ "QeaRHVTVDxtJtnbYxBupy1FDBO6AhVrp16Blvnip9cPn/aLfxDoFHzmsZmEg"
+ "IcOFqpT1fW+KN6i/JxLD3mn3gKzzdL1/8F36A2GxhCbefQFp0MfIovlnMLFv"
+ "mrINwMP8a9VnP8gIV5oW5CxmmMUPHuGkXrfg+69iVACaC2sTq6KGebhtg9OC"
+ "8vZhmu7+Eescst694pYa3b8Sbr5bTFXV68mMMjuRnhvF2NZgF+O0jzU+sFps"
+ "o7s1rUloCBk1clJUJ/r+j9vbhVahCeJQw62JAqjZu4R1JYAzON3S7jWU5zJ7"
+ "pWYPSAQkLYUz3FmRRS2Yv65mXDNHqR9vqkHTIphwA9CLMKC2rIONxSVB57q1"
+ "Npa/TFkVdXnw+cmYjyFWiWeDP7Mw0Kwy7tO008UrBY0rKQU466RI5ezDqYPc"
+ "Lm73dUH2EjUYmKUi8zCtXpzgfTYVa/DmkbVUL9ThHMVRq1OpT2nctE7kpXZk"
+ "OsZjEZHZX4MCrSOlc10ZW7MJIRreWMs70n7JX7MISU+8fK6JKOuaQNG8XcQp"
+ "5IrCTIH8vmN2rVt4UT8zgm640FtO3jWUxScvxCtUJJ49hGCwK+HwDDpO6fLw"
+ "LFuybey+6hnAbtaDyqgsgDh2KN8GSkQT9wixqwQPWsMQ4h0xQixf4IMdFOjP"
+ "ciwp3ul8KAp/q70i0xldWGqcDjUasx6WHKc++rFjVJjoVvijKgEhlod5wJIw"
+ "BqQVMKRsXle07NS1MOB+CRTVW6mwBEhDDERL+ym2GT2Q4uSDzoolmLq2y5vL"
+ "+RfDHuh3W0UeC3Q5D2bJclgMsVjgfQUN19iD+lPFp2xvLTaNWi5fYDn4uuJL"
+ "lgVDXIMmM8I+Z2hlTXTM1Pldz2/UFe3QXTbYnjP6kfd7Bo2Webhhgs/YmSR2"
+ "XPuA42tWNAAjlK77lETWodxi3UC7XELjZ9xoGPRbxjOklXXvev9v5Vo+vcmN"
+ "0KrLXhLdkyHRSm81SRsWoadCTSyT8ibv66P00GOt+OlIUOt0YKSUkULQfPvC"
+ "EgMpeTm1/9l8n9bJ6td5fpJFDqLDm+FpJX6T2sWevV/Tyt6aoDPuET5iHBHW"
+ "PoHxKl8YPRHBf+nRWoh45QMGQWNSrJRDlO8oYOhdznh4wxLn3DXEfDr0Z7Kd"
+ "gEg6xr1XCobBn6Gi7wWXp5FDTaRF41t7fH8VxPwwDa8Yfu3vsgB6q426kjAj"
+ "Q77wx1QFIg8gOYopTOgqze1i4h1U8ehP9btznDD6OR8+hPsVKoXYGp8Ukkc7"
+ "JBA0o8l9O2DSGh0StsD94UhdYzn+ri7ozkXFy2SHFT2/saC34NHLoIF0v/aw"
+ "L9G506Dtz6xXOACZ4brCG+NNnPLIcGblXIrYTy4+sm0KSdsl6BGzYh9uc8tu"
+ "tfCh+iDuhT0n+nfnvdCmPwonONFb53Is1+dz5sisILfjB7OPRW4ngyfjgfHm"
+ "oxxHDC/N01uoJIdmQRIisLi2nLhG+si8+Puz0SyPaB820VuV2mp77Y2osTAB"
+ "0hTDv/sU0DQjqcuepYPUMvMs3SlkEmaEzNSiu7xOOBQYB8FoK4PeOXDIW6n2"
+ "0hv6iS17hcZ+8GdhwC4x2Swkxt99ikRM0AxWrh1lCk5BagVN5xG79c/ZQ1M7"
+ "a0k3WTzYF1Y4d6QPNOYeOBP9+G7/a2o3hGXDRRXnFpO7gQtlXy9A15RfvsWH"
+ "O+UuFsOTtuiiZk1qRgWW5nkSCPCl2rP1Z7bwr3VD7o6VYhNCSdjuFfxwgNbW"
+ "x8t35dBn6xLkc6QcBs2SZaRxvPTSAfjON++Ke0iK5w3mec0Br4QSNB1B0Aza"
+ "w3t3AleqPyJC6IP1OQl5bi+PA+h3YZthwQmcwgXgW9bWxNDqUjUPZfsnNNDX"
+ "MU9ANDLjITxvwr3F3ZSfJyeeDdbhr3EJUTtnzzWC6157EL9dt0jdPO35V0w4"
+ "iUyZIW1FcYlCJp6t6Sy9n3TmxeLbq2xML4hncJBClaDMOp2QfabJ0XEYrD8F"
+ "jq+aDM0NEUHng+Gt9WNqnjc8GzNlhxTNm3eQ6gyM/9Ip154GhH6c9hsmkMy5"
+ "DlMjGFpFnsSTNFka2+DOzumWUiXLGbe4M3RePl1N4MLwXrkR2llguQynyoqF"
+ "Ptat2Ky5yW2q9+IQHY49NJTlsCpunE5HFkAK9rY/4lM4/Q7hVunP6U4a0Kbu"
+ "beFuOQMKQlBZvcplnYBefXD79uarY/q7ui6nFHlqND5mlXMknMrsQk3papfp"
+ "OpMS4T07rCTLek0ODtb5KsHdIF76NZXevko4+d/xbv7HLCUYd8xuOuqf+y4I"
+ "VJiT1FmYtZd9w+ubfHrOfHxY+SBtN6fs02WAccZqBXUYzZEijRbN2YUv1OnG"
+ "rfYe4EcfOu/Sa+wLbB7msYpLfvUfEO3iseKf4LXZkgtF5P610PBZR8edeSgr"
+ "YZW+J0K78PRAl5nEi1mvzBxi9DyNf6iQ9mWLyyCmr9p9HGE+aCMKVCn9jfZH"
+ "WeBDAJNYDcUh5NEckqJtbEc2S1FJM7yZBWLQUt3NCQvj+nvQT45osZ3BJvFg"
+ "IcGJ0CysoblVz4fCLybrYxby9HP89WMLHqdqsIeVX8IJ3x84SqLPuzrqf9FT"
+ "ZVYLo0F2oBjAzjT7obt9+NJc/psOMCg+OGQkAfwj3VNvaqkkQsVxSiozgxrC"
+ "7KaTXuAL6eKKspman96kz4QVk9P0usUPii+LFnW4XYc0RNfgJVO6BgJT7pLX"
+ "NWwv/izMIMNAqSiWfzHHRVkhq4f1TMSF91auXOSICpJb3QQ4XFh52Mgl8+zs"
+ "fobsb0geyb49WqFrZhUu+X+8LfQztppGmiUpFL+8EW0aPHbfaf4y9J1/Wthy"
+ "c28Yqu62j/ljXq4Qa21uaEkoxzH1wPKCoKM9TXJtZJ39Yl9cf119Qy4M6QsB"
+ "6oMXExlMjqIMCCWaLXLRiqbc2Y7rZHgEr08msibdoYHbSkEl8U+Kii2p6Vdx"
+ "zyiEIz4CadrFbrAzxmrR/+3u8JuBdq0K3KNR0WWx73BU+G0rgBX56GnP7Ixy"
+ "fuvkRb4YfJUF4PkDa50BGVhybPrIhoFteT6bSh6LQtBm9c4Kop8Svx3ZbqOT"
+ "kgQDa0n+O0iR7x3fvNZ0Wz4YJrKGnVOPCqJSlSsnX6v2JScmaNdrSwkMTnUf"
+ "F9450Hasd88+skC4jVAv3WAB03Gz1MtiGDhdUKFnHnU9HeHUnh38peCFEfnK"
+ "WihakVQNfc72YoFVZHeJI5fJAW8P7xGTZ95ysyirtirxt2zkRVJa5p7semOw"
+ "bL/lBC1bp4J6xHF/NHY8NQjvuhqkDyNlh3dRpIBVBu6Z04hRhLFW6IBxcCCv"
+ "pjfoxJoox9yxKQKpr3J6MiZKBlndZRbSogO/wYwFeh7HhUzMNM1xIy3jWVVC"
+ "CrzWp+Q1uxnL74SwrMP/EcZh+jZO4CYWk6guUMhTo1kbW03BZfyAqbPM+X+e"
+ "ZqMZljydH8AWgl0MZd2IAfajDxI03/6XZSgzq24n+J7wKMYWS3WzB98OIwr+"
+ "oKoQ7aKwaaT/KtR8ggUVYsCLs4ScFY24MnjUvMm+gQcVyeX74UlqR30Aipnf"
+ "qzDRVcAUMMNcs0fuqePcrZ/yxPo+P135YClPDo9J8bwNpioUY8g+BQxjEQTj"
+ "py3i2rAoX+Z5fcGjnZQVPMog0niIvLPRJ1Xl7yzPW0SevhlnMo6uDYDjWgQ2"
+ "TLeTehRCiSd3z7ZunYR3kvJIw1Kzo4YjdO3l3WNf3RQvxPmJcSKzeqKVxWxU"
+ "QBMIC/dIzmRDcY787qjAlKDZOdDp7qBKIqnfodWolxBA0KhvE61eYabZqUCT"
+ "G2HJaQE1SvOdL9KM4ORFlxE3/dqv8ttBJ6N1qKk423CJjajZHYTwf1dCfj8T"
+ "VAE/A3INTc6vg02tfkig+7ebmbeXJRH93KveEo2Wi1xQDsWNA+3DVzsMyTqV"
+ "+AgfSjjwKouXAznhpgNc5QjmD2I6RyTf+hngftve18ZmVhtlW5+K6qi62M7o"
+ "aM83KweH1QgCS12/p2tMEAfz//pPbod2NrFDxnmozhp2ZnD04wC+6HGz6bX/"
+ "h8x2PDaXrpuqnZREFEYzUDKQqxdglXj5oE/chBR8+eBfYSS4JW3TBkW6RfwM"
+ "KOBBOOv8pe3Sfq/bg7OLq5bn0jKwulqP50bysZJNlQUG/KqJagKRx60fnTqB"
+ "7gZRebvtqgn3JQU3fRCm8ikmGz9XHruoPlrUQJitWIt4AWFxjyl3oj+suLJn"
+ "7sK62KwsqAztLV7ztoC9dxldJF34ykok1XQ2cMT+uSrD6ghYZrmrG5QDkiKW"
+ "tOQCUvVh/CorZNlON2rt67UvueMoW+ua25K4pLKDW316c2hGZRf/jmCpRSdb"
+ "Xr3RDaRFIK6JpmEiFMMOEnk9yf4rChnS6MHrun7vPkf82w6Q0VxoR8NRdFyW"
+ "3mETtm2mmG5zPFMMD8uM0BYJ/mlJ2zUcD4P3hWZ8NRiU5y1kazvrC6v7NijV"
+ "o459AKOasZUj1rDMlXDLPloTHT2ViURHh/8GKqFHi2PDhIjPYUlLR5IrPRAl"
+ "3m6DLZ7/tvZ1hHEu9lUMMcjrt7EJ3ujS/RRkuxhrM9BFlwzpa2VK8eckuCHm"
+ "j89UH5Nn7TvH964K67hp3TeV5DKV6WTJmtIoZKCxSi6FFzMlky73gHZM4Vur"
+ "eccwycFHu+8o+tQqbIAVXaJvdDstHpluUCMtb2SzVmI0bxABXp5XrkOOCg8g"
+ "EDZz1I7rKLFcyERSifhsnXaC5E99BY0DJ/7v668ZR3bE5cU7Pmo/YmJctK3n"
+ "m8cThrYDXJNbUi0c5vrAs36ZQECn7BY/bdDDk2NPgi36UfePI8XsbezcyrUR"
+ "ZZwT+uQ5LOB931NjD5GOMEb96cjmECONcRjB0uD7DoTiVeS3QoWmf7Yz4g0p"
+ "v9894YWQgOl+CvmTERO4dxd7X5wJsM3Y0acGPwneDF+HtQrIpJlslm2DivEv"
+ "sikc6DtAQrnVRSNDr67HPPeIpgzThbxH3bm5UjvnP/zcGV1W8Nzk/OBQWi0l"
+ "fQM9DccS6P/DW3XPSD1+fDtUK5dfH8DFf8wwgnxeVwi/1hCBq9+33XPwiVpz"
+ "489DnjGhHqq7BdHjTIqAZvNm8UPQfXRpeexbkFZx1mJvS7so54Cs58/hHgQN"
+ "GHJh4AUCLEt0v7Hc3CMy38ovLr3Q8eZsyNGKO5GvGNa7EffGjzOKxgqtMwT2"
+ "yv8TOTFCWnZEUTtVA9+2CpwfmuEjD2UQ4vxoM+o=");
public void testClassCast()
throws IOException
{
parseEnveloped(classCastTest);
}
public void testDerExp()
throws IOException
{
parseEnveloped(derExpTest);
}
private void parseEnveloped(byte[] data) throws IOException
{
Asn1InputStream aIn = new Asn1InputStream(data);
ContentInfoParser cP = new ContentInfoParser((Asn1Sequence)aIn.readObject());
EnvelopedDataParser eP = new EnvelopedDataParser((Asn1Sequence)cP.getContent(BerTag.SEQUENCE));
eP.getRecipientInfos();
EncryptedContentInfoParser ecP = eP.getEncryptedContentInfo();
Asn1OctetString content = (Asn1OctetString)ecP.getEncryptedContent(BerTag.OCTET_STRING);
InputStream in = content.getOctetStream();
while (in.read() >= 0)
{
- ;
+ // do nothing
}
}
}
| true | true | private void parseEnveloped(byte[] data) throws IOException
{
Asn1InputStream aIn = new Asn1InputStream(data);
ContentInfoParser cP = new ContentInfoParser((Asn1Sequence)aIn.readObject());
EnvelopedDataParser eP = new EnvelopedDataParser((Asn1Sequence)cP.getContent(BerTag.SEQUENCE));
eP.getRecipientInfos();
EncryptedContentInfoParser ecP = eP.getEncryptedContentInfo();
Asn1OctetString content = (Asn1OctetString)ecP.getEncryptedContent(BerTag.OCTET_STRING);
InputStream in = content.getOctetStream();
while (in.read() >= 0)
{
;
}
}
| private void parseEnveloped(byte[] data) throws IOException
{
Asn1InputStream aIn = new Asn1InputStream(data);
ContentInfoParser cP = new ContentInfoParser((Asn1Sequence)aIn.readObject());
EnvelopedDataParser eP = new EnvelopedDataParser((Asn1Sequence)cP.getContent(BerTag.SEQUENCE));
eP.getRecipientInfos();
EncryptedContentInfoParser ecP = eP.getEncryptedContentInfo();
Asn1OctetString content = (Asn1OctetString)ecP.getEncryptedContent(BerTag.OCTET_STRING);
InputStream in = content.getOctetStream();
while (in.read() >= 0)
{
// do nothing
}
}
|
diff --git a/src/r/data/internal/TracingView.java b/src/r/data/internal/TracingView.java
index a505db1..614b78c 100644
--- a/src/r/data/internal/TracingView.java
+++ b/src/r/data/internal/TracingView.java
@@ -1,465 +1,465 @@
package r.data.internal;
import java.lang.reflect.*;
import java.util.*;
import r.*;
import r.data.*;
public interface TracingView {
public static final boolean VIEW_TRACING = false;
public ViewTrace getTrace();
public static class ViewTrace {
final RArray realView;
ViewTrace parentView;
int[] getCounts;
int materializeCount;
int getCount;
final StackTraceElement[] allocationSite;
StackTraceElement[] firstGetSite;
StackTraceElement[] firstMaterializeSite;
static HashSet<ViewTrace> viewsRegistry = new HashSet<ViewTrace>();
public ViewTrace(RArray real) {
getCounts = new int[real.size()];
allocationSite = Thread.currentThread().getStackTrace();
realView = real;
viewsRegistry.add(this);
linkChildren(real, this);
}
private static Field[] getAllFields(Class cls) {
ArrayList<Field> res = new ArrayList<>();
Class c = cls;
while (c != View.class) {
assert Utils.check(c != null);
res.addAll(Arrays.asList(c.getDeclaredFields()));
c = c.getSuperclass();
}
return res.toArray(new Field[res.size()]);
}
private static void linkChildren(RArray parentRealView, ViewTrace parentTrace) {
Class viewClass = parentRealView.getClass();
Field[] fields = getAllFields(viewClass);
for (Field f : fields) {
if (f.isSynthetic()) {
continue;
}
Class fieldClass = f.getType();
if (RArray.class.isAssignableFrom(fieldClass)) {
try {
f.setAccessible(true);
Object o = f.get(parentRealView);
if (o instanceof TracingView) {
((TracingView) o).getTrace().parentView = parentTrace;
}
} catch (IllegalAccessException e) {
assert Utils.check(false, "can't read a view field " + e);
}
}
}
}
public void get(int i) {
if (getCount == 0) {
firstGetSite = Thread.currentThread().getStackTrace();
}
getCount++;
getCounts[i]++;
}
public void materialize() {
if (materializeCount == 0) {
firstMaterializeSite = Thread.currentThread().getStackTrace();
}
materializeCount++;
}
public int unusedElements() {
int unused = 0;
for(int g : getCounts) {
if (g == 0) {
unused++;
}
}
return unused;
}
public int redundantGets() {
int redundant = 0;
for(int g : getCounts) {
if (g > 1) {
redundant += g - 1;
}
}
return redundant;
}
private static void printElement(StackTraceElement[] elements, int index) {
if (elements == null || index >= elements.length) {
System.err.print("(null)");
} else {
StackTraceElement e = elements[index];
System.err.print( e.getMethodName() + " (" + e.getFileName() + ":" + e.getLineNumber() + ")");
}
}
private ViewTrace getRootView() {
ViewTrace v = this;
while(v.parentView != null) {
v = v.parentView;
}
return v;
}
private static void indent(int depth) {
for(int i = 0; i < depth; i++) {
System.err.print(" ");
}
}
private static void dumpView(int depth, ViewTrace trace) {
printed.add(trace);
System.err.println(trace.realView + " size = " + trace.realView.size());
indent(depth);
System.err.print(" allocationSite = ");
printElement(trace.allocationSite, 4);
System.err.println();
int unused = trace.unusedElements();
int redundant = trace.redundantGets();
if (trace.getCount > 0) {
indent(depth);
System.err.print(" firstGetSite = ");
printElement(trace.firstGetSite, 3);
System.err.println();
if (trace.materializeCount == 0) {
if (unused > 0) {
indent(depth);
System.err.println(" unusedElements = " + unused);
}
if (redundant > 0) {
indent(depth);
System.err.println(" redundantGets = " + redundant + " (no materialize)");
}
}
} else {
if (trace.materializeCount == 0) {
indent(depth);
System.err.println(" UNUSED");
} else {
if (trace.getCount > 0) {
indent(depth);
System.err.println(" extraGets = " + trace.getCount + " (in addition to materialize)");
}
}
}
if (trace.materializeCount > 0) {
indent(depth);
- System.err.println(" firstMaterializeSite = ");
- printElement(trace.firstGetSite, 2);
+ System.err.print(" firstMaterializeSite = ");
+ printElement(trace.firstMaterializeSite, 3);
System.err.println();
}
System.err.println();
RArray view = trace.realView;
Class viewClass = view.getClass();
Field[] fields = getAllFields(viewClass);
boolean printedField = false;
for(Field f : fields) {
if (f.isSynthetic()) {
continue;
}
Class fieldClass = f.getType();
if (RArray.class.isAssignableFrom(fieldClass)) {
continue; // these later
}
indent(depth);
System.err.print(" " + f.getName() + " ");
try {
f.setAccessible(true);
System.err.println(f.get(view));
printedField = true;
} catch (IllegalAccessException e) {
assert Utils.check(false, "can't read a view field " + e);
}
}
boolean printNewline = printedField;
for(Field f : fields) {
if (f.isSynthetic()) {
continue;
}
Class fieldClass = f.getType();
if (!RArray.class.isAssignableFrom(fieldClass)) {
continue;
}
if (printNewline) {
System.err.println();
printNewline = false;
}
indent(depth);
System.err.print(" " + f.getName() + " ");
try {
f.setAccessible(true);
Object o = f.get(view);
if (o instanceof TracingView) {
System.err.print("VIEW ");
TracingView child = (TracingView) o;
dumpView(depth + 2, child.getTrace());
} else {
System.err.print("ARRAY " + o + " size = " + ((RArray)o).size());
if (o instanceof View) {
System.err.println("MISSED VIEW " + o);
}
}
System.err.println();
} catch (IllegalAccessException e) {
assert Utils.check(false, "can't read a view field " + e);
}
}
}
static HashSet<ViewTrace> printed;
public static void printGlobalStats() {
printed = new HashSet<ViewTrace>();
System.err.println("Global views statistics ------------------- \n");
for(ViewTrace trace : viewsRegistry) {
if (printed.contains(trace)) {
continue;
}
ViewTrace v = trace.getRootView();
System.err.print("ROOT ");
dumpView(0, v);
System.err.println();
}
}
public static <T extends RArray> T trace(RArray orig) { // FIXME: verify this has no overhead when tracing is disabled
if (VIEW_TRACING) {
RArray res;
if (orig instanceof RList) {
res = new RListTracingView((RList) orig);
} else if (orig instanceof RString) {
res = new RStringTracingView((RString) orig);
} else if (orig instanceof RComplex) {
res = new RComplexTracingView((RComplex) orig);
} else if (orig instanceof RDouble) {
res = new RDoubleTracingView((RDouble) orig);
} else if (orig instanceof RInt) {
res = new RIntTracingView((RInt) orig);
} else if (orig instanceof RLogical) {
res = new RLogicalTracingView((RLogical) orig);
} else if (orig instanceof RRaw) {
res = new RRawTracingView((RRaw) orig);
} else {
assert Utils.check(false, "missed view type");
res = orig;
}
return (T) res;
} else {
return (T) orig;
}
}
}
public static class RListTracingView extends View.RListProxy<RList> implements RList, TracingView {
private ViewTrace trace;
public RListTracingView(RList orig) {
super(orig);
trace = new ViewTrace(orig);
}
@Override
public ViewTrace getTrace() {
return trace;
}
@Override
public RAny getRAny(int i) {
trace.get(i);
return orig.getRAny(i);
}
}
public static class RStringTracingView extends View.RStringProxy<RString> implements RString, TracingView {
private ViewTrace trace;
public RStringTracingView(RString orig) {
super(orig);
trace = new ViewTrace(orig);
}
@Override
public ViewTrace getTrace() {
return trace;
}
@Override
public String getString(int i) {
trace.get(i);
return orig.getString(i);
}
}
public static class RComplexTracingView extends View.RComplexProxy<RComplex> implements RComplex, TracingView {
private ViewTrace trace;
public RComplexTracingView(RComplex orig) {
super(orig);
trace = new ViewTrace(orig);
}
@Override
public ViewTrace getTrace() {
return trace;
}
@Override
public double getReal(int i) { // TODO: perhaps special handling for complex numbers? (will always report redundancy)
trace.get(i);
return orig.getReal(i);
}
@Override
public double getImag(int i) { // TODO: perhaps special handling for complex numbers? (will always report redundancy)
trace.get(i);
return orig.getImag(i);
}
@Override
public RComplex materialize() {
trace.materialize();
return orig.materialize();
}
}
public static class RDoubleTracingView extends View.RDoubleProxy<RDouble> implements RDouble, TracingView {
private ViewTrace trace;
public RDoubleTracingView(RDouble orig) {
super(orig);
trace = new ViewTrace(orig);
}
@Override
public ViewTrace getTrace() {
return trace;
}
@Override
public double getDouble(int i) {
trace.get(i);
return orig.getDouble(i);
}
@Override
public RDouble materialize() {
trace.materialize();
return orig.materialize();
}
}
public static class RIntTracingView extends View.RIntProxy<RInt> implements RInt, TracingView {
private ViewTrace trace;
public RIntTracingView(RInt orig) {
super(orig);
trace = new ViewTrace(orig);
}
@Override
public ViewTrace getTrace() {
return trace;
}
@Override
public int getInt(int i) {
trace.get(i);
return orig.getInt(i);
}
@Override
public RInt materialize() {
trace.materialize();
return orig.materialize();
}
}
public static class RLogicalTracingView extends View.RLogicalProxy<RLogical> implements RLogical, TracingView {
private ViewTrace trace;
public RLogicalTracingView(RLogical orig) {
super(orig);
trace = new ViewTrace(orig);
}
@Override
public ViewTrace getTrace() {
return trace;
}
@Override
public int getLogical(int i) {
trace.get(i);
return orig.getLogical(i);
}
@Override
public RLogical materialize() {
trace.materialize();
return orig.materialize();
}
}
public static class RRawTracingView extends View.RRawProxy<RRaw> implements RRaw, TracingView {
private ViewTrace trace;
public RRawTracingView(RRaw orig) {
super(orig);
trace = new ViewTrace(orig);
}
@Override
public ViewTrace getTrace() {
return trace;
}
@Override
public byte getRaw(int i) {
trace.get(i);
return orig.getRaw(i);
}
@Override
public RRaw materialize() {
trace.materialize();
return orig.materialize();
}
}
}
| true | true | private static void dumpView(int depth, ViewTrace trace) {
printed.add(trace);
System.err.println(trace.realView + " size = " + trace.realView.size());
indent(depth);
System.err.print(" allocationSite = ");
printElement(trace.allocationSite, 4);
System.err.println();
int unused = trace.unusedElements();
int redundant = trace.redundantGets();
if (trace.getCount > 0) {
indent(depth);
System.err.print(" firstGetSite = ");
printElement(trace.firstGetSite, 3);
System.err.println();
if (trace.materializeCount == 0) {
if (unused > 0) {
indent(depth);
System.err.println(" unusedElements = " + unused);
}
if (redundant > 0) {
indent(depth);
System.err.println(" redundantGets = " + redundant + " (no materialize)");
}
}
} else {
if (trace.materializeCount == 0) {
indent(depth);
System.err.println(" UNUSED");
} else {
if (trace.getCount > 0) {
indent(depth);
System.err.println(" extraGets = " + trace.getCount + " (in addition to materialize)");
}
}
}
if (trace.materializeCount > 0) {
indent(depth);
System.err.println(" firstMaterializeSite = ");
printElement(trace.firstGetSite, 2);
System.err.println();
}
System.err.println();
RArray view = trace.realView;
Class viewClass = view.getClass();
Field[] fields = getAllFields(viewClass);
boolean printedField = false;
for(Field f : fields) {
if (f.isSynthetic()) {
continue;
}
Class fieldClass = f.getType();
if (RArray.class.isAssignableFrom(fieldClass)) {
continue; // these later
}
indent(depth);
System.err.print(" " + f.getName() + " ");
try {
f.setAccessible(true);
System.err.println(f.get(view));
printedField = true;
} catch (IllegalAccessException e) {
assert Utils.check(false, "can't read a view field " + e);
}
}
boolean printNewline = printedField;
for(Field f : fields) {
if (f.isSynthetic()) {
continue;
}
Class fieldClass = f.getType();
if (!RArray.class.isAssignableFrom(fieldClass)) {
continue;
}
if (printNewline) {
System.err.println();
printNewline = false;
}
indent(depth);
System.err.print(" " + f.getName() + " ");
try {
f.setAccessible(true);
Object o = f.get(view);
if (o instanceof TracingView) {
System.err.print("VIEW ");
TracingView child = (TracingView) o;
dumpView(depth + 2, child.getTrace());
} else {
System.err.print("ARRAY " + o + " size = " + ((RArray)o).size());
if (o instanceof View) {
System.err.println("MISSED VIEW " + o);
}
}
System.err.println();
} catch (IllegalAccessException e) {
assert Utils.check(false, "can't read a view field " + e);
}
}
}
| private static void dumpView(int depth, ViewTrace trace) {
printed.add(trace);
System.err.println(trace.realView + " size = " + trace.realView.size());
indent(depth);
System.err.print(" allocationSite = ");
printElement(trace.allocationSite, 4);
System.err.println();
int unused = trace.unusedElements();
int redundant = trace.redundantGets();
if (trace.getCount > 0) {
indent(depth);
System.err.print(" firstGetSite = ");
printElement(trace.firstGetSite, 3);
System.err.println();
if (trace.materializeCount == 0) {
if (unused > 0) {
indent(depth);
System.err.println(" unusedElements = " + unused);
}
if (redundant > 0) {
indent(depth);
System.err.println(" redundantGets = " + redundant + " (no materialize)");
}
}
} else {
if (trace.materializeCount == 0) {
indent(depth);
System.err.println(" UNUSED");
} else {
if (trace.getCount > 0) {
indent(depth);
System.err.println(" extraGets = " + trace.getCount + " (in addition to materialize)");
}
}
}
if (trace.materializeCount > 0) {
indent(depth);
System.err.print(" firstMaterializeSite = ");
printElement(trace.firstMaterializeSite, 3);
System.err.println();
}
System.err.println();
RArray view = trace.realView;
Class viewClass = view.getClass();
Field[] fields = getAllFields(viewClass);
boolean printedField = false;
for(Field f : fields) {
if (f.isSynthetic()) {
continue;
}
Class fieldClass = f.getType();
if (RArray.class.isAssignableFrom(fieldClass)) {
continue; // these later
}
indent(depth);
System.err.print(" " + f.getName() + " ");
try {
f.setAccessible(true);
System.err.println(f.get(view));
printedField = true;
} catch (IllegalAccessException e) {
assert Utils.check(false, "can't read a view field " + e);
}
}
boolean printNewline = printedField;
for(Field f : fields) {
if (f.isSynthetic()) {
continue;
}
Class fieldClass = f.getType();
if (!RArray.class.isAssignableFrom(fieldClass)) {
continue;
}
if (printNewline) {
System.err.println();
printNewline = false;
}
indent(depth);
System.err.print(" " + f.getName() + " ");
try {
f.setAccessible(true);
Object o = f.get(view);
if (o instanceof TracingView) {
System.err.print("VIEW ");
TracingView child = (TracingView) o;
dumpView(depth + 2, child.getTrace());
} else {
System.err.print("ARRAY " + o + " size = " + ((RArray)o).size());
if (o instanceof View) {
System.err.println("MISSED VIEW " + o);
}
}
System.err.println();
} catch (IllegalAccessException e) {
assert Utils.check(false, "can't read a view field " + e);
}
}
}
|
diff --git a/FFDot.java b/FFDot.java
index 1c303c6..1099f12 100644
--- a/FFDot.java
+++ b/FFDot.java
@@ -1,41 +1,41 @@
//////////////////////////////////////////////////////////////////////////////////
// Class: FFDot
//
// Purpose: This class encapsulates the functionality of the small particles used
// in our simulations, based on drawing an ellipse at (x,y) coordinates
// within a rectangular boundary.
//
//////////////////////////////////////////////////////////////////////////////////
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.util.Random;
public class FFDot
{
private int x;
private int y;
private int diameter;
private Random rando = new Random();
//Constructs a new dot w/given diameter at random coordinates within a rectangle
public FFDot(Rectangle boundary, int diameter)
{
this.diameter = diameter;
int height = (int) boundary.getHeight();
int width = (int) boundary.getWidth();
- y = rando.nextInt((int)(height - diameter )) ;
- x = rando.nextInt((int)(width - diameter )) ;
+ y = rando.nextInt((int)(height - diameter + 1)) ;
+ x = rando.nextInt((int)(width - diameter + 1)) ;
}
//returns the ellipse
public Ellipse2D.Double getEllipse()
{
return new Ellipse2D.Double(x, y, diameter, diameter);
}
public void setDiameter(int diameter)
{
this.diameter = diameter;
}
}
| true | true | public FFDot(Rectangle boundary, int diameter)
{
this.diameter = diameter;
int height = (int) boundary.getHeight();
int width = (int) boundary.getWidth();
y = rando.nextInt((int)(height - diameter )) ;
x = rando.nextInt((int)(width - diameter )) ;
}
| public FFDot(Rectangle boundary, int diameter)
{
this.diameter = diameter;
int height = (int) boundary.getHeight();
int width = (int) boundary.getWidth();
y = rando.nextInt((int)(height - diameter + 1)) ;
x = rando.nextInt((int)(width - diameter + 1)) ;
}
|
diff --git a/service/src/main/java/de/schildbach/pte/service/ConnectionController.java b/service/src/main/java/de/schildbach/pte/service/ConnectionController.java
index ba43dbf7..18960d90 100644
--- a/service/src/main/java/de/schildbach/pte/service/ConnectionController.java
+++ b/service/src/main/java/de/schildbach/pte/service/ConnectionController.java
@@ -1,58 +1,58 @@
/*
* Copyright 2012 the original author or authors.
*
* 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/>.
*/
package de.schildbach.pte.service;
import java.io.IOException;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import de.schildbach.pte.NetworkProvider.Accessibility;
import de.schildbach.pte.NetworkProvider.WalkSpeed;
import de.schildbach.pte.RtProvider;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.LocationType;
import de.schildbach.pte.dto.QueryConnectionsResult;
/**
* @author Andreas Schildbach
*/
@Controller
public class ConnectionController
{
private final RtProvider provider = new RtProvider();
@RequestMapping(value = "/connection", method = RequestMethod.GET)
@ResponseBody
public QueryConnectionsResult connection(@RequestParam(value = "fromType", required = false, defaultValue = "ANY") final LocationType fromType,
@RequestParam(value = "from", required = false) final String from,
@RequestParam(value = "fromId", required = false, defaultValue = "0") final int fromId,
@RequestParam(value = "toType", required = false, defaultValue = "ANY") final LocationType toType,
@RequestParam(value = "to", required = false) final String to,
@RequestParam(value = "toId", required = false, defaultValue = "0") final int toId) throws IOException
{
final Location fromLocation = new Location(fromType, fromId, null, from);
final Location toLocation = new Location(toType, toId, null, to);
final String products = "IRSUTBFC";
- return provider.queryConnections(fromLocation, null, toLocation, new Date(), true, products, WalkSpeed.NORMAL, Accessibility.NEUTRAL);
+ return provider.queryConnections(fromLocation, null, toLocation, new Date(), true, 4, products, WalkSpeed.NORMAL, Accessibility.NEUTRAL);
}
}
| true | true | public QueryConnectionsResult connection(@RequestParam(value = "fromType", required = false, defaultValue = "ANY") final LocationType fromType,
@RequestParam(value = "from", required = false) final String from,
@RequestParam(value = "fromId", required = false, defaultValue = "0") final int fromId,
@RequestParam(value = "toType", required = false, defaultValue = "ANY") final LocationType toType,
@RequestParam(value = "to", required = false) final String to,
@RequestParam(value = "toId", required = false, defaultValue = "0") final int toId) throws IOException
{
final Location fromLocation = new Location(fromType, fromId, null, from);
final Location toLocation = new Location(toType, toId, null, to);
final String products = "IRSUTBFC";
return provider.queryConnections(fromLocation, null, toLocation, new Date(), true, products, WalkSpeed.NORMAL, Accessibility.NEUTRAL);
}
| public QueryConnectionsResult connection(@RequestParam(value = "fromType", required = false, defaultValue = "ANY") final LocationType fromType,
@RequestParam(value = "from", required = false) final String from,
@RequestParam(value = "fromId", required = false, defaultValue = "0") final int fromId,
@RequestParam(value = "toType", required = false, defaultValue = "ANY") final LocationType toType,
@RequestParam(value = "to", required = false) final String to,
@RequestParam(value = "toId", required = false, defaultValue = "0") final int toId) throws IOException
{
final Location fromLocation = new Location(fromType, fromId, null, from);
final Location toLocation = new Location(toType, toId, null, to);
final String products = "IRSUTBFC";
return provider.queryConnections(fromLocation, null, toLocation, new Date(), true, 4, products, WalkSpeed.NORMAL, Accessibility.NEUTRAL);
}
|
diff --git a/src/main/java/org/junit/experimental/ParallelComputer.java b/src/main/java/org/junit/experimental/ParallelComputer.java
index 34ed52f9..96271e7d 100644
--- a/src/main/java/org/junit/experimental/ParallelComputer.java
+++ b/src/main/java/org/junit/experimental/ParallelComputer.java
@@ -1,67 +1,67 @@
package org.junit.experimental;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runner.Computer;
import org.junit.runner.Runner;
import org.junit.runners.ParentRunner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import org.junit.runners.model.RunnerScheduler;
public class ParallelComputer extends Computer {
private final boolean fClasses;
private final boolean fMethods;
public ParallelComputer(boolean classes, boolean methods) {
fClasses = classes;
fMethods = methods;
}
public static Computer classes() {
return new ParallelComputer(true, false);
}
public static Computer methods() {
return new ParallelComputer(false, true);
}
private static Runner parallelize(Runner runner) {
if (runner instanceof ParentRunner) {
((ParentRunner<?>) runner).setScheduler(new RunnerScheduler() {
private final ExecutorService fService = Executors.newCachedThreadPool();
public void schedule(Runnable childStatement) {
fService.submit(childStatement);
}
public void finished() {
try {
fService.shutdown();
- fService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
+ fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
return runner;
}
@Override
public Runner getSuite(RunnerBuilder builder, java.lang.Class<?>[] classes)
throws InitializationError {
Runner suite = super.getSuite(builder, classes);
return fClasses ? parallelize(suite) : suite;
}
@Override
protected Runner getRunner(RunnerBuilder builder, Class<?> testClass)
throws Throwable {
Runner runner = super.getRunner(builder, testClass);
return fMethods ? parallelize(runner) : runner;
}
}
| true | true | private static Runner parallelize(Runner runner) {
if (runner instanceof ParentRunner) {
((ParentRunner<?>) runner).setScheduler(new RunnerScheduler() {
private final ExecutorService fService = Executors.newCachedThreadPool();
public void schedule(Runnable childStatement) {
fService.submit(childStatement);
}
public void finished() {
try {
fService.shutdown();
fService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
return runner;
}
| private static Runner parallelize(Runner runner) {
if (runner instanceof ParentRunner) {
((ParentRunner<?>) runner).setScheduler(new RunnerScheduler() {
private final ExecutorService fService = Executors.newCachedThreadPool();
public void schedule(Runnable childStatement) {
fService.submit(childStatement);
}
public void finished() {
try {
fService.shutdown();
fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
});
}
return runner;
}
|
diff --git a/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/widgets/AvdSelector.java b/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/widgets/AvdSelector.java
index ae499e9d0..bbf17fa8c 100644
--- a/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/widgets/AvdSelector.java
+++ b/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/widgets/AvdSelector.java
@@ -1,1163 +1,1163 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.sdkuilib.internal.widgets;
import com.android.prefs.AndroidLocation.AndroidLocationException;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.ISdkLog;
import com.android.sdklib.NullSdkLog;
import com.android.sdklib.internal.avd.AvdInfo;
import com.android.sdklib.internal.avd.AvdManager;
import com.android.sdklib.internal.avd.AvdInfo.AvdStatus;
import com.android.sdklib.internal.repository.ITask;
import com.android.sdklib.internal.repository.ITaskMonitor;
import com.android.sdkuilib.internal.repository.SettingsController;
import com.android.sdkuilib.internal.repository.icons.ImageFactory;
import com.android.sdkuilib.internal.tasks.ProgressTask;
import com.android.sdkuilib.repository.SdkUpdaterWindow;
import com.android.sdkuilib.repository.SdkUpdaterWindow.SdkInvocationContext;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
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.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Formatter;
import java.util.Locale;
/**
* The AVD selector is a table that is added to the given parent composite.
* <p/>
* After using one of the constructors, call {@link #setSelection(AvdInfo)},
* {@link #setSelectionListener(SelectionListener)} and finally use
* {@link #getSelected()} to retrieve the selection.
*/
public final class AvdSelector {
private static int NUM_COL = 2;
private final DisplayMode mDisplayMode;
private AvdManager mAvdManager;
private final String mOsSdkPath;
private Table mTable;
private Button mDeleteButton;
private Button mDetailsButton;
private Button mNewButton;
private Button mEditButton;
private Button mRefreshButton;
private Button mManagerButton;
private Button mRepairButton;
private Button mStartButton;
private SelectionListener mSelectionListener;
private IAvdFilter mTargetFilter;
/** Defaults to true. Changed by the {@link #setEnabled(boolean)} method to represent the
* "global" enabled state on this composite. */
private boolean mIsEnabled = true;
private ImageFactory mImageFactory;
private Image mOkImage;
private Image mBrokenImage;
private Image mInvalidImage;
private SettingsController mController;
private final ISdkLog mSdkLog;
/**
* The display mode of the AVD Selector.
*/
public static enum DisplayMode {
/**
* Manager mode. Invalid AVDs are displayed. Buttons to create/delete AVDs
*/
MANAGER,
/**
* Non manager mode. Only valid AVDs are displayed. Cannot create/delete AVDs, but
* there is a button to open the AVD Manager.
* In the "check" selection mode, checkboxes are displayed on each line
* and {@link AvdSelector#getSelected()} returns the line that is checked
* even if it is not the currently selected line. Only one line can
* be checked at once.
*/
SIMPLE_CHECK,
/**
* Non manager mode. Only valid AVDs are displayed. Cannot create/delete AVDs, but
* there is a button to open the AVD Manager.
* In the "select" selection mode, there are no checkboxes and
* {@link AvdSelector#getSelected()} returns the line currently selected.
* Only one line can be selected at once.
*/
SIMPLE_SELECTION,
}
/**
* A filter to control the whether or not an AVD should be displayed by the AVD Selector.
*/
public interface IAvdFilter {
/**
* Called before {@link #accept(AvdInfo)} is called for any AVD.
*/
void prepare();
/**
* Called to decided whether an AVD should be displayed.
* @param avd the AVD to test.
* @return true if the AVD should be displayed.
*/
boolean accept(AvdInfo avd);
/**
* Called after {@link #accept(AvdInfo)} has been called on all the AVDs.
*/
void cleanup();
}
/**
* Internal implementation of {@link IAvdFilter} to filter out the AVDs that are not
* running an image compatible with a specific target.
*/
private final static class TargetBasedFilter implements IAvdFilter {
private final IAndroidTarget mTarget;
TargetBasedFilter(IAndroidTarget target) {
mTarget = target;
}
public void prepare() {
// nothing to prepare
}
public boolean accept(AvdInfo avd) {
if (avd != null) {
return mTarget.canRunOn(avd.getTarget());
}
return false;
}
public void cleanup() {
// nothing to clean up
}
}
/**
* Creates a new SDK Target Selector, and fills it with a list of {@link AvdInfo}, filtered
* by a {@link IAndroidTarget}.
* <p/>Only the {@link AvdInfo} able to run application developed for the given
* {@link IAndroidTarget} will be displayed.
*
* @param parent The parent composite where the selector will be added.
* @param osSdkPath The SDK root path. When not null, enables the start button to start
* an emulator on a given AVD.
* @param manager the AVD manager.
* @param filter When non-null, will allow filtering the AVDs to display.
* @param displayMode The display mode ({@link DisplayMode}).
* @param sdkLog The logger. Cannot be null.
*/
public AvdSelector(Composite parent,
String osSdkPath,
AvdManager manager,
IAvdFilter filter,
DisplayMode displayMode,
ISdkLog sdkLog) {
mOsSdkPath = osSdkPath;
mAvdManager = manager;
mTargetFilter = filter;
mDisplayMode = displayMode;
mSdkLog = sdkLog;
// get some bitmaps.
mImageFactory = new ImageFactory(parent.getDisplay());
mOkImage = mImageFactory.getImageByName("accept_icon16.png");
mBrokenImage = mImageFactory.getImageByName("broken_16.png");
mInvalidImage = mImageFactory.getImageByName("reject_icon16.png");
// Layout has 2 columns
Composite group = new Composite(parent, SWT.NONE);
GridLayout gl;
group.setLayout(gl = new GridLayout(NUM_COL, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
group.setLayoutData(new GridData(GridData.FILL_BOTH));
group.setFont(parent.getFont());
group.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent arg0) {
mImageFactory.dispose();
}
});
int style = SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER;
if (displayMode == DisplayMode.SIMPLE_CHECK) {
style |= SWT.CHECK;
}
mTable = new Table(group, style);
mTable.setHeaderVisible(true);
mTable.setLinesVisible(false);
setTableHeightHint(0);
Composite buttons = new Composite(group, SWT.NONE);
buttons.setLayout(gl = new GridLayout(1, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
buttons.setFont(group.getFont());
if (displayMode == DisplayMode.MANAGER) {
mNewButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mNewButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mNewButton.setText("New...");
mNewButton.setToolTipText("Creates a new AVD.");
mNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onNew();
}
});
mEditButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mEditButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mEditButton.setText("Edit...");
mEditButton.setToolTipText("Edit an existing AVD.");
mEditButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onEdit();
}
});
mDeleteButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mDeleteButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mDeleteButton.setText("Delete...");
mDeleteButton.setToolTipText("Deletes the selected AVD.");
mDeleteButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onDelete();
}
});
mRepairButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mRepairButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mRepairButton.setText("Repair...");
mRepairButton.setToolTipText("Repairs the selected AVD.");
mRepairButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onRepair();
}
});
Label l = new Label(buttons, SWT.SEPARATOR | SWT.HORIZONTAL);
l.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
mDetailsButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mDetailsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mDetailsButton.setText("Details...");
- mDetailsButton.setToolTipText("Diplays details of the selected AVD.");
+ mDetailsButton.setToolTipText("Displays details of the selected AVD.");
mDetailsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onDetails();
}
});
mStartButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mStartButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mStartButton.setText("Start...");
mStartButton.setToolTipText("Starts the selected AVD.");
mStartButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onStart();
}
});
Composite padding = new Composite(buttons, SWT.NONE);
padding.setLayoutData(new GridData(GridData.FILL_VERTICAL));
mRefreshButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mRefreshButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mRefreshButton.setText("Refresh");
mRefreshButton.setToolTipText("Reloads the list of AVD.\nUse this if you create AVDs from the command line.");
mRefreshButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
refresh(true);
}
});
if (displayMode != DisplayMode.MANAGER) {
mManagerButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mManagerButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mManagerButton.setText("Manager...");
mManagerButton.setToolTipText("Launches the AVD manager.");
mManagerButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onManager();
}
});
} else {
Composite legend = new Composite(group, SWT.NONE);
legend.setLayout(gl = new GridLayout(4, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
legend.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false,
NUM_COL, 1));
legend.setFont(group.getFont());
new Label(legend, SWT.NONE).setImage(mOkImage);
new Label(legend, SWT.NONE).setText("A valid Android Virtual Device.");
new Label(legend, SWT.NONE).setImage(mBrokenImage);
new Label(legend, SWT.NONE).setText(
"A repairable Android Virtual Device.");
new Label(legend, SWT.NONE).setImage(mInvalidImage);
Label l = new Label(legend, SWT.NONE);
l.setText("An Android Virtual Device that failed to load. Click 'Details' to see the error.");
GridData gd;
l.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
gd.horizontalSpan = 3;
}
// create the table columns
final TableColumn column0 = new TableColumn(mTable, SWT.NONE);
column0.setText("AVD Name");
final TableColumn column1 = new TableColumn(mTable, SWT.NONE);
column1.setText("Target Name");
final TableColumn column2 = new TableColumn(mTable, SWT.NONE);
column2.setText("Platform");
final TableColumn column3 = new TableColumn(mTable, SWT.NONE);
column3.setText("API Level");
final TableColumn column4 = new TableColumn(mTable, SWT.NONE);
column4.setText("ABI");
adjustColumnsWidth(mTable, column0, column1, column2, column3, column4);
setupSelectionListener(mTable);
fillTable(mTable);
setEnabled(true);
}
/**
* Creates a new SDK Target Selector, and fills it with a list of {@link AvdInfo}.
*
* @param parent The parent composite where the selector will be added.
* @param manager the AVD manager.
* @param displayMode The display mode ({@link DisplayMode}).
* @param sdkLog The logger. Cannot be null.
*/
public AvdSelector(Composite parent,
String osSdkPath,
AvdManager manager,
DisplayMode displayMode,
ISdkLog sdkLog) {
this(parent, osSdkPath, manager, (IAvdFilter)null /* filter */, displayMode, sdkLog);
}
/**
* Creates a new SDK Target Selector, and fills it with a list of {@link AvdInfo}, filtered
* by an {@link IAndroidTarget}.
* <p/>Only the {@link AvdInfo} able to run applications developed for the given
* {@link IAndroidTarget} will be displayed.
*
* @param parent The parent composite where the selector will be added.
* @param manager the AVD manager.
* @param filter Only shows the AVDs matching this target (must not be null).
* @param displayMode The display mode ({@link DisplayMode}).
* @param sdkLog The logger. Cannot be null.
*/
public AvdSelector(Composite parent,
String osSdkPath,
AvdManager manager,
IAndroidTarget filter,
DisplayMode displayMode,
ISdkLog sdkLog) {
this(parent, osSdkPath, manager, new TargetBasedFilter(filter), displayMode, sdkLog);
}
/**
* Sets an optional SettingsController.
* @param controller the controller.
*/
public void setSettingsController(SettingsController controller) {
mController = controller;
}
/**
* Sets the table grid layout data.
*
* @param heightHint If > 0, the height hint is set to the requested value.
*/
public void setTableHeightHint(int heightHint) {
GridData data = new GridData();
if (heightHint > 0) {
data.heightHint = heightHint;
}
data.grabExcessVerticalSpace = true;
data.grabExcessHorizontalSpace = true;
data.horizontalAlignment = GridData.FILL;
data.verticalAlignment = GridData.FILL;
mTable.setLayoutData(data);
}
/**
* Refresh the display of Android Virtual Devices.
* Tries to keep the selection.
* <p/>
* This must be called from the UI thread.
*
* @param reload if true, the AVD manager will reload the AVD from the disk.
* @return false if the reloading failed. This is always true if <var>reload</var> is
* <code>false</code>.
*/
public boolean refresh(boolean reload) {
if (reload) {
try {
mAvdManager.reloadAvds(NullSdkLog.getLogger());
} catch (AndroidLocationException e) {
return false;
}
}
AvdInfo selected = getSelected();
fillTable(mTable);
setSelection(selected);
return true;
}
/**
* Sets a new AVD manager
* This does not refresh the display. Call {@link #refresh(boolean)} to do so.
* @param manager the AVD manager.
*/
public void setManager(AvdManager manager) {
mAvdManager = manager;
}
/**
* Sets a new AVD filter.
* This does not refresh the display. Call {@link #refresh(boolean)} to do so.
* @param filter An IAvdFilter. If non-null, this will filter out the AVD to not display.
*/
public void setFilter(IAvdFilter filter) {
mTargetFilter = filter;
}
/**
* Sets a new Android Target-based AVD filter.
* This does not refresh the display. Call {@link #refresh(boolean)} to do so.
* @param target An IAndroidTarget. If non-null, only AVD whose target are compatible with the
* filter target will displayed an available for selection.
*/
public void setFilter(IAndroidTarget target) {
if (target != null) {
mTargetFilter = new TargetBasedFilter(target);
} else {
mTargetFilter = null;
}
}
/**
* Sets a selection listener. Set it to null to remove it.
* The listener will be called <em>after</em> this table processed its selection
* events so that the caller can see the updated state.
* <p/>
* The event's item contains a {@link TableItem}.
* The {@link TableItem#getData()} contains an {@link IAndroidTarget}.
* <p/>
* It is recommended that the caller uses the {@link #getSelected()} method instead.
* <p/>
* The default behavior for double click (when not in {@link DisplayMode#SIMPLE_CHECK}) is to
* display the details of the selected AVD.<br>
* To disable it (when you provide your own double click action), set
* {@link SelectionEvent#doit} to false in
* {@link SelectionListener#widgetDefaultSelected(SelectionEvent)}
*
* @param selectionListener The new listener or null to remove it.
*/
public void setSelectionListener(SelectionListener selectionListener) {
mSelectionListener = selectionListener;
}
/**
* Sets the current target selection.
* <p/>
* If the selection is actually changed, this will invoke the selection listener
* (if any) with a null event.
*
* @param target the target to be selected. Use null to deselect everything.
* @return true if the target could be selected, false otherwise.
*/
public boolean setSelection(AvdInfo target) {
boolean found = false;
boolean modified = false;
int selIndex = mTable.getSelectionIndex();
int index = 0;
for (TableItem i : mTable.getItems()) {
if (mDisplayMode == DisplayMode.SIMPLE_CHECK) {
if ((AvdInfo) i.getData() == target) {
found = true;
if (!i.getChecked()) {
modified = true;
i.setChecked(true);
}
} else if (i.getChecked()) {
modified = true;
i.setChecked(false);
}
} else {
if ((AvdInfo) i.getData() == target) {
found = true;
if (index != selIndex) {
mTable.setSelection(index);
modified = true;
}
break;
}
index++;
}
}
if (modified && mSelectionListener != null) {
mSelectionListener.widgetSelected(null);
}
enableActionButtons();
return found;
}
/**
* Returns the currently selected item. In {@link DisplayMode#SIMPLE_CHECK} mode this will
* return the {@link AvdInfo} that is checked instead of the list selection.
*
* @return The currently selected item or null.
*/
public AvdInfo getSelected() {
if (mDisplayMode == DisplayMode.SIMPLE_CHECK) {
for (TableItem i : mTable.getItems()) {
if (i.getChecked()) {
return (AvdInfo) i.getData();
}
}
} else {
int selIndex = mTable.getSelectionIndex();
if (selIndex >= 0) {
return (AvdInfo) mTable.getItem(selIndex).getData();
}
}
return null;
}
/**
* Enables the receiver if the argument is true, and disables it otherwise.
* A disabled control is typically not selectable from the user interface
* and draws with an inactive or "grayed" look.
*
* @param enabled the new enabled state.
*/
public void setEnabled(boolean enabled) {
// We can only enable widgets if the AVD Manager is defined.
mIsEnabled = enabled && mAvdManager != null;
mTable.setEnabled(mIsEnabled);
mRefreshButton.setEnabled(mIsEnabled);
if (mNewButton != null) {
mNewButton.setEnabled(mIsEnabled);
}
if (mManagerButton != null) {
mManagerButton.setEnabled(mIsEnabled);
}
enableActionButtons();
}
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Adds a listener to adjust the columns width when the parent is resized.
* <p/>
* If we need something more fancy, we might want to use this:
* http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet77.java?view=co
*/
private void adjustColumnsWidth(final Table table,
final TableColumn column0,
final TableColumn column1,
final TableColumn column2,
final TableColumn column3,
final TableColumn column4) {
// Add a listener to resize the column to the full width of the table
table.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
Rectangle r = table.getClientArea();
column0.setWidth(r.width * 20 / 100); // 20%
column1.setWidth(r.width * 30 / 100); // 30%
column2.setWidth(r.width * 15 / 100); // 15%
column3.setWidth(r.width * 15 / 100); // 15%
column4.setWidth(r.width * 20 / 100); // 22%
}
});
}
/**
* Creates a selection listener that will check or uncheck the whole line when
* double-clicked (aka "the default selection").
*/
private void setupSelectionListener(final Table table) {
// Add a selection listener that will check/uncheck items when they are double-clicked
table.addSelectionListener(new SelectionListener() {
/**
* Handles single-click selection on the table.
* {@inheritDoc}
*/
public void widgetSelected(SelectionEvent e) {
if (e.item instanceof TableItem) {
TableItem i = (TableItem) e.item;
enforceSingleSelection(i);
}
if (mSelectionListener != null) {
mSelectionListener.widgetSelected(e);
}
enableActionButtons();
}
/**
* Handles double-click selection on the table.
* Note that the single-click handler will probably already have been called.
*
* On double-click, <em>always</em> check the table item.
*
* {@inheritDoc}
*/
public void widgetDefaultSelected(SelectionEvent e) {
if (e.item instanceof TableItem) {
TableItem i = (TableItem) e.item;
if (mDisplayMode == DisplayMode.SIMPLE_CHECK) {
i.setChecked(true);
}
enforceSingleSelection(i);
}
// whether or not we display details. default: true when not in SIMPLE_CHECK mode.
boolean showDetails = mDisplayMode != DisplayMode.SIMPLE_CHECK;
if (mSelectionListener != null) {
mSelectionListener.widgetDefaultSelected(e);
showDetails &= e.doit; // enforce false in SIMPLE_CHECK
}
if (showDetails) {
onDetails();
}
enableActionButtons();
}
/**
* To ensure single selection, uncheck all other items when this one is selected.
* This makes the chekboxes act as radio buttons.
*/
private void enforceSingleSelection(TableItem item) {
if (mDisplayMode == DisplayMode.SIMPLE_CHECK) {
if (item.getChecked()) {
Table parentTable = item.getParent();
for (TableItem i2 : parentTable.getItems()) {
if (i2 != item && i2.getChecked()) {
i2.setChecked(false);
}
}
}
} else {
// pass
}
}
});
}
/**
* Fills the table with all AVD.
* The table columns are:
* <ul>
* <li>column 0: sdk name
* <li>column 1: sdk vendor
* <li>column 2: sdk api name
* <li>column 3: sdk version
* </ul>
*/
private void fillTable(final Table table) {
table.removeAll();
// get the AVDs
AvdInfo avds[] = null;
if (mAvdManager != null) {
if (mDisplayMode == DisplayMode.MANAGER) {
avds = mAvdManager.getAllAvds();
} else {
avds = mAvdManager.getValidAvds();
}
}
if (avds != null && avds.length > 0) {
Arrays.sort(avds, new Comparator<AvdInfo>() {
public int compare(AvdInfo o1, AvdInfo o2) {
return o1.compareTo(o2);
}
});
table.setEnabled(true);
if (mTargetFilter != null) {
mTargetFilter.prepare();
}
for (AvdInfo avd : avds) {
if (mTargetFilter == null || mTargetFilter.accept(avd)) {
TableItem item = new TableItem(table, SWT.NONE);
item.setData(avd);
item.setText(0, avd.getName());
if (mDisplayMode == DisplayMode.MANAGER) {
AvdStatus status = avd.getStatus();
item.setImage(0, status == AvdStatus.OK ? mOkImage :
isAvdRepairable(status) ? mBrokenImage : mInvalidImage);
}
IAndroidTarget target = avd.getTarget();
if (target != null) {
item.setText(1, target.getFullName());
item.setText(2, target.getVersionName());
item.setText(3, target.getVersion().getApiString());
item.setText(4, AvdInfo.getPrettyAbiType(avd.getAbiType()));
} else {
item.setText(1, "?");
item.setText(2, "?");
item.setText(3, "?");
item.setText(4, "?");
}
}
}
if (mTargetFilter != null) {
mTargetFilter.cleanup();
}
}
if (table.getItemCount() == 0) {
table.setEnabled(false);
TableItem item = new TableItem(table, SWT.NONE);
item.setData(null);
item.setText(0, "--");
item.setText(1, "No AVD available");
item.setText(2, "--");
item.setText(3, "--");
}
}
/**
* Returns the currently selected AVD in the table.
* <p/>
* Unlike {@link #getSelected()} this will always return the item being selected
* in the list, ignoring the check boxes state in {@link DisplayMode#SIMPLE_CHECK} mode.
*/
private AvdInfo getTableSelection() {
int selIndex = mTable.getSelectionIndex();
if (selIndex >= 0) {
return (AvdInfo) mTable.getItem(selIndex).getData();
}
return null;
}
/**
* Updates the enable state of the Details, Start, Delete and Update buttons.
*/
@SuppressWarnings("null")
private void enableActionButtons() {
if (mIsEnabled == false) {
mDetailsButton.setEnabled(false);
mStartButton.setEnabled(false);
if (mEditButton != null) {
mEditButton.setEnabled(false);
}
if (mDeleteButton != null) {
mDeleteButton.setEnabled(false);
}
if (mRepairButton != null) {
mRepairButton.setEnabled(false);
}
} else {
AvdInfo selection = getTableSelection();
boolean hasSelection = selection != null;
mDetailsButton.setEnabled(hasSelection);
mStartButton.setEnabled(mOsSdkPath != null &&
hasSelection &&
selection.getStatus() == AvdStatus.OK);
if (mEditButton != null) {
mEditButton.setEnabled(hasSelection);
}
if (mDeleteButton != null) {
mDeleteButton.setEnabled(hasSelection);
}
if (mRepairButton != null) {
mRepairButton.setEnabled(hasSelection && isAvdRepairable(selection.getStatus()));
}
}
}
private void onNew() {
AvdCreationDialog dlg = new AvdCreationDialog(mTable.getShell(),
mAvdManager,
mImageFactory,
mSdkLog,
null);
if (dlg.open() == Window.OK) {
refresh(false /*reload*/);
}
}
private void onEdit() {
AvdInfo avdInfo = getTableSelection();
AvdCreationDialog dlg = new AvdCreationDialog(mTable.getShell(),
mAvdManager,
mImageFactory,
mSdkLog,
avdInfo);
if (dlg.open() == Window.OK) {
refresh(false /*reload*/);
}
}
private void onDetails() {
AvdInfo avdInfo = getTableSelection();
AvdDetailsDialog dlg = new AvdDetailsDialog(mTable.getShell(), avdInfo);
dlg.open();
}
private void onDelete() {
final AvdInfo avdInfo = getTableSelection();
// get the current Display
final Display display = mTable.getDisplay();
// check if the AVD is running
if (avdInfo.isRunning()) {
display.asyncExec(new Runnable() {
public void run() {
Shell shell = display.getActiveShell();
MessageDialog.openError(shell,
"Delete Android Virtual Device",
String.format(
"The Android Virtual Device '%1$s' is currently running in an emulator and cannot be deleted.",
avdInfo.getName()));
}
});
return;
}
// Confirm you want to delete this AVD
final boolean[] result = new boolean[1];
display.syncExec(new Runnable() {
public void run() {
Shell shell = display.getActiveShell();
result[0] = MessageDialog.openQuestion(shell,
"Delete Android Virtual Device",
String.format(
"Please confirm that you want to delete the Android Virtual Device named '%s'. This operation cannot be reverted.",
avdInfo.getName()));
}
});
if (result[0] == false) {
return;
}
// log for this action.
ISdkLog log = mSdkLog;
if (log == null || log instanceof MessageBoxLog) {
// If the current logger is a message box, we use our own (to make sure
// to display errors right away and customize the title).
log = new MessageBoxLog(
String.format("Result of deleting AVD '%s':", avdInfo.getName()),
display,
false /*logErrorsOnly*/);
}
// delete the AVD
boolean success = mAvdManager.deleteAvd(avdInfo, log);
// display the result
if (log instanceof MessageBoxLog) {
((MessageBoxLog) log).displayResult(success);
}
if (success) {
refresh(false /*reload*/);
}
}
/**
* Repairs the selected AVD.
* <p/>
* For now this only supports fixing the wrong value in image.sysdir.*
*/
private void onRepair() {
final AvdInfo avdInfo = getTableSelection();
// get the current Display
final Display display = mTable.getDisplay();
// log for this action.
ISdkLog log = mSdkLog;
if (log == null || log instanceof MessageBoxLog) {
// If the current logger is a message box, we use our own (to make sure
// to display errors right away and customize the title).
log = new MessageBoxLog(
String.format("Result of updating AVD '%s':", avdInfo.getName()),
display,
false /*logErrorsOnly*/);
}
// delete the AVD
try {
mAvdManager.updateAvd(avdInfo, log);
// display the result
if (log instanceof MessageBoxLog) {
((MessageBoxLog) log).displayResult(true /* success */);
}
refresh(false /*reload*/);
} catch (IOException e) {
log.error(e, null);
if (log instanceof MessageBoxLog) {
((MessageBoxLog) log).displayResult(false /* success */);
}
}
}
private void onManager() {
// get the current Display
Display display = mTable.getDisplay();
// log for this action.
ISdkLog log = mSdkLog;
if (log == null || log instanceof MessageBoxLog) {
// If the current logger is a message box, we use our own (to make sure
// to display errors right away and customize the title).
log = new MessageBoxLog("Result of SDK Manager", display, true /*logErrorsOnly*/);
}
SdkUpdaterWindow window = new SdkUpdaterWindow(
mTable.getShell(),
log,
mAvdManager.getSdkManager().getLocation(),
SdkInvocationContext.AVD_SELECTOR);
window.open();
refresh(true /*reload*/); // UpdaterWindow uses its own AVD manager so this one must reload.
if (log instanceof MessageBoxLog) {
((MessageBoxLog) log).displayResult(true);
}
}
private void onStart() {
AvdInfo avdInfo = getTableSelection();
if (avdInfo == null || mOsSdkPath == null) {
return;
}
AvdStartDialog dialog = new AvdStartDialog(mTable.getShell(), avdInfo, mOsSdkPath,
mController);
if (dialog.open() == Window.OK) {
String path = avdInfo.getEmulatorPath(mOsSdkPath + File.separator);
final String avdName = avdInfo.getName();
// build the command line based on the available parameters.
ArrayList<String> list = new ArrayList<String>();
list.add(path);
list.add("-avd"); //$NON-NLS-1$
list.add(avdName);
if (dialog.hasWipeData()) {
list.add("-wipe-data"); //$NON-NLS-1$
}
if (dialog.hasSnapshot()) {
if (!dialog.hasSnapshotLaunch()) {
list.add("-no-snapshot-load");
}
if (!dialog.hasSnapshotSave()) {
list.add("-no-snapshot-save");
}
}
float scale = dialog.getScale();
if (scale != 0.f) {
// do the rounding ourselves. This is because %.1f will write .4899 as .4
scale = Math.round(scale * 100);
scale /= 100.f;
list.add("-scale"); //$NON-NLS-1$
// because the emulator expects English decimal values, don't use String.format
// but a Formatter.
Formatter formatter = new Formatter(Locale.US);
formatter.format("%.2f", scale); //$NON-NLS-1$
list.add(formatter.toString());
}
// convert the list into an array for the call to exec.
final String[] command = list.toArray(new String[list.size()]);
// launch the emulator
new ProgressTask(mTable.getShell(),
"Starting Android Emulator",
new ITask() {
public void run(ITaskMonitor monitor) {
try {
monitor.setDescription(
"Starting emulator for AVD '%1$s'",
avdName);
int n = 10;
monitor.setProgressMax(n);
Process process = Runtime.getRuntime().exec(command);
grabEmulatorOutput(process, monitor);
// This small wait prevents the dialog from closing too fast:
// When it works, the emulator returns immediately, even if
// no UI is shown yet. And when it fails (because the AVD is
// locked/running)
// if we don't have a wait we don't capture the error for
// some reason.
for (int i = 0; i < n; i++) {
try {
Thread.sleep(100);
monitor.incProgress(1);
} catch (InterruptedException e) {
// ignore
}
}
} catch (IOException e) {
monitor.logError("Failed to start emulator: %1$s",
e.getMessage());
}
}
});
}
}
/**
* Get the stderr/stdout outputs of a process and return when the process is done.
* Both <b>must</b> be read or the process will block on windows.
* @param process The process to get the output from.
* @param monitor An {@link ITaskMonitor} to capture errors. Cannot be null.
*/
private void grabEmulatorOutput(final Process process, final ITaskMonitor monitor) {
// read the lines as they come. if null is returned, it's because the process finished
new Thread("emu-stderr") { //$NON-NLS-1$
@Override
public void run() {
// create a buffer to read the stderr output
InputStreamReader is = new InputStreamReader(process.getErrorStream());
BufferedReader errReader = new BufferedReader(is);
try {
while (true) {
String line = errReader.readLine();
if (line != null) {
monitor.logError("%1$s", line); //$NON-NLS-1$
} else {
break;
}
}
} catch (IOException e) {
// do nothing.
}
}
}.start();
new Thread("emu-stdout") { //$NON-NLS-1$
@Override
public void run() {
InputStreamReader is = new InputStreamReader(process.getInputStream());
BufferedReader outReader = new BufferedReader(is);
try {
while (true) {
String line = outReader.readLine();
if (line != null) {
monitor.log("%1$s", line); //$NON-NLS-1$
} else {
break;
}
}
} catch (IOException e) {
// do nothing.
}
}
}.start();
}
private boolean isAvdRepairable(AvdStatus avdStatus) {
return avdStatus == AvdStatus.ERROR_IMAGE_DIR;
}
}
| true | true | public AvdSelector(Composite parent,
String osSdkPath,
AvdManager manager,
IAvdFilter filter,
DisplayMode displayMode,
ISdkLog sdkLog) {
mOsSdkPath = osSdkPath;
mAvdManager = manager;
mTargetFilter = filter;
mDisplayMode = displayMode;
mSdkLog = sdkLog;
// get some bitmaps.
mImageFactory = new ImageFactory(parent.getDisplay());
mOkImage = mImageFactory.getImageByName("accept_icon16.png");
mBrokenImage = mImageFactory.getImageByName("broken_16.png");
mInvalidImage = mImageFactory.getImageByName("reject_icon16.png");
// Layout has 2 columns
Composite group = new Composite(parent, SWT.NONE);
GridLayout gl;
group.setLayout(gl = new GridLayout(NUM_COL, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
group.setLayoutData(new GridData(GridData.FILL_BOTH));
group.setFont(parent.getFont());
group.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent arg0) {
mImageFactory.dispose();
}
});
int style = SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER;
if (displayMode == DisplayMode.SIMPLE_CHECK) {
style |= SWT.CHECK;
}
mTable = new Table(group, style);
mTable.setHeaderVisible(true);
mTable.setLinesVisible(false);
setTableHeightHint(0);
Composite buttons = new Composite(group, SWT.NONE);
buttons.setLayout(gl = new GridLayout(1, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
buttons.setFont(group.getFont());
if (displayMode == DisplayMode.MANAGER) {
mNewButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mNewButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mNewButton.setText("New...");
mNewButton.setToolTipText("Creates a new AVD.");
mNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onNew();
}
});
mEditButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mEditButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mEditButton.setText("Edit...");
mEditButton.setToolTipText("Edit an existing AVD.");
mEditButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onEdit();
}
});
mDeleteButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mDeleteButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mDeleteButton.setText("Delete...");
mDeleteButton.setToolTipText("Deletes the selected AVD.");
mDeleteButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onDelete();
}
});
mRepairButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mRepairButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mRepairButton.setText("Repair...");
mRepairButton.setToolTipText("Repairs the selected AVD.");
mRepairButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onRepair();
}
});
Label l = new Label(buttons, SWT.SEPARATOR | SWT.HORIZONTAL);
l.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
mDetailsButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mDetailsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mDetailsButton.setText("Details...");
mDetailsButton.setToolTipText("Diplays details of the selected AVD.");
mDetailsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onDetails();
}
});
mStartButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mStartButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mStartButton.setText("Start...");
mStartButton.setToolTipText("Starts the selected AVD.");
mStartButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onStart();
}
});
Composite padding = new Composite(buttons, SWT.NONE);
padding.setLayoutData(new GridData(GridData.FILL_VERTICAL));
mRefreshButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mRefreshButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mRefreshButton.setText("Refresh");
mRefreshButton.setToolTipText("Reloads the list of AVD.\nUse this if you create AVDs from the command line.");
mRefreshButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
refresh(true);
}
});
if (displayMode != DisplayMode.MANAGER) {
mManagerButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mManagerButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mManagerButton.setText("Manager...");
mManagerButton.setToolTipText("Launches the AVD manager.");
mManagerButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onManager();
}
});
} else {
Composite legend = new Composite(group, SWT.NONE);
legend.setLayout(gl = new GridLayout(4, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
legend.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false,
NUM_COL, 1));
legend.setFont(group.getFont());
new Label(legend, SWT.NONE).setImage(mOkImage);
new Label(legend, SWT.NONE).setText("A valid Android Virtual Device.");
new Label(legend, SWT.NONE).setImage(mBrokenImage);
new Label(legend, SWT.NONE).setText(
"A repairable Android Virtual Device.");
new Label(legend, SWT.NONE).setImage(mInvalidImage);
Label l = new Label(legend, SWT.NONE);
l.setText("An Android Virtual Device that failed to load. Click 'Details' to see the error.");
GridData gd;
l.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
gd.horizontalSpan = 3;
}
// create the table columns
final TableColumn column0 = new TableColumn(mTable, SWT.NONE);
column0.setText("AVD Name");
final TableColumn column1 = new TableColumn(mTable, SWT.NONE);
column1.setText("Target Name");
final TableColumn column2 = new TableColumn(mTable, SWT.NONE);
column2.setText("Platform");
final TableColumn column3 = new TableColumn(mTable, SWT.NONE);
column3.setText("API Level");
final TableColumn column4 = new TableColumn(mTable, SWT.NONE);
column4.setText("ABI");
adjustColumnsWidth(mTable, column0, column1, column2, column3, column4);
setupSelectionListener(mTable);
fillTable(mTable);
setEnabled(true);
}
| public AvdSelector(Composite parent,
String osSdkPath,
AvdManager manager,
IAvdFilter filter,
DisplayMode displayMode,
ISdkLog sdkLog) {
mOsSdkPath = osSdkPath;
mAvdManager = manager;
mTargetFilter = filter;
mDisplayMode = displayMode;
mSdkLog = sdkLog;
// get some bitmaps.
mImageFactory = new ImageFactory(parent.getDisplay());
mOkImage = mImageFactory.getImageByName("accept_icon16.png");
mBrokenImage = mImageFactory.getImageByName("broken_16.png");
mInvalidImage = mImageFactory.getImageByName("reject_icon16.png");
// Layout has 2 columns
Composite group = new Composite(parent, SWT.NONE);
GridLayout gl;
group.setLayout(gl = new GridLayout(NUM_COL, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
group.setLayoutData(new GridData(GridData.FILL_BOTH));
group.setFont(parent.getFont());
group.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent arg0) {
mImageFactory.dispose();
}
});
int style = SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER;
if (displayMode == DisplayMode.SIMPLE_CHECK) {
style |= SWT.CHECK;
}
mTable = new Table(group, style);
mTable.setHeaderVisible(true);
mTable.setLinesVisible(false);
setTableHeightHint(0);
Composite buttons = new Composite(group, SWT.NONE);
buttons.setLayout(gl = new GridLayout(1, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
buttons.setFont(group.getFont());
if (displayMode == DisplayMode.MANAGER) {
mNewButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mNewButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mNewButton.setText("New...");
mNewButton.setToolTipText("Creates a new AVD.");
mNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onNew();
}
});
mEditButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mEditButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mEditButton.setText("Edit...");
mEditButton.setToolTipText("Edit an existing AVD.");
mEditButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onEdit();
}
});
mDeleteButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mDeleteButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mDeleteButton.setText("Delete...");
mDeleteButton.setToolTipText("Deletes the selected AVD.");
mDeleteButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onDelete();
}
});
mRepairButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mRepairButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mRepairButton.setText("Repair...");
mRepairButton.setToolTipText("Repairs the selected AVD.");
mRepairButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onRepair();
}
});
Label l = new Label(buttons, SWT.SEPARATOR | SWT.HORIZONTAL);
l.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
mDetailsButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mDetailsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mDetailsButton.setText("Details...");
mDetailsButton.setToolTipText("Displays details of the selected AVD.");
mDetailsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onDetails();
}
});
mStartButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mStartButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mStartButton.setText("Start...");
mStartButton.setToolTipText("Starts the selected AVD.");
mStartButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onStart();
}
});
Composite padding = new Composite(buttons, SWT.NONE);
padding.setLayoutData(new GridData(GridData.FILL_VERTICAL));
mRefreshButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mRefreshButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mRefreshButton.setText("Refresh");
mRefreshButton.setToolTipText("Reloads the list of AVD.\nUse this if you create AVDs from the command line.");
mRefreshButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
refresh(true);
}
});
if (displayMode != DisplayMode.MANAGER) {
mManagerButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mManagerButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mManagerButton.setText("Manager...");
mManagerButton.setToolTipText("Launches the AVD manager.");
mManagerButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onManager();
}
});
} else {
Composite legend = new Composite(group, SWT.NONE);
legend.setLayout(gl = new GridLayout(4, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
legend.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false,
NUM_COL, 1));
legend.setFont(group.getFont());
new Label(legend, SWT.NONE).setImage(mOkImage);
new Label(legend, SWT.NONE).setText("A valid Android Virtual Device.");
new Label(legend, SWT.NONE).setImage(mBrokenImage);
new Label(legend, SWT.NONE).setText(
"A repairable Android Virtual Device.");
new Label(legend, SWT.NONE).setImage(mInvalidImage);
Label l = new Label(legend, SWT.NONE);
l.setText("An Android Virtual Device that failed to load. Click 'Details' to see the error.");
GridData gd;
l.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
gd.horizontalSpan = 3;
}
// create the table columns
final TableColumn column0 = new TableColumn(mTable, SWT.NONE);
column0.setText("AVD Name");
final TableColumn column1 = new TableColumn(mTable, SWT.NONE);
column1.setText("Target Name");
final TableColumn column2 = new TableColumn(mTable, SWT.NONE);
column2.setText("Platform");
final TableColumn column3 = new TableColumn(mTable, SWT.NONE);
column3.setText("API Level");
final TableColumn column4 = new TableColumn(mTable, SWT.NONE);
column4.setText("ABI");
adjustColumnsWidth(mTable, column0, column1, column2, column3, column4);
setupSelectionListener(mTable);
fillTable(mTable);
setEnabled(true);
}
|
diff --git a/grid-incubation/incubator/projects/sdkQuery42/src/java/processor/org/cagrid/data/sdkquery42/processor/SDK42QueryProcessor.java b/grid-incubation/incubator/projects/sdkQuery42/src/java/processor/org/cagrid/data/sdkquery42/processor/SDK42QueryProcessor.java
index 0e22bca6..13bad17d 100644
--- a/grid-incubation/incubator/projects/sdkQuery42/src/java/processor/org/cagrid/data/sdkquery42/processor/SDK42QueryProcessor.java
+++ b/grid-incubation/incubator/projects/sdkQuery42/src/java/processor/org/cagrid/data/sdkquery42/processor/SDK42QueryProcessor.java
@@ -1,277 +1,279 @@
package org.cagrid.data.sdkquery42.processor;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.cqlquery.QueryModifier;
import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import gov.nih.nci.cagrid.data.InitializationException;
import gov.nih.nci.cagrid.data.MalformedQueryException;
import gov.nih.nci.cagrid.data.QueryProcessingException;
import gov.nih.nci.cagrid.data.cql.CQLQueryProcessor;
import gov.nih.nci.cagrid.data.mapping.Mappings;
import gov.nih.nci.cagrid.data.service.ServiceConfigUtil;
import gov.nih.nci.cagrid.data.utilities.CQLResultsCreationUtil;
import gov.nih.nci.cagrid.data.utilities.ResultsCreationException;
import gov.nih.nci.system.applicationservice.ApplicationException;
import gov.nih.nci.system.applicationservice.ApplicationService;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.wsrf.security.SecurityManager;
public class SDK42QueryProcessor extends CQLQueryProcessor {
private static Log LOG = LogFactory.getLog(SDK42QueryProcessor.class);
// general configuration options
public static final String PROPERTY_APPLICATION_NAME = "applicationName";
public static final String PROPERTY_USE_LOCAL_API = "useLocalApiFlag";
// remote service configuration properties
public static final String PROPERTY_HOST_NAME = "applicationHostName";
public static final String PROPERTY_HOST_PORT = "applicationHostPort";
public static final String PROPERTY_HOST_HTTPS = "useHttpsUrl";
// security configuration properties
public static final String PROPERTY_USE_GRID_IDENTITY_LOGIN = "useGridIdentityLogin";
public static final String PROPERTY_USE_STATIC_LOGIN = "useStaticLogin";
public static final String PROPERTY_STATIC_LOGIN_USER = "staticLoginUser";
public static final String PROPERTY_STATIC_LOGIN_PASS = "staticLoginPass";
// default values for properties
public static final String DEFAULT_USE_LOCAL_API = String.valueOf(false);
public static final String DEFAULT_HOST_HTTPS = String.valueOf(false);
public static final String DEFAULT_USE_GRID_IDENTITY_LOGIN = String.valueOf(false);
public static final String DEFAULT_USE_STATIC_LOGIN = String.valueOf(false);
private Mappings mappings = null;
public SDK42QueryProcessor() {
super();
}
public Properties getRequiredParameters() {
Properties props = super.getRequiredParameters();
props.setProperty(PROPERTY_APPLICATION_NAME, "");
props.setProperty(PROPERTY_USE_LOCAL_API, DEFAULT_USE_LOCAL_API);
props.setProperty(PROPERTY_HOST_NAME, "");
props.setProperty(PROPERTY_HOST_PORT, "");
props.setProperty(PROPERTY_HOST_HTTPS, DEFAULT_HOST_HTTPS);
props.setProperty(PROPERTY_USE_GRID_IDENTITY_LOGIN, DEFAULT_USE_GRID_IDENTITY_LOGIN);
props.setProperty(PROPERTY_USE_STATIC_LOGIN, DEFAULT_USE_STATIC_LOGIN);
props.setProperty(PROPERTY_STATIC_LOGIN_USER, "");
props.setProperty(PROPERTY_STATIC_LOGIN_PASS, "");
return props;
}
public void initialize(Properties parameters, InputStream wsdd) throws InitializationException {
super.initialize(parameters, wsdd);
// verify that if we're using grid identity login, we're also using the Local API
if (isUseGridIdentLogin() && !isUseLocalApi()) {
throw new InitializationException("Grid identity + CSM authentication can only be used with the local API!");
}
// verify we have a URL for the remote API
if (!isUseLocalApi()) {
try {
new URL(getRemoteApplicationUrl());
} catch (MalformedURLException ex) {
throw new InitializationException("Could not determine a remote API url: " + ex.getMessage(), ex);
}
}
}
public CQLQueryResults processQuery(CQLQuery cqlQuery) throws MalformedQueryException, QueryProcessingException {
try {
cqlQuery = CQLAttributeDefaultPredicateUtil.checkDefaultPredicates(cqlQuery);
} catch (Exception ex) {
throw new QueryProcessingException(
"Error checking query for default Attribute predicate values: " + ex.getMessage(), ex);
}
ApplicationService applicationService = getApplicationService();
List<?> rawResults = null;
try {
rawResults = applicationService.query(cqlQuery);
} catch (ApplicationException ex) {
String message = "Error processing CQL query in the caCORE ApplicationService: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
CQLQueryResults cqlResults = null;
// determine which type of results to package up
if (cqlQuery.getQueryModifier() != null) {
QueryModifier mods = cqlQuery.getQueryModifier();
if (mods.isCountOnly()) {
long count = Long.parseLong(rawResults.get(0).toString());
cqlResults = CQLResultsCreationUtil.createCountResults(count, cqlQuery.getTarget().getName());
} else { // attributes
String[] attributeNames = null;
List<Object[]> resultsAsArrays = null;
if (mods.getDistinctAttribute() != null) {
attributeNames = new String[] {mods.getDistinctAttribute()};
resultsAsArrays = new LinkedList<Object[]>();
for (Object o : rawResults) {
resultsAsArrays.add(new Object[] {o});
}
} else { // multiple attributes
attributeNames = mods.getAttributeNames();
resultsAsArrays = new LinkedList<Object[]>();
for (Object o : rawResults) {
Object[] array = null;
- if (o.getClass().isArray()) {
+ if (o == null) {
+ o = new Object[attributeNames.length];
+ } else if (o.getClass().isArray()) {
array = (Object[]) o;
} else {
array = new Object[] {o};
}
resultsAsArrays.add(array);
}
}
cqlResults = CQLResultsCreationUtil.createAttributeResults(
resultsAsArrays, cqlQuery.getTarget().getName(), attributeNames);
}
} else {
Mappings classToQname = null;
try {
classToQname = getClassToQnameMappings();
} catch (Exception ex) {
throw new QueryProcessingException("Error loading class to QName mappings: " + ex.getMessage(), ex);
}
try {
cqlResults = CQLResultsCreationUtil.createObjectResults(
rawResults, cqlQuery.getTarget().getName(), classToQname);
} catch (ResultsCreationException ex) {
throw new QueryProcessingException("Error packaging query results: " + ex.getMessage(), ex);
}
}
return cqlResults;
}
private boolean isUseLocalApi() {
boolean useLocal = Boolean.parseBoolean(DEFAULT_USE_LOCAL_API);
String useLocalApiValue = getConfiguredParameters().getProperty(PROPERTY_USE_LOCAL_API);
try {
useLocal = Boolean.parseBoolean(useLocalApiValue);
} catch (Exception ex) {
LOG.error("Error parsing property " + PROPERTY_USE_LOCAL_API
+ ". Value was " + useLocalApiValue, ex);
}
return useLocal;
}
private boolean isUseGridIdentLogin() {
boolean useGridIdent = Boolean.parseBoolean(DEFAULT_USE_GRID_IDENTITY_LOGIN);
String useGridIdentValue = getConfiguredParameters().getProperty(PROPERTY_USE_GRID_IDENTITY_LOGIN);
try {
useGridIdent = Boolean.parseBoolean(useGridIdentValue);
} catch (Exception ex) {
LOG.error("Error parsing property " + PROPERTY_USE_GRID_IDENTITY_LOGIN
+ ". Value was " + useGridIdentValue, ex);
}
return useGridIdent;
}
private boolean isUseStaticLogin() {
boolean useStatic = false;
String useStaticValue = getConfiguredParameters().getProperty(PROPERTY_USE_STATIC_LOGIN);
try {
useStatic = Boolean.parseBoolean(useStaticValue);
} catch (Exception ex) {
LOG.error("Error parsing property " + PROPERTY_USE_STATIC_LOGIN
+ ". Value was " + useStaticValue, ex);
}
return useStatic;
}
private boolean isUseHttps() {
boolean useHttps = Boolean.parseBoolean(DEFAULT_HOST_HTTPS);
String useHttpsValue = getConfiguredParameters().getProperty(PROPERTY_HOST_HTTPS);
try {
useHttps = Boolean.parseBoolean(PROPERTY_HOST_HTTPS);
} catch (Exception ex) {
LOG.error("Error parsing property " + PROPERTY_HOST_HTTPS
+ ". Value was " + useHttpsValue, ex);
}
return useHttps;
}
private String getStaticLoginUser() {
return getConfiguredParameters().getProperty(PROPERTY_STATIC_LOGIN_USER);
}
private String getStaticLoginPass() {
return getConfiguredParameters().getProperty(PROPERTY_STATIC_LOGIN_PASS);
}
private String getRemoteApplicationUrl() {
StringBuffer url = new StringBuffer();
if (isUseHttps()) {
url.append("https://");
} else {
url.append("http://");
}
url.append(getConfiguredParameters().getProperty(PROPERTY_HOST_NAME));
url.append(":");
url.append(getConfiguredParameters().getProperty(PROPERTY_HOST_PORT));
url.append("/");
url.append(getConfiguredParameters().getProperty(PROPERTY_APPLICATION_NAME));
String completedUrl = url.toString();
LOG.debug("Application Service remote URL determined to be: " + completedUrl);
return completedUrl;
}
private ApplicationService getApplicationService() throws QueryProcessingException {
ApplicationService service = null;
try {
if (isUseLocalApi()) {
if (isUseGridIdentLogin()) {
SecurityManager securityManager = SecurityManager.getManager();
String username = securityManager.getCaller();
service = ApplicationServiceProvider.getApplicationServiceForUser(username);
} else {
service = ApplicationServiceProvider.getApplicationService();
}
} else {
String url = getRemoteApplicationUrl();
if (isUseStaticLogin()) {
String username = getStaticLoginUser();
String password = getStaticLoginPass();
service = ApplicationServiceProvider.getApplicationServiceFromUrl(url, username, password);
} else {
service = ApplicationServiceProvider.getApplicationServiceFromUrl(url);
}
}
} catch (Exception ex) {
throw new QueryProcessingException("Error obtaining application service: " + ex.getMessage(), ex);
}
return service;
}
private Mappings getClassToQnameMappings() throws Exception {
if (mappings == null) {
// get the mapping file name
String filename = ServiceConfigUtil.getClassToQnameMappingsFile();
mappings = (Mappings) Utils.deserializeDocument(filename, Mappings.class);
}
return mappings;
}
}
| true | true | public CQLQueryResults processQuery(CQLQuery cqlQuery) throws MalformedQueryException, QueryProcessingException {
try {
cqlQuery = CQLAttributeDefaultPredicateUtil.checkDefaultPredicates(cqlQuery);
} catch (Exception ex) {
throw new QueryProcessingException(
"Error checking query for default Attribute predicate values: " + ex.getMessage(), ex);
}
ApplicationService applicationService = getApplicationService();
List<?> rawResults = null;
try {
rawResults = applicationService.query(cqlQuery);
} catch (ApplicationException ex) {
String message = "Error processing CQL query in the caCORE ApplicationService: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
CQLQueryResults cqlResults = null;
// determine which type of results to package up
if (cqlQuery.getQueryModifier() != null) {
QueryModifier mods = cqlQuery.getQueryModifier();
if (mods.isCountOnly()) {
long count = Long.parseLong(rawResults.get(0).toString());
cqlResults = CQLResultsCreationUtil.createCountResults(count, cqlQuery.getTarget().getName());
} else { // attributes
String[] attributeNames = null;
List<Object[]> resultsAsArrays = null;
if (mods.getDistinctAttribute() != null) {
attributeNames = new String[] {mods.getDistinctAttribute()};
resultsAsArrays = new LinkedList<Object[]>();
for (Object o : rawResults) {
resultsAsArrays.add(new Object[] {o});
}
} else { // multiple attributes
attributeNames = mods.getAttributeNames();
resultsAsArrays = new LinkedList<Object[]>();
for (Object o : rawResults) {
Object[] array = null;
if (o.getClass().isArray()) {
array = (Object[]) o;
} else {
array = new Object[] {o};
}
resultsAsArrays.add(array);
}
}
cqlResults = CQLResultsCreationUtil.createAttributeResults(
resultsAsArrays, cqlQuery.getTarget().getName(), attributeNames);
}
} else {
Mappings classToQname = null;
try {
classToQname = getClassToQnameMappings();
} catch (Exception ex) {
throw new QueryProcessingException("Error loading class to QName mappings: " + ex.getMessage(), ex);
}
try {
cqlResults = CQLResultsCreationUtil.createObjectResults(
rawResults, cqlQuery.getTarget().getName(), classToQname);
} catch (ResultsCreationException ex) {
throw new QueryProcessingException("Error packaging query results: " + ex.getMessage(), ex);
}
}
return cqlResults;
}
| public CQLQueryResults processQuery(CQLQuery cqlQuery) throws MalformedQueryException, QueryProcessingException {
try {
cqlQuery = CQLAttributeDefaultPredicateUtil.checkDefaultPredicates(cqlQuery);
} catch (Exception ex) {
throw new QueryProcessingException(
"Error checking query for default Attribute predicate values: " + ex.getMessage(), ex);
}
ApplicationService applicationService = getApplicationService();
List<?> rawResults = null;
try {
rawResults = applicationService.query(cqlQuery);
} catch (ApplicationException ex) {
String message = "Error processing CQL query in the caCORE ApplicationService: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
CQLQueryResults cqlResults = null;
// determine which type of results to package up
if (cqlQuery.getQueryModifier() != null) {
QueryModifier mods = cqlQuery.getQueryModifier();
if (mods.isCountOnly()) {
long count = Long.parseLong(rawResults.get(0).toString());
cqlResults = CQLResultsCreationUtil.createCountResults(count, cqlQuery.getTarget().getName());
} else { // attributes
String[] attributeNames = null;
List<Object[]> resultsAsArrays = null;
if (mods.getDistinctAttribute() != null) {
attributeNames = new String[] {mods.getDistinctAttribute()};
resultsAsArrays = new LinkedList<Object[]>();
for (Object o : rawResults) {
resultsAsArrays.add(new Object[] {o});
}
} else { // multiple attributes
attributeNames = mods.getAttributeNames();
resultsAsArrays = new LinkedList<Object[]>();
for (Object o : rawResults) {
Object[] array = null;
if (o == null) {
o = new Object[attributeNames.length];
} else if (o.getClass().isArray()) {
array = (Object[]) o;
} else {
array = new Object[] {o};
}
resultsAsArrays.add(array);
}
}
cqlResults = CQLResultsCreationUtil.createAttributeResults(
resultsAsArrays, cqlQuery.getTarget().getName(), attributeNames);
}
} else {
Mappings classToQname = null;
try {
classToQname = getClassToQnameMappings();
} catch (Exception ex) {
throw new QueryProcessingException("Error loading class to QName mappings: " + ex.getMessage(), ex);
}
try {
cqlResults = CQLResultsCreationUtil.createObjectResults(
rawResults, cqlQuery.getTarget().getName(), classToQname);
} catch (ResultsCreationException ex) {
throw new QueryProcessingException("Error packaging query results: " + ex.getMessage(), ex);
}
}
return cqlResults;
}
|
diff --git a/src/test/java/org/lastbamboo/common/stun/client/StunClientTest.java b/src/test/java/org/lastbamboo/common/stun/client/StunClientTest.java
index 6d55305..c18a82d 100644
--- a/src/test/java/org/lastbamboo/common/stun/client/StunClientTest.java
+++ b/src/test/java/org/lastbamboo/common/stun/client/StunClientTest.java
@@ -1,104 +1,104 @@
package org.lastbamboo.common.stun.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.junit.Test;
import org.littleshoot.stun.stack.StunConstants;
import org.littleshoot.util.CandidateProvider;
import org.littleshoot.util.DnsSrvCandidateProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test for STUN clients.
*/
public class StunClientTest {
private final Logger LOG = LoggerFactory.getLogger(StunClientTest.class);
@Test
public void testClient() throws Exception {
//final SrvUtil srv = new SrvUtilImpl();
final CandidateProvider<InetSocketAddress> stunCandidateProvider =
new DnsSrvCandidateProvider("_stun._udp.littleshoot.org");
/*
new SrvCandidateProvider(srv, "_stun._udp.littleshoot.org",
new InetSocketAddress("stun.littleshoot.org", StunConstants.STUN_PORT));
*/
// We do this a bunch of times because the server selection is random.
for (int i = 0; i < 20; i++) {
final UdpStunClient client = new UdpStunClient(
stunCandidateProvider);
final InetSocketAddress srflx = client.getServerReflexiveAddress();
// System.out.println("Got address: "+srflx);
assertNotNull("Did not get server reflexive address", srflx);
}
}
@Test
public void testDifferentServers() throws Exception {
final int port = StunConstants.STUN_PORT;
// See http://www.voip-info.org/wiki/view/STUN
final InetSocketAddress[] servers = {
new InetSocketAddress("stun.l.google.com", 19302),
//new InetSocketAddress("stun.ekiga.net", port),
//new InetSocketAddress("stun.fwdnet.net", port),
- new InetSocketAddress("stun.ideasip.com", port),
+ //new InetSocketAddress("stun.ideasip.com", port),
//new InetSocketAddress("stun01.sipphone.com", port),
//new InetSocketAddress("stun.softjoys.com", port),
new InetSocketAddress("stun.voipbuster.com", port),
- new InetSocketAddress("stun.voxgratia.org", port),
+ //new InetSocketAddress("stun.voxgratia.org", port),
//new InetSocketAddress("stun.xten.com", port),
//new InetSocketAddress("stunserver.org", port),
- new InetSocketAddress("stun.sipgate.net", 10000),
- new InetSocketAddress("numb.viagenie.ca", port)
+ //new InetSocketAddress("stun.sipgate.net", 10000),
+ //new InetSocketAddress("numb.viagenie.ca", port)
};
InetAddress ia = null;
for (final InetSocketAddress server : servers) {
LOG.info("Hitting: "+server);
final StunClient sc = new UdpStunClient(server);
sc.connect();
final InetSocketAddress ip = sc.getServerReflexiveAddress();
if (ia != null) {
- assertEquals(ia, ip.getAddress());
+ assertEquals("Address lookup failed for "+server, ia, ip.getAddress());
}
else {
ia = ip.getAddress();
}
}
}
@Test
public void testRanking() throws Exception {
final int port = StunConstants.STUN_PORT;
// See http://www.voip-info.org/wiki/view/STUN
final InetSocketAddress[] servers = {
//new InetSocketAddress("stun.ekiga.net", port),
//new InetSocketAddress("stunserver.org", port),
//new InetSocketAddress("stun.fwdnet.net", port),
// Re-enable these to see dynamic ranking in action..
new InetSocketAddress("stun.ideasip.com", port),
new InetSocketAddress("stun01.sipphone.com", port),
new InetSocketAddress("stun.softjoys.com", port),
new InetSocketAddress("stun.voipbuster.com", port),
new InetSocketAddress("stun.voxgratia.org", port),
//new InetSocketAddress("stun.xten.com", port),
new InetSocketAddress("stun.sipgate.net", 10000),
new InetSocketAddress("numb.viagenie.ca", port)
};
final StunClient sc = new UdpStunClient(servers);
sc.connect();
for (int i = 0; i < 20; i++) {
sc.getServerReflexiveAddress();
}
}
}
| false | true | public void testDifferentServers() throws Exception {
final int port = StunConstants.STUN_PORT;
// See http://www.voip-info.org/wiki/view/STUN
final InetSocketAddress[] servers = {
new InetSocketAddress("stun.l.google.com", 19302),
//new InetSocketAddress("stun.ekiga.net", port),
//new InetSocketAddress("stun.fwdnet.net", port),
new InetSocketAddress("stun.ideasip.com", port),
//new InetSocketAddress("stun01.sipphone.com", port),
//new InetSocketAddress("stun.softjoys.com", port),
new InetSocketAddress("stun.voipbuster.com", port),
new InetSocketAddress("stun.voxgratia.org", port),
//new InetSocketAddress("stun.xten.com", port),
//new InetSocketAddress("stunserver.org", port),
new InetSocketAddress("stun.sipgate.net", 10000),
new InetSocketAddress("numb.viagenie.ca", port)
};
InetAddress ia = null;
for (final InetSocketAddress server : servers) {
LOG.info("Hitting: "+server);
final StunClient sc = new UdpStunClient(server);
sc.connect();
final InetSocketAddress ip = sc.getServerReflexiveAddress();
if (ia != null) {
assertEquals(ia, ip.getAddress());
}
else {
ia = ip.getAddress();
}
}
}
| public void testDifferentServers() throws Exception {
final int port = StunConstants.STUN_PORT;
// See http://www.voip-info.org/wiki/view/STUN
final InetSocketAddress[] servers = {
new InetSocketAddress("stun.l.google.com", 19302),
//new InetSocketAddress("stun.ekiga.net", port),
//new InetSocketAddress("stun.fwdnet.net", port),
//new InetSocketAddress("stun.ideasip.com", port),
//new InetSocketAddress("stun01.sipphone.com", port),
//new InetSocketAddress("stun.softjoys.com", port),
new InetSocketAddress("stun.voipbuster.com", port),
//new InetSocketAddress("stun.voxgratia.org", port),
//new InetSocketAddress("stun.xten.com", port),
//new InetSocketAddress("stunserver.org", port),
//new InetSocketAddress("stun.sipgate.net", 10000),
//new InetSocketAddress("numb.viagenie.ca", port)
};
InetAddress ia = null;
for (final InetSocketAddress server : servers) {
LOG.info("Hitting: "+server);
final StunClient sc = new UdpStunClient(server);
sc.connect();
final InetSocketAddress ip = sc.getServerReflexiveAddress();
if (ia != null) {
assertEquals("Address lookup failed for "+server, ia, ip.getAddress());
}
else {
ia = ip.getAddress();
}
}
}
|
diff --git a/CS5430/src/database/SocialNetworkDatabasePosts.java b/CS5430/src/database/SocialNetworkDatabasePosts.java
index 11153d9..54c1bf2 100644
--- a/CS5430/src/database/SocialNetworkDatabasePosts.java
+++ b/CS5430/src/database/SocialNetworkDatabasePosts.java
@@ -1,420 +1,420 @@
package database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SocialNetworkDatabasePosts {
private static String specialStrPostable = "*";
private static String specialStrCreatedPost = "**";
/**
* Verifies whether a post exists in the given board (and region).
*/
public static Boolean postExists(Connection conn, String boardName, String regionName, int postNum) {
PreparedStatement pstmt = null;
ResultSet postResult = null;
String getPost = "";
if (boardName.equals("freeforall")) {
getPost = "SELECT * FROM freeforall.posts " +
"WHERE pid = ?";
}
else {
getPost = "SELECT * FROM " + boardName + ".posts " +
"WHERE pid = ? AND rname = ?";
}
Boolean postExists = null;
try {
pstmt = conn.prepareStatement(getPost);
pstmt.setInt(1, postNum);
if (!boardName.equals("freeforall")) {
pstmt.setString(2, regionName);
}
postResult = pstmt.executeQuery();
postExists = new Boolean(postResult.next());
}
catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getSQLState());
}
finally {
DBManager.closePreparedStatement(pstmt);
}
return postExists;
}
/**
* Returns the list of posts within the Free For All board that the
* specified user can see.
*
* A User can see a post if they are:
* - the creator of the post (username == postedBy)
* - granted view privilege in PostsPrivileges
*
* Different from a regular board because you must check each post
* one by one to ensure that the user has the privilege for it.
*/
public static String getPostListFreeForAll(Connection conn, String username) {
String posts = "print Posts:;";
/*Retrieves all posts, joined with their most recent reply*/
Statement getPosts = null;
String getPostsFreeForAll = "SELECT pid, P.postedBy, P.datePosted, R.repliedBy, MAX(R.dateReplied) " +
"FROM freeforall.posts AS P LEFT OUTER JOIN " +
"freeforall.replies as R USING (pid) " +
"GROUP BY pid ORDER BY R.dateReplied DESC, P.datePosted DESC";
ResultSet postsResults = null;
/*Retrieves the privilege for a given post and user*/
PreparedStatement getPrivs = null;
String getPostPrivileges = "SELECT privilege " +
"FROM freeforall.postprivileges " +
"WHERE pid = ? AND username = ?";
ResultSet privsResult = null;
boolean sqlex = false;
try {
getPrivs = conn.prepareStatement(getPostPrivileges);
getPosts = conn.createStatement();
postsResults = getPosts.executeQuery(getPostsFreeForAll);
int pid;
String postedBy;
while (postsResults.next()) {
pid = postsResults.getInt("pid");
postedBy = postsResults.getString("P.postedBy");
if (!postedBy.equals(username)) {
getPrivs.setInt(1, pid);
getPrivs.setString(2, username);
privsResult = getPrivs.executeQuery();
/*Only expect one result set*/
if (privsResult.next()) { //user has view or viewpost priv
posts += "print \t" +
(privsResult.getString("privilege").equals("viewpost")? specialStrPostable : "") +
"Post#" + pid + "[" + postsResults.getString("P.postedBy") + "];";
if (postsResults.getTimestamp("MAX(R.dateReplied)") != null) {
posts += "print \t" +
"Most Recent Reply: [" + postsResults.getString("R.repliedBy") + "]" +
postsResults.getTimestamp("MAX(R.dateReplied)") + ";";
}
}
}
else { //the user is the creator of the post
posts += "print \t" + specialStrCreatedPost +
"Post#" + pid + "[" + postsResults.getString("P.postedBy") + "];";
if (postsResults.getTimestamp("MAX(R.dateReplied)") != null) {
posts += "print \t" +
"Most Recent Reply: [" + postsResults.getString("R.repliedBy") + "]" +
postsResults.getTimestamp("MAX(R.dateReplied)") + ";";
}
}
}
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
finally {
DBManager.closeStatement(getPosts);
DBManager.closeResultSet(postsResults);
DBManager.closePreparedStatement(getPrivs);
DBManager.closeResultSet(privsResult);
}
if (posts.equals("print Posts:;") && !sqlex) {
return "print No posts for this board.";
}
else if (sqlex) {
return "print Error: Database Error while querying viewable posts. Contact an admin.";
}
else {
return posts;
}
}
/**
* Gets the post list for the given region.
* The board is assumed not to be the free for all board.
* Assumes all parameters are valid (boardName and regionName especially)
* TODO (author) ensure that the user can view the posts for this region
*/
public static String getPostList(Connection conn, String username, String boardName, String regionName) {
PreparedStatement pstmt = null;
String posts = "print Posts:;";
String getPosts = "SELECT rname, pid, P.postedBy, P.datePosted, R.repliedBy, MAX(R.dateReplied) " +
"FROM " + boardName + ".posts AS P LEFT OUTER JOIN " +
boardName + ".replies as R USING (rname, pid) " +
"WHERE rname = ? " +
"GROUP BY pid ORDER BY R.dateReplied DESC, P.datePosted DESC ";
ResultSet postsResults = null;
boolean sqlex = false;
try {
pstmt = conn.prepareStatement(getPosts);
pstmt.setString(1, regionName);
postsResults = pstmt.executeQuery();
while (postsResults.next()) {
posts += "print \tPost#" + postsResults.getInt("pid") +
"[" + postsResults.getString("P.postedBy") + "]; print \t" +
"Most Recent Reply: [" + postsResults.getString("R.repliedBy") + "] " +
postsResults.getTimestamp("MAX(R.dateReplied)") + ";";
}
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
finally {
DBManager.closePreparedStatement(pstmt);
DBManager.closeResultSet(postsResults);
}
if (posts.equals("print Posts:;") && !sqlex) { //board and region assumed to be valid
return "print No Posts for this Region";
}
else if (sqlex) {
return "print Error: Database Error while querying viewable posts. Contact an admin.";
}
else return posts;
}
//TODO need a way to add post privileges for the free for all board.
public static String createPostFreeForAll(Connection conn, String username, String content) {
return createPost(conn, username, content, "freeforall", null);
}
/**
* Inserts the post into the database, then tries its best to
* return the pid that contains the post.
* Assumes the board and region are correct (unless the board is freeforall)
* Does NOT do "Post Privileges" processing.
*
* TODO (author) For regular boards and regions, ensure the user can post under it
*/
public static String createPost(Connection conn, String username, String content,
String boardName, String regionName) {
PreparedStatement createPstmt = null;
String createPost = "";
/*Have to retrieve the pid that is generated for the post*/
PreparedStatement getPstmt = null;
String getPost = "";
ResultSet getResult = null;
if (boardName.equals("freeforall")) {
createPost = "INSERT INTO freeforall.posts " +
"VALUES (null, ?, NOW(), ?)";
getPost = "SELECT pid, MAX(datePosted) FROM freeforall.posts " +
"WHERE postedBy = ? AND content = ?";
}
else {
createPost = "INSERT INTO " + boardName + ".posts " +
- "VALUES (?, null, ?. NOW(), ?)";
+ "VALUES (?, null, ?, NOW(), ?)";
getPost = "SELECT pid, MAX(datePosted) FROM " + boardName + ".posts " +
"WHERE rname = ? postedBy = ? AND content = ?";
}
boolean sqlex = false;
boolean success = false;
try {
createPstmt = conn.prepareStatement(createPost);
if (boardName.equals("freeforall")) {
createPstmt.setString(1, username);
createPstmt.setString(2, content);
}
else {
createPstmt.setString(1, regionName);
createPstmt.setString(2, username);
createPstmt.setString(3, content);
}
success = (createPstmt.executeUpdate() == 1);
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
finally {
DBManager.closePreparedStatement(createPstmt);
}
if (sqlex) {
return "print Error: Database error while inserting the post. Contact an admin.";
}
else if (success) {
/*Try to retrieve the pid for the user to reference*/
Integer pid = null;
try {
getPstmt = conn.prepareStatement(getPost);
if (boardName.equals("freeforall")) {
getPstmt.setString(1, username);
getPstmt.setString(2, content);
}
else {
getPstmt.setString(1, regionName);
getPstmt.setString(2, username);
getPstmt.setString(3, content);
}
getResult = getPstmt.executeQuery();
if (getResult.next()) { //There should be at most one result... just inserted!
pid = new Integer(getResult.getInt("pid"));
}
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
finally {
DBManager.closePreparedStatement(getPstmt);
DBManager.closeResultSet(getResult);
}
if (pid == null || sqlex) {
return "print Post successfully added (post num cannot be retrieved).;" +
"print Don't forget to give people permission to view/reply to it!";
}
else {
return "print Post#" + pid + " successfully added.;" +
"print Don't forget to give people permission to view/reply to it!";
}
}
else { //not successful
return "print Error: Post could not be uploaded. If this problem persists, contact an admin.";
}
}
public static String createReplyFreeForAll(Connection conn, String username, String content,
int postNum) {
return createReply(conn, username, content, "freeforall", null, postNum);
}
/**
* Inserts the reply for the given post.
* Assumes the board, the region, and the post are valid.
*/
public static String createReply(Connection conn, String username, String content,
String boardName, String regionName, int postNum) {
PreparedStatement createPstmt = null;
String createReply = "";
if (boardName.equals("freeforall")) {
createReply = "INSERT INTO freeforall.replies " +
"VALUES (?, null, ?, NOW(), ?)";
}
else {
createReply = "INSERT INTO " + boardName + ".replies " +
"VALUES (?, ?, null, ?, NOW(), ?)";
}
boolean success = false;
boolean sqlex = false;
try {
createPstmt = conn.prepareStatement(createReply);
if (boardName.equals("freeforall")) {
createPstmt.setInt(1, postNum);
createPstmt.setString(2, username);
createPstmt.setString(3, content);
}
else {
createPstmt.setString(1 , regionName);
createPstmt.setInt(2, postNum);
createPstmt.setString(3, username);
createPstmt.setString(4, content);
}
success = (createPstmt.executeUpdate() == 1);
}
catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getSQLState());
sqlex = true;
}
finally {
DBManager.closePreparedStatement(createPstmt);
}
if (!success || sqlex) {
return "print Error: Database error while inserting reply. Contact an admin";
}
else if (success) {
return "print Reply successfully added. Refresh the post to view";
}
else {
return "print Error: Reply could not be uploaded. If this problem persists, contact an admin";
}
}
/** Gets a post from the free for all board designated
* by the post number.
* postNum is assumed to be an accurate post number.
*/
//TODO (author) ensure that the user has access to this post.
public static String getPostFreeForAll(Connection conn, String username, int postNum) {
return getPost(conn, username, "freeforall", "", postNum);
}
/** Gets a post from the designated board and region
* with the given post number.
* ASSUMES that the board, region, and post are all valid.
*/
//TODO (author) ensure that the user has access to the encapsulating region.
public static String getPost(Connection conn, String username, String boardName,
String regionName, int postNum) {
String getOriginalPost = "";
String getReplies = "";
String postAndReplies = "";
/*No joining of results because of redundancy of data returned*/
if (boardName.equals("freeforall")) {
getOriginalPost = "SELECT * FROM freeforall.posts " +
"WHERE pid = ?";
getReplies = "SELECT * FROM freeforall.replies " +
"WHERE pid = ? ORDER BY dateReplied ASC";
}
else {
getOriginalPost = "SELECT * FROM " + boardName + ".posts " +
"WHERE pid = ? AND rname = ?";
getReplies = "SELECT * FROM " + boardName + ".replies " +
"WHERE pid = ? AND rname = ? ORDER BY dateReplied";
}
PreparedStatement originalPost = null;
ResultSet postResult = null;
PreparedStatement replies = null;
ResultSet repliesResult = null;
boolean sqlex = false;
try {
originalPost = conn.prepareStatement(getOriginalPost);
replies = conn.prepareStatement(getReplies);
originalPost.setInt(1, postNum);
replies.setInt(1, postNum);
if (!boardName.equals("freeforall")) {
originalPost.setString(2, regionName);
replies.setString(2, regionName);
}
postResult = originalPost.executeQuery();
if (postResult.next()) { /*Only expect one post result*/
postAndReplies +=
"print ----- Post# " + postNum + "[" + postResult.getString("postedBy") + "]----- " +
postResult.getTimestamp("datePosted").toString() + ";print \t" +
postResult.getString("content") + ";";
repliesResult = replies.executeQuery();
while (repliesResult.next()) { //Print out all replies
postAndReplies += "print ----- Reply[" + repliesResult.getString("repliedBy") + "] ----- " +
repliesResult.getTimestamp("dateReplied").toString() + ";print \t" +
repliesResult.getString("content") + ";";
}
}
// if there's no postResult, the post DNE.
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
if (postAndReplies.equals("") && !sqlex) {
return "print Error: Post does not exist. Refresh. If the problem persists, contact an admin.";
}
else if (sqlex) {
return "print Error: Database error while querying post and replies. Contact an admin.";
}
else return postAndReplies;
}
}
| true | true | public static String createPost(Connection conn, String username, String content,
String boardName, String regionName) {
PreparedStatement createPstmt = null;
String createPost = "";
/*Have to retrieve the pid that is generated for the post*/
PreparedStatement getPstmt = null;
String getPost = "";
ResultSet getResult = null;
if (boardName.equals("freeforall")) {
createPost = "INSERT INTO freeforall.posts " +
"VALUES (null, ?, NOW(), ?)";
getPost = "SELECT pid, MAX(datePosted) FROM freeforall.posts " +
"WHERE postedBy = ? AND content = ?";
}
else {
createPost = "INSERT INTO " + boardName + ".posts " +
"VALUES (?, null, ?. NOW(), ?)";
getPost = "SELECT pid, MAX(datePosted) FROM " + boardName + ".posts " +
"WHERE rname = ? postedBy = ? AND content = ?";
}
boolean sqlex = false;
boolean success = false;
try {
createPstmt = conn.prepareStatement(createPost);
if (boardName.equals("freeforall")) {
createPstmt.setString(1, username);
createPstmt.setString(2, content);
}
else {
createPstmt.setString(1, regionName);
createPstmt.setString(2, username);
createPstmt.setString(3, content);
}
success = (createPstmt.executeUpdate() == 1);
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
finally {
DBManager.closePreparedStatement(createPstmt);
}
if (sqlex) {
return "print Error: Database error while inserting the post. Contact an admin.";
}
else if (success) {
/*Try to retrieve the pid for the user to reference*/
Integer pid = null;
try {
getPstmt = conn.prepareStatement(getPost);
if (boardName.equals("freeforall")) {
getPstmt.setString(1, username);
getPstmt.setString(2, content);
}
else {
getPstmt.setString(1, regionName);
getPstmt.setString(2, username);
getPstmt.setString(3, content);
}
getResult = getPstmt.executeQuery();
if (getResult.next()) { //There should be at most one result... just inserted!
pid = new Integer(getResult.getInt("pid"));
}
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
finally {
DBManager.closePreparedStatement(getPstmt);
DBManager.closeResultSet(getResult);
}
if (pid == null || sqlex) {
return "print Post successfully added (post num cannot be retrieved).;" +
"print Don't forget to give people permission to view/reply to it!";
}
else {
return "print Post#" + pid + " successfully added.;" +
"print Don't forget to give people permission to view/reply to it!";
}
}
else { //not successful
return "print Error: Post could not be uploaded. If this problem persists, contact an admin.";
}
}
| public static String createPost(Connection conn, String username, String content,
String boardName, String regionName) {
PreparedStatement createPstmt = null;
String createPost = "";
/*Have to retrieve the pid that is generated for the post*/
PreparedStatement getPstmt = null;
String getPost = "";
ResultSet getResult = null;
if (boardName.equals("freeforall")) {
createPost = "INSERT INTO freeforall.posts " +
"VALUES (null, ?, NOW(), ?)";
getPost = "SELECT pid, MAX(datePosted) FROM freeforall.posts " +
"WHERE postedBy = ? AND content = ?";
}
else {
createPost = "INSERT INTO " + boardName + ".posts " +
"VALUES (?, null, ?, NOW(), ?)";
getPost = "SELECT pid, MAX(datePosted) FROM " + boardName + ".posts " +
"WHERE rname = ? postedBy = ? AND content = ?";
}
boolean sqlex = false;
boolean success = false;
try {
createPstmt = conn.prepareStatement(createPost);
if (boardName.equals("freeforall")) {
createPstmt.setString(1, username);
createPstmt.setString(2, content);
}
else {
createPstmt.setString(1, regionName);
createPstmt.setString(2, username);
createPstmt.setString(3, content);
}
success = (createPstmt.executeUpdate() == 1);
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
finally {
DBManager.closePreparedStatement(createPstmt);
}
if (sqlex) {
return "print Error: Database error while inserting the post. Contact an admin.";
}
else if (success) {
/*Try to retrieve the pid for the user to reference*/
Integer pid = null;
try {
getPstmt = conn.prepareStatement(getPost);
if (boardName.equals("freeforall")) {
getPstmt.setString(1, username);
getPstmt.setString(2, content);
}
else {
getPstmt.setString(1, regionName);
getPstmt.setString(2, username);
getPstmt.setString(3, content);
}
getResult = getPstmt.executeQuery();
if (getResult.next()) { //There should be at most one result... just inserted!
pid = new Integer(getResult.getInt("pid"));
}
}
catch (SQLException e) {
e.printStackTrace();
sqlex = true;
}
finally {
DBManager.closePreparedStatement(getPstmt);
DBManager.closeResultSet(getResult);
}
if (pid == null || sqlex) {
return "print Post successfully added (post num cannot be retrieved).;" +
"print Don't forget to give people permission to view/reply to it!";
}
else {
return "print Post#" + pid + " successfully added.;" +
"print Don't forget to give people permission to view/reply to it!";
}
}
else { //not successful
return "print Error: Post could not be uploaded. If this problem persists, contact an admin.";
}
}
|
diff --git a/Allelon/src/main/java/com/ciplogic/allelon/songname/CurrentSongNameProvider.java b/Allelon/src/main/java/com/ciplogic/allelon/songname/CurrentSongNameProvider.java
index bcb6f36..bc41bef 100644
--- a/Allelon/src/main/java/com/ciplogic/allelon/songname/CurrentSongNameProvider.java
+++ b/Allelon/src/main/java/com/ciplogic/allelon/songname/CurrentSongNameProvider.java
@@ -1,54 +1,54 @@
package com.ciplogic.allelon.songname;
import com.ciplogic.allelon.player.AvailableStream;
public class CurrentSongNameProvider {
private CurrentSongNameChangeListener currentSongNameChangeListener;
private volatile String currentTitle;
private CurrentSongFetcherThread currentSongFetcherThread;
public void setUrl(String url) {
- currentTitle = "..."; // when the URL changes, we need to reload the title.
+ currentTitle = url == null? "" : "..."; // when the URL changes, we need to reload the title.
if (currentSongFetcherThread != null) {
currentSongFetcherThread.stop();
currentSongFetcherThread = null;
}
if (url != null) {
String titleUrl = AvailableStream.fromUrl(url).getTitleUrl();
currentSongFetcherThread = new CurrentSongFetcherThread(this, titleUrl);
}
}
public String getCurrentTitle() {
return currentTitle;
}
public CurrentSongNameChangeListener getCurrentSongNameChangeListener() {
return currentSongNameChangeListener;
}
public void setCurrentSongNameChangeListener(CurrentSongNameChangeListener currentSongNameChangeListener) {
this.currentSongNameChangeListener = currentSongNameChangeListener;
}
public void setFetchedTitle(String title) {
String oldTitle = currentTitle;
currentTitle = title;
if (!areStringsEquals(oldTitle, currentTitle)) {
if (currentSongNameChangeListener != null) {
currentSongNameChangeListener.onTitleChange(currentTitle);
}
}
}
private boolean areStringsEquals(String oldTitle, String currentTitle1) {
if (oldTitle == null) {
return currentTitle1 == null;
}
return oldTitle.equals(currentTitle1);
}
}
| true | true | public void setUrl(String url) {
currentTitle = "..."; // when the URL changes, we need to reload the title.
if (currentSongFetcherThread != null) {
currentSongFetcherThread.stop();
currentSongFetcherThread = null;
}
if (url != null) {
String titleUrl = AvailableStream.fromUrl(url).getTitleUrl();
currentSongFetcherThread = new CurrentSongFetcherThread(this, titleUrl);
}
}
| public void setUrl(String url) {
currentTitle = url == null? "" : "..."; // when the URL changes, we need to reload the title.
if (currentSongFetcherThread != null) {
currentSongFetcherThread.stop();
currentSongFetcherThread = null;
}
if (url != null) {
String titleUrl = AvailableStream.fromUrl(url).getTitleUrl();
currentSongFetcherThread = new CurrentSongFetcherThread(this, titleUrl);
}
}
|
diff --git a/src/main/java/net/spy/memcached/tapmessage/TapFlag.java b/src/main/java/net/spy/memcached/tapmessage/TapFlag.java
index 1fe786d..867f7d4 100644
--- a/src/main/java/net/spy/memcached/tapmessage/TapFlag.java
+++ b/src/main/java/net/spy/memcached/tapmessage/TapFlag.java
@@ -1,71 +1,71 @@
package net.spy.memcached.tapmessage;
/**
* The Flag enum contains a list all of the different flags that can be passed
* in a tap message in the flag field.
*/
public enum TapFlag {
/**
* Tap backfill flag definition
*/
BACKFILL((byte) 0x01),
/**
* Tap dump flag definition
*/
DUMP((byte) 0x02),
/**
* Tap list vBuckets flag definition
*/
LIST_VBUCKETS((byte) 0x04),
/**
* Tap take over vBuckets flag definition
*/
TAKEOVER_VBUCKETS((byte) 0x08),
/**
* Tap support acknowledgment flag definition
*/
SUPPORT_ACK((byte) 0x10),
/**
* Tap send keys only flag definition
*/
KEYS_ONLY((byte) 0x20),
/**
* Tap use checkpoints
*/
CHECKPOINT((byte) 0x40);
/**
* The flag value
*/
public byte flag;
/**
* Defines the flag value
*
* @param flag - The new flag value
*/
TapFlag(byte flag) {
this.flag = flag;
}
/**
* Checks to see if a flag is contained in a flag field. The flag field must be converted to
* an integer before calling this function
*
* @param f The integer value of the flag field in a tap packet
*
* @return Returns true if the flag is contained in the flag field
*/
boolean hasFlag(int f) {
- if ((f & (int) flag) == 1) {
- return false;
+ if ((f & (int) flag) > 0) {
+ return true;
}
- return true;
+ return false;
}
}
| false | true | boolean hasFlag(int f) {
if ((f & (int) flag) == 1) {
return false;
}
return true;
}
| boolean hasFlag(int f) {
if ((f & (int) flag) > 0) {
return true;
}
return false;
}
|
diff --git a/src/org/jruby/runtime/CallAdapter.java b/src/org/jruby/runtime/CallAdapter.java
index 20c736281..9e6cefd6f 100644
--- a/src/org/jruby/runtime/CallAdapter.java
+++ b/src/org/jruby/runtime/CallAdapter.java
@@ -1,190 +1,191 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common 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/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Charles O Nutter <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.runtime;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.exceptions.JumpException;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
*/
public abstract class CallAdapter {
public final int methodID;
public final String methodName;
protected final CallType callType;
public CallAdapter(int methodID, String methodName, CallType callType) {
this.methodID = methodID;
this.methodName = methodName;
this.callType = callType;
}
// no block
public abstract IRubyObject call(ThreadContext context, IRubyObject self);
public abstract IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1);
public abstract IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2);
public abstract IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3);
public abstract IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject[] args);
// with block
public abstract IRubyObject call(ThreadContext context, IRubyObject self, Block block);
public abstract IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, Block block);
public abstract IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2, Block block);
public abstract IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3, Block block);
public abstract IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block);
public static class DefaultCallAdapter extends CallAdapter implements CacheMap.CacheSite {
byte[] cachedTable;
DynamicMethod cachedMethod;
RubyClass cachedType;
public DefaultCallAdapter(String methodName, CallType callType) {
super(MethodIndex.getIndex(methodName), methodName, callType);
}
public IRubyObject call(ThreadContext context, IRubyObject self) {
IRubyObject[] args = IRubyObject.NULL_ARRAY;
Block block = Block.NULL_BLOCK;
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1) {
IRubyObject[] args = new IRubyObject[] {arg1};
Block block = Block.NULL_BLOCK;
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2) {
IRubyObject[] args = new IRubyObject[] {arg1,arg2};
Block block = Block.NULL_BLOCK;
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3) {
IRubyObject[] args = new IRubyObject[] {arg1,arg2,arg3};
Block block = Block.NULL_BLOCK;
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject[] args) {
Block block = Block.NULL_BLOCK;
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, Block block) {
IRubyObject[] args = IRubyObject.NULL_ARRAY;
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, Block block) {
IRubyObject[] args = new IRubyObject[] {arg1};
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2, Block block) {
IRubyObject[] args = new IRubyObject[] {arg1,arg2};
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3, Block block) {
IRubyObject[] args = new IRubyObject[] {arg1,arg2,arg3};
return call(context, self, args, block);
}
public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block) {
while (true) {
try {
RubyClass selfType = self.getMetaClass();
+ byte[] cTable = this.cachedTable;
DynamicMethod cMethod = this.cachedMethod;
RubyModule cType = this.cachedType;
- if (cType == selfType && cMethod != null) {
- if (cachedTable.length > methodID && cachedTable[methodID] != 0) {
+ if (cType == selfType && cachedTable != null) {
+ if (cTable.length > methodID && cTable[methodID] != 0) {
return selfType.getDispatcher().callMethod(context, self, selfType, methodID, methodName, args, callType, block);
- } else {
+ } else if (cMethod != null) {
return cMethod.call(context, self, selfType, methodName, args, block);
}
}
byte[] table = selfType.getDispatcher().switchTable;
if (table.length > methodID && table[methodID] != 0) {
cachedTable = table;
cachedType = selfType;
return selfType.getDispatcher().callMethod(context, self, selfType, methodID, methodName, args, callType, block);
}
DynamicMethod method = null;
method = selfType.searchMethod(methodName);
if (method.isUndefined() || (!methodName.equals("method_missing") && !method.isCallableFrom(context.getFrameSelf(), callType))) {
return RubyObject.callMethodMissing(context, self, method, methodName, args, context.getFrameSelf(), callType, block);
}
cachedMethod = method;
cachedType = selfType;
cachedTable = table;
selfType.getRuntime().getCacheMap().add(method, this);
return method.call(context, self, selfType, methodName, args, block);
} catch (JumpException.BreakJump bj) {
// JRUBY-530, Kernel#loop case:
if (bj.isBreakInKernelLoop()) {
// consume and rethrow or just keep rethrowing?
if (block == bj.getTarget()) bj.setBreakInKernelLoop(false);
throw bj;
}
return (IRubyObject)bj.getValue();
} catch (StackOverflowError soe) {
throw context.getRuntime().newSystemStackError("stack level too deep");
}
}
}
public void removeCachedMethod(String name) {
cachedType = null;
cachedMethod = null;
}
}
}
| false | true | public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block) {
while (true) {
try {
RubyClass selfType = self.getMetaClass();
DynamicMethod cMethod = this.cachedMethod;
RubyModule cType = this.cachedType;
if (cType == selfType && cMethod != null) {
if (cachedTable.length > methodID && cachedTable[methodID] != 0) {
return selfType.getDispatcher().callMethod(context, self, selfType, methodID, methodName, args, callType, block);
} else {
return cMethod.call(context, self, selfType, methodName, args, block);
}
}
byte[] table = selfType.getDispatcher().switchTable;
if (table.length > methodID && table[methodID] != 0) {
cachedTable = table;
cachedType = selfType;
return selfType.getDispatcher().callMethod(context, self, selfType, methodID, methodName, args, callType, block);
}
DynamicMethod method = null;
method = selfType.searchMethod(methodName);
if (method.isUndefined() || (!methodName.equals("method_missing") && !method.isCallableFrom(context.getFrameSelf(), callType))) {
return RubyObject.callMethodMissing(context, self, method, methodName, args, context.getFrameSelf(), callType, block);
}
cachedMethod = method;
cachedType = selfType;
cachedTable = table;
selfType.getRuntime().getCacheMap().add(method, this);
return method.call(context, self, selfType, methodName, args, block);
} catch (JumpException.BreakJump bj) {
// JRUBY-530, Kernel#loop case:
if (bj.isBreakInKernelLoop()) {
// consume and rethrow or just keep rethrowing?
if (block == bj.getTarget()) bj.setBreakInKernelLoop(false);
throw bj;
}
return (IRubyObject)bj.getValue();
} catch (StackOverflowError soe) {
throw context.getRuntime().newSystemStackError("stack level too deep");
}
}
}
| public IRubyObject call(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block) {
while (true) {
try {
RubyClass selfType = self.getMetaClass();
byte[] cTable = this.cachedTable;
DynamicMethod cMethod = this.cachedMethod;
RubyModule cType = this.cachedType;
if (cType == selfType && cachedTable != null) {
if (cTable.length > methodID && cTable[methodID] != 0) {
return selfType.getDispatcher().callMethod(context, self, selfType, methodID, methodName, args, callType, block);
} else if (cMethod != null) {
return cMethod.call(context, self, selfType, methodName, args, block);
}
}
byte[] table = selfType.getDispatcher().switchTable;
if (table.length > methodID && table[methodID] != 0) {
cachedTable = table;
cachedType = selfType;
return selfType.getDispatcher().callMethod(context, self, selfType, methodID, methodName, args, callType, block);
}
DynamicMethod method = null;
method = selfType.searchMethod(methodName);
if (method.isUndefined() || (!methodName.equals("method_missing") && !method.isCallableFrom(context.getFrameSelf(), callType))) {
return RubyObject.callMethodMissing(context, self, method, methodName, args, context.getFrameSelf(), callType, block);
}
cachedMethod = method;
cachedType = selfType;
cachedTable = table;
selfType.getRuntime().getCacheMap().add(method, this);
return method.call(context, self, selfType, methodName, args, block);
} catch (JumpException.BreakJump bj) {
// JRUBY-530, Kernel#loop case:
if (bj.isBreakInKernelLoop()) {
// consume and rethrow or just keep rethrowing?
if (block == bj.getTarget()) bj.setBreakInKernelLoop(false);
throw bj;
}
return (IRubyObject)bj.getValue();
} catch (StackOverflowError soe) {
throw context.getRuntime().newSystemStackError("stack level too deep");
}
}
}
|
diff --git a/databus-audit/src/main/java/com/inmobi/databus/audit/AuditStats.java b/databus-audit/src/main/java/com/inmobi/databus/audit/AuditStats.java
index e1bb799f..8e01724b 100644
--- a/databus-audit/src/main/java/com/inmobi/databus/audit/AuditStats.java
+++ b/databus-audit/src/main/java/com/inmobi/databus/audit/AuditStats.java
@@ -1,169 +1,169 @@
package com.inmobi.databus.audit;
import com.inmobi.databus.audit.services.AuditRollUpService;
import info.ganglia.gmetric4j.gmetric.GMetric;
import info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.codahale.metrics.CsvReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ganglia.GangliaReporter;
import com.inmobi.databus.Cluster;
import com.inmobi.databus.DatabusConfig;
import com.inmobi.databus.DatabusConfigParser;
import com.inmobi.databus.audit.services.AuditFeederService;
import com.inmobi.databus.audit.util.AuditDBConstants;
import com.inmobi.messaging.ClientConfig;
import com.inmobi.messaging.consumer.databus.MessagingConsumerConfig;
/*
* This class is responsible for launching multiple AuditStatsFeeder instances one per cluster
*/
public class AuditStats {
private static final Log LOG = LogFactory.getLog(AuditStats.class);
public final static MetricRegistry metrics = new MetricRegistry();
final List<AuditDBService> dbServices = new ArrayList<AuditDBService>();
private final ClientConfig config;
private List<DatabusConfig> databusConfigList;
private Map<String, Cluster> clusterMap;
public AuditStats() throws Exception {
config = ClientConfig.loadFromClasspath(AuditDBConstants.FEEDER_CONF_FILE);
config.set(MessagingConsumerConfig.hadoopConfigFileKey,
"audit-core-site.xml");
String databusConfFolder = config.getString(AuditDBConstants
.DATABUS_CONF_FILE_KEY);
loadConfigFiles(databusConfFolder);
createClusterMap();
for (Entry<String, Cluster> cluster : clusterMap.entrySet()) {
String rootDir = cluster.getValue().getRootDir();
AuditDBService feeder = new AuditFeederService(cluster.getKey(), rootDir,
config);
dbServices.add(feeder);
}
AuditDBService rollup = new AuditRollUpService(config);
dbServices.add(rollup);
}
private void createClusterMap() {
clusterMap = new HashMap<String, Cluster>();
for (DatabusConfig dataBusConfig : databusConfigList) {
clusterMap.putAll(dataBusConfig.getClusters());
}
}
private void loadConfigFiles(String databusConfFolder) {
File folder = new File(databusConfFolder);
File[] xmlFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.getName().toLowerCase().endsWith(".xml")) {
return true;
}
return false;
}
});
databusConfigList = new ArrayList<DatabusConfig>();
if (xmlFiles.length == 0) {
- LOG.info("No xml files found in the conf folder:"+databusConfFolder);
+ LOG.error("No xml files found in the conf folder:"+databusConfFolder);
return;
}
LOG.info("Databus xmls included in the conf folder:");
for (File file : xmlFiles) {
String fullPath = file.getAbsolutePath();
LOG.info("File:"+fullPath);
try {
DatabusConfigParser parser = new DatabusConfigParser(fullPath);
databusConfigList.add(parser.getConfig());
} catch (Exception e) {
e.printStackTrace();
}
}
}
private synchronized void start() throws Exception {
// start all dbServices
for (AuditDBService service : dbServices) {
LOG.info("Starting service: " + service.getServiceName());
service.start();
}
startMetricsReporter(config);
}
private void join() {
for (AuditDBService service : dbServices) {
service.join();
}
}
private void startMetricsReporter(ClientConfig config) {
String gangliaHost = config.getString(AuditDBConstants.GANGLIA_HOST);
int gangliaPort = config.getInteger(AuditDBConstants.GANGLIA_PORT, 8649);
if (gangliaHost != null) {
GMetric ganglia;
try {
ganglia = new GMetric(gangliaHost, gangliaPort,
UDPAddressingMode.MULTICAST, 1);
GangliaReporter gangliaReporter = GangliaReporter.forRegistry(metrics)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS).build(ganglia);
gangliaReporter.start(1, TimeUnit.MINUTES);
} catch (IOException e) {
LOG.error("Cannot start ganglia reporter", e);
}
}
String csvDir = config.getString(AuditDBConstants.CSV_REPORT_DIR, "/tmp");
CsvReporter csvreporter = CsvReporter.forRegistry(metrics)
.formatFor(Locale.US).convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS).build(new File(csvDir));
csvreporter.start(1, TimeUnit.MINUTES);
}
public synchronized void stop() {
try {
LOG.info("Stopping all services...");
for (AuditDBService service : dbServices) {
LOG.info("Stopping service :" + service.getServiceName());
service.stop();
}
LOG.info("All services signalled to stop");
} catch (Exception e) {
LOG.warn("Error in shutting down feeder and rollup services", e);
}
}
public static void main(String args[]) throws Exception {
final AuditStats stats = new AuditStats();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
stats.stop();
stats.join();
LOG.info("Finishing the shutdown hook");
}
});
// TODO check if current table exist else create it.NOTE:This will be done
// in next version
try {
stats.start();
// wait for all dbServices to finish
stats.join();
} finally {
stats.stop();
}
}
}
| true | true | private void loadConfigFiles(String databusConfFolder) {
File folder = new File(databusConfFolder);
File[] xmlFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.getName().toLowerCase().endsWith(".xml")) {
return true;
}
return false;
}
});
databusConfigList = new ArrayList<DatabusConfig>();
if (xmlFiles.length == 0) {
LOG.info("No xml files found in the conf folder:"+databusConfFolder);
return;
}
LOG.info("Databus xmls included in the conf folder:");
for (File file : xmlFiles) {
String fullPath = file.getAbsolutePath();
LOG.info("File:"+fullPath);
try {
DatabusConfigParser parser = new DatabusConfigParser(fullPath);
databusConfigList.add(parser.getConfig());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| private void loadConfigFiles(String databusConfFolder) {
File folder = new File(databusConfFolder);
File[] xmlFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.getName().toLowerCase().endsWith(".xml")) {
return true;
}
return false;
}
});
databusConfigList = new ArrayList<DatabusConfig>();
if (xmlFiles.length == 0) {
LOG.error("No xml files found in the conf folder:"+databusConfFolder);
return;
}
LOG.info("Databus xmls included in the conf folder:");
for (File file : xmlFiles) {
String fullPath = file.getAbsolutePath();
LOG.info("File:"+fullPath);
try {
DatabusConfigParser parser = new DatabusConfigParser(fullPath);
databusConfigList.add(parser.getConfig());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
diff --git a/Fanorona.java b/Fanorona.java
index 8455d6b..5f10473 100644
--- a/Fanorona.java
+++ b/Fanorona.java
@@ -1,506 +1,506 @@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.Timer;
import javax.sound.midi.*;
import javax.swing.JOptionPane;
import java.lang.reflect.InvocationTargetException;
import java.net.*;
import java.io.*;
public class Fanorona extends JPanel implements ActionListener, MouseListener {
StateMachine stateMachine; //contains grid
//No flags necessary beyond the state machine itself
private JButton newGameButton;
private JButton instructionsButton;
private JButton nameButton;
private JButton aiButton;
private JLabel timerBox;
private JLabel messageBox;
static final int LOOP_CONTINUOUSLY = 9999;
int BUTTON_SIZE_WIDTH = 120;
int BUTTON_SIZE_HEIGHT = 30;
double xGridAndExcess;
double yGridAndExcess;
double xGridSize;
double yGridSize;
double changeFactor = 1.0;
String playerName;
int timePerTurn;
Clock clock;
String networkSetting;
String serverName;
int serverPort = 8725;
int clientPort = 8725;
String clientStartingSide = "B";
int rowSize;
int colSize;
Boolean aiIsOn;
public static AI ai;
public static void main(String[] args) throws Exception {//{{{
//setup game window
JFrame window = new JFrame("Fanorona");
Fanorona content = new Fanorona();
window.setContentPane(content);
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
URL url = new URL("http://www.vgmusic.com/music/console/nintendo/nes/advlolo1_theme.mid");
Sequence sequence = MidiSystem.getSequence(url);
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);
sequencer.setLoopCount(LOOP_CONTINUOUSLY);
sequencer.start();
}//}}}
public Fanorona() {//{{{
setLayout(null);
askServerClientInfo();
ObjectOutputStream socketOut = null;
ObjectInputStream socketIn = null;
if(networkSetting == "Server") {
getServerConfig();
askGridSize();
askTimePerTurn();
Socket acceptSocket = null;
try {
acceptSocket = setupServerSockets();
socketOut = new ObjectOutputStream(acceptSocket.getOutputStream());
socketOut.flush();
socketIn = new ObjectInputStream(acceptSocket.getInputStream());
String welcome = "WELCOME";
socketOut.writeObject(welcome);
System.out.println("Server: " + welcome);
socketOut.flush();
} catch (IOException e) {}
sendGameInfo(socketOut, colSize, rowSize, timePerTurn);
waitForClient(socketIn, socketOut);
} else if (networkSetting == "Client") {
getClientConfig();
Socket acceptSocket = null;
try{
acceptSocket = setupClientSocket();
socketOut = new ObjectOutputStream(acceptSocket.getOutputStream());
socketOut.flush();
socketIn = new ObjectInputStream(acceptSocket.getInputStream());
receiveGameInfo(socketIn);
String ready = "READY";
socketOut.writeObject(ready);
System.out.println("Client: " + ready);
socketOut.flush();
waitForBegin(socketIn);
} catch (IOException e) {}
} else {
askGridSize();
askTimePerTurn();
}
createGrid();
setPreferredSize(new Dimension((BUTTON_SIZE_WIDTH*2+30)+((int)((colSize*100+100)*changeFactor)),(int)((rowSize*100+100)*changeFactor)));
stateMachine = new StateMachine(colSize, rowSize, timePerTurn, changeFactor, networkSetting, socketOut, socketIn, clientStartingSide);
add(stateMachine.grid);
stateMachine.grid.setBounds(BUTTON_SIZE_WIDTH*2+30,1,(int)((colSize*100+100)*changeFactor),(int)((rowSize*100+100)*changeFactor));
ai = new AI();
- ai.setBounds(colSize - 1 , rowSize - 1);
+ ai.setBounds(colSize, rowSize);
aiIsOn = false;
initButtons();
//add listeners
instructionsButton.addActionListener(this);
newGameButton.addActionListener(this);
nameButton.addActionListener(this);
aiButton.addActionListener(this);
addMouseListener(this);
String message = stateMachine.run("NewGame", null);
messageBox.setText(message);
clock = new Clock(timePerTurn);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
clock.startTimer();
}
});
} //}}}
public void createGrid() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//resize the grid
System.out.println("screenWidth: " + screenSize.getWidth());
System.out.println("screenHeight: " + screenSize.getHeight());
xGridAndExcess = (colSize*100)+(BUTTON_SIZE_WIDTH*2+30);
yGridAndExcess = (rowSize*100)+100;
System.out.println("xGridAndExcess: " + xGridAndExcess);
System.out.println("yGridAndExcess: " + yGridAndExcess);
if(xGridAndExcess > screenSize.getWidth() || yGridAndExcess > screenSize.getHeight()) {
xGridSize = screenSize.getWidth() - ((BUTTON_SIZE_WIDTH*2)+30);
yGridSize = screenSize.getHeight() - ((BUTTON_SIZE_HEIGHT*2)+30);
System.out.println("xGridSize: " + xGridSize);
System.out.println("yGridSize: " + yGridSize);
if((xGridAndExcess-screenSize.getWidth()) >= (yGridAndExcess-screenSize.getHeight())) {
changeFactor = xGridSize / xGridAndExcess;
System.out.println("% change: " + (xGridSize / xGridAndExcess));
}
else {
changeFactor = yGridSize / yGridAndExcess;
System.out.println("% change: " + (yGridSize / yGridAndExcess));
}
}
}
public void initButtons() {//{{{
instructionsButton = new JButton("Instructions");
newGameButton = new JButton("New Game");
aiButton = new JButton("Toggle AI");
nameButton = new JButton("Change Name");
timerBox = new JLabel("",JLabel.LEFT);
timerBox.setVerticalAlignment(JLabel.TOP);
timerBox.setFont(new Font("Serif", Font.BOLD, 12));
timerBox.setForeground(Color.BLACK);
messageBox = new JLabel("",JLabel.LEFT);
messageBox.setVerticalAlignment(JLabel.TOP);
messageBox.setFont(new Font("Serif", Font.BOLD, 12));
messageBox.setForeground(Color.BLACK);
add(newGameButton);
add(aiButton);
add(instructionsButton);
add(nameButton);
add(timerBox);
add(messageBox);
newGameButton.setBounds(10, 10, BUTTON_SIZE_WIDTH, BUTTON_SIZE_HEIGHT);
instructionsButton.setBounds(BUTTON_SIZE_WIDTH+20, 10, BUTTON_SIZE_WIDTH, BUTTON_SIZE_HEIGHT);
nameButton.setBounds(10, BUTTON_SIZE_HEIGHT+20, BUTTON_SIZE_WIDTH, BUTTON_SIZE_HEIGHT);
aiButton.setBounds(BUTTON_SIZE_WIDTH+20, BUTTON_SIZE_HEIGHT+20, BUTTON_SIZE_WIDTH, BUTTON_SIZE_HEIGHT);
timerBox.setBounds(10, (BUTTON_SIZE_HEIGHT*2)+25, BUTTON_SIZE_WIDTH*2, BUTTON_SIZE_HEIGHT);
messageBox.setBounds(10, (BUTTON_SIZE_HEIGHT*3)+25, BUTTON_SIZE_WIDTH*2, BUTTON_SIZE_HEIGHT*4);
}//}}}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
public void mousePressed(MouseEvent evt) {
if(clickingIsAllowed()) {
if(SwingUtilities.isRightMouseButton(evt)) {
String message = stateMachine.run("RClick", null);
messageBox.setText(message);
} else { //left click
String message = stateMachine.run("Click", evt.getPoint());
messageBox.setText(message);
}
}
//start AI on transition to enemy turn
runAI();
}
public void mouseReleased(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {}
private Boolean clickingIsAllowed() {//{{{
return !aiIsOn || (aiIsOn && stateMachine.isPlayerTurn());
}//}}}
public void runAI() {//{{{
//if at state of AI turn
if(aiIsOn && (stateMachine.getState() == State.ENEMY_SELECT)) {
//get the move from AI
ArrayList<Point> points = new ArrayList<Point>();
Move move = ai.getMove(stateMachine.grid.getState());
Point startLocation = new Point(move.startPointX, move.startPointY);
Point endLocation = new Point(move.endPointX, move.endPointY);
points.add(startLocation);
points.add(endLocation);
//feed all the points to the state machine
for(Point p : points) {
System.out.println("INSIDE OF FANORONA.JAVA " + p.x + " " + p.y);
String message = stateMachine.run("AIChoice", p);
messageBox.setText(message);
}
}
}//}}}
public void actionPerformed(ActionEvent evt) {//{{{
Object src = evt.getSource();
if(src == newGameButton) {
String message = stateMachine.run("NewGame", null);
messageBox.setText(message);
} else if(src == instructionsButton) {
instructions();
} else if(src == nameButton) {
changeName();
} else if(src == aiButton) {
if(stateMachine.isPlayerTurn()) {
aiIsOn = !aiIsOn; //toggle
String aiState = aiIsOn?"on":"off";
JOptionPane.showMessageDialog(this, "AI is now " + aiState + ".", "AI toggle", JOptionPane.PLAIN_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Can only toggle AI during the white player's turn.", "AI toggle", JOptionPane.PLAIN_MESSAGE);
}
}
}//}}}
//asks the user if the game is to be played in a server/client config
void askServerClientInfo() {
JPanel panel = new JPanel();
panel.add(new JLabel("Please choose what network function you would like this game instance to perform: "));
DefaultComboBoxModel networkConfig = new DefaultComboBoxModel();
networkConfig.addElement("Just Play a Local Game");
networkConfig.addElement("Server");
networkConfig.addElement("Client");
JComboBox networkConfigBox = new JComboBox(networkConfig);
panel.add(networkConfigBox);
int result = JOptionPane.showConfirmDialog(null, panel, "Choose Game Network Configuration", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
switch (result) {
case JOptionPane.OK_OPTION:
networkSetting = (String)networkConfigBox.getSelectedItem();
System.out.println("network: " + networkSetting);
break;
default:
System.exit(0);
break;
}
}
Socket setupServerSockets() throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(serverPort);
} catch (IOException e) {
System.err.println("Could not listen on port: " + serverPort + ".");
System.exit(1);
}
/*String socketNotice = "Fanarona will continue once a client connects to the server.\nPress OK to dismiss this message and continue.";
JOptionPane.showMessageDialog(this, socketNotice, "Waiting for client connect...", JOptionPane.PLAIN_MESSAGE);*/
Socket acceptSocket = null;
try {
acceptSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
return acceptSocket;
}
Socket setupClientSocket() throws IOException {
Socket acceptSocket = new Socket(serverName, clientPort);
return acceptSocket;
}
void getServerConfig() {
try {
String value = JOptionPane.showInputDialog(null, "What port should the server listen on? (Leave Blank for Default Fanarona Port 8725)", "Server Port Configuration", JOptionPane.QUESTION_MESSAGE);
if(value == null)
System.exit(0);
serverPort = Integer.parseInt(value);
} catch(NumberFormatException e) {}
}
void getClientConfig() {
try {
String value = JOptionPane.showInputDialog(null, "Please enter the hostname of the server you wish to connect.", "Server Hostname", JOptionPane.QUESTION_MESSAGE);
if(value == null)
System.exit(0);
serverName = value;
} catch(NumberFormatException e) {}
try {
String value = JOptionPane.showInputDialog(null, "What port should the client connect on? (Leave Blank for Default Fanarona Port 8725)", "Server Port Configuration", JOptionPane.QUESTION_MESSAGE);
if(value == null)
System.exit(0);
clientPort = Integer.parseInt(value);
} catch(NumberFormatException e) {}
}
void sendGameInfo(ObjectOutputStream m_socketOut, int cols, int rows, int timeout) {
//send game info over the socket
try{
String gameInfoMessage = "INFO " + cols + " " + rows + " B " + timeout;
m_socketOut.writeObject(gameInfoMessage);
System.out.println("Server: " + gameInfoMessage);
m_socketOut.flush();
}
catch(IOException ioException){}
}
void waitForClient(ObjectInputStream m_socketIn, ObjectOutputStream m_socketOut) {
try {
String message = "";
while(!message.equals("READY")) {
message = (String)m_socketIn.readObject();
System.out.println("Client: " + message);
}
String response = "BEGIN";
m_socketOut.writeObject(response);
System.out.println("Server: " + response);
m_socketOut.flush();
} catch (Exception e) {}
}
void waitForBegin(ObjectInputStream m_socketIn) {
try {
String message = "";
while(!message.equals("BEGIN")) {
message = (String)m_socketIn.readObject();
System.out.println("Server: " + message);
}
} catch (Exception e) {}
}
void receiveGameInfo(ObjectInputStream m_socketIn) {
//get game info from the socket
String message = "";
try{
while(!message.equals("WELCOME")) {
message = (String)m_socketIn.readObject();
System.out.println("Server: " + message);
}
while(!message.startsWith("INFO")) {
message = (String)m_socketIn.readObject();
System.out.println("Server: " + message);
String[] infoArray = message.split(" ");
if(infoArray.length != 5)
System.err.println("Bad info received from server.");
colSize = Integer.parseInt(infoArray[1]);
rowSize = Integer.parseInt(infoArray[2]);
clientStartingSide = infoArray[3];
timePerTurn = Integer.parseInt(infoArray[4]);
}
} catch (Exception e) {}
}
//asks the user for a grid size (row, col)
void askGridSize() {
JPanel panel = new JPanel();
panel.add(new JLabel("Choose a Fanorona board size (row, column): "));
DefaultComboBoxModel rows = new DefaultComboBoxModel();
DefaultComboBoxModel cols = new DefaultComboBoxModel();
for(int n = 1; n <= 13; n+=2) {
rows.addElement(n);
cols.addElement(n);
}
rows.setSelectedItem(rows.getElementAt(2));
cols.setSelectedItem(cols.getElementAt(4));
JComboBox rowsBox = new JComboBox(rows);
panel.add(rowsBox);
JComboBox colsBox = new JComboBox(cols);
panel.add(colsBox);
int result = JOptionPane.showConfirmDialog(null, panel, "Choose Fanorona Grid Size", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
switch (result) {
case JOptionPane.OK_OPTION:
rowSize = (Integer)rowsBox.getSelectedItem();
colSize = (Integer)colsBox.getSelectedItem();
System.out.println("rows: " + rowSize);
System.out.println("columns: " + colSize);
break;
default:
System.exit(0);
break;
}
}
// prompts user for time per turn
void askTimePerTurn() {
//JPanel panel = new JPanel();
try {
String value = JOptionPane.showInputDialog(null, "Enter a time limit per turn (milliseconds): (If no time limit is wanted, just leave blank.)", "", JOptionPane.PLAIN_MESSAGE);
if(value == null)
System.exit(0);
timePerTurn = Integer.parseInt(value);
} catch(NumberFormatException e) {}
}
void changeName() {//{{{
playerName = JOptionPane.showInputDialog(null, "Enter player name: ", "", JOptionPane.PLAIN_MESSAGE);
if(playerName != null)
messageBox.setText("Player name is: " + playerName);
}//}}}
void instructions() {//{{{
String instructionDialog = "From Wikipedia:\n" +
"* Players alternate turns, starting with White.\n" +
"* We distinguish two kinds of moves, non-capturing and capturing moves. A non-capturing move is called a paika move.\n" +
"* A paika move consists of moving one stone along a line to an adjacent intersection.\n" +
"* Capturing moves are obligatory and have to be played in preference to paika moves.\n" +
"* Capturing implies removing one or more pieces of the opponent. It can be done in two ways, either (1) by approach or (2) by withdrawal.\n" +
" (1) An approach is moving the capturing stone to a point adjacent to an opponent stone provided that the stone is on the continuation of the capturing stone's movement line.\n" +
" (2) A withdrawal works analogously to an approach except that the movement is away from the opponent stone.\n" +
"* When an opponent stone is captured, all opponent pieces in line behind that stone (as long as there is no interruption by an empty point or an own stone) are captured as well.\n" +
"* If a player can do an approach and a withdrawal at the same time, he has to choose which one he plays.\n" +
"* As in checkers, the capturing piece is allowed to continue making successive captures, with these restrictions:\n" +
" (1) The piece is not allowed to arrive at the same position twice.\n" +
" (2) It is not allowed to move a piece in the same direction as directly before in the capturing sequence. This can happen if an approach follows on a withdrawal.\n" +
"* The game ends when one player captures all stones of the opponent. If neither player can achieve this, the game is a draw.\n";
JOptionPane.showMessageDialog(this, instructionDialog, "Fanorona Instructions", JOptionPane.PLAIN_MESSAGE);
}//}}}
public class Clock {
private Timer timer = new Timer();
private int timeRemaining;
private boolean timerOff;
public Clock(int time) {
timeRemaining = time;
if(time <= 0)
timerOff = true;
else
timerOff = false;
}
private class UpdateUITask extends TimerTask {
@Override
public void run() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if(timeRemaining <= 0) {
System.out.println("LOSER");
timer.cancel();
}
timerBox.setText("Time left for turn (seconds): " + String.valueOf(timeRemaining--));
}
});
}
}
public void startTimer() {
if(timerOff)
timerBox.setText("Time left for turn (seconds): OFF");
else
timer.schedule(new UpdateUITask(), timeRemaining, 1000);
}
}
}
| true | true | public Fanorona() {//{{{
setLayout(null);
askServerClientInfo();
ObjectOutputStream socketOut = null;
ObjectInputStream socketIn = null;
if(networkSetting == "Server") {
getServerConfig();
askGridSize();
askTimePerTurn();
Socket acceptSocket = null;
try {
acceptSocket = setupServerSockets();
socketOut = new ObjectOutputStream(acceptSocket.getOutputStream());
socketOut.flush();
socketIn = new ObjectInputStream(acceptSocket.getInputStream());
String welcome = "WELCOME";
socketOut.writeObject(welcome);
System.out.println("Server: " + welcome);
socketOut.flush();
} catch (IOException e) {}
sendGameInfo(socketOut, colSize, rowSize, timePerTurn);
waitForClient(socketIn, socketOut);
} else if (networkSetting == "Client") {
getClientConfig();
Socket acceptSocket = null;
try{
acceptSocket = setupClientSocket();
socketOut = new ObjectOutputStream(acceptSocket.getOutputStream());
socketOut.flush();
socketIn = new ObjectInputStream(acceptSocket.getInputStream());
receiveGameInfo(socketIn);
String ready = "READY";
socketOut.writeObject(ready);
System.out.println("Client: " + ready);
socketOut.flush();
waitForBegin(socketIn);
} catch (IOException e) {}
} else {
askGridSize();
askTimePerTurn();
}
createGrid();
setPreferredSize(new Dimension((BUTTON_SIZE_WIDTH*2+30)+((int)((colSize*100+100)*changeFactor)),(int)((rowSize*100+100)*changeFactor)));
stateMachine = new StateMachine(colSize, rowSize, timePerTurn, changeFactor, networkSetting, socketOut, socketIn, clientStartingSide);
add(stateMachine.grid);
stateMachine.grid.setBounds(BUTTON_SIZE_WIDTH*2+30,1,(int)((colSize*100+100)*changeFactor),(int)((rowSize*100+100)*changeFactor));
ai = new AI();
ai.setBounds(colSize - 1 , rowSize - 1);
aiIsOn = false;
initButtons();
//add listeners
instructionsButton.addActionListener(this);
newGameButton.addActionListener(this);
nameButton.addActionListener(this);
aiButton.addActionListener(this);
addMouseListener(this);
String message = stateMachine.run("NewGame", null);
messageBox.setText(message);
clock = new Clock(timePerTurn);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
clock.startTimer();
}
});
} //}}}
| public Fanorona() {//{{{
setLayout(null);
askServerClientInfo();
ObjectOutputStream socketOut = null;
ObjectInputStream socketIn = null;
if(networkSetting == "Server") {
getServerConfig();
askGridSize();
askTimePerTurn();
Socket acceptSocket = null;
try {
acceptSocket = setupServerSockets();
socketOut = new ObjectOutputStream(acceptSocket.getOutputStream());
socketOut.flush();
socketIn = new ObjectInputStream(acceptSocket.getInputStream());
String welcome = "WELCOME";
socketOut.writeObject(welcome);
System.out.println("Server: " + welcome);
socketOut.flush();
} catch (IOException e) {}
sendGameInfo(socketOut, colSize, rowSize, timePerTurn);
waitForClient(socketIn, socketOut);
} else if (networkSetting == "Client") {
getClientConfig();
Socket acceptSocket = null;
try{
acceptSocket = setupClientSocket();
socketOut = new ObjectOutputStream(acceptSocket.getOutputStream());
socketOut.flush();
socketIn = new ObjectInputStream(acceptSocket.getInputStream());
receiveGameInfo(socketIn);
String ready = "READY";
socketOut.writeObject(ready);
System.out.println("Client: " + ready);
socketOut.flush();
waitForBegin(socketIn);
} catch (IOException e) {}
} else {
askGridSize();
askTimePerTurn();
}
createGrid();
setPreferredSize(new Dimension((BUTTON_SIZE_WIDTH*2+30)+((int)((colSize*100+100)*changeFactor)),(int)((rowSize*100+100)*changeFactor)));
stateMachine = new StateMachine(colSize, rowSize, timePerTurn, changeFactor, networkSetting, socketOut, socketIn, clientStartingSide);
add(stateMachine.grid);
stateMachine.grid.setBounds(BUTTON_SIZE_WIDTH*2+30,1,(int)((colSize*100+100)*changeFactor),(int)((rowSize*100+100)*changeFactor));
ai = new AI();
ai.setBounds(colSize, rowSize);
aiIsOn = false;
initButtons();
//add listeners
instructionsButton.addActionListener(this);
newGameButton.addActionListener(this);
nameButton.addActionListener(this);
aiButton.addActionListener(this);
addMouseListener(this);
String message = stateMachine.run("NewGame", null);
messageBox.setText(message);
clock = new Clock(timePerTurn);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
clock.startTimer();
}
});
} //}}}
|
diff --git a/src/org/flowvisor/message/actions/FVActionStripVirtualLan.java b/src/org/flowvisor/message/actions/FVActionStripVirtualLan.java
index f6917cd..d799f04 100644
--- a/src/org/flowvisor/message/actions/FVActionStripVirtualLan.java
+++ b/src/org/flowvisor/message/actions/FVActionStripVirtualLan.java
@@ -1,50 +1,51 @@
package org.flowvisor.message.actions;
import java.util.Iterator;
import java.util.List;
import org.flowvisor.classifier.FVClassifier;
import org.flowvisor.exceptions.ActionDisallowedException;
import org.flowvisor.flows.FlowEntry;
import org.flowvisor.flows.FlowSpaceRuleStore;
import org.flowvisor.flows.SliceAction;
import org.flowvisor.log.FVLog;
import org.flowvisor.log.LogLevel;
import org.flowvisor.openflow.protocol.FVMatch;
import org.flowvisor.slicer.FVSlicer;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.OFError.OFBadActionCode;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionStripVirtualLan;
public class FVActionStripVirtualLan extends OFActionStripVirtualLan implements
SlicableAction {
@Override
public void slice(List<OFAction> approvedActions, OFMatch match,
FVClassifier fvClassifier, FVSlicer fvSlicer)
throws ActionDisallowedException {
FVMatch neoMatch = new FVMatch(match);
match.setDataLayerVirtualLan(FlowSpaceRuleStore.ANY_VLAN_ID);
List<FlowEntry> flowEntries = fvClassifier.getSwitchFlowMap().matches(fvClassifier.getDPID(), neoMatch);
for (FlowEntry fe : flowEntries) {
Iterator<OFAction> it = fe.getActionsList().iterator();
while (it.hasNext()) {
OFAction act = it.next();
if (act instanceof SliceAction) {
SliceAction action = (SliceAction) act;
if (action.getSliceName().equals(fvSlicer.getSliceName())) {
FVLog.log(LogLevel.DEBUG, fvSlicer, "Approving " + this +
" for " + match);
approvedActions.add(this);
+ return;
}
}
}
}
throw new ActionDisallowedException(
"Slice " + fvSlicer.getSliceName() + " may not strip the vlan tag.",
OFBadActionCode.OFPBAC_BAD_ARGUMENT);
}
}
| true | true | public void slice(List<OFAction> approvedActions, OFMatch match,
FVClassifier fvClassifier, FVSlicer fvSlicer)
throws ActionDisallowedException {
FVMatch neoMatch = new FVMatch(match);
match.setDataLayerVirtualLan(FlowSpaceRuleStore.ANY_VLAN_ID);
List<FlowEntry> flowEntries = fvClassifier.getSwitchFlowMap().matches(fvClassifier.getDPID(), neoMatch);
for (FlowEntry fe : flowEntries) {
Iterator<OFAction> it = fe.getActionsList().iterator();
while (it.hasNext()) {
OFAction act = it.next();
if (act instanceof SliceAction) {
SliceAction action = (SliceAction) act;
if (action.getSliceName().equals(fvSlicer.getSliceName())) {
FVLog.log(LogLevel.DEBUG, fvSlicer, "Approving " + this +
" for " + match);
approvedActions.add(this);
}
}
}
}
throw new ActionDisallowedException(
"Slice " + fvSlicer.getSliceName() + " may not strip the vlan tag.",
OFBadActionCode.OFPBAC_BAD_ARGUMENT);
}
| public void slice(List<OFAction> approvedActions, OFMatch match,
FVClassifier fvClassifier, FVSlicer fvSlicer)
throws ActionDisallowedException {
FVMatch neoMatch = new FVMatch(match);
match.setDataLayerVirtualLan(FlowSpaceRuleStore.ANY_VLAN_ID);
List<FlowEntry> flowEntries = fvClassifier.getSwitchFlowMap().matches(fvClassifier.getDPID(), neoMatch);
for (FlowEntry fe : flowEntries) {
Iterator<OFAction> it = fe.getActionsList().iterator();
while (it.hasNext()) {
OFAction act = it.next();
if (act instanceof SliceAction) {
SliceAction action = (SliceAction) act;
if (action.getSliceName().equals(fvSlicer.getSliceName())) {
FVLog.log(LogLevel.DEBUG, fvSlicer, "Approving " + this +
" for " + match);
approvedActions.add(this);
return;
}
}
}
}
throw new ActionDisallowedException(
"Slice " + fvSlicer.getSliceName() + " may not strip the vlan tag.",
OFBadActionCode.OFPBAC_BAD_ARGUMENT);
}
|
diff --git a/src/main/java/org/jboss/as/weld/WeldSubsystemAdd.java b/src/main/java/org/jboss/as/weld/WeldSubsystemAdd.java
index 66a3c74..67aa3f7 100644
--- a/src/main/java/org/jboss/as/weld/WeldSubsystemAdd.java
+++ b/src/main/java/org/jboss/as/weld/WeldSubsystemAdd.java
@@ -1,99 +1,99 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import org.jboss.as.controller.BasicOperationResult;
import org.jboss.as.controller.ModelAddOperationHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationResult;
import org.jboss.as.controller.ResultHandler;
import org.jboss.as.controller.RuntimeTask;
import org.jboss.as.controller.RuntimeTaskContext;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.server.BootOperationContext;
import org.jboss.as.server.BootOperationHandler;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.weld.deployment.processors.BeanArchiveProcessor;
import org.jboss.as.weld.deployment.processors.BeansXmlProcessor;
import org.jboss.as.weld.deployment.processors.WebIntegrationProcessor;
import org.jboss.as.weld.deployment.processors.WeldBeanManagerServiceProcessor;
import org.jboss.as.weld.deployment.processors.WeldComponentIntegrationProcessor;
import org.jboss.as.weld.deployment.processors.WeldDependencyProcessor;
import org.jboss.as.weld.deployment.processors.WeldDeploymentProcessor;
import org.jboss.as.weld.deployment.processors.WeldEjbInterceptorIntegrationProcessor;
import org.jboss.as.weld.deployment.processors.WeldPortableExtensionProcessor;
import org.jboss.as.weld.services.TCCLSingletonService;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceController.Mode;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
/**
* The weld subsystem add update handler.
*
* @author Stuart Douglas
* @author Emanuel Muckenhuber
*/
class WeldSubsystemAdd implements ModelAddOperationHandler, BootOperationHandler {
static final WeldSubsystemAdd INSTANCE = new WeldSubsystemAdd();
/**
* {@inheritDoc}
*/
@Override
public OperationResult execute(final OperationContext context, final ModelNode operation, final ResultHandler resultHandler) {
context.getSubModel().setEmptyObject();
if (context instanceof BootOperationContext) {
final BootOperationContext bootContext = (BootOperationContext) context;
context.getRuntimeContext().setRuntimeTask(new RuntimeTask() {
public void execute(RuntimeTaskContext context) throws OperationFailedException {
bootContext.addDeploymentProcessor(Phase.DEPENDENCIES, Phase.DEPENDENCIES_WELD, new WeldDependencyProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_DEPLOYMENT, new BeansXmlProcessor());
- bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_EJB_INTERCEPTORS_INTEGRATION, new WeldEjbInterceptorIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_COMPONENT_INTEGRATION, new WeldComponentIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_WEB_INTEGRATION, new WebIntegrationProcessor());
+ bootContext.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_WELD_EJB_INTERCEPTORS_INTEGRATION, new WeldEjbInterceptorIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_WELD_BEAN_ARCHIVE, new BeanArchiveProcessor());
bootContext.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_WELD_PORTABLE_EXTENSIONS, new WeldPortableExtensionProcessor());
bootContext.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_WELD_DEPLOYMENT, new WeldDeploymentProcessor());
bootContext.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_WELD_BEAN_MANAGER, new WeldBeanManagerServiceProcessor());
TCCLSingletonService singleton = new TCCLSingletonService();
context.getServiceTarget().addService(TCCLSingletonService.SERVICE_NAME, singleton).setInitialMode(
Mode.ON_DEMAND).install();
resultHandler.handleResultComplete();
}
});
CurrentServiceRegistry.setServiceRegistry(bootContext.getController().getServiceRegistry());
} else {
resultHandler.handleResultComplete();
}
final ModelNode compensatingOperation = Util.getResourceRemoveOperation(operation.require(OP_ADDR));
return new BasicOperationResult(compensatingOperation);
}
}
| false | true | public OperationResult execute(final OperationContext context, final ModelNode operation, final ResultHandler resultHandler) {
context.getSubModel().setEmptyObject();
if (context instanceof BootOperationContext) {
final BootOperationContext bootContext = (BootOperationContext) context;
context.getRuntimeContext().setRuntimeTask(new RuntimeTask() {
public void execute(RuntimeTaskContext context) throws OperationFailedException {
bootContext.addDeploymentProcessor(Phase.DEPENDENCIES, Phase.DEPENDENCIES_WELD, new WeldDependencyProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_DEPLOYMENT, new BeansXmlProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_EJB_INTERCEPTORS_INTEGRATION, new WeldEjbInterceptorIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_COMPONENT_INTEGRATION, new WeldComponentIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_WEB_INTEGRATION, new WebIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_WELD_BEAN_ARCHIVE, new BeanArchiveProcessor());
bootContext.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_WELD_PORTABLE_EXTENSIONS, new WeldPortableExtensionProcessor());
bootContext.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_WELD_DEPLOYMENT, new WeldDeploymentProcessor());
bootContext.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_WELD_BEAN_MANAGER, new WeldBeanManagerServiceProcessor());
TCCLSingletonService singleton = new TCCLSingletonService();
context.getServiceTarget().addService(TCCLSingletonService.SERVICE_NAME, singleton).setInitialMode(
Mode.ON_DEMAND).install();
resultHandler.handleResultComplete();
}
});
CurrentServiceRegistry.setServiceRegistry(bootContext.getController().getServiceRegistry());
} else {
resultHandler.handleResultComplete();
}
final ModelNode compensatingOperation = Util.getResourceRemoveOperation(operation.require(OP_ADDR));
return new BasicOperationResult(compensatingOperation);
}
| public OperationResult execute(final OperationContext context, final ModelNode operation, final ResultHandler resultHandler) {
context.getSubModel().setEmptyObject();
if (context instanceof BootOperationContext) {
final BootOperationContext bootContext = (BootOperationContext) context;
context.getRuntimeContext().setRuntimeTask(new RuntimeTask() {
public void execute(RuntimeTaskContext context) throws OperationFailedException {
bootContext.addDeploymentProcessor(Phase.DEPENDENCIES, Phase.DEPENDENCIES_WELD, new WeldDependencyProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_DEPLOYMENT, new BeansXmlProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_COMPONENT_INTEGRATION, new WeldComponentIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WELD_WEB_INTEGRATION, new WebIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_WELD_EJB_INTERCEPTORS_INTEGRATION, new WeldEjbInterceptorIntegrationProcessor());
bootContext.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_WELD_BEAN_ARCHIVE, new BeanArchiveProcessor());
bootContext.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_WELD_PORTABLE_EXTENSIONS, new WeldPortableExtensionProcessor());
bootContext.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_WELD_DEPLOYMENT, new WeldDeploymentProcessor());
bootContext.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_WELD_BEAN_MANAGER, new WeldBeanManagerServiceProcessor());
TCCLSingletonService singleton = new TCCLSingletonService();
context.getServiceTarget().addService(TCCLSingletonService.SERVICE_NAME, singleton).setInitialMode(
Mode.ON_DEMAND).install();
resultHandler.handleResultComplete();
}
});
CurrentServiceRegistry.setServiceRegistry(bootContext.getController().getServiceRegistry());
} else {
resultHandler.handleResultComplete();
}
final ModelNode compensatingOperation = Util.getResourceRemoveOperation(operation.require(OP_ADDR));
return new BasicOperationResult(compensatingOperation);
}
|
diff --git a/src/com/bergerkiller/bukkit/nolagg/NoLaggUtil.java b/src/com/bergerkiller/bukkit/nolagg/NoLaggUtil.java
index a7206c0..d63e3ad 100644
--- a/src/com/bergerkiller/bukkit/nolagg/NoLaggUtil.java
+++ b/src/com/bergerkiller/bukkit/nolagg/NoLaggUtil.java
@@ -1,84 +1,99 @@
package com.bergerkiller.bukkit.nolagg;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
public class NoLaggUtil {
public static void logFilterMainThread(StackTraceElement[] stackTrace, Level level, String header) {
logFilterMainThread(Arrays.asList(stackTrace), level, header);
}
public static void logFilterMainThread(List<StackTraceElement> stackTrace, Level level, String header) {
for (StackTraceElement element : stackTrace) {
String className = element.getClassName().toLowerCase();
String m = element.getMethodName();
if (className.equals("net.minecraft.server.minecraftserver") || className.equals("net.minecraft.server.dedicatedserver")) {
if (m.equals("p") || m.equals("q") || m.equals("ai")) {
break;
}
}
if (className.equals("org.bukkit.craftbukkit.scheduler.craftscheduler")) {
if (m.equals("mainThreadHeartbeat")) {
break;
}
}
Bukkit.getLogger().log(level, header + " at " + element.toString());
}
}
public static StackTraceElement findExternal(StackTraceElement[] stackTrace) {
return findExternal(Arrays.asList(stackTrace));
}
/**
* Gets the first stack trace element that is outside Bukkit/nms scope
*
* @param stackTrace
* to look at
* @return first element
*/
public static StackTraceElement findExternal(List<StackTraceElement> stackTrace) {
// bottom to top
for (int j = stackTrace.size() - 1; j >= 0; j--) {
String className = stackTrace.get(j).getClassName().toLowerCase();
if (className.startsWith("org.bukkit")) {
continue;
}
if (className.startsWith("net.minecraft.server")) {
continue;
}
return stackTrace.get(j);
}
return new StackTraceElement("net.minecraft.server.MinecraftServer", "main", "MinecraftServer.java", 0);
}
public static Plugin[] findPlugins(StackTraceElement[] stackTrace) {
return findPlugins(Arrays.asList(stackTrace));
}
public static Plugin[] findPlugins(List<StackTraceElement> stackTrace) {
Plugin[] plugins = Bukkit.getServer().getPluginManager().getPlugins();
String[] packages = new String[plugins.length];
+ // Generate package paths
int i;
for (i = 0; i < plugins.length; i++) {
packages[i] = plugins[i].getDescription().getMain().toLowerCase();
- packages[i] = packages[i].substring(0, packages[i].lastIndexOf('.'));
+ int packidx = packages[i].lastIndexOf('.');
+ if (packidx == -1) {
+ packages[i] = "";
+ } else {
+ packages[i] = packages[i].substring(0, packidx);
+ }
}
+ // Get all the plugins that match this stack trace
LinkedHashSet<Plugin> found = new LinkedHashSet<Plugin>(3);
for (StackTraceElement elem : stackTrace) {
String className = elem.getClassName().toLowerCase();
for (i = 0; i < plugins.length; i++) {
- if (className.startsWith(packages[i])) {
- found.add(plugins[i]);
+ if (packages[i].isEmpty()) {
+ // No package name - verify
+ if (!className.contains(".")) {
+ found.add(plugins[i]);
+ }
+ } else {
+ // Package name is there - verify
+ if (className.startsWith(packages[i])) {
+ found.add(plugins[i]);
+ }
}
}
}
return found.toArray(new Plugin[0]);
}
}
| false | true | public static Plugin[] findPlugins(List<StackTraceElement> stackTrace) {
Plugin[] plugins = Bukkit.getServer().getPluginManager().getPlugins();
String[] packages = new String[plugins.length];
int i;
for (i = 0; i < plugins.length; i++) {
packages[i] = plugins[i].getDescription().getMain().toLowerCase();
packages[i] = packages[i].substring(0, packages[i].lastIndexOf('.'));
}
LinkedHashSet<Plugin> found = new LinkedHashSet<Plugin>(3);
for (StackTraceElement elem : stackTrace) {
String className = elem.getClassName().toLowerCase();
for (i = 0; i < plugins.length; i++) {
if (className.startsWith(packages[i])) {
found.add(plugins[i]);
}
}
}
return found.toArray(new Plugin[0]);
}
| public static Plugin[] findPlugins(List<StackTraceElement> stackTrace) {
Plugin[] plugins = Bukkit.getServer().getPluginManager().getPlugins();
String[] packages = new String[plugins.length];
// Generate package paths
int i;
for (i = 0; i < plugins.length; i++) {
packages[i] = plugins[i].getDescription().getMain().toLowerCase();
int packidx = packages[i].lastIndexOf('.');
if (packidx == -1) {
packages[i] = "";
} else {
packages[i] = packages[i].substring(0, packidx);
}
}
// Get all the plugins that match this stack trace
LinkedHashSet<Plugin> found = new LinkedHashSet<Plugin>(3);
for (StackTraceElement elem : stackTrace) {
String className = elem.getClassName().toLowerCase();
for (i = 0; i < plugins.length; i++) {
if (packages[i].isEmpty()) {
// No package name - verify
if (!className.contains(".")) {
found.add(plugins[i]);
}
} else {
// Package name is there - verify
if (className.startsWith(packages[i])) {
found.add(plugins[i]);
}
}
}
}
return found.toArray(new Plugin[0]);
}
|
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/employee/panes/EmployeePane.java b/OpERP/src/main/java/devopsdistilled/operp/client/employee/panes/EmployeePane.java
index 5d121b6d..fd0626f1 100644
--- a/OpERP/src/main/java/devopsdistilled/operp/client/employee/panes/EmployeePane.java
+++ b/OpERP/src/main/java/devopsdistilled/operp/client/employee/panes/EmployeePane.java
@@ -1,202 +1,203 @@
package devopsdistilled.operp.client.employee.panes;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.Date;
import javax.inject.Inject;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import devopsdistilled.operp.client.abstracts.EntityOperation;
import devopsdistilled.operp.client.abstracts.EntityPane;
import devopsdistilled.operp.client.employee.controllers.EmployeeController;
import devopsdistilled.operp.client.employee.panes.controllers.EmployeePaneController;
import devopsdistilled.operp.client.employee.panes.models.observers.EmployeePaneModelObserver;
import devopsdistilled.operp.server.data.entity.employee.Employee;
public class EmployeePane extends
EntityPane<Employee, EmployeeController, EmployeePaneController>
implements EmployeePaneModelObserver {
@Inject
private EmployeeController employeeController;
private final JPanel pane;
private final JTextField nameField;
private final JLabel lblEmployeeId;
private final JTextField employeeIdField;
private JPanel contactInfoPanel;
private JPanel opBtnPanel;
private final JTextField designationField;
private final JTextField salaryField;
private final JLabel lblJoinDate;
private final JTextField dateField;
public EmployeePane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[][grow]", "[][][][][][][][]"));
lblEmployeeId = new JLabel("Employee ID");
pane.add(lblEmployeeId, "cell 0 0,alignx trailing");
employeeIdField = new JTextField();
employeeIdField.setEditable(false);
pane.add(employeeIdField, "cell 1 0,growx");
employeeIdField.setColumns(10);
JLabel lblEmployeeName = new JLabel("Employee Name");
pane.add(lblEmployeeName, "cell 0 1,alignx trailing");
nameField = new JTextField();
nameField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
String empName = nameField.getText().trim();
- if (empName.equalsIgnoreCase("")) {
+ if (empName.equalsIgnoreCase("")
+ && e.getOppositeComponent() != null) {
JOptionPane.showMessageDialog(getPane(),
"Employee Name must not be empty");
e.getComponent().requestFocus();
}
getController().getModel().getEntity().setEmployeeName(empName);
}
});
pane.add(nameField, "cell 1 1,growx");
nameField.setColumns(10);
JLabel lblDesignation = new JLabel("Designation");
pane.add(lblDesignation, "cell 0 2,alignx trailing");
designationField = new JTextField();
designationField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
getController().getModel().getEntity()
.setDesignation(designationField.getText().trim());
}
});
pane.add(designationField, "cell 1 2,growx");
designationField.setColumns(10);
JLabel lblSalary = new JLabel("Salary");
pane.add(lblSalary, "cell 0 3,alignx trailing");
salaryField = new JTextField();
salaryField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
try {
Double salary = Double.parseDouble(salaryField.getText()
.trim());
getController().getModel().getEntity().setSalary(salary);
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(getPane(),
"Salary field must be numeric value");
e.getComponent().requestFocus();
}
}
});
pane.add(salaryField, "cell 1 3,growx");
salaryField.setColumns(10);
lblJoinDate = new JLabel("Join Date");
pane.add(lblJoinDate, "cell 0 4,alignx trailing");
dateField = new JTextField();
dateField.setEditable(false);
pane.add(dateField, "cell 1 4,growx");
dateField.setColumns(10);
contactInfoPanel = new JPanel();
pane.add(contactInfoPanel, "cell 0 5 2 1,grow");
opBtnPanel = new JPanel();
pane.add(opBtnPanel, "cell 1 7,grow");
}
@Override
public JComponent getPane() {
return pane;
}
public void setContactInfopanel(JPanel contactInfoPanel) {
MigLayout layout = (MigLayout) pane.getLayout();
Object constraints = layout
.getComponentConstraints(this.contactInfoPanel);
pane.remove(this.contactInfoPanel);
pane.add(contactInfoPanel, constraints);
this.contactInfoPanel = contactInfoPanel;
pane.validate();
}
@Override
public void updateEntity(Employee employee, EntityOperation entityOperation) {
if (EntityOperation.Create == entityOperation) {
getController().getModel().setTitle("Create Employee");
opBtnPanel = setBtnPanel(createOpPanel, opBtnPanel);
lblEmployeeId.setVisible(false);
employeeIdField.setVisible(false);
} else if (EntityOperation.Edit == entityOperation) {
getController().getModel().setTitle("Edit Employee");
opBtnPanel = setBtnPanel(editOpPanel, opBtnPanel);
lblJoinDate.setVisible(true);
dateField.setVisible(true);
} else if (EntityOperation.Details == entityOperation) {
getController().getModel().setTitle("Employee Details");
opBtnPanel = setBtnPanel(detailsOpPanel, opBtnPanel);
employeeIdField.setText(employee.getEmployeeId().toString());
nameField.setEditable(false);
lblJoinDate.setVisible(true);
dateField.setVisible(true);
designationField.setEditable(false);
salaryField.setEditable(false);
}
nameField.setText(employee.getEmployeeName());
designationField.setText(employee.getDesignation());
salaryField.setText(employee.getSalary().toString());
Date joinedDate = employee.getJoinedDate();
if (joinedDate != null)
dateField.setText(joinedDate.toString());
}
@Override
public void resetComponents() {
lblEmployeeId.setVisible(true);
employeeIdField.setVisible(true);
nameField.setEditable(true);
dateField.setVisible(false);
lblJoinDate.setVisible(false);
dateField.setEditable(false);
designationField.setEditable(true);
salaryField.setEditable(true);
}
@Override
public EmployeeController getEntityController() {
return employeeController;
}
}
| true | true | public EmployeePane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[][grow]", "[][][][][][][][]"));
lblEmployeeId = new JLabel("Employee ID");
pane.add(lblEmployeeId, "cell 0 0,alignx trailing");
employeeIdField = new JTextField();
employeeIdField.setEditable(false);
pane.add(employeeIdField, "cell 1 0,growx");
employeeIdField.setColumns(10);
JLabel lblEmployeeName = new JLabel("Employee Name");
pane.add(lblEmployeeName, "cell 0 1,alignx trailing");
nameField = new JTextField();
nameField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
String empName = nameField.getText().trim();
if (empName.equalsIgnoreCase("")) {
JOptionPane.showMessageDialog(getPane(),
"Employee Name must not be empty");
e.getComponent().requestFocus();
}
getController().getModel().getEntity().setEmployeeName(empName);
}
});
pane.add(nameField, "cell 1 1,growx");
nameField.setColumns(10);
JLabel lblDesignation = new JLabel("Designation");
pane.add(lblDesignation, "cell 0 2,alignx trailing");
designationField = new JTextField();
designationField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
getController().getModel().getEntity()
.setDesignation(designationField.getText().trim());
}
});
pane.add(designationField, "cell 1 2,growx");
designationField.setColumns(10);
JLabel lblSalary = new JLabel("Salary");
pane.add(lblSalary, "cell 0 3,alignx trailing");
salaryField = new JTextField();
salaryField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
try {
Double salary = Double.parseDouble(salaryField.getText()
.trim());
getController().getModel().getEntity().setSalary(salary);
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(getPane(),
"Salary field must be numeric value");
e.getComponent().requestFocus();
}
}
});
pane.add(salaryField, "cell 1 3,growx");
salaryField.setColumns(10);
lblJoinDate = new JLabel("Join Date");
pane.add(lblJoinDate, "cell 0 4,alignx trailing");
dateField = new JTextField();
dateField.setEditable(false);
pane.add(dateField, "cell 1 4,growx");
dateField.setColumns(10);
contactInfoPanel = new JPanel();
pane.add(contactInfoPanel, "cell 0 5 2 1,grow");
opBtnPanel = new JPanel();
pane.add(opBtnPanel, "cell 1 7,grow");
}
| public EmployeePane() {
pane = new JPanel();
pane.setLayout(new MigLayout("", "[][grow]", "[][][][][][][][]"));
lblEmployeeId = new JLabel("Employee ID");
pane.add(lblEmployeeId, "cell 0 0,alignx trailing");
employeeIdField = new JTextField();
employeeIdField.setEditable(false);
pane.add(employeeIdField, "cell 1 0,growx");
employeeIdField.setColumns(10);
JLabel lblEmployeeName = new JLabel("Employee Name");
pane.add(lblEmployeeName, "cell 0 1,alignx trailing");
nameField = new JTextField();
nameField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
String empName = nameField.getText().trim();
if (empName.equalsIgnoreCase("")
&& e.getOppositeComponent() != null) {
JOptionPane.showMessageDialog(getPane(),
"Employee Name must not be empty");
e.getComponent().requestFocus();
}
getController().getModel().getEntity().setEmployeeName(empName);
}
});
pane.add(nameField, "cell 1 1,growx");
nameField.setColumns(10);
JLabel lblDesignation = new JLabel("Designation");
pane.add(lblDesignation, "cell 0 2,alignx trailing");
designationField = new JTextField();
designationField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
getController().getModel().getEntity()
.setDesignation(designationField.getText().trim());
}
});
pane.add(designationField, "cell 1 2,growx");
designationField.setColumns(10);
JLabel lblSalary = new JLabel("Salary");
pane.add(lblSalary, "cell 0 3,alignx trailing");
salaryField = new JTextField();
salaryField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
try {
Double salary = Double.parseDouble(salaryField.getText()
.trim());
getController().getModel().getEntity().setSalary(salary);
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(getPane(),
"Salary field must be numeric value");
e.getComponent().requestFocus();
}
}
});
pane.add(salaryField, "cell 1 3,growx");
salaryField.setColumns(10);
lblJoinDate = new JLabel("Join Date");
pane.add(lblJoinDate, "cell 0 4,alignx trailing");
dateField = new JTextField();
dateField.setEditable(false);
pane.add(dateField, "cell 1 4,growx");
dateField.setColumns(10);
contactInfoPanel = new JPanel();
pane.add(contactInfoPanel, "cell 0 5 2 1,grow");
opBtnPanel = new JPanel();
pane.add(opBtnPanel, "cell 1 7,grow");
}
|
diff --git a/src/main/java/com/santoris/bsimple/axa/dao/bank/AxaCustomerBankDAO.java b/src/main/java/com/santoris/bsimple/axa/dao/bank/AxaCustomerBankDAO.java
index e378205..b61a49c 100644
--- a/src/main/java/com/santoris/bsimple/axa/dao/bank/AxaCustomerBankDAO.java
+++ b/src/main/java/com/santoris/bsimple/axa/dao/bank/AxaCustomerBankDAO.java
@@ -1,44 +1,44 @@
package com.santoris.bsimple.axa.dao.bank;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;
import com.santoris.bsimple.axa.model.AxaAccount;
import com.santoris.bsimple.axa.model.AxaCustomer;
@Repository
public class AxaCustomerBankDAO {
private Logger logger = Logger.getLogger(getClass());
@Autowired
private AxaAccountBankDAO accountDAO;
@Value("${base_url}")
private String baseUrl;
@Value("${client_id}")
private String clientId;
@Value("${access_token}")
private String accessToken;
private RestTemplate restTemplate = new RestTemplate();
public AxaCustomer getCustomerById(Long customerId) {
- AxaCustomer customer = restTemplate.getForObject(baseUrl + "/customers/{customerId}?client_id={clientId}&access_token={accessToken}",
+ AxaCustomer customer = restTemplate.getForObject(baseUrl + "/customers/{customerId}?client_id={clientId}&access_token={accessToken}&customer_id={customerId}",
AxaCustomer.class,
- customerId,clientId,accessToken);
+ customerId,clientId,accessToken,customerId);
List<AxaAccount> accounts = accountDAO.getAllAccountsByCustomer(customerId);
customer.setAccounts(accounts);
return customer;
}
}
| false | true | public AxaCustomer getCustomerById(Long customerId) {
AxaCustomer customer = restTemplate.getForObject(baseUrl + "/customers/{customerId}?client_id={clientId}&access_token={accessToken}",
AxaCustomer.class,
customerId,clientId,accessToken);
List<AxaAccount> accounts = accountDAO.getAllAccountsByCustomer(customerId);
customer.setAccounts(accounts);
return customer;
}
| public AxaCustomer getCustomerById(Long customerId) {
AxaCustomer customer = restTemplate.getForObject(baseUrl + "/customers/{customerId}?client_id={clientId}&access_token={accessToken}&customer_id={customerId}",
AxaCustomer.class,
customerId,clientId,accessToken,customerId);
List<AxaAccount> accounts = accountDAO.getAllAccountsByCustomer(customerId);
customer.setAccounts(accounts);
return customer;
}
|
diff --git a/src/no/ntnu/stud/flatcraft/music/MusicPlayer.java b/src/no/ntnu/stud/flatcraft/music/MusicPlayer.java
index faaa298..2413ea6 100644
--- a/src/no/ntnu/stud/flatcraft/music/MusicPlayer.java
+++ b/src/no/ntnu/stud/flatcraft/music/MusicPlayer.java
@@ -1,121 +1,121 @@
package no.ntnu.stud.flatcraft.music;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.newdawn.slick.openal.Audio;
import org.newdawn.slick.openal.OggInputStream;
import org.newdawn.slick.openal.OpenALStreamPlayer;
import org.newdawn.slick.openal.SoundStore;
import org.newdawn.slick.openal.StreamSound;
public class MusicPlayer {
private SoundStore soundStore;
private ArrayList<Audio> music;
private ArrayList<Audio> ambientMusic;
private ArrayList<Audio> ambientNoise;
private boolean enabled;
private Audio musicPlaying;
private Audio ambientMusicPlaying;
private Audio[] ambientNoisePlaying = new Audio[2];
private int musicDelay;
private int ambientMusicDelay;
private int[] ambientNoiseDelay = new int[2];
public MusicPlayer() {
soundStore = SoundStore.get();
soundStore.setMaxSources(4);
soundStore.init();
music = new ArrayList<Audio>();
ambientMusic = new ArrayList<Audio>();
ambientNoise = new ArrayList<Audio>();
}
public void addMusic(String res) throws IOException {
music.add(soundStore.getOggStream(res));
}
public void addAmbientMusic(String res) throws IOException {
ambientMusic.add(soundStore.getOgg(res));
}
public void addAmbientNoise(String res) throws IOException {
ambientNoise.add(soundStore.getOgg(res));
}
public void startMusic(boolean enabled) {
this.enabled = enabled;
}
public void stopMusic() {
enabled = false;
}
public void update(int delta) {
if (enabled) {
if (musicPlaying == null) {
musicDelay -= delta;
if (musicDelay <= 0) {
musicPlaying = music.get((int)(Math.random()*music.size()));
musicPlaying.playAsMusic(1.0f, 1.0f, false);
soundStore.setSoundVolume(0.75f);
}
} else if (!soundStore.isMusicPlaying()) {
musicPlaying.stop();
musicDelay = (int) (Math.random()*90000) + 30000;
musicPlaying = null;
soundStore.setSoundVolume(1.0f);
}
- if (ambientMusic == null) {
+ if (ambientMusicPlaying == null) {
ambientMusicDelay -= delta;
if (ambientMusicDelay <= 0) {
ambientMusicPlaying = ambientMusic.get((int)(Math.random()*ambientMusic.size()));
ambientMusicPlaying.playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientMusicPlaying.isPlaying()) {
ambientMusicPlaying.stop();
ambientMusicDelay = (int) (Math.random()*6000) + 1000;
ambientMusicPlaying = null;
}
if (ambientNoisePlaying[0] == null) {
ambientNoiseDelay[0] -= delta;
if (ambientNoiseDelay[0] <= 0) {
ambientNoisePlaying[0] = ambientNoise.get((int)(Math.random()*ambientNoise.size()));
ambientNoisePlaying[0].playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientNoisePlaying[0].isPlaying()) {
ambientNoisePlaying[0].stop();
ambientNoiseDelay[0] = (int) (Math.random()*16000) + 1000;
ambientNoisePlaying[0] = null;
}
if (ambientNoisePlaying[1] == null) {
ambientNoiseDelay[1] -= delta;
if (ambientNoiseDelay[1] <= 0) {
ambientNoisePlaying[1] = ambientNoise.get((int)(Math.random()*ambientNoise.size()));
ambientNoisePlaying[1].playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientNoisePlaying[1].isPlaying()) {
ambientNoisePlaying[1].stop();
ambientNoiseDelay[1] = (int) (Math.random()*16000) + 1000;
ambientNoisePlaying[1] = null;
}
soundStore.poll(delta);
}
}
}
| true | true | public void update(int delta) {
if (enabled) {
if (musicPlaying == null) {
musicDelay -= delta;
if (musicDelay <= 0) {
musicPlaying = music.get((int)(Math.random()*music.size()));
musicPlaying.playAsMusic(1.0f, 1.0f, false);
soundStore.setSoundVolume(0.75f);
}
} else if (!soundStore.isMusicPlaying()) {
musicPlaying.stop();
musicDelay = (int) (Math.random()*90000) + 30000;
musicPlaying = null;
soundStore.setSoundVolume(1.0f);
}
if (ambientMusic == null) {
ambientMusicDelay -= delta;
if (ambientMusicDelay <= 0) {
ambientMusicPlaying = ambientMusic.get((int)(Math.random()*ambientMusic.size()));
ambientMusicPlaying.playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientMusicPlaying.isPlaying()) {
ambientMusicPlaying.stop();
ambientMusicDelay = (int) (Math.random()*6000) + 1000;
ambientMusicPlaying = null;
}
if (ambientNoisePlaying[0] == null) {
ambientNoiseDelay[0] -= delta;
if (ambientNoiseDelay[0] <= 0) {
ambientNoisePlaying[0] = ambientNoise.get((int)(Math.random()*ambientNoise.size()));
ambientNoisePlaying[0].playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientNoisePlaying[0].isPlaying()) {
ambientNoisePlaying[0].stop();
ambientNoiseDelay[0] = (int) (Math.random()*16000) + 1000;
ambientNoisePlaying[0] = null;
}
if (ambientNoisePlaying[1] == null) {
ambientNoiseDelay[1] -= delta;
if (ambientNoiseDelay[1] <= 0) {
ambientNoisePlaying[1] = ambientNoise.get((int)(Math.random()*ambientNoise.size()));
ambientNoisePlaying[1].playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientNoisePlaying[1].isPlaying()) {
ambientNoisePlaying[1].stop();
ambientNoiseDelay[1] = (int) (Math.random()*16000) + 1000;
ambientNoisePlaying[1] = null;
}
soundStore.poll(delta);
}
}
| public void update(int delta) {
if (enabled) {
if (musicPlaying == null) {
musicDelay -= delta;
if (musicDelay <= 0) {
musicPlaying = music.get((int)(Math.random()*music.size()));
musicPlaying.playAsMusic(1.0f, 1.0f, false);
soundStore.setSoundVolume(0.75f);
}
} else if (!soundStore.isMusicPlaying()) {
musicPlaying.stop();
musicDelay = (int) (Math.random()*90000) + 30000;
musicPlaying = null;
soundStore.setSoundVolume(1.0f);
}
if (ambientMusicPlaying == null) {
ambientMusicDelay -= delta;
if (ambientMusicDelay <= 0) {
ambientMusicPlaying = ambientMusic.get((int)(Math.random()*ambientMusic.size()));
ambientMusicPlaying.playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientMusicPlaying.isPlaying()) {
ambientMusicPlaying.stop();
ambientMusicDelay = (int) (Math.random()*6000) + 1000;
ambientMusicPlaying = null;
}
if (ambientNoisePlaying[0] == null) {
ambientNoiseDelay[0] -= delta;
if (ambientNoiseDelay[0] <= 0) {
ambientNoisePlaying[0] = ambientNoise.get((int)(Math.random()*ambientNoise.size()));
ambientNoisePlaying[0].playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientNoisePlaying[0].isPlaying()) {
ambientNoisePlaying[0].stop();
ambientNoiseDelay[0] = (int) (Math.random()*16000) + 1000;
ambientNoisePlaying[0] = null;
}
if (ambientNoisePlaying[1] == null) {
ambientNoiseDelay[1] -= delta;
if (ambientNoiseDelay[1] <= 0) {
ambientNoisePlaying[1] = ambientNoise.get((int)(Math.random()*ambientNoise.size()));
ambientNoisePlaying[1].playAsSoundEffect(1.0f, (float) Math.random()*0.2f + 1f, false);
}
} else if (!ambientNoisePlaying[1].isPlaying()) {
ambientNoisePlaying[1].stop();
ambientNoiseDelay[1] = (int) (Math.random()*16000) + 1000;
ambientNoisePlaying[1] = null;
}
soundStore.poll(delta);
}
}
|
diff --git a/bundles/org.eclipse.equinox.ds/src/org/eclipse/equinox/internal/ds/impl/ComponentInstanceImpl.java b/bundles/org.eclipse.equinox.ds/src/org/eclipse/equinox/internal/ds/impl/ComponentInstanceImpl.java
index 74477e0c..fbd3b02a 100644
--- a/bundles/org.eclipse.equinox.ds/src/org/eclipse/equinox/internal/ds/impl/ComponentInstanceImpl.java
+++ b/bundles/org.eclipse.equinox.ds/src/org/eclipse/equinox/internal/ds/impl/ComponentInstanceImpl.java
@@ -1,107 +1,107 @@
/*******************************************************************************
* Copyright (c) 1997, 2010 by ProSyst Software GmbH
* http://www.prosyst.com
* 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:
* ProSyst Software GmbH - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.ds.impl;
import java.util.*;
import org.apache.felix.scr.Component;
import org.eclipse.equinox.internal.ds.Activator;
import org.eclipse.equinox.internal.ds.InstanceProcess;
import org.eclipse.equinox.internal.ds.model.ServiceComponentProp;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.*;
/**
* ComponentInstanceImpl.java
*
* @author Valentin Valchev
* @author Stoyan Boshev
* @author Pavlin Dobrev
*/
public class ComponentInstanceImpl implements ComponentInstance {
private Object instance;
private ServiceComponentProp scp;
private ComponentContext componentContext;
// ServiceReference to service objects which are binded to this instance
public Hashtable bindedServices = new Hashtable(11);
public ComponentInstanceImpl(Object instance, ServiceComponentProp scp) {
this.instance = instance;
this.scp = scp;
}
/*
* (non-Javadoc)
*
* @see org.osgi.service.component.ComponentInstance#dispose()
*/
public void dispose() {
if (scp == null) {
// already disposed!
return;
}
if (Activator.DEBUG) {
Activator.log.debug("ComponentInstanceImpl.dispose(): disposing instance of component " + scp.name, null); //$NON-NLS-1$
}
if (!scp.isComponentFactory() && scp.serviceComponent.factory != null) {
// this is a component factory instance, so dispose SCP
scp.serviceComponent.componentProps.removeElement(scp);
Vector toDispose = new Vector(1);
toDispose.addElement(scp);
InstanceProcess.resolver.disposeComponentConfigs(toDispose, ComponentConstants.DEACTIVATION_REASON_DISPOSED);
if (scp != null) {
scp.setState(Component.STATE_DISPOSED);
- scp = null;
}
} else {
scp.dispose(this, ComponentConstants.DEACTIVATION_REASON_DISPOSED);
}
// free service references if some are left ungotten
freeServiceReferences();
+ scp = null;
componentContext = null;
instance = null;
}
// check whether some cached service references are not yet removed and
// ungotten
public void freeServiceReferences() {
if (!bindedServices.isEmpty()) {
Enumeration keys = bindedServices.keys();
while (keys.hasMoreElements()) {
ServiceReference reference = (ServiceReference) keys.nextElement();
bindedServices.remove(reference);
scp.bc.ungetService(reference);
}
}
}
/*
* (non-Javadoc)
*
* @see org.osgi.service.component.ComponentInstance#getInstance()
*/
public Object getInstance() {
return instance;
}
public ComponentContext getComponentContext() {
return componentContext;
}
public void setComponentContext(ComponentContext componentContext) {
this.componentContext = componentContext;
}
}
| false | true | public void dispose() {
if (scp == null) {
// already disposed!
return;
}
if (Activator.DEBUG) {
Activator.log.debug("ComponentInstanceImpl.dispose(): disposing instance of component " + scp.name, null); //$NON-NLS-1$
}
if (!scp.isComponentFactory() && scp.serviceComponent.factory != null) {
// this is a component factory instance, so dispose SCP
scp.serviceComponent.componentProps.removeElement(scp);
Vector toDispose = new Vector(1);
toDispose.addElement(scp);
InstanceProcess.resolver.disposeComponentConfigs(toDispose, ComponentConstants.DEACTIVATION_REASON_DISPOSED);
if (scp != null) {
scp.setState(Component.STATE_DISPOSED);
scp = null;
}
} else {
scp.dispose(this, ComponentConstants.DEACTIVATION_REASON_DISPOSED);
}
// free service references if some are left ungotten
freeServiceReferences();
componentContext = null;
instance = null;
}
| public void dispose() {
if (scp == null) {
// already disposed!
return;
}
if (Activator.DEBUG) {
Activator.log.debug("ComponentInstanceImpl.dispose(): disposing instance of component " + scp.name, null); //$NON-NLS-1$
}
if (!scp.isComponentFactory() && scp.serviceComponent.factory != null) {
// this is a component factory instance, so dispose SCP
scp.serviceComponent.componentProps.removeElement(scp);
Vector toDispose = new Vector(1);
toDispose.addElement(scp);
InstanceProcess.resolver.disposeComponentConfigs(toDispose, ComponentConstants.DEACTIVATION_REASON_DISPOSED);
if (scp != null) {
scp.setState(Component.STATE_DISPOSED);
}
} else {
scp.dispose(this, ComponentConstants.DEACTIVATION_REASON_DISPOSED);
}
// free service references if some are left ungotten
freeServiceReferences();
scp = null;
componentContext = null;
instance = null;
}
|
diff --git a/modules/org.restlet/src/org/restlet/engine/http/adapter/ServerAdapter.java b/modules/org.restlet/src/org/restlet/engine/http/adapter/ServerAdapter.java
index 253c902fa..be05215a2 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/adapter/ServerAdapter.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/adapter/ServerAdapter.java
@@ -1,279 +1,282 @@
/**
* Copyright 2005-2009 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.engine.http.adapter;
import java.io.IOException;
import java.security.cert.Certificate;
import java.util.List;
import java.util.logging.Level;
import org.restlet.Context;
import org.restlet.data.Method;
import org.restlet.data.Parameter;
import org.restlet.data.Status;
import org.restlet.engine.http.HttpRequest;
import org.restlet.engine.http.HttpResponse;
import org.restlet.engine.http.ServerCall;
import org.restlet.engine.http.header.HeaderConstants;
import org.restlet.engine.http.header.HeaderUtils;
import org.restlet.representation.Representation;
import org.restlet.util.Series;
/**
* Converter of low-level HTTP server calls into high-level uniform calls.
*
* @author Jerome Louvel
*/
public class ServerAdapter extends Adapter {
/**
* Constructor.
*
* @param context
* The client context.
*/
public ServerAdapter(Context context) {
super(context);
}
/**
* Adds the entity headers for the handled uniform call.
*
* @param response
* The response returned.
*/
protected void addEntityHeaders(HttpResponse response) {
Series<Parameter> responseHeaders = response.getHttpCall()
.getResponseHeaders();
Representation entity = response.getEntity();
HeaderUtils.addEntityHeaders(entity, responseHeaders);
}
/**
* Adds the response headers for the handled uniform call.
*
* @param response
* The response returned.
*/
@SuppressWarnings("unchecked")
protected void addResponseHeaders(HttpResponse response) {
// Add all the necessary response headers
final Series<Parameter> responseHeaders = response.getHttpCall()
.getResponseHeaders();
try {
HeaderUtils.addResponseHeaders(response, responseHeaders);
// Add user-defined extension headers
Series<Parameter> additionalHeaders = (Series<Parameter>) response
.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
addAdditionalHeaders(responseHeaders, additionalHeaders);
// Set the server name again
response.getHttpCall().getResponseHeaders().add(
HeaderConstants.HEADER_SERVER,
response.getServerInfo().getAgent());
// Set the status code in the response
if (response.getStatus() != null) {
response.getHttpCall().setStatusCode(
response.getStatus().getCode());
response.getHttpCall().setReasonPhrase(
response.getStatus().getDescription());
}
} catch (Exception e) {
getLogger().log(Level.INFO,
"Exception intercepted while adding the response headers",
e);
response.getHttpCall().setStatusCode(
Status.SERVER_ERROR_INTERNAL.getCode());
response.getHttpCall().setReasonPhrase(
Status.SERVER_ERROR_INTERNAL.getDescription());
}
}
/**
* Commits the changes to a handled uniform call back into the original HTTP
* call. The default implementation first invokes the "addResponseHeaders"
* then asks the "htppCall" to send the response back to the client.
*
* @param response
* The high-level response.
*/
public void commit(HttpResponse response) {
try {
if ((response.getRequest().getMethod() != null)
&& response.getRequest().getMethod().equals(Method.HEAD)) {
addEntityHeaders(response);
response.setEntity(null);
} else if (Method.GET.equals(response.getRequest().getMethod())
&& Status.SUCCESS_OK.equals(response.getStatus())
&& (!response.isEntityAvailable())) {
addEntityHeaders(response);
getLogger()
.warning(
"A response with a 200 (Ok) status should have an entity. Make sure that resource \""
+ response.getRequest()
.getResourceRef()
+ "\" returns one or sets the status to 204 (No content).");
} else if (response.getStatus().equals(Status.SUCCESS_NO_CONTENT)) {
addEntityHeaders(response);
if (response.isEntityAvailable()) {
getLogger()
.fine(
"Responses with a 204 (No content) status generally don't have an entity. Only adding entity headers for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus()
.equals(Status.SUCCESS_RESET_CONTENT)) {
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with a 205 (Reset content) status can't have an entity. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus().equals(
Status.REDIRECTION_NOT_MODIFIED)) {
addEntityHeaders(response);
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with a 304 (Not modified) status can't have an entity. Only adding entity headers for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus().isInformational()) {
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with an informational (1xx) status can't have an entity. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else {
addEntityHeaders(response);
if ((response.getEntity() != null)
&& !response.getEntity().isAvailable()) {
// An entity was returned but isn't really available
getLogger()
.warning(
"A response with an unavailable entity was returned. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
}
// Add the response headers
addResponseHeaders(response);
// Send the response to the client
response.getHttpCall().sendResponse(response);
} catch (Exception e) {
+ // [ifndef gae]
if (response.getHttpCall().isConnectionBroken(e)) {
getLogger()
.log(
Level.INFO,
"The connection was broken. It was probably closed by the client.",
e);
- } else {
+ } else
+ // [enddef]
+ {
getLogger().log(Level.SEVERE,
"An exception occured writing the response entity", e);
response.getHttpCall().setStatusCode(
Status.SERVER_ERROR_INTERNAL.getCode());
response.getHttpCall().setReasonPhrase(
"An exception occured writing the response entity");
response.setEntity(null);
try {
response.getHttpCall().sendResponse(response);
} catch (IOException ioe) {
getLogger().log(Level.WARNING,
"Unable to send error response", ioe);
}
}
} finally {
response.getHttpCall().complete();
}
}
/**
* Converts a low-level HTTP call into a high-level uniform request.
*
* @param httpCall
* The low-level HTTP call.
* @return A new high-level uniform request.
*/
@SuppressWarnings("deprecation")
public HttpRequest toRequest(ServerCall httpCall) {
final HttpRequest result = new HttpRequest(getContext(), httpCall);
result.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS,
httpCall.getRequestHeaders());
if (httpCall.getVersion() != null) {
result.getAttributes().put(HeaderConstants.ATTRIBUTE_VERSION,
httpCall.getVersion());
}
if (httpCall.isConfidential()) {
final List<Certificate> clientCertificates = httpCall
.getSslClientCertificates();
if (clientCertificates != null) {
result.getAttributes().put(
HeaderConstants.ATTRIBUTE_HTTPS_CLIENT_CERTIFICATES,
clientCertificates);
}
final String cipherSuite = httpCall.getSslCipherSuite();
if (cipherSuite != null) {
result.getAttributes().put(
HeaderConstants.ATTRIBUTE_HTTPS_CIPHER_SUITE,
cipherSuite);
}
final Integer keySize = httpCall.getSslKeySize();
if (keySize != null) {
result.getAttributes().put(
HeaderConstants.ATTRIBUTE_HTTPS_KEY_SIZE, keySize);
}
}
return result;
}
}
| false | true | public void commit(HttpResponse response) {
try {
if ((response.getRequest().getMethod() != null)
&& response.getRequest().getMethod().equals(Method.HEAD)) {
addEntityHeaders(response);
response.setEntity(null);
} else if (Method.GET.equals(response.getRequest().getMethod())
&& Status.SUCCESS_OK.equals(response.getStatus())
&& (!response.isEntityAvailable())) {
addEntityHeaders(response);
getLogger()
.warning(
"A response with a 200 (Ok) status should have an entity. Make sure that resource \""
+ response.getRequest()
.getResourceRef()
+ "\" returns one or sets the status to 204 (No content).");
} else if (response.getStatus().equals(Status.SUCCESS_NO_CONTENT)) {
addEntityHeaders(response);
if (response.isEntityAvailable()) {
getLogger()
.fine(
"Responses with a 204 (No content) status generally don't have an entity. Only adding entity headers for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus()
.equals(Status.SUCCESS_RESET_CONTENT)) {
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with a 205 (Reset content) status can't have an entity. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus().equals(
Status.REDIRECTION_NOT_MODIFIED)) {
addEntityHeaders(response);
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with a 304 (Not modified) status can't have an entity. Only adding entity headers for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus().isInformational()) {
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with an informational (1xx) status can't have an entity. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else {
addEntityHeaders(response);
if ((response.getEntity() != null)
&& !response.getEntity().isAvailable()) {
// An entity was returned but isn't really available
getLogger()
.warning(
"A response with an unavailable entity was returned. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
}
// Add the response headers
addResponseHeaders(response);
// Send the response to the client
response.getHttpCall().sendResponse(response);
} catch (Exception e) {
if (response.getHttpCall().isConnectionBroken(e)) {
getLogger()
.log(
Level.INFO,
"The connection was broken. It was probably closed by the client.",
e);
} else {
getLogger().log(Level.SEVERE,
"An exception occured writing the response entity", e);
response.getHttpCall().setStatusCode(
Status.SERVER_ERROR_INTERNAL.getCode());
response.getHttpCall().setReasonPhrase(
"An exception occured writing the response entity");
response.setEntity(null);
try {
response.getHttpCall().sendResponse(response);
} catch (IOException ioe) {
getLogger().log(Level.WARNING,
"Unable to send error response", ioe);
}
}
} finally {
response.getHttpCall().complete();
}
}
| public void commit(HttpResponse response) {
try {
if ((response.getRequest().getMethod() != null)
&& response.getRequest().getMethod().equals(Method.HEAD)) {
addEntityHeaders(response);
response.setEntity(null);
} else if (Method.GET.equals(response.getRequest().getMethod())
&& Status.SUCCESS_OK.equals(response.getStatus())
&& (!response.isEntityAvailable())) {
addEntityHeaders(response);
getLogger()
.warning(
"A response with a 200 (Ok) status should have an entity. Make sure that resource \""
+ response.getRequest()
.getResourceRef()
+ "\" returns one or sets the status to 204 (No content).");
} else if (response.getStatus().equals(Status.SUCCESS_NO_CONTENT)) {
addEntityHeaders(response);
if (response.isEntityAvailable()) {
getLogger()
.fine(
"Responses with a 204 (No content) status generally don't have an entity. Only adding entity headers for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus()
.equals(Status.SUCCESS_RESET_CONTENT)) {
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with a 205 (Reset content) status can't have an entity. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus().equals(
Status.REDIRECTION_NOT_MODIFIED)) {
addEntityHeaders(response);
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with a 304 (Not modified) status can't have an entity. Only adding entity headers for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else if (response.getStatus().isInformational()) {
if (response.isEntityAvailable()) {
getLogger()
.warning(
"Responses with an informational (1xx) status can't have an entity. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
} else {
addEntityHeaders(response);
if ((response.getEntity() != null)
&& !response.getEntity().isAvailable()) {
// An entity was returned but isn't really available
getLogger()
.warning(
"A response with an unavailable entity was returned. Ignoring the entity for resource \""
+ response.getRequest()
.getResourceRef() + "\".");
response.setEntity(null);
}
}
// Add the response headers
addResponseHeaders(response);
// Send the response to the client
response.getHttpCall().sendResponse(response);
} catch (Exception e) {
// [ifndef gae]
if (response.getHttpCall().isConnectionBroken(e)) {
getLogger()
.log(
Level.INFO,
"The connection was broken. It was probably closed by the client.",
e);
} else
// [enddef]
{
getLogger().log(Level.SEVERE,
"An exception occured writing the response entity", e);
response.getHttpCall().setStatusCode(
Status.SERVER_ERROR_INTERNAL.getCode());
response.getHttpCall().setReasonPhrase(
"An exception occured writing the response entity");
response.setEntity(null);
try {
response.getHttpCall().sendResponse(response);
} catch (IOException ioe) {
getLogger().log(Level.WARNING,
"Unable to send error response", ioe);
}
}
} finally {
response.getHttpCall().complete();
}
}
|
diff --git a/src/org/jdominion/effects/darkAges/VagrantEffect.java b/src/org/jdominion/effects/darkAges/VagrantEffect.java
index ef7a14a..89609fa 100644
--- a/src/org/jdominion/effects/darkAges/VagrantEffect.java
+++ b/src/org/jdominion/effects/darkAges/VagrantEffect.java
@@ -1,24 +1,27 @@
package org.jdominion.effects.darkAges;
import org.jdominion.Card;
import org.jdominion.Card.Type;
import org.jdominion.Player;
import org.jdominion.Supply;
import org.jdominion.Turn;
import org.jdominion.effects.CardEffectAction;
public class VagrantEffect extends CardEffectAction {
@Override
public boolean execute(Player activePlayer, Turn currentTurn, Supply supply) {
Card revealedCard = activePlayer.revealCard();
+ if (revealedCard == null) {
+ return false;
+ }
if (revealedCard.isOfType(Type.CURSE) || revealedCard.isOfType(Type.RUINS) || revealedCard.isOfType(Type.SHELTER)
|| revealedCard.isOfType(Type.VICTORY)) {
activePlayer.getHand().add(revealedCard);
} else {
activePlayer.placeOnDeck(revealedCard);
}
return true;
}
}
| true | true | public boolean execute(Player activePlayer, Turn currentTurn, Supply supply) {
Card revealedCard = activePlayer.revealCard();
if (revealedCard.isOfType(Type.CURSE) || revealedCard.isOfType(Type.RUINS) || revealedCard.isOfType(Type.SHELTER)
|| revealedCard.isOfType(Type.VICTORY)) {
activePlayer.getHand().add(revealedCard);
} else {
activePlayer.placeOnDeck(revealedCard);
}
return true;
}
| public boolean execute(Player activePlayer, Turn currentTurn, Supply supply) {
Card revealedCard = activePlayer.revealCard();
if (revealedCard == null) {
return false;
}
if (revealedCard.isOfType(Type.CURSE) || revealedCard.isOfType(Type.RUINS) || revealedCard.isOfType(Type.SHELTER)
|| revealedCard.isOfType(Type.VICTORY)) {
activePlayer.getHand().add(revealedCard);
} else {
activePlayer.placeOnDeck(revealedCard);
}
return true;
}
|
diff --git a/src/swing/org/pathvisio/gex/GexTxtImporter.java b/src/swing/org/pathvisio/gex/GexTxtImporter.java
index 3e367835..27901ccd 100644
--- a/src/swing/org/pathvisio/gex/GexTxtImporter.java
+++ b/src/swing/org/pathvisio/gex/GexTxtImporter.java
@@ -1,313 +1,313 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2009 BiGCaT Bioinformatics
//
// 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.pathvisio.gex;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.Types;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.bridgedb.IDMapperException;
import org.bridgedb.DataSource;
import org.bridgedb.IDMapperRdb;
import org.bridgedb.Xref;
import org.pathvisio.debug.Logger;
import org.pathvisio.debug.StopWatch;
import org.pathvisio.gex.ImportInformation.ColumnType;
import org.pathvisio.util.FileUtils;
import org.pathvisio.util.ProgressKeeper;
/**
* Functions to create a new Gex database
* based on a text file.
*/
public class GexTxtImporter
{
/**
* Imports expression data from a text file and saves it to an hsqldb expression database
* @param info {@link GexImportWizard.ImportInformation} object that contains the
* information needed to import the data
* @param p {@link ProgressKeeper} that reports the progress of the process and enables
* the user to cancel. May be null for headless mode operation.
*/
public static void importFromTxt(ImportInformation info, ProgressKeeper p, IDMapperRdb currentGdb, GexManager gexManager)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getGexName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getGexName(), true, gexManager.getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
List<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
ColumnType type = info.getColumnType(i);
//skip the id and systemcode column if there is one
if(type == ColumnType.COL_NUMBER || type == ColumnType.COL_STRING)
{
String header = headers[i];
if (header.length() >= 50)
{
header = header.substring(0, 49);
}
try {
result.addSample(
sampleId++,
header,
type == ColumnType.COL_STRING ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 0; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow();
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
NumberFormat nf = NumberFormat.getInstance(
info.digitIsDot() ? Locale.US : Locale.FRANCE);
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.isSyscodeFixed())
{
ds = info.getDataSource();
}
else
{
ds = DataSource.getBySystemCode(data[info.getSyscodeColumn()].trim());
}
Xref ref = new Xref (id, ds);
//check if the ref exists
boolean refExists = currentGdb.xrefExists(ref);
if(!refExists)
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\tCould not look up this identifier in the synonym database", errors);
}
// add row anyway
{
boolean success = true;
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
- double dNumber = nf.parse(value).doubleValue();
+ double dNumber = nf.parse(value.toUpperCase()).doubleValue();
value = "" + dNumber;
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (ParseException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
result.addExpr(
ref,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
in.close();
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " rows of data were imported succesfully");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null)
{
p.setTaskName("Finalizing database (this may take some time)");
p.report ("Finalizing database");
}
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
gexManager.setCurrentGex(result.getDbName(), false);
if (p != null)
{
p.setTaskName ("Done.");
p.report ("Done.");
p.finished();
}
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (IDMapperException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
private static int reportError(ImportInformation info, PrintStream log, String message, int nrError)
{
info.addError(message);
log.println(message);
nrError++;
return nrError;
}
}
| true | true | public static void importFromTxt(ImportInformation info, ProgressKeeper p, IDMapperRdb currentGdb, GexManager gexManager)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getGexName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getGexName(), true, gexManager.getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
List<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
ColumnType type = info.getColumnType(i);
//skip the id and systemcode column if there is one
if(type == ColumnType.COL_NUMBER || type == ColumnType.COL_STRING)
{
String header = headers[i];
if (header.length() >= 50)
{
header = header.substring(0, 49);
}
try {
result.addSample(
sampleId++,
header,
type == ColumnType.COL_STRING ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 0; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow();
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
NumberFormat nf = NumberFormat.getInstance(
info.digitIsDot() ? Locale.US : Locale.FRANCE);
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.isSyscodeFixed())
{
ds = info.getDataSource();
}
else
{
ds = DataSource.getBySystemCode(data[info.getSyscodeColumn()].trim());
}
Xref ref = new Xref (id, ds);
//check if the ref exists
boolean refExists = currentGdb.xrefExists(ref);
if(!refExists)
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\tCould not look up this identifier in the synonym database", errors);
}
// add row anyway
{
boolean success = true;
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
double dNumber = nf.parse(value).doubleValue();
value = "" + dNumber;
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (ParseException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
result.addExpr(
ref,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
in.close();
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " rows of data were imported succesfully");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null)
{
p.setTaskName("Finalizing database (this may take some time)");
p.report ("Finalizing database");
}
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
gexManager.setCurrentGex(result.getDbName(), false);
if (p != null)
{
p.setTaskName ("Done.");
p.report ("Done.");
p.finished();
}
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (IDMapperException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
| public static void importFromTxt(ImportInformation info, ProgressKeeper p, IDMapperRdb currentGdb, GexManager gexManager)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getGexName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getGexName(), true, gexManager.getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
List<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
ColumnType type = info.getColumnType(i);
//skip the id and systemcode column if there is one
if(type == ColumnType.COL_NUMBER || type == ColumnType.COL_STRING)
{
String header = headers[i];
if (header.length() >= 50)
{
header = header.substring(0, 49);
}
try {
result.addSample(
sampleId++,
header,
type == ColumnType.COL_STRING ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 0; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow();
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
NumberFormat nf = NumberFormat.getInstance(
info.digitIsDot() ? Locale.US : Locale.FRANCE);
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.isSyscodeFixed())
{
ds = info.getDataSource();
}
else
{
ds = DataSource.getBySystemCode(data[info.getSyscodeColumn()].trim());
}
Xref ref = new Xref (id, ds);
//check if the ref exists
boolean refExists = currentGdb.xrefExists(ref);
if(!refExists)
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\tCould not look up this identifier in the synonym database", errors);
}
// add row anyway
{
boolean success = true;
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
double dNumber = nf.parse(value.toUpperCase()).doubleValue();
value = "" + dNumber;
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (ParseException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
result.addExpr(
ref,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
in.close();
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " rows of data were imported succesfully");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null)
{
p.setTaskName("Finalizing database (this may take some time)");
p.report ("Finalizing database");
}
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
gexManager.setCurrentGex(result.getDbName(), false);
if (p != null)
{
p.setTaskName ("Done.");
p.report ("Done.");
p.finished();
}
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (IDMapperException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
|
diff --git a/src/edu/first/util/Strings.java b/src/edu/first/util/Strings.java
index dab69a2..58f1070 100644
--- a/src/edu/first/util/Strings.java
+++ b/src/edu/first/util/Strings.java
@@ -1,627 +1,630 @@
package edu.first.util;
import edu.first.util.list.ArrayList;
/**
* A set of utility methods to manipulate and test strings. Contains many of the
* methods that {@code String} is missing in Java ME.
*
* @since May 14 13
* @author Joel Gallant
*/
public final class Strings {
// cannot be subclassed or instantiated
private Strings() throws IllegalAccessException {
throw new IllegalAccessException();
}
/**
* Determines if the string does not contain anything.
*
* @param string string to test
* @return whether the string is empty
*/
public static boolean isEmpty(String string) {
return string.length() == 0;
}
/**
* Returns the index of {@code s} that is not {@code i}. If no {@code s}
* exists that is not an {@code i}, this returns -1.
*
* @param string string to test
* @param s element to find index of
* @param i element that {@code s} should not have the same index as
* @return index of {@code s} that isn't the same index as {@code i}
*/
public static int indexThatIsnt(String string, String s, String i) {
int index;
int spare = 0;
while ((index = string.indexOf(s)) >= 0 && index == string.indexOf(i)) {
string = string.substring(index + i.length());
spare += index + i.length();
}
return index < 0 ? -1 : index + spare;
}
/**
* Returns the index of {@code s} that is not {@code i}. If no {@code s}
* exists that is not an {@code i}, this returns -1.
*
* @param string string to test
* @param s element to find index of
* @param i element that {@code s} should not have the same index as
* @return index of {@code s} that isn't the same index as {@code i}
*/
public static int indexThatIsnt(String string, char s, String i) {
return indexThatIsnt(string, String.valueOf(s), i);
}
/**
* Returns the index of {@code s} that is not {@code i}. If no {@code s}
* exists that is not an {@code i}, this returns -1.
*
* @param string string to test
* @param s element to find index of
* @param i element that {@code s} should not have the same index as
* @return index of {@code s} that isn't the same index as {@code i}
*/
public static int indexThatIsnt(String string, String s, char i) {
return indexThatIsnt(string, s, String.valueOf(i));
}
/**
* Returns the index of {@code s} that is not {@code i}. If no {@code s}
* exists that is not an {@code i}, this returns -1.
*
* @param string string to test
* @param s element to find index of
* @param i element that {@code s} should not have the same index as
* @return index of {@code s} that isn't the same index as {@code i}
*/
public static int indexThatIsnt(String string, char s, char i) {
return indexThatIsnt(string, String.valueOf(s), String.valueOf(i));
}
/**
* Uses {@link #isBeside(java.lang.String, int, int, java.lang.String)} to
* test if the first instance of {@code is} is beside {@code beside}.
*
* <p> Basically equivalent to calling
* <pre>
* isBeside(string, string.indexOf(is), is.length(), beside)
* </pre>
*
* @param string original string to check in
* @param is string to check beside
* @param beside string that could be beside {@code is}
* @return if {@code beside} is directly beside the first instance of
* {@code is}
*/
public static boolean isFirstInstanceBeside(String string, String is, String beside) {
return isBeside(string, string.indexOf(is), is.length(), beside);
}
/**
* Uses {@link #isBeside(java.lang.String, int, int, java.lang.String)} to
* test if the first instance of {@code is} is beside {@code beside}.
*
* <p> Basically equivalent to calling
* <pre>
* isBeside(string, string.indexOf(is), is.length(), beside)
* </pre>
*
* @param string original string to check in
* @param is string to check beside
* @param beside character that could be beside {@code is}
* @return if {@code beside} is directly beside the first instance of
* {@code is}
*/
public static boolean isFirstInstanceBeside(String string, String is, char beside) {
return isFirstInstanceBeside(string, is, String.valueOf(beside));
}
/**
* Uses {@link #isBeside(java.lang.String, int, int, java.lang.String)} to
* test if the first instance of {@code is} is beside {@code beside}.
*
* <p> Basically equivalent to calling
* <pre>
* isBeside(string, string.indexOf(is), 1, beside)
* </pre>
*
* @param string original string to check in
* @param is string to check beside
* @param beside string that could be beside {@code is}
* @return if {@code beside} is directly beside the first instance of
* {@code is}
*/
public static boolean isFirstInstanceBeside(String string, char is, String beside) {
return isBeside(string, string.indexOf(is), 1, beside);
}
/**
* Uses {@link #isBeside(java.lang.String, int, int, java.lang.String)} to
* test if the first instance of {@code is} is beside {@code beside}.
*
* <p> Basically equivalent to calling
* <pre>
* isBeside(string, string.indexOf(is), 1, beside)
* </pre>
*
* @param string original string to check in
* @param is string to check beside
* @param beside character that could be beside {@code is}
* @return if {@code beside} is directly beside the first instance of
* {@code is}
*/
public static boolean isFirstInstanceBeside(String string, char is, char beside) {
return isFirstInstanceBeside(string, is, String.valueOf(beside));
}
/**
* Returns whether the element at {@code c} index in {@code string} with
* {@code length} length is directly beside {@code beside}.
*
* @param string original string to check in
* @param c index of the element to check beside
* @param length the length of {@code c}
* @param beside string that could be beside {@code c}
* @return if {@code beside} is directly beside {@code c}, in the context of
* {@code c}'s length
*/
public static boolean isBeside(String string, int c, int length, String beside) {
if (c < 0 || c + length >= string.length()) {
return false;
}
int startFront = c - beside.length();
int endback = c + length + beside.length();
boolean f = true, b = true;
if (startFront < 0 || startFront >= string.length()) {
f = false;
}
if (endback < 0 || endback >= string.length()) {
b = false;
}
return f || b ? ((f ? (string.substring(startFront, c).equals(beside)) : false)
|| (b ? string.substring(c + length, endback).equals(beside) : false)) : false;
}
/**
* Returns whether <b>any</b> of the instances of {@code is} are directly
* beside {@code beside}. Use
* {@link #isBeside(java.lang.String, int, int, java.lang.String)} to check
* a specific instance of the string.
*
* @param string original string to check in
* @param is string to check beside
* @param beside string that could be beside {@code is}
* @return if {@code beside} is directly beside any instances of {@code is}
*/
public static boolean isBeside(String string, String is, String beside) {
String[] s = split(string, beside);
for (int x = 0; x < s.length; x++) {
if (s[x].startsWith(is) || s[x].endsWith(is)) {
return true;
}
}
return false;
}
/**
* Returns whether any instances of {@code c} are directly beside
* {@code beside} in {@code string}.
*
* @param string original string to check in
* @param c character to check beside
* @param beside string that could be beside {@code c}
* @return if {@code beside} is directly beside any instances of {@code c}
*/
public static boolean isBeside(String string, char c, String beside) {
return isBeside(string, String.valueOf(c), beside);
}
/**
* Returns whether any instances of {@code c} are directly beside
* {@code beside} in {@code string}.
*
* @param string original string to check in
* @param c character to check beside
* @param beside character that could be beside {@code c}
* @return if {@code beside} is directly beside any instances of {@code c}
*/
public static boolean isBeside(String string, char c, char beside) {
return isBeside(string, c, String.valueOf(beside));
}
/**
* Splits the string into separate parts that happen in between the split.
* <p>
* Ex. {@code spilt("Hello world, my name is Tim.", ",")}
*
* Would return {@code ["Hello World", " my name is Tim."]}
*
* @param string original string to split
* @param split spliting artifact in the string
* @return parts of the string in between the splits
* @throws NullPointerException when {@code split} is null
*/
public static String[] split(String string, String split) {
if (string == null) {
return null;
}
if (split == null) {
throw new NullPointerException();
}
+ if (isEmpty(string)) {
+ return new String[0];
+ }
if (string.indexOf(split) < 0) {
return new String[]{string};
}
ArrayList node = new ArrayList();
int index = string.indexOf(split);
while (index >= 0) {
node.add(string.substring(0, index));
string = string.substring(index + split.length());
index = string.indexOf(split);
}
node.add(string);
String[] a = new String[node.size()];
for (int x = 0; x < a.length; x++) {
a[x] = node.get(x).toString();
}
return a;
}
/**
* Splits the string into separate parts that happen in between the split.
* <p>
* Ex. {@code spilt("Hello world, my name is Tim.", ',')}
*
* Would return {@code ["Hello World", " my name is Tim."]}
*
* @param string original string to split
* @param split spliting character in the string
* @return parts of the string in between the splits
*/
public static String[] split(String string, char split) {
return split(string, String.valueOf(split));
}
/**
* Determines whether a string contains a different string.
*
* @param string string to test
* @param contains the string it could contain
* @return whether the string contains the other
* @throws NullPointerException when {@code string} or {@code contains} are
* null
*/
public static boolean contains(String string, String contains) {
if (string == null || contains == null) {
throw new NullPointerException();
}
return string.indexOf(contains) > -1;
}
/**
* Determines whether a string contains a specific character.
*
* @param string string to test
* @param contains the character it could contain
* @return whether the string contains the other
* @throws NullPointerException when {@code string} is null
*/
public static boolean contains(String string, char contains) {
return contains(string, String.valueOf(contains));
}
/**
* Determines whether a string contains a different string, regardless of
* case.
*
* @param string string to test
* @param contains the string it could contain
* @return whether the string contains the other
* @throws NullPointerException when {@code string} or {@code contains} are
* null
*/
public static boolean containsIgnoreCase(String string, String contains) {
return contains(string.toLowerCase(), contains.toLowerCase());
}
/**
* Determines whether a string contains a specific character, regardless of
* case.
*
* @param string string to test
* @param contains the character it could contain
* @return whether the string contains the other
* @throws NullPointerException when {@code string} is null
*/
public static boolean containsIgnoreCase(String string, char contains) {
return containsIgnoreCase(string, String.valueOf(contains));
}
/**
* Returns whether {@code string} contains an instance of {@code contains}
* that isn't {@code isnt}.
*
* @param string string to test
* @param contains element it could contain
* @param isnt element that index cannot be of
* @return if string contains an instance of {@code contains} that isn't
* {@code isnt}
*/
public static boolean containsThatIsnt(String string, String contains, String isnt) {
return indexThatIsnt(string, contains, isnt) >= 0;
}
/**
* Returns whether {@code string} contains an instance of {@code contains}
* that isn't {@code isnt}.
*
* @param string string to test
* @param contains element it could contain
* @param isnt element that index cannot be of
* @return if string contains an instance of {@code contains} that isn't
* {@code isnt}
*/
public static boolean containsThatIsnt(String string, char contains, String isnt) {
return containsThatIsnt(string, String.valueOf(contains), isnt);
}
/**
* Returns whether {@code string} contains an instance of {@code contains}
* that isn't {@code isnt}.
*
* @param string string to test
* @param contains element it could contain
* @param isnt element that index cannot be of
* @return if string contains an instance of {@code contains} that isn't
* {@code isnt}
*/
public static boolean containsThatIsnt(String string, String contains, char isnt) {
return containsThatIsnt(string, contains, String.valueOf(isnt));
}
/**
* Returns whether {@code string} contains an instance of {@code contains}
* that isn't {@code isnt}.
*
* @param string string to test
* @param contains element it could contain
* @param isnt element that index cannot be of
* @return if string contains an instance of {@code contains} that isn't
* {@code isnt}
*/
public static boolean containsThatIsnt(String string, char contains, char isnt) {
return containsThatIsnt(string, String.valueOf(contains), String.valueOf(isnt));
}
/**
* Returns the string before {@code regex} in {@code string}.
*
* @param string original string
* @param regex element to split before
* @return string before {@code regex}
*/
public static String before(String string, String regex) {
return before(string, string.indexOf(regex));
}
/**
* Returns the string before {@code regex} in {@code string}.
*
* @param string original string
* @param regex element to split before
* @return string before {@code regex}
*/
public static String before(String string, char regex) {
return before(string, string.indexOf(regex));
}
/**
* Returns the string before {@code index} in {@code string}.
*
* @param string original string
* @param index index to split at
* @return string before {@code index}
*/
public static String before(String string, int index) {
return string.substring(0, index);
}
/**
* Returns the string after {@code regex} in {@code string}.
*
* @param string original string
* @param regex element to split after
* @return string after {@code regex}
*/
public static String after(String string, String regex) {
return after(string, string.indexOf(regex), regex.length());
}
/**
* Returns the string after {@code regex} in {@code string}.
*
* @param string original string
* @param regex element to split after
* @return string after {@code regex}
*/
public static String after(String string, char regex) {
return after(string, string.indexOf(regex), 1);
}
/**
* Returns the string after {@code index} in {@code string}.
*
* @param string original string
* @param index index to split at
* @param length length after index to ignore
* @return string after {@code index}
*/
public static String after(String string, int index, int length) {
return string.substring(index + length);
}
/**
* Replaces the selected section with the replacement.
*
* <p>
* Ex: {@code replace("ABC", "B", "D")} returns {@code "ADC"}.
*
* @param string main string to do replacement on
* @param replace what section to replace
* @param replacement the replacement for the section
* @return string with {@code replace} replaced with {@code replacement}
* @throws NullPointerException when replace string or replacement string
* are null
*/
public static String replace(String string, String replace, String replacement) {
if (string == null) {
return null;
}
if (replace == null || replacement == null) {
throw new NullPointerException();
}
if (string.indexOf(replace) < 0) {
return string;
}
return string.substring(0, string.indexOf(replace)) + replacement
+ string.substring(string.indexOf(replace) + replace.length(), string.length());
}
/**
* Replaces the selected section with the replacement.
*
* <p>
* Ex: {@code replace("ABC", 'B', "D")} returns {@code "ADC"}.
*
* @param string main string to do replacement on
* @param replace what section to replace
* @param replacement the replacement for the section
* @return string with {@code replace} replaced with {@code replacement}
* @throws NullPointerException when replacement string is null
*/
public static String replace(String string, char replace, String replacement) {
return replace(string, String.valueOf(replace), replacement);
}
/**
* Replaces the selected section with the replacement.
*
* <p>
* Ex: {@code replace("ABC", "B", 'D')} returns {@code "ADC"}.
*
* @param string main string to do replacement on
* @param replace what section to replace
* @param replacement the replacement for the section
* @return string with {@code replace} replaced with {@code replacement}
* @throws NullPointerException when replace string is null
*/
public static String replace(String string, String replace, char replacement) {
return replace(string, replace, String.valueOf(replacement));
}
/**
* Replaces the selected section with the replacement.
*
* <p>
* Ex: {@code replace("ABC", 'B', 'D')} returns {@code "ADC"}.
*
* @param string main string to do replacement on
* @param replace what section to replace
* @param replacement the replacement for the section
* @return string with {@code replace} replaced with {@code replacement}
*/
public static String replace(String string, char replace, char replacement) {
return replace(string, String.valueOf(replace), String.valueOf(replacement));
}
/**
* Replaces all instances of {@code replace} with {@code replacement}.
*
* <p>
* Ex: {@code replaceAll("ABCABC", "B", "D")} returns {@code "ADCADC"}.
*
* @param string main string to do replacement on
* @param replace what section to replace
* @param replacement the replacement for the section
* @return string with all instances of {@code replace} replaced with
* {@code replacement}
* @throws NullPointerException when {@code replace} string or
* {@code replacement} string are null
*/
public static String replaceAll(String string, String replace, String replacement) {
if (string == null) {
return null;
}
if (replace == null || replacement == null) {
throw new NullPointerException();
}
String[] s = split(string, replace);
if (s.length == 0) {
return string;
}
StringBuffer tmp = new StringBuffer(s[0]);
for (int x = 1; x < s.length; x++) {
tmp.append(replacement).append(s[x]);
}
return tmp.toString();
}
/**
* Replaces all instances of {@code replace} with {@code replacement}.
*
* <p>
* Ex: {@code replaceAll("ABCABC", 'B', "D")} returns {@code "ADCADC"}.
*
* @param string main string to do replacement on
* @param replace what section to replace
* @param replacement the replacement for the section
* @return string with all instances of {@code replace} replaced with
* {@code replacement}
* @throws NullPointerException when {@code replacement} string is null
*/
public static String replaceAll(String string, char replace, String replacement) {
return replaceAll(string, String.valueOf(replace), replacement);
}
/**
* Replaces all instances of {@code replace} with {@code replacement}.
*
* <p>
* Ex: {@code replaceAll("ABCABC", "B", 'D')} returns {@code "ADCADC"}.
*
* @param string main string to do replacement on
* @param replace what section to replace
* @param replacement the replacement for the section
* @return string with all instances of {@code replace} replaced with
* {@code replacement}
* @throws NullPointerException when {@code replace} string is null
*/
public static String replaceAll(String string, String replace, char replacement) {
return replaceAll(string, replace, String.valueOf(replacement));
}
/**
* Replaces all instances of {@code replace} with {@code replacement}.
*
* <p>
* Ex: {@code replaceAll("ABCABC", 'B', 'D')} returns {@code "ADCADC"}.
*
* @param string main string to do replacement on
* @param replace what section to replace
* @param replacement the replacement for the section
* @return string with all instances of {@code replace} replaced with
* {@code replacement}
*/
public static String replaceAll(String string, char replace, char replacement) {
return replaceAll(string, String.valueOf(replace), String.valueOf(replacement));
}
}
| true | true | public static String[] split(String string, String split) {
if (string == null) {
return null;
}
if (split == null) {
throw new NullPointerException();
}
if (string.indexOf(split) < 0) {
return new String[]{string};
}
ArrayList node = new ArrayList();
int index = string.indexOf(split);
while (index >= 0) {
node.add(string.substring(0, index));
string = string.substring(index + split.length());
index = string.indexOf(split);
}
node.add(string);
String[] a = new String[node.size()];
for (int x = 0; x < a.length; x++) {
a[x] = node.get(x).toString();
}
return a;
}
| public static String[] split(String string, String split) {
if (string == null) {
return null;
}
if (split == null) {
throw new NullPointerException();
}
if (isEmpty(string)) {
return new String[0];
}
if (string.indexOf(split) < 0) {
return new String[]{string};
}
ArrayList node = new ArrayList();
int index = string.indexOf(split);
while (index >= 0) {
node.add(string.substring(0, index));
string = string.substring(index + split.length());
index = string.indexOf(split);
}
node.add(string);
String[] a = new String[node.size()];
for (int x = 0; x < a.length; x++) {
a[x] = node.get(x).toString();
}
return a;
}
|
diff --git a/search-impl/impl/src/java/org/sakaiproject/search/component/service/impl/SearchIndexBuilderImpl.java b/search-impl/impl/src/java/org/sakaiproject/search/component/service/impl/SearchIndexBuilderImpl.java
index f12223ea..5db14eff 100644
--- a/search-impl/impl/src/java/org/sakaiproject/search/component/service/impl/SearchIndexBuilderImpl.java
+++ b/search-impl/impl/src/java/org/sakaiproject/search/component/service/impl/SearchIndexBuilderImpl.java
@@ -1,596 +1,596 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.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 org.sakaiproject.search.component.service.impl;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.api.ComponentManager;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.Notification;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.search.api.EntityContentProducer;
import org.sakaiproject.search.api.SearchIndexBuilder;
import org.sakaiproject.search.api.SearchIndexBuilderWorker;
import org.sakaiproject.search.dao.SearchBuilderItemDao;
import org.sakaiproject.search.model.SearchBuilderItem;
import org.sakaiproject.search.model.SearchWriterLock;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.cover.SiteService;
/**
* Search index builder is expected to be registered in spring as
* org.sakaiproject.search.api.SearchIndexBuilder as a singleton. It receives
* resources which it adds to its list of pending documents to be indexed. A
* seperate thread then runs thtough the list of entities to be indexed,
* updating the index. Each time the index is updates an event is posted to
* force the Search components that are using the index to reload. Incremental
* updates to the Lucene index require that the searchers reload the index once
* the idex writer has been built.
*
* @author ieb
*/
public class SearchIndexBuilderImpl implements SearchIndexBuilder
{
private static Log log = LogFactory.getLog(SearchIndexBuilderImpl.class);
private SearchBuilderItemDao searchBuilderItemDao = null;
private SearchIndexBuilderWorker searchIndexBuilderWorker = null;
private List producers = new ArrayList();
private boolean onlyIndexSearchToolSites = false;
private boolean diagnostics = false;
public void init()
{
ComponentManager cm = org.sakaiproject.component.cover.ComponentManager
.getInstance();
searchIndexBuilderWorker = (SearchIndexBuilderWorker) load(cm,
SearchIndexBuilderWorker.class.getName());
try
{
}
catch (Throwable t)
{
log.error("Failed to init ", t);
}
log.info(this + " completed init()");
}
private Object load(ComponentManager cm, String name)
{
Object o = cm.get(name);
if (o == null)
{
log.error("Cant find Spring component named " + name);
}
return o;
}
/**
* register an entity content producer to provide content to the search
* engine {@inheritDoc}
*/
public void registerEntityContentProducer(EntityContentProducer ecp)
{
log.debug("register " + ecp);
producers.add(ecp);
}
/**
* Add a resource to the indexing queue {@inheritDoc}
*/
public void addResource(Notification notification, Event event)
{
log.debug("Add resource " + notification + "::" + event);
String resourceName = event.getResource();
if (resourceName == null)
{
// default if null
resourceName = "";
}
if (resourceName.length() > 255)
{
log
.warn("Entity Reference is longer than 255 characters, not indexing. Reference="
+ resourceName);
return;
}
EntityContentProducer ecp = newEntityContentProducer(event);
- if (ecp.getSiteId(resourceName) == null)
+ if ( ecp == null || ecp.getSiteId(resourceName) == null)
{
log.debug("Not indexing " + resourceName + " as it has no context");
return;
}
if (onlyIndexSearchToolSites)
{
try
{
String siteId = ecp.getSiteId(resourceName);
Site s = SiteService.getSite(siteId);
ToolConfiguration t = s.getToolForCommonId("sakai.search");
if (t == null)
{
log.debug("Not indexing " + resourceName
+ " as it has no search tool");
return;
}
}
catch (Exception ex)
{
log.debug("Not indexing " + resourceName + " as it has no site", ex);
return;
}
}
Integer action = ecp.getAction(event);
try
{
SearchBuilderItem sb = searchBuilderItemDao.findByName(resourceName);
if (sb == null)
{
// new
sb = searchBuilderItemDao.create();
sb.setSearchaction(action);
sb.setName(resourceName);
String siteId = ecp.getSiteId(resourceName);
if (siteId == null || siteId.length() == 0)
{
// default if null should neve happen
siteId = "none";
}
sb.setContext(siteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM);
}
else
{
sb.setSearchaction(action);
String siteId = ecp.getSiteId(resourceName);
if (siteId == null || siteId.length() == 0)
{
// default if null, should never happen
siteId = "none";
}
sb.setContext(siteId);
sb.setName(resourceName);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM);
}
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: Added Resource " + action + " " + sb.getName());
}
catch (Throwable t)
{
log.debug("In trying to register resource " + resourceName
+ " in search engine this resource will"
+ " not be indexed untill it is modified");
}
searchIndexBuilderWorker.incrementActivity();
restartBuilder();
}
/**
* refresh the index from the current stored state {@inheritDoc}
*/
public void refreshIndex()
{
SearchBuilderItem sb = searchBuilderItemDao
.findByName(SearchBuilderItem.GLOBAL_MASTER);
if (sb == null)
{
log.debug("Created NEW " + SearchBuilderItem.GLOBAL_MASTER);
sb = searchBuilderItemDao.create();
}
if ((SearchBuilderItem.STATE_COMPLETED.equals(sb.getSearchstate()))
|| (!SearchBuilderItem.ACTION_REBUILD.equals(sb.getSearchaction())
&& !SearchBuilderItem.STATE_PENDING.equals(sb.getSearchstate()) && !SearchBuilderItem.STATE_PENDING_2
.equals(sb.getSearchstate())))
{
sb.setSearchaction(SearchBuilderItem.ACTION_REFRESH);
sb.setName(SearchBuilderItem.GLOBAL_MASTER);
sb.setContext(SearchBuilderItem.GLOBAL_CONTEXT);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM_GLOBAL_MASTER);
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: REFRESH ALL " + sb.getSearchaction() + " "
+ sb.getName());
restartBuilder();
}
else
{
log.debug("SEARCHBUILDER: REFRESH ALL IN PROGRESS " + sb.getSearchaction()
+ " " + sb.getName());
}
}
public void destroy()
{
searchIndexBuilderWorker.destroy();
}
/*
* List l = searchBuilderItemDao.getAll(); for (Iterator i = l.iterator();
* i.hasNext();) { SearchBuilderItemImpl sbi = (SearchBuilderItemImpl)
* i.next(); sbi.setSearchstate(SearchBuilderItem.STATE_PENDING);
* sbi.setSearchaction(SearchBuilderItem.ACTION_ADD); try { log.info("
* Updating " + sbi.getName()); searchBuilderItemDao.update(sbi); } catch
* (Exception ex) { try { sbi = (SearchBuilderItemImpl) searchBuilderItemDao
* .findByName(sbi.getName()); if (sbi != null) {
* sbi.setSearchstate(SearchBuilderItem.STATE_PENDING);
* sbi.setSearchaction(SearchBuilderItem.ACTION_ADD);
* searchBuilderItemDao.update(sbi); } } catch (Exception e) {
* log.warn("Failed to update on second attempt " + e.getMessage()); } } }
* restartBuilder(); }
*/
/**
* Rebuild the index from the entities own stored state {@inheritDoc}
*/
public void rebuildIndex()
{
try
{
SearchBuilderItem sb = searchBuilderItemDao
.findByName(SearchBuilderItem.GLOBAL_MASTER);
if (sb == null)
{
sb = searchBuilderItemDao.create();
}
sb.setSearchaction(SearchBuilderItem.ACTION_REBUILD);
sb.setName(SearchBuilderItem.GLOBAL_MASTER);
sb.setContext(SearchBuilderItem.GLOBAL_CONTEXT);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM_GLOBAL_MASTER);
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: REBUILD ALL " + sb.getSearchaction() + " "
+ sb.getName());
}
catch (Exception ex)
{
log.warn(" rebuild index encountered a problme " + ex.getMessage());
}
restartBuilder();
}
/*
* for (Iterator i = producers.iterator(); i.hasNext();) {
* EntityContentProducer ecp = (EntityContentProducer) i.next(); List
* contentList = ecp.getAllContent(); for (Iterator ci =
* contentList.iterator(); ci.hasNext();) { String resourceName = (String)
* ci.next(); } } }
*/
/**
* This adds and event to the list and if necessary starts a processing
* thread The method is syncronised with removeFromList
*
* @param e
*/
private void restartBuilder()
{
searchIndexBuilderWorker.checkRunning();
}
/**
* Generates a SearchableEntityProducer
*
* @param ref
* @return
* @throws PermissionException
* @throws IdUnusedException
* @throws TypeException
*/
public EntityContentProducer newEntityContentProducer(String ref)
{
log.debug(" new entitycontent producer");
for (Iterator i = producers.iterator(); i.hasNext();)
{
EntityContentProducer ecp = (EntityContentProducer) i.next();
if (ecp.matches(ref))
{
return ecp;
}
}
return null;
}
/**
* get hold of an entity content producer using the event
*
* @param event
* @return
*/
public EntityContentProducer newEntityContentProducer(Event event)
{
log.debug(" new entitycontent producer");
for (Iterator i = producers.iterator(); i.hasNext();)
{
EntityContentProducer ecp = (EntityContentProducer) i.next();
if (ecp.matches(event))
{
log.debug(" Matched Entity Content Producer for event " + event
+ " with " + ecp);
return ecp;
}
else
{
log.debug("Skipped ECP " + ecp);
}
}
log.debug("Failed to match any Entity Content Producer for event " + event);
return null;
}
/**
* @return Returns the searchBuilderItemDao.
*/
public SearchBuilderItemDao getSearchBuilderItemDao()
{
return searchBuilderItemDao;
}
/**
* @param searchBuilderItemDao
* The searchBuilderItemDao to set.
*/
public void setSearchBuilderItemDao(SearchBuilderItemDao searchBuilderItemDao)
{
this.searchBuilderItemDao = searchBuilderItemDao;
}
/**
* return true if the queue is empty
*
* @{inheritDoc}
*/
public boolean isBuildQueueEmpty()
{
int n = searchBuilderItemDao.countPending();
log.debug("Queue has " + n);
return (n == 0);
}
/**
* get all the producers registerd, as a clone to avoid concurrent
* modification exceptions
*
* @return
*/
public List getContentProducers()
{
return new ArrayList(producers);
}
public int getPendingDocuments()
{
return searchBuilderItemDao.countPending();
}
/**
* Rebuild the index from the entities own stored state {@inheritDoc}, just
* the supplied siteId
*/
public void rebuildIndex(String currentSiteId)
{
try
{
if (currentSiteId == null || currentSiteId.length() == 0)
{
currentSiteId = "none";
}
String siteMaster = MessageFormat.format(
SearchBuilderItem.SITE_MASTER_FORMAT, new Object[] { currentSiteId });
SearchBuilderItem sb = searchBuilderItemDao.findByName(siteMaster);
if (sb == null)
{
sb = searchBuilderItemDao.create();
}
sb.setSearchaction(SearchBuilderItem.ACTION_REBUILD);
sb.setName(siteMaster);
sb.setContext(currentSiteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM_SITE_MASTER);
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: REBUILD CONTEXT " + sb.getSearchaction() + " "
+ sb.getName());
}
catch (Exception ex)
{
log.warn(" rebuild index encountered a problme " + ex.getMessage());
}
restartBuilder();
}
/**
* Refresh the index fo the supplied site.
*/
public void refreshIndex(String currentSiteId)
{
if (currentSiteId == null || currentSiteId.length() == 0)
{
currentSiteId = "none";
}
String siteMaster = MessageFormat.format(SearchBuilderItem.SITE_MASTER_FORMAT,
new Object[] { currentSiteId });
SearchBuilderItem sb = searchBuilderItemDao.findByName(siteMaster);
if (sb == null)
{
log.debug("Created NEW " + siteMaster);
sb = searchBuilderItemDao.create();
sb.setContext(currentSiteId);
sb.setName(siteMaster);
sb.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
sb.setSearchaction(SearchBuilderItem.ACTION_REFRESH);
sb.setItemscope(SearchBuilderItem.ITEM_SITE_MASTER);
}
if ((SearchBuilderItem.STATE_COMPLETED.equals(sb.getSearchstate()))
|| (!SearchBuilderItem.ACTION_REBUILD.equals(sb.getSearchaction())
&& !SearchBuilderItem.STATE_PENDING.equals(sb.getSearchstate()) && !SearchBuilderItem.STATE_PENDING_2
.equals(sb.getSearchstate())))
{
sb.setSearchaction(SearchBuilderItem.ACTION_REFRESH);
sb.setName(siteMaster);
sb.setContext(currentSiteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM_SITE_MASTER);
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: REFRESH CONTEXT " + sb.getSearchaction() + " "
+ sb.getName());
restartBuilder();
}
else
{
log.debug("SEARCHBUILDER: REFRESH CONTEXT IN PROGRESS "
+ sb.getSearchaction() + " " + sb.getName());
}
}
public List getAllSearchItems()
{
return searchBuilderItemDao.getAll();
}
public List getGlobalMasterSearchItems()
{
return searchBuilderItemDao.getGlobalMasters();
}
public List getSiteMasterSearchItems()
{
return searchBuilderItemDao.getSiteMasters();
}
public SearchWriterLock getCurrentLock()
{
return searchIndexBuilderWorker.getCurrentLock();
}
public List getNodeStatus()
{
return searchIndexBuilderWorker.getNodeStatus();
}
public boolean removeWorkerLock()
{
return searchIndexBuilderWorker.removeWorkerLock();
}
public String getLastDocument()
{
return searchIndexBuilderWorker.getLastDocument();
}
public String getLastElapsed()
{
return searchIndexBuilderWorker.getLastElapsed();
}
public String getCurrentDocument()
{
return searchIndexBuilderWorker.getCurrentDocument();
}
public String getCurrentElapsed()
{
return searchIndexBuilderWorker.getCurrentElapsed();
}
/**
* @return the onlyIndexSearchToolSites
*/
public boolean isOnlyIndexSearchToolSites()
{
return onlyIndexSearchToolSites;
}
/**
* @param onlyIndexSearchToolSites
* the onlyIndexSearchToolSites to set
*/
public void setOnlyIndexSearchToolSites(boolean onlyIndexSearchToolSites)
{
this.onlyIndexSearchToolSites = onlyIndexSearchToolSites;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.search.api.SearchIndexBuilder#isLocalLock()
*/
public boolean isLocalLock()
{
return searchIndexBuilderWorker.isLocalLock();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.search.api.Diagnosable#disableDiagnostics()
*/
public void disableDiagnostics()
{
diagnostics = false;
searchIndexBuilderWorker.enableDiagnostics();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.search.api.Diagnosable#enableDiagnostics()
*/
public void enableDiagnostics()
{
diagnostics = true;
searchIndexBuilderWorker.disableDiagnostics();
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.search.api.Diagnosable#hasDiagnostics()
*/
public boolean hasDiagnostics()
{
return diagnostics;
}
}
| true | true | public void addResource(Notification notification, Event event)
{
log.debug("Add resource " + notification + "::" + event);
String resourceName = event.getResource();
if (resourceName == null)
{
// default if null
resourceName = "";
}
if (resourceName.length() > 255)
{
log
.warn("Entity Reference is longer than 255 characters, not indexing. Reference="
+ resourceName);
return;
}
EntityContentProducer ecp = newEntityContentProducer(event);
if (ecp.getSiteId(resourceName) == null)
{
log.debug("Not indexing " + resourceName + " as it has no context");
return;
}
if (onlyIndexSearchToolSites)
{
try
{
String siteId = ecp.getSiteId(resourceName);
Site s = SiteService.getSite(siteId);
ToolConfiguration t = s.getToolForCommonId("sakai.search");
if (t == null)
{
log.debug("Not indexing " + resourceName
+ " as it has no search tool");
return;
}
}
catch (Exception ex)
{
log.debug("Not indexing " + resourceName + " as it has no site", ex);
return;
}
}
Integer action = ecp.getAction(event);
try
{
SearchBuilderItem sb = searchBuilderItemDao.findByName(resourceName);
if (sb == null)
{
// new
sb = searchBuilderItemDao.create();
sb.setSearchaction(action);
sb.setName(resourceName);
String siteId = ecp.getSiteId(resourceName);
if (siteId == null || siteId.length() == 0)
{
// default if null should neve happen
siteId = "none";
}
sb.setContext(siteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM);
}
else
{
sb.setSearchaction(action);
String siteId = ecp.getSiteId(resourceName);
if (siteId == null || siteId.length() == 0)
{
// default if null, should never happen
siteId = "none";
}
sb.setContext(siteId);
sb.setName(resourceName);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM);
}
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: Added Resource " + action + " " + sb.getName());
}
catch (Throwable t)
{
log.debug("In trying to register resource " + resourceName
+ " in search engine this resource will"
+ " not be indexed untill it is modified");
}
searchIndexBuilderWorker.incrementActivity();
restartBuilder();
}
| public void addResource(Notification notification, Event event)
{
log.debug("Add resource " + notification + "::" + event);
String resourceName = event.getResource();
if (resourceName == null)
{
// default if null
resourceName = "";
}
if (resourceName.length() > 255)
{
log
.warn("Entity Reference is longer than 255 characters, not indexing. Reference="
+ resourceName);
return;
}
EntityContentProducer ecp = newEntityContentProducer(event);
if ( ecp == null || ecp.getSiteId(resourceName) == null)
{
log.debug("Not indexing " + resourceName + " as it has no context");
return;
}
if (onlyIndexSearchToolSites)
{
try
{
String siteId = ecp.getSiteId(resourceName);
Site s = SiteService.getSite(siteId);
ToolConfiguration t = s.getToolForCommonId("sakai.search");
if (t == null)
{
log.debug("Not indexing " + resourceName
+ " as it has no search tool");
return;
}
}
catch (Exception ex)
{
log.debug("Not indexing " + resourceName + " as it has no site", ex);
return;
}
}
Integer action = ecp.getAction(event);
try
{
SearchBuilderItem sb = searchBuilderItemDao.findByName(resourceName);
if (sb == null)
{
// new
sb = searchBuilderItemDao.create();
sb.setSearchaction(action);
sb.setName(resourceName);
String siteId = ecp.getSiteId(resourceName);
if (siteId == null || siteId.length() == 0)
{
// default if null should neve happen
siteId = "none";
}
sb.setContext(siteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM);
}
else
{
sb.setSearchaction(action);
String siteId = ecp.getSiteId(resourceName);
if (siteId == null || siteId.length() == 0)
{
// default if null, should never happen
siteId = "none";
}
sb.setContext(siteId);
sb.setName(resourceName);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
sb.setItemscope(SearchBuilderItem.ITEM);
}
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: Added Resource " + action + " " + sb.getName());
}
catch (Throwable t)
{
log.debug("In trying to register resource " + resourceName
+ " in search engine this resource will"
+ " not be indexed untill it is modified");
}
searchIndexBuilderWorker.incrementActivity();
restartBuilder();
}
|
diff --git a/trunk/CruxModulesCompiler/src/br/com/sysmap/crux/tools/compile/SchemaGeneratorModulesTask.java b/trunk/CruxModulesCompiler/src/br/com/sysmap/crux/tools/compile/SchemaGeneratorModulesTask.java
index fc594f8be..7a94cec2b 100644
--- a/trunk/CruxModulesCompiler/src/br/com/sysmap/crux/tools/compile/SchemaGeneratorModulesTask.java
+++ b/trunk/CruxModulesCompiler/src/br/com/sysmap/crux/tools/compile/SchemaGeneratorModulesTask.java
@@ -1,48 +1,48 @@
/*
* Copyright 2009 Sysmap Solutions Software e Consultoria Ltda.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.sysmap.crux.tools.compile;
import java.io.File;
import br.com.sysmap.crux.module.CruxModuleBridge;
import br.com.sysmap.crux.tools.schema.SchemaGeneratorTask;
/**
* @author Thiago da Rosa de Bustamante
*
*/
public class SchemaGeneratorModulesTask extends SchemaGeneratorTask
{
private String moduleName;
public String getModuleName()
{
return moduleName;
}
public void setModuleName(String moduleName)
{
this.moduleName = moduleName;
}
@Override
- protected void generateSchemas(File baseDir, String outputDir) throws Exception
+ protected void generateSchemas(File baseDir, File outputDir, File webDir) throws Exception
{
CruxModuleBridge.getInstance().registerCurrentModule(moduleName);
- super.generateSchemas(baseDir, outputDir);
+ super.generateSchemas(baseDir, outputDir, webDir);
}
}
| false | true | protected void generateSchemas(File baseDir, String outputDir) throws Exception
{
CruxModuleBridge.getInstance().registerCurrentModule(moduleName);
super.generateSchemas(baseDir, outputDir);
}
| protected void generateSchemas(File baseDir, File outputDir, File webDir) throws Exception
{
CruxModuleBridge.getInstance().registerCurrentModule(moduleName);
super.generateSchemas(baseDir, outputDir, webDir);
}
|
diff --git a/wicket-contrib-dojo/src/main/java/wicket/contrib/dojo/markup/html/DojoLink.java b/wicket-contrib-dojo/src/main/java/wicket/contrib/dojo/markup/html/DojoLink.java
index 256d5eb78..bcf306b9b 100644
--- a/wicket-contrib-dojo/src/main/java/wicket/contrib/dojo/markup/html/DojoLink.java
+++ b/wicket-contrib-dojo/src/main/java/wicket/contrib/dojo/markup/html/DojoLink.java
@@ -1,74 +1,75 @@
/*
* 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 wicket.contrib.dojo.markup.html;
import wicket.MarkupContainer;
import wicket.ajax.AjaxRequestTarget;
import wicket.ajax.markup.html.AjaxLink;
import wicket.contrib.dojo.AbstractDefaultDojoBehavior;
import wicket.markup.ComponentTag;
import wicket.model.IModel;
/**
* A component that allows a trigger request to be triggered via html anchor tag
*
*
* @author Vincent Demay
*
*/
public abstract class DojoLink extends AjaxLink
{
/**
* Construct.
*
* @param id
*/
public DojoLink(final String id)
{
this(id, null);
}
/**
* Construct.
*
* @param id
* @param model
*/
public DojoLink(final String id, final IModel model)
{
super(id, model);
add(new AbstractDefaultDojoBehavior()
{
private static final long serialVersionUID = 1L;
protected void onComponentTag(ComponentTag tag)
{
// return false to end event processing in case the DojoLink is bound to a <button> contained in a form
- tag.put("onclick", getCallbackScript() + "; return false;");
+ // stop all event after the click : see http://wicketstuff.org/jira/browse/DOJO-45
+ tag.put("onclick", getCallbackScript() + "; dojo.event.browser.stopEvent(event); return false;");
}
protected void respond(AjaxRequestTarget target)
{
((DojoLink)getComponent()).onClick(target);
}
});
}
}
| true | true | public DojoLink(final String id, final IModel model)
{
super(id, model);
add(new AbstractDefaultDojoBehavior()
{
private static final long serialVersionUID = 1L;
protected void onComponentTag(ComponentTag tag)
{
// return false to end event processing in case the DojoLink is bound to a <button> contained in a form
tag.put("onclick", getCallbackScript() + "; return false;");
}
protected void respond(AjaxRequestTarget target)
{
((DojoLink)getComponent()).onClick(target);
}
});
}
| public DojoLink(final String id, final IModel model)
{
super(id, model);
add(new AbstractDefaultDojoBehavior()
{
private static final long serialVersionUID = 1L;
protected void onComponentTag(ComponentTag tag)
{
// return false to end event processing in case the DojoLink is bound to a <button> contained in a form
// stop all event after the click : see http://wicketstuff.org/jira/browse/DOJO-45
tag.put("onclick", getCallbackScript() + "; dojo.event.browser.stopEvent(event); return false;");
}
protected void respond(AjaxRequestTarget target)
{
((DojoLink)getComponent()).onClick(target);
}
});
}
|
diff --git a/src/main/java/com/minesnap/dcpu/assembler/AssemblerLauncher.java b/src/main/java/com/minesnap/dcpu/assembler/AssemblerLauncher.java
index af04fe0..51291f1 100644
--- a/src/main/java/com/minesnap/dcpu/assembler/AssemblerLauncher.java
+++ b/src/main/java/com/minesnap/dcpu/assembler/AssemblerLauncher.java
@@ -1,127 +1,127 @@
package com.minesnap.dcpu.assembler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class AssemblerLauncher {
public static void main(String[] args) {
boolean endianDecided = false;
boolean littleEndian = true;
boolean optimize = true;
List<String> argsList = new ArrayList<String>(2);
Map<String, Integer> newNBOpcodes = new HashMap<String, Integer>();
for(int i=0; i<args.length; i++) {
if(args[i].length() == 0)
continue;
switch(args[i].charAt(0)) {
case '-':
if(args[i].length() == 1) {
// Just "-" represents stdin or stdout
argsList.add(args[i]);
} else if(args[i].equals("-h") || args[i].equals("--help")) {
usage();
return;
} else if(args[i].equals("--no-optimizations")) {
optimize = false;
} else if(args[i].equals("-b") || args[i].equals("--big-endian")) {
if(endianDecided) {
System.err.println("Error: You can't specify multiple endian types.");
usage();
System.exit(1);
}
endianDecided = true;
littleEndian = false;
} else if(args[i].equals("-l") || args[i].equals("--little-endian")) {
if(endianDecided) {
System.err.println("Error: You can't specify multiple endian types.");
usage();
System.exit(1);
}
endianDecided = true;
littleEndian = true;
} else if(args[i].equals("-n") || args[i].equals("--new-nbopcode")) {
if(args.length <= i+2) {
System.err.println("-n/--new-nbopcode requires two arguments.");
usage();
System.exit(1);
}
String name = args[++i].toUpperCase();
int number = Integer.parseInt(args[++i]);
if(newNBOpcodes.containsKey(name)) {
System.err.println("You may not specify multiple NB-opcodes with the same name: "+name);
usage();
System.exit(1);
}
if(newNBOpcodes.containsValue(number)) {
System.err.println("You may not specify multiple NB-opcodes with the same number: "+number);
usage();
System.exit(1);
}
newNBOpcodes.put(name, number);
} else {
System.err.println("Not a valid argument: "+args[i]);
usage();
System.exit(1);
}
break;
default:
argsList.add(args[i]);
}
}
if(argsList.size() < 1 || argsList.size() > 2) {
System.err.println("Wrong number of arguments.");
usage();
System.exit(1);
}
String filename = argsList.get(0);
String outname;
if(argsList.size() < 2)
outname = "a.out";
else
outname = argsList.get(1);
Assembler as = new Assembler();
as.setLittleEndian(littleEndian);
as.setOptimizations(optimize);
as.setNewNBOpcodes(newNBOpcodes);
try {
as.assemble(filename);
- as.writeTo(outname);
+ as.writeTo(outname);
} catch (FileNotFoundException e) {
- System.err.println("Error: Could not find file "+filename);
+ System.err.println("Error: "+e.getMessage());
System.exit(2);
} catch (CompileError e) {
System.err.println("Compile Error: "+e.getMessage());
System.exit(3);
} catch (IOException e) {
System.err.println(e);
System.exit(5);
}
System.out.println("Successfully assembled "+filename+" to "+outname);
}
public static void usage() {
System.out.println("Parameters: [OPTION]... INPUTFILENAME [OUTPUTFILENAME]");
System.out.println("Assembles INPUTFILENAME and writes the output to OUTPUTFILENAME.");
System.out.println("Default OUTPUTFILENAME is \"a.out\".");
System.out.println();
System.out.println("Available options:");
System.out.println(" -h, --help Show this help message.");
System.out.println(" --no-optimizations");
System.out.println(" Disable automatic optimiziations.");
System.out.println(" -l, --little-endian");
System.out.println(" Output little endian binaries (default).");
System.out.println(" -b, --big-endian");
System.out.println(" Output big endian binaries.");
System.out.println(" -n, --new-nbopcode name number");
System.out.println(" Define a custom non-basic opcode. May be used more than once.");
}
}
| false | true | public static void main(String[] args) {
boolean endianDecided = false;
boolean littleEndian = true;
boolean optimize = true;
List<String> argsList = new ArrayList<String>(2);
Map<String, Integer> newNBOpcodes = new HashMap<String, Integer>();
for(int i=0; i<args.length; i++) {
if(args[i].length() == 0)
continue;
switch(args[i].charAt(0)) {
case '-':
if(args[i].length() == 1) {
// Just "-" represents stdin or stdout
argsList.add(args[i]);
} else if(args[i].equals("-h") || args[i].equals("--help")) {
usage();
return;
} else if(args[i].equals("--no-optimizations")) {
optimize = false;
} else if(args[i].equals("-b") || args[i].equals("--big-endian")) {
if(endianDecided) {
System.err.println("Error: You can't specify multiple endian types.");
usage();
System.exit(1);
}
endianDecided = true;
littleEndian = false;
} else if(args[i].equals("-l") || args[i].equals("--little-endian")) {
if(endianDecided) {
System.err.println("Error: You can't specify multiple endian types.");
usage();
System.exit(1);
}
endianDecided = true;
littleEndian = true;
} else if(args[i].equals("-n") || args[i].equals("--new-nbopcode")) {
if(args.length <= i+2) {
System.err.println("-n/--new-nbopcode requires two arguments.");
usage();
System.exit(1);
}
String name = args[++i].toUpperCase();
int number = Integer.parseInt(args[++i]);
if(newNBOpcodes.containsKey(name)) {
System.err.println("You may not specify multiple NB-opcodes with the same name: "+name);
usage();
System.exit(1);
}
if(newNBOpcodes.containsValue(number)) {
System.err.println("You may not specify multiple NB-opcodes with the same number: "+number);
usage();
System.exit(1);
}
newNBOpcodes.put(name, number);
} else {
System.err.println("Not a valid argument: "+args[i]);
usage();
System.exit(1);
}
break;
default:
argsList.add(args[i]);
}
}
if(argsList.size() < 1 || argsList.size() > 2) {
System.err.println("Wrong number of arguments.");
usage();
System.exit(1);
}
String filename = argsList.get(0);
String outname;
if(argsList.size() < 2)
outname = "a.out";
else
outname = argsList.get(1);
Assembler as = new Assembler();
as.setLittleEndian(littleEndian);
as.setOptimizations(optimize);
as.setNewNBOpcodes(newNBOpcodes);
try {
as.assemble(filename);
as.writeTo(outname);
} catch (FileNotFoundException e) {
System.err.println("Error: Could not find file "+filename);
System.exit(2);
} catch (CompileError e) {
System.err.println("Compile Error: "+e.getMessage());
System.exit(3);
} catch (IOException e) {
System.err.println(e);
System.exit(5);
}
System.out.println("Successfully assembled "+filename+" to "+outname);
}
| public static void main(String[] args) {
boolean endianDecided = false;
boolean littleEndian = true;
boolean optimize = true;
List<String> argsList = new ArrayList<String>(2);
Map<String, Integer> newNBOpcodes = new HashMap<String, Integer>();
for(int i=0; i<args.length; i++) {
if(args[i].length() == 0)
continue;
switch(args[i].charAt(0)) {
case '-':
if(args[i].length() == 1) {
// Just "-" represents stdin or stdout
argsList.add(args[i]);
} else if(args[i].equals("-h") || args[i].equals("--help")) {
usage();
return;
} else if(args[i].equals("--no-optimizations")) {
optimize = false;
} else if(args[i].equals("-b") || args[i].equals("--big-endian")) {
if(endianDecided) {
System.err.println("Error: You can't specify multiple endian types.");
usage();
System.exit(1);
}
endianDecided = true;
littleEndian = false;
} else if(args[i].equals("-l") || args[i].equals("--little-endian")) {
if(endianDecided) {
System.err.println("Error: You can't specify multiple endian types.");
usage();
System.exit(1);
}
endianDecided = true;
littleEndian = true;
} else if(args[i].equals("-n") || args[i].equals("--new-nbopcode")) {
if(args.length <= i+2) {
System.err.println("-n/--new-nbopcode requires two arguments.");
usage();
System.exit(1);
}
String name = args[++i].toUpperCase();
int number = Integer.parseInt(args[++i]);
if(newNBOpcodes.containsKey(name)) {
System.err.println("You may not specify multiple NB-opcodes with the same name: "+name);
usage();
System.exit(1);
}
if(newNBOpcodes.containsValue(number)) {
System.err.println("You may not specify multiple NB-opcodes with the same number: "+number);
usage();
System.exit(1);
}
newNBOpcodes.put(name, number);
} else {
System.err.println("Not a valid argument: "+args[i]);
usage();
System.exit(1);
}
break;
default:
argsList.add(args[i]);
}
}
if(argsList.size() < 1 || argsList.size() > 2) {
System.err.println("Wrong number of arguments.");
usage();
System.exit(1);
}
String filename = argsList.get(0);
String outname;
if(argsList.size() < 2)
outname = "a.out";
else
outname = argsList.get(1);
Assembler as = new Assembler();
as.setLittleEndian(littleEndian);
as.setOptimizations(optimize);
as.setNewNBOpcodes(newNBOpcodes);
try {
as.assemble(filename);
as.writeTo(outname);
} catch (FileNotFoundException e) {
System.err.println("Error: "+e.getMessage());
System.exit(2);
} catch (CompileError e) {
System.err.println("Compile Error: "+e.getMessage());
System.exit(3);
} catch (IOException e) {
System.err.println(e);
System.exit(5);
}
System.out.println("Successfully assembled "+filename+" to "+outname);
}
|
diff --git a/src/main/java/org/psjava/algo/math/numbertheory/PrimalityTesterByPreparedPrimeDivision.java b/src/main/java/org/psjava/algo/math/numbertheory/PrimalityTesterByPreparedPrimeDivision.java
index b0f35ab..d2512cd 100644
--- a/src/main/java/org/psjava/algo/math/numbertheory/PrimalityTesterByPreparedPrimeDivision.java
+++ b/src/main/java/org/psjava/algo/math/numbertheory/PrimalityTesterByPreparedPrimeDivision.java
@@ -1,40 +1,39 @@
package org.psjava.algo.math.numbertheory;
import org.psjava.ds.array.Array;
/**
* Almost same with {@link PrimalityTesterByDivision}. But if there are prepared primes, we can do division-test only for primes.
*
* Then, the time is almost 10 times faster than {@link PrimalityTesterByDivision}.
*
* Here, we uses prime number sieve to get prime number list.
*/
public class PrimalityTesterByPreparedPrimeDivision {
public static PrimalityTester getInstance(long max, PrimeNumberSieve sieve) {
final Array<Integer> primes = sieve.calcList((int) Math.sqrt(max) + 1);
return new PrimalityTester() {
@Override
- public boolean isPrime(long longv) {
- int v = (int) longv;
+ public boolean isPrime(long v) {
if (v <= 1)
return false;
- for (int p : primes) {
+ for (long p : primes) {
if (p * p <= v) {
if (v % p == 0)
return false;
} else {
break;
}
}
return true;
}
};
}
private PrimalityTesterByPreparedPrimeDivision() {
}
}
| false | true | public static PrimalityTester getInstance(long max, PrimeNumberSieve sieve) {
final Array<Integer> primes = sieve.calcList((int) Math.sqrt(max) + 1);
return new PrimalityTester() {
@Override
public boolean isPrime(long longv) {
int v = (int) longv;
if (v <= 1)
return false;
for (int p : primes) {
if (p * p <= v) {
if (v % p == 0)
return false;
} else {
break;
}
}
return true;
}
};
}
| public static PrimalityTester getInstance(long max, PrimeNumberSieve sieve) {
final Array<Integer> primes = sieve.calcList((int) Math.sqrt(max) + 1);
return new PrimalityTester() {
@Override
public boolean isPrime(long v) {
if (v <= 1)
return false;
for (long p : primes) {
if (p * p <= v) {
if (v % p == 0)
return false;
} else {
break;
}
}
return true;
}
};
}
|
diff --git a/src/main/java/hudson/plugins/perforce/PerforceSCM.java b/src/main/java/hudson/plugins/perforce/PerforceSCM.java
index d8cf54e..0a39f00 100644
--- a/src/main/java/hudson/plugins/perforce/PerforceSCM.java
+++ b/src/main/java/hudson/plugins/perforce/PerforceSCM.java
@@ -1,487 +1,486 @@
package hudson.plugins.perforce;
import java.io.File;
import java.io.IOException;
import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.List;
import org.apache.xml.utils.URI;
import org.kohsuke.stapler.StaplerRequest;
import hudson.FilePath;
import hudson.Launcher;
import hudson.util.FormFieldValidator;
import static hudson.Util.fixEmpty;
import static hudson.Util.fixNull;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.TaskListener;
import hudson.scm.ChangeLogParser;
import hudson.scm.*;
import hudson.scm.SCMDescriptor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import com.tek42.perforce.*;
import com.tek42.perforce.model.*;
/**
* Extends {@link SCM} to provide integration with Perforce SCM.
*
* @author Mike Wille
*
*/
public class PerforceSCM extends SCM {
public static final PerforceSCM.PerforceSCMDescriptor DESCRIPTOR = new PerforceSCM.PerforceSCMDescriptor();
String p4User;
String p4Passwd;
String p4Port;
String p4Client;
String projectPath;
String p4Exe = "C:\\Program Files\\Perforce\\p4.exe";
String p4SysDrive = "C:";
String p4SysRoot = "C:\\WINDOWS";
int lastChange = 0;
Depot depot;
PerforceRepositoryBrowser browser;
/**
* force sync is a one time trigger from the config area to force a sync with the depot.
* it is reset to false after the first checkout.
*/
boolean forceSync = false;
public PerforceSCM(String p4User, String p4Pass, String p4Client, String p4Port, String projectPath,
String p4Exe, String p4SysRoot, String p4SysDrive, boolean forceSync, PerforceRepositoryBrowser browser) {
this.p4User = p4User;
this.p4Passwd = p4Pass;
this.p4Client = p4Client;
this.p4Port = p4Port;
this.projectPath = projectPath;
if(p4Exe != null)
this.p4Exe = p4Exe;
if(p4SysRoot != null)
this.p4SysRoot = p4SysRoot;
if(p4SysDrive != null)
this.p4SysDrive = p4SysDrive;
this.forceSync = forceSync;
this.browser = browser;
}
/**
* This only exists because we need to do initialization after we have been brought
* back to life. I'm not quite clear on stapler and how all that works.
* At any rate, it doesn't look like we have an init() method for setting up our Depot
* after all of the setters have been called. Someone correct me if I'm wrong...
*/
private Depot getDepot() {
if(depot == null) {
depot = new Depot();
depot.setUser(p4User);
depot.setPassword(p4Passwd);
depot.setPort(p4Port);
depot.setClient(p4Client);
depot.setExecutable(p4Exe);
depot.setSystemDrive(p4SysDrive);
depot.setSystemRoot(p4SysRoot);
}
return depot;
}
/**
* Perform some manipulation on the workspace URI to get a valid local path
* <p>
* Is there an issue doing this? What about remote workspaces? does that happen?
*
* @param path
* @return
* @throws IOException
* @throws InterruptedException
*/
private String getLocalPathName(FilePath path) throws IOException, InterruptedException {
String uriString = path.toURI().toString();
// Get rid of URI prefix
// NOTE: this won't handle remote files, is that a problem?
uriString = uriString.replaceAll("file:/", "");
// It seems there is a /./ to denote the root in the path on my test instance.
// I don't know if this is in production, or how it works on other platforms (non win32)
// but I am removing it here because perforce doesn't like it.
uriString = uriString.replaceAll("/./", "/");
// The URL is also escaped. We need to unescape it because %20 in path names isn't cool for perforce.
uriString = URLDecoder.decode(uriString, "UTF-8");
// Last but not least, we need to convert this to local path separators.
String sep = System.getProperty("file.separator");
if(sep.equals("\\")) {
// just replace with sep doesn't work because java's foobar regexp replaceAll
uriString = uriString.replaceAll("/", "\\\\");
} else {
// on unixen we need to prepend with /
uriString = "/" + uriString;
}
return uriString;
}
/* (non-Javadoc)
* @see hudson.scm.SCM#checkout(hudson.model.AbstractBuild, hudson.Launcher, hudson.FilePath, hudson.model.BuildListener, java.io.File)
*/
@Override
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
try {
listener.getLogger().println("Performing sync with Perforce for: " + projectPath);
// Check to make sure our client is mapped to the local hudson directory...
// The problem is that perforce assumes a local directory on your computer maps
// directly to the remote depot. Unfortunately, this doesn't work with they way
// Hudson sets up workspaces. Not to worry! What we do here is manipulate the
// perforce client spec before we do a checkout.
// An alternative would be to setup a single client for each build project. While,
// that is possible, I think its wasteful makes setup time for the user longer as
// they have to go and create a workspace in perforce for each new project.
// 1. Retrieve the client specified, throw an exception if we are configured wrong and the
// client spec doesn't exist.
Workspace p4workspace = getDepot().getWorkspaces().getWorkspace(p4Client);
if(p4workspace == null) {
throw new PerforceException("Workspace: " + p4Client + " doesn't exist.");
}
// 2. Before we sync, we need to update the client spec. (we do this on every build)
// Here we are getting the local file path to the workspace. We will use this as the "Root"
// config property of the client spec. This tells perforce where to store the files on our local disk
String localPath = getLocalPathName(workspace);
listener.getLogger().println("Changing P4 Client Root to: " + localPath);
// 3. We tell perforce to map the project contents directly (this drops off the project
// name from the workspace. So instead of:
// [Hudson]/[job]/workspace/[Project]/contents
// we get:
// [Hudson]/[job]/workspace/contents
String view = projectPath + " //" + p4workspace.getName() + "/...";
listener.getLogger().println("Changing P4 Client View to: " + view);
// 4. Go and save the client using our custom method and not the Perforce API...
p4workspace.setRoot(localPath);
p4workspace.clearViews();
p4workspace.addView(view);
depot.getWorkspaces().saveWorkspace(p4workspace);
// 5. Get the list of changes since the last time we looked...
listener.getLogger().println("Last sync'd change: " + lastChange);
List<Changelist> changes = depot.getChanges().getChangelistsFromNumbers(depot.getChanges().getChangeNumbersTo(projectPath, lastChange + 1));
if(changes.size() > 0) {
// save the last change we sync'd to for use when polling...
lastChange = changes.get(0).getChangeNumber();
System.out.println("Changelog file: " + changelogFile);
PerforceChangeLogSet.saveToChangeLog(new FileOutputStream(changelogFile), changes);
} else if(!forceSync) {
listener.getLogger().println("No changes since last build.");
- createEmptyChangeLog(changelogFile, listener, "changelog");
- return false;
+ return createEmptyChangeLog(changelogFile, listener, "changelog");
}
// 7. Now we can actually do the sync process...
long startTime = System.currentTimeMillis();
listener.getLogger().println("Sync'ing workspace to depot.");
if(forceSync)
listener.getLogger().println("ForceSync flag is set, forcing: p4 sync " + projectPath);
depot.getWorkspaces().syncToHead(projectPath, forceSync);
forceSync = false;
listener.getLogger().println("Sync complete, took " + (System.currentTimeMillis() - startTime) + " MS");
// Add tagging action...
build.addAction(new PerforceTagAction(build, depot, lastChange, projectPath));
// And I'm spent...
return true;
} catch(PerforceException e) {
listener.getLogger().print("Caught Exception communicating with perforce." + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. Check log file for: " + e.getMessage());
} finally {
//Utils.cleanUp();
}
}
@Override
public PerforceRepositoryBrowser getBrowser() {
return browser;
}
/* (non-Javadoc)
* @see hudson.scm.SCM#createChangeLogParser()
*/
@Override
public ChangeLogParser createChangeLogParser() {
return new PerforceChangeLogParser();
}
/* (non-Javadoc)
* @see hudson.scm.SCM#getDescriptor()
*/
@Override
public SCMDescriptor<?> getDescriptor() {
return DESCRIPTOR;
}
/* (non-Javadoc)
* @see hudson.scm.SCM#pollChanges(hudson.model.AbstractProject, hudson.Launcher, hudson.FilePath, hudson.model.TaskListener)
*/
@Override
public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException {
try {
listener.getLogger().println("Looking for changes...");
List<Changelist> changes = getDepot().getChanges().getChangelists(projectPath, -1, 1);
listener.getLogger().println("Latest change in depot is: " + changes.get(0).getChangeNumber());
listener.getLogger().println(changes.get(0).toString());
listener.getLogger().println("Last sync'd change is : " + lastChange);
if(lastChange != changes.get(0).getChangeNumber()) {
return true;
}
return false;
} catch(PerforceException e) {
System.out.println("Problem: " + e.getMessage());
listener.getLogger().println("Caught Exception communicating with perforce." + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. Check log file for: " + e.getMessage());
} finally {
//Utils.cleanUp();
}
//return false;
}
public static final class PerforceSCMDescriptor extends SCMDescriptor<PerforceSCM> {
private PerforceSCMDescriptor() {
super(PerforceSCM.class, PerforceRepositoryBrowser.class);
load();
}
public String getDisplayName() {
return "Perforce";
}
public SCM newInstance(StaplerRequest req) throws FormException {
String value = req.getParameter("p4.forceSync");
boolean force = false;
if(value != null && !value.equals(""))
force = new Boolean(value);
return new PerforceSCM(
req.getParameter("p4.user"),
req.getParameter("p4.passwd"),
req.getParameter("p4.client"),
req.getParameter("p4.port"),
req.getParameter("projectPath"),
req.getParameter("p4.exe"),
req.getParameter("p4.sysRoot"),
req.getParameter("p4.sysDrive"),
force,
RepositoryBrowsers.createInstance(PerforceRepositoryBrowser.class, req, "p4.browser"));
}
public String isValidProjectPath(String path) {
if(!path.startsWith("//")) {
return "Path must start with '//' (Example: //depot/ProjectName/...)";
}
if(!path.endsWith("/...")) {
return "Path must end with Perforce wildcard: '/...' (Example: //depot/ProjectName/...)";
}
return null;
}
public void doValidatePerforceLogin(StaplerRequest request, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(request,rsp,false) {
protected void check() throws IOException, ServletException {
String port = fixNull(request.getParameter("port")).trim();
String exe = fixNull(request.getParameter("exe")).trim();
String user = fixNull(request.getParameter("user")).trim();
String pass = fixNull(request.getParameter("pass")).trim();
if(port.length()==0 || exe.length() == 0 || user.length() == 0 || pass.length() == 0) {// nothing entered yet
ok();
return;
}
Depot depot = new Depot();
depot.setUser(user);
depot.setPassword(pass);
depot.setPort(port);
depot.setExecutable(exe);
try {
depot.getStatus().isValid();
} catch(PerforceException e) {
error(e.getMessage());
}
ok();
return;
}
}.check();
}
/**
* Checks if the value is a valid Perforce project path.
*/
public void doCheckProjectPath(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req,rsp,false) {
protected void check() throws IOException, ServletException {
String tag = fixNull(request.getParameter("value")).trim();
if(tag.length()==0) {// nothing entered yet
ok();
return;
}
error(isValidProjectPath(tag));
}
}.check();
}
}
/**
* @return the projectPath
*/
public String getProjectPath() {
return projectPath;
}
/**
* @param projectPath the projectPath to set
*/
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
/**
* @return the p4User
*/
public String getP4User() {
return p4User;
}
/**
* @param user the p4User to set
*/
public void setP4User(String user) {
p4User = user;
}
/**
* @return the p4Passwd
*/
public String getP4Passwd() {
return p4Passwd;
}
/**
* @param passwd the p4Passwd to set
*/
public void setP4Passwd(String passwd) {
p4Passwd = passwd;
}
/**
* @return the p4Port
*/
public String getP4Port() {
return p4Port;
}
/**
* @param port the p4Port to set
*/
public void setP4Port(String port) {
p4Port = port;
}
/**
* @return the p4Client
*/
public String getP4Client() {
return p4Client;
}
/**
* @param client the p4Client to set
*/
public void setP4Client(String client) {
p4Client = client;
}
/**
* @return the p4SysDrive
*/
public String getP4SysDrive() {
return p4SysDrive;
}
/**
* @param sysDrive the p4SysDrive to set
*/
public void setP4SysDrive(String sysDrive) {
p4SysDrive = sysDrive;
}
/**
* @return the p4SysRoot
*/
public String getP4SysRoot() {
return p4SysRoot;
}
/**
* @param sysRoot the p4SysRoot to set
*/
public void setP4SysRoot(String sysRoot) {
p4SysRoot = sysRoot;
}
/**
* @return the p4Exe
*/
public String getP4Exe() {
return p4Exe;
}
/**
* @param exe the p4Exe to set
*/
public void setP4Exe(String exe) {
p4Exe = exe;
}
public void setLastChange(int change) {
lastChange = change;
}
public int getLastChange() {
return lastChange;
}
}
| true | true | public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
try {
listener.getLogger().println("Performing sync with Perforce for: " + projectPath);
// Check to make sure our client is mapped to the local hudson directory...
// The problem is that perforce assumes a local directory on your computer maps
// directly to the remote depot. Unfortunately, this doesn't work with they way
// Hudson sets up workspaces. Not to worry! What we do here is manipulate the
// perforce client spec before we do a checkout.
// An alternative would be to setup a single client for each build project. While,
// that is possible, I think its wasteful makes setup time for the user longer as
// they have to go and create a workspace in perforce for each new project.
// 1. Retrieve the client specified, throw an exception if we are configured wrong and the
// client spec doesn't exist.
Workspace p4workspace = getDepot().getWorkspaces().getWorkspace(p4Client);
if(p4workspace == null) {
throw new PerforceException("Workspace: " + p4Client + " doesn't exist.");
}
// 2. Before we sync, we need to update the client spec. (we do this on every build)
// Here we are getting the local file path to the workspace. We will use this as the "Root"
// config property of the client spec. This tells perforce where to store the files on our local disk
String localPath = getLocalPathName(workspace);
listener.getLogger().println("Changing P4 Client Root to: " + localPath);
// 3. We tell perforce to map the project contents directly (this drops off the project
// name from the workspace. So instead of:
// [Hudson]/[job]/workspace/[Project]/contents
// we get:
// [Hudson]/[job]/workspace/contents
String view = projectPath + " //" + p4workspace.getName() + "/...";
listener.getLogger().println("Changing P4 Client View to: " + view);
// 4. Go and save the client using our custom method and not the Perforce API...
p4workspace.setRoot(localPath);
p4workspace.clearViews();
p4workspace.addView(view);
depot.getWorkspaces().saveWorkspace(p4workspace);
// 5. Get the list of changes since the last time we looked...
listener.getLogger().println("Last sync'd change: " + lastChange);
List<Changelist> changes = depot.getChanges().getChangelistsFromNumbers(depot.getChanges().getChangeNumbersTo(projectPath, lastChange + 1));
if(changes.size() > 0) {
// save the last change we sync'd to for use when polling...
lastChange = changes.get(0).getChangeNumber();
System.out.println("Changelog file: " + changelogFile);
PerforceChangeLogSet.saveToChangeLog(new FileOutputStream(changelogFile), changes);
} else if(!forceSync) {
listener.getLogger().println("No changes since last build.");
createEmptyChangeLog(changelogFile, listener, "changelog");
return false;
}
// 7. Now we can actually do the sync process...
long startTime = System.currentTimeMillis();
listener.getLogger().println("Sync'ing workspace to depot.");
if(forceSync)
listener.getLogger().println("ForceSync flag is set, forcing: p4 sync " + projectPath);
depot.getWorkspaces().syncToHead(projectPath, forceSync);
forceSync = false;
listener.getLogger().println("Sync complete, took " + (System.currentTimeMillis() - startTime) + " MS");
// Add tagging action...
build.addAction(new PerforceTagAction(build, depot, lastChange, projectPath));
// And I'm spent...
return true;
} catch(PerforceException e) {
listener.getLogger().print("Caught Exception communicating with perforce." + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. Check log file for: " + e.getMessage());
} finally {
//Utils.cleanUp();
}
}
| public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
try {
listener.getLogger().println("Performing sync with Perforce for: " + projectPath);
// Check to make sure our client is mapped to the local hudson directory...
// The problem is that perforce assumes a local directory on your computer maps
// directly to the remote depot. Unfortunately, this doesn't work with they way
// Hudson sets up workspaces. Not to worry! What we do here is manipulate the
// perforce client spec before we do a checkout.
// An alternative would be to setup a single client for each build project. While,
// that is possible, I think its wasteful makes setup time for the user longer as
// they have to go and create a workspace in perforce for each new project.
// 1. Retrieve the client specified, throw an exception if we are configured wrong and the
// client spec doesn't exist.
Workspace p4workspace = getDepot().getWorkspaces().getWorkspace(p4Client);
if(p4workspace == null) {
throw new PerforceException("Workspace: " + p4Client + " doesn't exist.");
}
// 2. Before we sync, we need to update the client spec. (we do this on every build)
// Here we are getting the local file path to the workspace. We will use this as the "Root"
// config property of the client spec. This tells perforce where to store the files on our local disk
String localPath = getLocalPathName(workspace);
listener.getLogger().println("Changing P4 Client Root to: " + localPath);
// 3. We tell perforce to map the project contents directly (this drops off the project
// name from the workspace. So instead of:
// [Hudson]/[job]/workspace/[Project]/contents
// we get:
// [Hudson]/[job]/workspace/contents
String view = projectPath + " //" + p4workspace.getName() + "/...";
listener.getLogger().println("Changing P4 Client View to: " + view);
// 4. Go and save the client using our custom method and not the Perforce API...
p4workspace.setRoot(localPath);
p4workspace.clearViews();
p4workspace.addView(view);
depot.getWorkspaces().saveWorkspace(p4workspace);
// 5. Get the list of changes since the last time we looked...
listener.getLogger().println("Last sync'd change: " + lastChange);
List<Changelist> changes = depot.getChanges().getChangelistsFromNumbers(depot.getChanges().getChangeNumbersTo(projectPath, lastChange + 1));
if(changes.size() > 0) {
// save the last change we sync'd to for use when polling...
lastChange = changes.get(0).getChangeNumber();
System.out.println("Changelog file: " + changelogFile);
PerforceChangeLogSet.saveToChangeLog(new FileOutputStream(changelogFile), changes);
} else if(!forceSync) {
listener.getLogger().println("No changes since last build.");
return createEmptyChangeLog(changelogFile, listener, "changelog");
}
// 7. Now we can actually do the sync process...
long startTime = System.currentTimeMillis();
listener.getLogger().println("Sync'ing workspace to depot.");
if(forceSync)
listener.getLogger().println("ForceSync flag is set, forcing: p4 sync " + projectPath);
depot.getWorkspaces().syncToHead(projectPath, forceSync);
forceSync = false;
listener.getLogger().println("Sync complete, took " + (System.currentTimeMillis() - startTime) + " MS");
// Add tagging action...
build.addAction(new PerforceTagAction(build, depot, lastChange, projectPath));
// And I'm spent...
return true;
} catch(PerforceException e) {
listener.getLogger().print("Caught Exception communicating with perforce." + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. Check log file for: " + e.getMessage());
} finally {
//Utils.cleanUp();
}
}
|
diff --git a/src/main/java/no/steria/quizzical/SubmitServlet.java b/src/main/java/no/steria/quizzical/SubmitServlet.java
index ac0b9ba..12f659b 100644
--- a/src/main/java/no/steria/quizzical/SubmitServlet.java
+++ b/src/main/java/no/steria/quizzical/SubmitServlet.java
@@ -1,66 +1,67 @@
package no.steria.quizzical;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
public class SubmitServlet extends HttpServlet {
private MongoResponseDao mongoResponseDao;
private Response quizResponse;
private MongoQuizDao mongoQuizDao;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(req.getReader().readLine());
+ System.out.println();
int quizId=0;
String name="", email="";
HashMap<String,Integer> answersToDB = new HashMap<String,Integer>();
Iterator<Entry<String,JsonNode>> allEntries = rootNode.getFields();
while(allEntries.hasNext()){
Entry<String, JsonNode> entry = allEntries.next();
if(entry.getKey().equals("answers")){
Iterator<Entry<String,JsonNode>> answerEntries = entry.getValue().getFields();
while(answerEntries.hasNext()){
Entry<String,JsonNode> answer = answerEntries.next();
answersToDB.put(answer.getKey(), answer.getValue().asInt());
}
}else if(entry.getKey().equals("quizId")){
- quizId = Integer.parseInt(entry.getValue().toString());
+ quizId = Integer.parseInt(entry.getValue().asText());
}else if(entry.getKey().equals("name")){
- name = entry.getValue().toString();
+ name = entry.getValue().asText();
}else if(entry.getKey().equals("email")){
- email = entry.getValue().toString();
+ email = entry.getValue().asText();
}
}
quizResponse = new Response(quizId, name, email, answersToDB);
quizResponse.calculateScore(mongoQuizDao.getQuiz(quizId));
mongoResponseDao.setResponse(quizResponse);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
public void init() throws ServletException {
super.init();
mongoResponseDao = new MongoResponseDao();
mongoQuizDao = new MongoQuizDao();
}
}
| false | true | protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(req.getReader().readLine());
int quizId=0;
String name="", email="";
HashMap<String,Integer> answersToDB = new HashMap<String,Integer>();
Iterator<Entry<String,JsonNode>> allEntries = rootNode.getFields();
while(allEntries.hasNext()){
Entry<String, JsonNode> entry = allEntries.next();
if(entry.getKey().equals("answers")){
Iterator<Entry<String,JsonNode>> answerEntries = entry.getValue().getFields();
while(answerEntries.hasNext()){
Entry<String,JsonNode> answer = answerEntries.next();
answersToDB.put(answer.getKey(), answer.getValue().asInt());
}
}else if(entry.getKey().equals("quizId")){
quizId = Integer.parseInt(entry.getValue().toString());
}else if(entry.getKey().equals("name")){
name = entry.getValue().toString();
}else if(entry.getKey().equals("email")){
email = entry.getValue().toString();
}
}
quizResponse = new Response(quizId, name, email, answersToDB);
quizResponse.calculateScore(mongoQuizDao.getQuiz(quizId));
mongoResponseDao.setResponse(quizResponse);
}
| protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(req.getReader().readLine());
System.out.println();
int quizId=0;
String name="", email="";
HashMap<String,Integer> answersToDB = new HashMap<String,Integer>();
Iterator<Entry<String,JsonNode>> allEntries = rootNode.getFields();
while(allEntries.hasNext()){
Entry<String, JsonNode> entry = allEntries.next();
if(entry.getKey().equals("answers")){
Iterator<Entry<String,JsonNode>> answerEntries = entry.getValue().getFields();
while(answerEntries.hasNext()){
Entry<String,JsonNode> answer = answerEntries.next();
answersToDB.put(answer.getKey(), answer.getValue().asInt());
}
}else if(entry.getKey().equals("quizId")){
quizId = Integer.parseInt(entry.getValue().asText());
}else if(entry.getKey().equals("name")){
name = entry.getValue().asText();
}else if(entry.getKey().equals("email")){
email = entry.getValue().asText();
}
}
quizResponse = new Response(quizId, name, email, answersToDB);
quizResponse.calculateScore(mongoQuizDao.getQuiz(quizId));
mongoResponseDao.setResponse(quizResponse);
}
|
diff --git a/src/com/android/apps/tag/MyTagList.java b/src/com/android/apps/tag/MyTagList.java
index e4541c5..9186389 100644
--- a/src/com/android/apps/tag/MyTagList.java
+++ b/src/com/android/apps/tag/MyTagList.java
@@ -1,661 +1,661 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.apps.tag;
import com.android.apps.tag.provider.TagContract.NdefMessages;
import com.android.apps.tag.record.RecordEditInfo;
import com.android.apps.tag.record.TextRecord;
import com.android.apps.tag.record.UriRecord;
import com.android.apps.tag.record.VCardRecord;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/**
* Displays the list of tags that can be set as "My tag", and allows the user to select the
* active tag that the device shares.
*/
public class MyTagList
extends Activity
implements OnItemClickListener, View.OnClickListener,
TagService.SaveCallbacks,
DialogInterface.OnClickListener {
static final String TAG = "TagList";
private static final int REQUEST_EDIT = 0;
private static final int DIALOG_ID_SELECT_ACTIVE_TAG = 0;
private static final int DIALOG_ID_ADD_NEW_TAG = 1;
private static final String BUNDLE_KEY_TAG_ID_IN_EDIT = "tag-edit";
private static final String PREF_KEY_ACTIVE_TAG = "active-my-tag";
static final String PREF_KEY_TAG_TO_WRITE = "tag-to-write";
static final String[] SUPPORTED_TYPES = new String[] {
VCardRecord.RECORD_TYPE,
UriRecord.RECORD_TYPE,
TextRecord.RECORD_TYPE,
};
private View mSelectActiveTagAnchor;
private View mActiveTagDetails;
private CheckBox mEnabled;
private ListView mList;
private TagAdapter mAdapter;
private long mActiveTagId;
private Uri mTagBeingSaved;
private NdefMessage mActiveTag;
private WeakReference<SelectActiveTagDialog> mSelectActiveTagDialog;
private long mTagIdInEdit = -1;
private long mTagIdLongPressed;
private boolean mWriteSupport = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
- registerForContextMenu(mList);
}
+ registerForContextMenu(mList);
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}
@Override
protected void onRestart() {
super.onRestart();
mTagIdInEdit = -1;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(BUNDLE_KEY_TAG_ID_IN_EDIT, mTagIdInEdit);
}
@Override
protected void onDestroy() {
if (mAdapter != null) {
mAdapter.changeCursor(null);
}
super.onDestroy();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
editTag(id);
}
/**
* Opens the tag editor for a particular tag.
*/
private void editTag(long id) {
// TODO: use implicit Intent?
Intent intent = new Intent(this, EditTagActivity.class);
intent.setData(ContentUris.withAppendedId(NdefMessages.CONTENT_URI, id));
mTagIdInEdit = id;
startActivityForResult(intent, REQUEST_EDIT);
}
public void setEmptyView() {
// TODO: set empty view.
}
public interface TagQuery {
static final String[] PROJECTION = new String[] {
NdefMessages._ID, // 0
NdefMessages.DATE, // 1
NdefMessages.TITLE, // 2
NdefMessages.BYTES, // 3
};
static final int COLUMN_ID = 0;
static final int COLUMN_DATE = 1;
static final int COLUMN_TITLE = 2;
static final int COLUMN_BYTES = 3;
}
/**
* Asynchronously loads the tags info from the database.
*/
final class TagLoaderTask extends AsyncTask<Void, Void, Cursor> {
@Override
public Cursor doInBackground(Void... args) {
Cursor cursor = getContentResolver().query(
NdefMessages.CONTENT_URI,
TagQuery.PROJECTION,
NdefMessages.IS_MY_TAG + "=1",
null, NdefMessages.DATE + " DESC");
// Ensure the cursor executes and fills its window
if (cursor != null) cursor.getCount();
return cursor;
}
@Override
protected void onPostExecute(Cursor cursor) {
mAdapter.changeCursor(cursor);
if (cursor == null || cursor.getCount() == 0) {
setEmptyView();
} else {
// Find the active tag.
if (mTagBeingSaved != null) {
selectTagBeingSaved(mTagBeingSaved);
} else if (mActiveTagId != -1) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
if (mActiveTagId == cursor.getLong(TagQuery.COLUMN_ID)) {
selectActiveTag(cursor.getPosition());
break;
}
}
}
}
SelectActiveTagDialog dialog = (mSelectActiveTagDialog == null)
? null : mSelectActiveTagDialog.get();
if (dialog != null) {
dialog.setData(cursor);
}
}
}
/**
* Struct to hold pointers to views in the list items to save time at view binding time.
*/
static final class ViewHolder {
public CharArrayBuffer titleBuffer;
public TextView mainLine;
public ImageView activeIcon;
}
/**
* Adapter to display the the My tag entries.
*/
public class TagAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public TagAdapter(Context context) {
super(context, null, false);
mInflater = LayoutInflater.from(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
CharArrayBuffer buf = holder.titleBuffer;
cursor.copyStringToBuffer(TagQuery.COLUMN_TITLE, buf);
holder.mainLine.setText(buf.data, 0, buf.sizeCopied);
boolean isActive = cursor.getLong(TagQuery.COLUMN_ID) == mActiveTagId;
holder.activeIcon.setVisibility(isActive ? View.VISIBLE : View.GONE);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.tag_list_item, null);
// Cache items for the view
ViewHolder holder = new ViewHolder();
holder.titleBuffer = new CharArrayBuffer(64);
holder.mainLine = (TextView) view.findViewById(R.id.title);
holder.activeIcon = (ImageView) view.findViewById(R.id.active_tag_icon);
view.findViewById(R.id.date).setVisibility(View.GONE);
view.setTag(holder);
return view;
}
@Override
public void onContentChanged() {
// Kick off an async query to refresh the list
new TagLoaderTask().execute((Void[]) null);
}
}
@Override
public void onClick(View target) {
switch (target.getId()) {
case R.id.toggle_enabled_target:
boolean enabled = !mEnabled.isChecked();
if (enabled) {
if (mActiveTag != null) {
enableSharingAndStoreTag();
return;
}
Toast.makeText(
this,
getResources().getString(R.string.no_tag_selected),
Toast.LENGTH_SHORT).show();
}
disableSharing();
break;
case R.id.add_tag:
showDialog(DIALOG_ID_ADD_NEW_TAG);
break;
case R.id.active_tag:
if (mAdapter.getCursor() == null || mAdapter.getCursor().isClosed()) {
// Hopefully shouldn't happen.
return;
}
if (mAdapter.getCursor().getCount() == 0) {
OnClickListener onAdd = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == AlertDialog.BUTTON_POSITIVE) {
showDialog(DIALOG_ID_ADD_NEW_TAG);
}
}
};
new AlertDialog.Builder(this)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.add_tag, onAdd)
.setMessage(R.string.no_tags_created)
.show();
return;
}
showDialog(DIALOG_ID_SELECT_ACTIVE_TAG);
break;
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
Cursor cursor = mAdapter.getCursor();
if (cursor == null
|| cursor.isClosed()
|| !cursor.moveToPosition(((AdapterContextMenuInfo) info).position)) {
return;
}
menu.setHeaderTitle(cursor.getString(TagQuery.COLUMN_TITLE));
long id = cursor.getLong(TagQuery.COLUMN_ID);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_tag_list_context_menu, menu);
// Prepare the menu for the item.
menu.findItem(R.id.set_as_active).setVisible(id != mActiveTagId);
mTagIdLongPressed = id;
if (mWriteSupport) {
menu.add(0, 1, 0, "Write to tag");
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
long id = mTagIdLongPressed;
switch (item.getItemId()) {
case R.id.delete:
deleteTag(id);
return true;
case R.id.set_as_active:
Cursor cursor = mAdapter.getCursor();
if (cursor == null || cursor.isClosed()) {
break;
}
for (int position = 0; cursor.moveToPosition(position); position++) {
if (cursor.getLong(TagQuery.COLUMN_ID) == id) {
selectActiveTag(position);
return true;
}
}
break;
case R.id.edit:
editTag(id);
return true;
case 1:
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
break;
}
Intent intent = new Intent(this, WriteTagActivity.class);
intent.putExtra("id", info.id);
startActivity(intent);
return true;
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EDIT && resultCode == RESULT_OK) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
data.getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
if (mTagIdInEdit != -1) {
TagService.updateMyMessage(this, mTagIdInEdit, msg);
} else {
saveNewMessage(msg);
}
}
}
private void saveNewMessage(NdefMessage msg) {
TagService.saveMyMessage(this, msg, this);
}
@Override
public void onSaveComplete(Uri newMsgUri) {
if (isFinishing()) {
// Callback came asynchronously and was after we finished - ignore.
return;
}
mTagBeingSaved = newMsgUri;
selectTagBeingSaved(newMsgUri);
}
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
Context lightTheme = new ContextThemeWrapper(this, android.R.style.Theme_Light);
if (id == DIALOG_ID_SELECT_ACTIVE_TAG) {
SelectActiveTagDialog dialog = new SelectActiveTagDialog(lightTheme,
mAdapter.getCursor());
dialog.setInverseBackgroundForced(true);
mSelectActiveTagDialog = new WeakReference<SelectActiveTagDialog>(dialog);
return dialog;
} else if (id == DIALOG_ID_ADD_NEW_TAG) {
ContentSelectorAdapter adapter = new ContentSelectorAdapter(lightTheme,
SUPPORTED_TYPES);
AlertDialog dialog = new AlertDialog.Builder(lightTheme)
.setTitle(R.string.select_type)
.setIcon(0)
.setNegativeButton(android.R.string.cancel, this)
.setAdapter(adapter, this)
.create();
adapter.setListView(dialog.getListView());
dialog.setInverseBackgroundForced(true);
return dialog;
}
return super.onCreateDialog(id, args);
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
} else {
RecordEditInfo info = (RecordEditInfo) ((AlertDialog) dialog).getListView()
.getAdapter().getItem(which);
Intent intent = new Intent(this, EditTagActivity.class);
intent.putExtra(EditTagActivity.EXTRA_NEW_RECORD_INFO, info);
startActivityForResult(intent, REQUEST_EDIT);
}
}
/**
* Selects the tag to be used as the "My tag" shared tag.
*
* This does not necessarily persist the selection to the {@code NfcAdapter}. That must be done
* via {@link #enableSharingAndStoreTag()}. However, it will call {@link #disableSharing()}
* if the tag is invalid.
*/
private void selectActiveTag(int position) {
Cursor cursor = mAdapter.getCursor();
if (cursor != null && cursor.moveToPosition(position)) {
mActiveTagId = cursor.getLong(TagQuery.COLUMN_ID);
try {
mActiveTag = new NdefMessage(cursor.getBlob(TagQuery.COLUMN_BYTES));
// Persist active tag info to preferences.
getPreferences(Context.MODE_PRIVATE)
.edit()
.putLong(PREF_KEY_ACTIVE_TAG, mActiveTagId)
.apply();
updateActiveTagView(cursor.getString(TagQuery.COLUMN_TITLE));
mAdapter.notifyDataSetChanged();
// If there was an existing shared tag, we update the contents, since
// the active tag contents may have been changed. This also forces the
// active tag to be in sync with what the NfcAdapter.
if (NfcAdapter.getDefaultAdapter(this).getLocalNdefMessage() != null) {
enableSharingAndStoreTag();
}
} catch (FormatException e) {
// TODO: handle.
disableSharing();
}
} else {
updateActiveTagView(null);
disableSharing();
}
mTagBeingSaved = null;
}
/**
* Selects the tag to be used as the "My tag" shared tag, if the specified URI is found.
* If the URI is not found, the next load will attempt to look for a matching tag to select.
*
* Commonly used for new tags that was just added to the database, and may not yet be
* reflected in the {@code Cursor}.
*/
private void selectTagBeingSaved(Uri uri) {
Cursor cursor = mAdapter.getCursor();
if (cursor == null) {
return;
}
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
Uri tagUri = ContentUris.withAppendedId(
NdefMessages.CONTENT_URI,
cursor.getLong(TagQuery.COLUMN_ID));
if (tagUri.equals(uri)) {
selectActiveTag(cursor.getPosition());
return;
}
}
}
private void enableSharingAndStoreTag() {
mEnabled.setChecked(true);
NfcAdapter.getDefaultAdapter(this).setLocalNdefMessage(
Preconditions.checkNotNull(mActiveTag));
}
private void disableSharing() {
mEnabled.setChecked(false);
NfcAdapter.getDefaultAdapter(this).setLocalNdefMessage(null);
}
private void updateActiveTagView(String title) {
if (title == null) {
mActiveTagDetails.setVisibility(View.GONE);
mSelectActiveTagAnchor.setVisibility(View.VISIBLE);
} else {
mActiveTagDetails.setVisibility(View.VISIBLE);
((TextView) mActiveTagDetails.findViewById(R.id.active_tag_title)).setText(title);
mSelectActiveTagAnchor.setVisibility(View.GONE);
}
}
/**
* Removes the tag from the "My tag" list.
*/
private void deleteTag(long id) {
if (id == mActiveTagId) {
selectActiveTag(-1);
}
TagService.delete(this, ContentUris.withAppendedId(NdefMessages.CONTENT_URI, id));
}
class SelectActiveTagDialog extends AlertDialog
implements DialogInterface.OnClickListener, OnItemClickListener {
private final ArrayList<HashMap<String, String>> mData;
private final SimpleAdapter mSelectAdapter;
protected SelectActiveTagDialog(Context context, Cursor cursor) {
super(context);
setTitle(context.getResources().getString(R.string.choose_my_tag));
ListView list = new ListView(context);
mData = Lists.newArrayList();
mSelectAdapter = new SimpleAdapter(
context,
mData,
android.R.layout.simple_list_item_1,
new String[] { "title" },
new int[] { android.R.id.text1 });
list.setAdapter(mSelectAdapter);
list.setOnItemClickListener(this);
setView(list);
setIcon(0);
setButton(
DialogInterface.BUTTON_POSITIVE,
context.getString(android.R.string.cancel),
this);
setData(cursor);
}
public void setData(final Cursor cursor) {
if ((cursor == null) || (cursor.getCount() == 0)) {
cancel();
return;
}
mData.clear();
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
mData.add(new HashMap<String, String>() {{
put("title", cursor.getString(MyTagList.TagQuery.COLUMN_TITLE));
}});
}
mSelectAdapter.notifyDataSetChanged();
}
@Override
public void onClick(DialogInterface dialog, int which) {
cancel();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectActiveTag(position);
enableSharingAndStoreTag();
cancel();
}
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
registerForContextMenu(mList);
}
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
}
registerForContextMenu(mList);
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
index 099a2cb30..6e08e1de5 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
@@ -1,682 +1,679 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2003 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.checks.javadoc;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.Scope;
import com.puppycrawl.tools.checkstyle.api.ScopeUtils;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.Utils;
import com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import org.apache.regexp.RE;
/**
* <p>
* Checks the Javadoc of a method or constructor.
* By default, does not check for unused throws.
* To allow documented <code>java.lang.RuntimeException</code>s
* that are not declared, set property allowUndeclaredRTE to true.
* The scope to verify is specified using the {@link Scope} class and
* defaults to {@link Scope#PRIVATE}. To verify another scope,
* set property scope to one of the {@link Scope} constants.
* </p>
* <p>
* Error messages about parameters for which no param tags are
* present can be suppressed by defining property
* <code>allowMissingParamTags</code>.
* Error messages about exceptions which are declared to be thrown,
* but for which no throws tag is present can be suppressed by
* defining property <code>allowMissingThrowsTags</code>.
* Error messages about methods which return non-void but for
* which no return tag is present can be suppressed by defining
* property <code>allowMissingReturnTag</code>.
* </p>
* <p>
* An example of how to configure the check is:
* </p>
* <pre>
* <module name="JavadocMethod"/>
* </pre>
* <p> An example of how to configure the check to check to allow
* documentation of undeclared RuntimeExceptions
* and for the {@link Scope#PUBLIC} scope, while ignoring any missing
* param tags is:
*</p>
* <pre>
* <module name="JavadocMethod">
* <property name="scope" value="public"/>
* <property name="allowUndeclaredRTE" value="true"/>
* <property name="allowMissingParamTags" value="true"/>
* </module>
* </pre>
*
* @author Oliver Burn
* @author Rick Giles
* @author o_sukhodoslky
* @version 1.1
*/
public class JavadocMethodCheck
extends AbstractTypeAwareCheck
{
/** the pattern to match Javadoc tags that take an argument **/
private static final String MATCH_JAVADOC_ARG_PAT =
"@(throws|exception|param)\\s+(\\S+)\\s+\\S";
/** compiled regexp to match Javadoc tags that take an argument **/
private static final RE MATCH_JAVADOC_ARG =
Utils.createRE(MATCH_JAVADOC_ARG_PAT);
/**
* the pattern to match the first line of a multi-line Javadoc
* tag that takes an argument.
**/
private static final String MATCH_JAVADOC_ARG_MULTILINE_START_PAT =
"@(throws|exception|param)\\s+(\\S+)\\s*$";
/** compiled regexp to match first part of multilineJavadoc tags **/
private static final RE MATCH_JAVADOC_ARG_MULTILINE_START =
Utils.createRE(MATCH_JAVADOC_ARG_MULTILINE_START_PAT);
/** the pattern that looks for a continuation of the comment **/
private static final String MATCH_JAVADOC_MULTILINE_CONT_PAT =
"(\\*/|@|[^\\s\\*])";
/** compiled regexp to look for a continuation of the comment **/
private static final RE MATCH_JAVADOC_MULTILINE_CONT =
Utils.createRE(MATCH_JAVADOC_MULTILINE_CONT_PAT);
/** Multiline finished at end of comment **/
private static final String END_JAVADOC = "*/";
/** Multiline finished at next Javadoc **/
private static final String NEXT_TAG = "@";
/** the pattern to match Javadoc tags with no argument **/
private static final String MATCH_JAVADOC_NOARG_PAT =
"@(return|see)\\s+\\S";
/** compiled regexp to match Javadoc tags with no argument **/
private static final RE MATCH_JAVADOC_NOARG =
Utils.createRE(MATCH_JAVADOC_NOARG_PAT);
/**
* the pattern to match the first line of a multi-line Javadoc
* tag that takes no argument.
**/
private static final String MATCH_JAVADOC_NOARG_MULTILINE_START_PAT =
"@(return|see)\\s*$";
/** compiled regexp to match first part of multilineJavadoc tags **/
private static final RE MATCH_JAVADOC_NOARG_MULTILINE_START =
Utils.createRE(MATCH_JAVADOC_NOARG_MULTILINE_START_PAT);
/** the pattern to match Javadoc tags with no argument and {} **/
private static final String MATCH_JAVADOC_NOARG_CURLY_PAT =
"\\{\\s*@(inheritDoc)\\s*\\}";
/** compiled regexp to match Javadoc tags with no argument and {} **/
private static final RE MATCH_JAVADOC_NOARG_CURLY =
Utils.createRE(MATCH_JAVADOC_NOARG_CURLY_PAT);
/** the visibility scope where Javadoc comments are checked **/
private Scope mScope = Scope.PRIVATE;
/**
* controls whether to allow documented exceptions that
* are not declared if they are a subclass of
* java.lang.RuntimeException.
**/
private boolean mAllowUndeclaredRTE = false;
/**
* controls whether to allow documented exceptions that
* are subclass of one of declared exception.
* Defaults to false (backward compatibility).
**/
private boolean mAllowThrowsTagsForSubclasses = false;
/**
* controls whether to ignore errors when a method has parameters
* but does not have matching param tags in the javadoc.
* Defaults to false.
**/
private boolean mAllowMissingParamTags = false;
/**
* controls whether to ignore errors when a method declares that
* it throws exceptions but does not have matching throws tags
* in the javadoc. Defaults to false.
**/
private boolean mAllowMissingThrowsTags = false;
/**
* controls whether to ignore errors when a method returns
* non-void type but does not have a return tag in the javadoc.
* Defaults to false.
**/
private boolean mAllowMissingReturnTag = false;
/**
* Set the scope.
* @param aFrom a <code>String</code> value
*/
public void setScope(String aFrom)
{
mScope = Scope.getInstance(aFrom);
}
/**
* controls whether to allow documented exceptions that
* are not declared if they are a subclass of
* java.lang.RuntimeException.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowUndeclaredRTE(boolean aFlag)
{
mAllowUndeclaredRTE = aFlag;
}
/**
* controls whether to allow documented exception that
* are subclass of one of declared exceptions.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowThrowsTagsForSubclasses(boolean aFlag)
{
mAllowThrowsTagsForSubclasses = aFlag;
}
/**
* controls whether to allow a method which has parameters
* to omit matching param tags in the javadoc.
* Defaults to false.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingParamTags(boolean aFlag)
{
mAllowMissingParamTags = aFlag;
}
/**
* controls whether to allow a method which declares that
* it throws exceptions to omit matching throws tags
* in the javadoc. Defaults to false.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingThrowsTags(boolean aFlag)
{
mAllowMissingThrowsTags = aFlag;
}
/**
* controls whether to allow a method which returns
* non-void type to omit the return tag in the javadoc.
* Defaults to false.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingReturnTag(boolean aFlag)
{
mAllowMissingReturnTag = aFlag;
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getDefaultTokens()
{
return new int[] {
TokenTypes.PACKAGE_DEF,
TokenTypes.IMPORT,
TokenTypes.METHOD_DEF,
TokenTypes.CTOR_DEF,
};
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getAcceptableTokens()
{
return new int[] {
TokenTypes.METHOD_DEF,
TokenTypes.CTOR_DEF,
};
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getRequiredTokens()
{
return new int[] {
TokenTypes.PACKAGE_DEF,
TokenTypes.IMPORT,
};
}
/**
* Checks Javadoc comments for a method or constructor.
* @param aAST the tree node for the method or constructor.
*/
protected final void processAST(DetailAST aAST)
{
final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS);
final Scope declaredScope = ScopeUtils.getScopeFromMods(mods);
final Scope targetScope =
ScopeUtils.inInterfaceBlock(aAST)
? Scope.PUBLIC
: declaredScope;
if (targetScope.isIn(mScope)) {
final Scope surroundingScope =
ScopeUtils.getSurroundingScope(aAST);
if (surroundingScope.isIn(mScope)) {
final FileContents contents = getFileContents();
final String[] cmt =
contents.getJavadocBefore(aAST.getLineNo());
if (cmt == null) {
log(aAST.getLineNo(),
aAST.getColumnNo(),
"javadoc.missing");
}
else {
checkComment(aAST, cmt);
}
}
}
}
/**
* Checks the Javadoc for a method.
* @param aAST the token for the method
* @param aComment the Javadoc comment
*/
private void checkComment(DetailAST aAST, String[] aComment)
{
final List tags = getMethodTags(aComment, aAST.getLineNo() - 1);
// Check for only one @see tag
if ((tags.size() != 1)
|| !((JavadocTag) tags.get(0)).isSeeOrInheritDocTag())
{
checkParamTags(tags, getParameters(aAST));
checkThrowsTags(tags, getThrows(aAST));
if (isFunction(aAST)) {
checkReturnTag(tags, aAST.getLineNo());
}
// Dump out all unused tags
final Iterator it = tags.iterator();
while (it.hasNext()) {
final JavadocTag jt = (JavadocTag) it.next();
if (!jt.isSeeOrInheritDocTag()) {
log(jt.getLineNo(), "javadoc.unusedTagGeneral");
}
}
}
}
/**
* Returns the tags in a javadoc comment. Only finds throws, exception,
* param, return and see tags.
* @return the tags found
* @param aLines the Javadoc comment
* @param aLastLineNo the line number of the last line in the Javadoc
* comment
**/
private List getMethodTags(String[] aLines, int aLastLineNo)
{
final List tags = new ArrayList();
int currentLine = aLastLineNo - aLines.length;
for (int i = 0; i < aLines.length; i++) {
currentLine++;
if (MATCH_JAVADOC_ARG.match(aLines[i])) {
tags.add(new JavadocTag(currentLine,
MATCH_JAVADOC_ARG.getParen(1),
MATCH_JAVADOC_ARG.getParen(2)));
}
else if (MATCH_JAVADOC_NOARG.match(aLines[i])) {
tags.add(new JavadocTag(currentLine,
MATCH_JAVADOC_NOARG.getParen(1)));
}
else if (MATCH_JAVADOC_NOARG_CURLY.match(aLines[i])) {
tags.add(new JavadocTag(currentLine,
MATCH_JAVADOC_NOARG_CURLY.getParen(1)));
}
else if (MATCH_JAVADOC_ARG_MULTILINE_START.match(aLines[i])) {
final String p1 = MATCH_JAVADOC_ARG_MULTILINE_START.getParen(1);
final String p2 = MATCH_JAVADOC_ARG_MULTILINE_START.getParen(2);
// Look for the rest of the comment if all we saw was
// the tag and the name. Stop when we see '*/' (end of
// Javadoc, '@' (start of next tag), or anything that's
// not whitespace or '*' characters.
int remIndex = i + 1;
while (remIndex < aLines.length) {
if (MATCH_JAVADOC_MULTILINE_CONT.match(aLines[remIndex])) {
remIndex = aLines.length;
String lFin = MATCH_JAVADOC_MULTILINE_CONT.getParen(1);
if (!lFin.equals(NEXT_TAG)
&& !lFin.equals(END_JAVADOC))
{
tags.add(new JavadocTag(currentLine, p1, p2));
}
}
remIndex++;
}
}
else if (MATCH_JAVADOC_NOARG_MULTILINE_START.match(aLines[i])) {
final String p1 =
MATCH_JAVADOC_NOARG_MULTILINE_START.getParen(1);
// Look for the rest of the comment if all we saw was
// the tag and the name. Stop when we see '*/' (end of
// Javadoc, '@' (start of next tag), or anything that's
// not whitespace or '*' characters.
int remIndex = i + 1;
while (remIndex < aLines.length) {
if (MATCH_JAVADOC_MULTILINE_CONT.match(aLines[remIndex])) {
remIndex = aLines.length;
String lFin = MATCH_JAVADOC_MULTILINE_CONT.getParen(1);
if (!lFin.equals(NEXT_TAG)
&& !lFin.equals(END_JAVADOC))
{
tags.add(new JavadocTag(currentLine, p1));
}
}
remIndex++;
}
}
}
return tags;
}
/**
* Computes the parameter nodes for a method.
* @param aAST the method node.
* @return the list of parameter nodes for aAST.
**/
private List getParameters(DetailAST aAST)
{
final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS);
final List retVal = new ArrayList();
DetailAST child = (DetailAST) params.getFirstChild();
while (child != null) {
if (child.getType() == TokenTypes.PARAMETER_DEF) {
final DetailAST ident = child.findFirstToken(TokenTypes.IDENT);
retVal.add(ident);
}
child = (DetailAST) child.getNextSibling();
}
return retVal;
}
/**
* Computes the exception nodes for a method.
* @param aAST the method node.
* @return the list of exception nodes for aAST.
**/
private List getThrows(DetailAST aAST)
{
final List retVal = new ArrayList();
final DetailAST throwsAST =
aAST.findFirstToken(TokenTypes.LITERAL_THROWS);
if (throwsAST != null) {
DetailAST child = (DetailAST) throwsAST.getFirstChild();
while (child != null) {
if ((child.getType() == TokenTypes.IDENT)
|| (child.getType() == TokenTypes.DOT))
{
final ExceptionInfo ei =
new ExceptionInfo(FullIdent.createFullIdent(child));
retVal.add(ei);
}
child = (DetailAST) child.getNextSibling();
}
}
return retVal;
}
/**
* Checks a set of tags for matching parameters.
* @param aTags the tags to check
* @param aParams the list of parameters to check
**/
private void checkParamTags(List aTags, List aParams)
{
// Loop over the tags, checking to see they exist in the params.
final ListIterator tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = (JavadocTag) tagIt.next();
if (!tag.isParamTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching param
boolean found = false;
final Iterator paramIt = aParams.iterator();
while (paramIt.hasNext()) {
final DetailAST param = (DetailAST) paramIt.next();
if (param.getText().equals(tag.getArg1())) {
found = true;
paramIt.remove();
break;
}
}
// Handle extra JavadocTag
if (!found) {
log(tag.getLineNo(), "javadoc.unusedTag",
"@param", tag.getArg1());
}
}
// Now dump out all parameters without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingParamTags) {
final Iterator paramIt = aParams.iterator();
while (paramIt.hasNext()) {
final DetailAST param = (DetailAST) paramIt.next();
log(param.getLineNo(), param.getColumnNo(),
"javadoc.expectedTag", "@param", param.getText());
}
}
}
/**
* Checks whether a method is a function.
* @param aAST the method node.
* @return whether the method is a function.
**/
private boolean isFunction(DetailAST aAST)
{
boolean retVal = false;
if (aAST.getType() == TokenTypes.METHOD_DEF) {
final DetailAST typeAST = aAST.findFirstToken(TokenTypes.TYPE);
if ((typeAST != null)
&& (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) == null))
{
retVal = true;
}
}
return retVal;
}
/**
* Checks for only one return tag. All return tags will be removed from the
* supplied list.
* @param aTags the tags to check
* @param aLineNo the line number of the expected tag
**/
private void checkReturnTag(List aTags, int aLineNo)
{
// Loop over tags finding return tags. After the first one, report an
// error.
boolean found = false;
final ListIterator it = aTags.listIterator();
while (it.hasNext()) {
final JavadocTag jt = (JavadocTag) it.next();
if (jt.isReturnTag()) {
if (found) {
log(jt.getLineNo(), "javadoc.return.duplicate");
}
found = true;
it.remove();
}
}
// Handle there being no @return tags :- unless
// the user has chosen to suppress these problems
if (!found && !mAllowMissingReturnTag) {
log(aLineNo, "javadoc.return.expected");
}
}
/**
* Checks a set of tags for matching throws.
* @param aTags the tags to check
* @param aThrows the throws to check
**/
private void checkThrowsTags(List aTags, List aThrows)
{
// Loop over the tags, checking to see they exist in the throws.
final Set foundThrows = new HashSet(); //used for performance only
final ListIterator tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = (JavadocTag) tagIt.next();
if (!tag.isThrowsTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching throw
final String documentedEx = tag.getArg1();
boolean found = foundThrows.contains(documentedEx);
Class documentedClass = null;
boolean classLoaded = false;
final ListIterator throwIt = aThrows.listIterator();
while (!found && throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
final FullIdent fi = ei.getName();
final String declaredEx = fi.getText();
if (isSameType(declaredEx, documentedEx)) {
found = true;
ei.setFound();
foundThrows.add(documentedEx);
}
else if (mAllowThrowsTagsForSubclasses) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
found = isSubclass(documentedClass, ei.getClazz());
-// if (found) {
-// ei.setFound();
-// }
}
}
// Handle extra JavadocTag.
if (!found) {
boolean reqd = true;
if (mAllowUndeclaredRTE) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
reqd = !isUnchecked(documentedClass);
}
if (reqd) {
log(tag.getLineNo(), "javadoc.unusedTag",
"@throws", tag.getArg1());
}
}
}
// Now dump out all throws without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingThrowsTags) {
final ListIterator throwIt = aThrows.listIterator();
while (throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
if (!ei.isFound()) {
final FullIdent fi = ei.getName();
log(fi.getLineNo(), fi.getColumnNo(),
"javadoc.expectedTag", "@throws", fi.getText());
}
}
}
}
/**
* Tries to load class for throws tag. Logs error if unable.
* @param aTag name of class which we try to load.
* @return <code>Class</code> for the tag.
*/
private Class loadClassForTag(JavadocTag aTag)
{
Class clazz = resolveClass(aTag.getArg1());
if (clazz == null) {
log(aTag.getLineNo(), "javadoc.classInfo",
"@throws", aTag.getArg1());
}
return clazz;
}
/**
* Logs error if unable to load class information.
* @param aIdent class name for which we can no load class.
*/
protected final void logLoadError(FullIdent aIdent)
{
log(aIdent.getLineNo(), "javadoc.classInfo", "@throws",
aIdent.getText());
}
/** Stores useful information about declared exception. */
class ExceptionInfo extends ClassInfo
{
/** does the exception have throws tag associated with. */
private boolean mFound;
/**
* Creates new instance for <code>FullIdent</code>.
* @param aIdent <code>FullIdent</code> of the exception
*/
ExceptionInfo(FullIdent aIdent)
{
super(aIdent);
}
/** Mark that the exception has associated throws tag */
final void setFound()
{
mFound = true;
}
/** @return whether the exception has throws tag associated with */
final boolean isFound()
{
return mFound;
}
}
}
| true | true | private void checkThrowsTags(List aTags, List aThrows)
{
// Loop over the tags, checking to see they exist in the throws.
final Set foundThrows = new HashSet(); //used for performance only
final ListIterator tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = (JavadocTag) tagIt.next();
if (!tag.isThrowsTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching throw
final String documentedEx = tag.getArg1();
boolean found = foundThrows.contains(documentedEx);
Class documentedClass = null;
boolean classLoaded = false;
final ListIterator throwIt = aThrows.listIterator();
while (!found && throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
final FullIdent fi = ei.getName();
final String declaredEx = fi.getText();
if (isSameType(declaredEx, documentedEx)) {
found = true;
ei.setFound();
foundThrows.add(documentedEx);
}
else if (mAllowThrowsTagsForSubclasses) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
found = isSubclass(documentedClass, ei.getClazz());
// if (found) {
// ei.setFound();
// }
}
}
// Handle extra JavadocTag.
if (!found) {
boolean reqd = true;
if (mAllowUndeclaredRTE) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
reqd = !isUnchecked(documentedClass);
}
if (reqd) {
log(tag.getLineNo(), "javadoc.unusedTag",
"@throws", tag.getArg1());
}
}
}
// Now dump out all throws without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingThrowsTags) {
final ListIterator throwIt = aThrows.listIterator();
while (throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
if (!ei.isFound()) {
final FullIdent fi = ei.getName();
log(fi.getLineNo(), fi.getColumnNo(),
"javadoc.expectedTag", "@throws", fi.getText());
}
}
}
}
| private void checkThrowsTags(List aTags, List aThrows)
{
// Loop over the tags, checking to see they exist in the throws.
final Set foundThrows = new HashSet(); //used for performance only
final ListIterator tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = (JavadocTag) tagIt.next();
if (!tag.isThrowsTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching throw
final String documentedEx = tag.getArg1();
boolean found = foundThrows.contains(documentedEx);
Class documentedClass = null;
boolean classLoaded = false;
final ListIterator throwIt = aThrows.listIterator();
while (!found && throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
final FullIdent fi = ei.getName();
final String declaredEx = fi.getText();
if (isSameType(declaredEx, documentedEx)) {
found = true;
ei.setFound();
foundThrows.add(documentedEx);
}
else if (mAllowThrowsTagsForSubclasses) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
found = isSubclass(documentedClass, ei.getClazz());
}
}
// Handle extra JavadocTag.
if (!found) {
boolean reqd = true;
if (mAllowUndeclaredRTE) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
reqd = !isUnchecked(documentedClass);
}
if (reqd) {
log(tag.getLineNo(), "javadoc.unusedTag",
"@throws", tag.getArg1());
}
}
}
// Now dump out all throws without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingThrowsTags) {
final ListIterator throwIt = aThrows.listIterator();
while (throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
if (!ei.isFound()) {
final FullIdent fi = ei.getName();
log(fi.getLineNo(), fi.getColumnNo(),
"javadoc.expectedTag", "@throws", fi.getText());
}
}
}
}
|
diff --git a/amibe/src/org/jcae/mesh/bora/ds/BCADGraphCell.java b/amibe/src/org/jcae/mesh/bora/ds/BCADGraphCell.java
index 3f82127b..cb32f6dd 100644
--- a/amibe/src/org/jcae/mesh/bora/ds/BCADGraphCell.java
+++ b/amibe/src/org/jcae/mesh/bora/ds/BCADGraphCell.java
@@ -1,441 +1,441 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finite element mesher, Plugin architecture.
Copyright (C) 2006, by EADS CRC
Copyright (C) 2007,2009, by EADS France
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 org.jcae.mesh.bora.ds;
import org.jcae.mesh.cad.CADShape;
import org.jcae.mesh.cad.CADShapeFactory;
import org.jcae.mesh.cad.CADShapeEnum;
import org.jcae.mesh.cad.CADExplorer;
import org.jcae.mesh.cad.CADIterator;
import java.util.Collection;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Iterator;
import gnu.trove.THashSet;
import java.util.Collections;
/**
* Graph cell. This class is a decorator for the CAD graph.
*/
public class BCADGraphCell
{
/**
* Unique identifier.
*/
private int id = -1;
/**
* Link to root graph.
*/
private final BCADGraph graph;
/**
* CAD shape.
*/
private final CADShape shape;
/**
* CAD shape type.
*/
private final CADShapeEnum type;
/**
* Link to the reversed shape, if it does exist.
*/
private BCADGraphCell reversed;
/**
* List of parents.
*/
private final Collection<BCADGraphCell> parents = new LinkedHashSet<BCADGraphCell>();
/**
* List of discretizations.
*/
private Collection<BDiscretization> discrete = new ArrayList<BDiscretization>();
/**
* Constructor.
* @param g graph cell
* @param s CAD shape contained in this cell
* @param t CAD shape type
*/
protected BCADGraphCell (BCADGraph g, CADShape s, CADShapeEnum t)
{
graph = g;
shape = s;
type = t;
}
/**
* Returns cell id.
* @return cell id
*/
public int getId()
{
return id;
}
/**
* Sets cell id.
* @param i cell id
*/
public void setId(int i)
{
id = i;
}
/**
* Returns CAD graph.
* @return CAD graph
*/
public BCADGraph getGraph()
{
return graph;
}
/**
* Returns CAD shape.
* @return CAD shape
*/
public CADShape getShape()
{
return shape;
}
/**
* Returns shape orientation.
* @return shape orientation
*/
public int getOrientation()
{
return shape.orientation();
}
/**
* Returns cell containing reversed shape.
* @return cell containing reversed shape
*/
public BCADGraphCell getReversed()
{
return reversed;
}
/**
* Returns CAD shape type.
* @return CAD shape type
*/
public CADShapeEnum getType()
{
return type;
}
public Collection<BCADGraphCell> getParents()
{
return Collections.unmodifiableCollection(parents);
}
protected void addParent(BCADGraphCell that)
{
assert that != null;
parents.add(that);
}
/**
* Binds two cells containing reversed shapes together. These shapes then
* contain the same discretizations.
*/
protected void bindReversed(BCADGraphCell that)
{
assert shape.equals(that.shape);
assert shape.orientation() != that.shape.orientation();
reversed = that;
that.reversed = this;
if (shape.orientation() != 0)
discrete = that.discrete;
else
that.discrete = discrete;
}
/**
* Returns an iterator on geometrical elements of a given type.
* CAD graph is traversed recursively and geometrical elements of
* a given type are returned. There are no duplicates, but shapes
* with different orientations may both be listed.
*
* @param cse CAD shape type
* @return iterator on geometrical elements.
*/
public Iterator<BCADGraphCell> shapesExplorer(CADShapeEnum cse)
{
return shapesExplorer(cse, new THashSet<CADShape>(KeepOrientationHashingStrategy.getInstance()));
}
/**
* Returns an iterator on unique geometrical elements.
* CAD graph is traversed recursively and geometrical elements of a
* given type are returned. There are no duplicates, shapes with
* different orientations are listed only once.
*
* @param cse CAD shape type
* @return iterator on unique geometrical elements.
*/
public Iterator<BCADGraphCell> uniqueShapesExplorer(CADShapeEnum cse)
{
return shapesExplorer(cse, new THashSet<CADShape>());
}
/**
* Returns an iterator on all geometrical elements of a given type.
* CAD graph is traversed recursively and geometrical elements of a
* given type are returned, even if they have already been seen.
*
* @param cse CAD shape type
* @return iterator on all geometrical elements.
*/
public Iterator<BCADGraphCell> allShapesExplorer(CADShapeEnum cse)
{
return shapesExplorer(cse, null);
}
private Iterator<BCADGraphCell> shapesExplorer(final CADShapeEnum cse, final Collection<CADShape> cadShapeSet)
{
final CADExplorer exp = CADShapeFactory.getFactory().newExplorer();
exp.init(shape, cse);
return new Iterator<BCADGraphCell>()
{
public boolean hasNext()
{
return exp.more();
}
public BCADGraphCell next()
{
CADShape curr = exp.current();
BCADGraphCell ret = graph.getByShape(curr);
if (cadShapeSet == null)
{
if (exp.more())
exp.next();
}
else
{
cadShapeSet.add(curr);
while (exp.more())
{
if (!cadShapeSet.contains(exp.current()))
break;
exp.next();
}
}
return ret;
}
public void remove()
{
}
};
}
/**
* Returns an iterator on immediate sub-shapes.
* There are no duplicates, but shapes with different orientations may
* both be listed.
*
* @return an iterator on immediate sub-shapes
*/
public Iterator<BCADGraphCell> shapesIterator()
{
return shapesIterator(new THashSet<CADShape>(KeepOrientationHashingStrategy.getInstance()));
}
/**
* Returns an iterator on immediate sub-shapes.
* There are no duplicates, shapes with different orientations are
* listed only once.
*
* @return an iterator on immediate sub-shapes
*/
public Iterator<BCADGraphCell> uniqueShapesIterator()
{
return shapesIterator(new THashSet<CADShape>());
}
/**
* Returns an iterator on all immediate sub-shapes.
*
* @return an iterator on all immediate sub-shapes
*/
public Iterator<BCADGraphCell> allShapesIterator()
{
return shapesIterator(null);
}
private Iterator<BCADGraphCell> shapesIterator(final Collection<CADShape> cadShapeSet)
{
final CADIterator it = CADShapeFactory.getFactory().newIterator();
it.initialize(shape);
return new Iterator<BCADGraphCell>()
{
public boolean hasNext()
{
return it.more();
}
public BCADGraphCell next()
{
CADShape curr = it.value();
BCADGraphCell ret = graph.getByShape(curr);
if (cadShapeSet == null)
{
if (it.more())
it.next();
}
else
{
cadShapeSet.add(curr);
while (it.more())
{
if (!cadShapeSet.contains(it.value()))
break;
it.next();
}
}
return ret;
}
public void remove()
{
}
};
}
/**
* Returns the BDiscretization instance corresponding to a given submesh.
*
* @param sub submesh
* @return the discretization corresponding to a given submesh.
*/
public BDiscretization getDiscretizationSubMesh(BSubMesh sub)
{
for (BDiscretization discr : discrete)
{
if (discr.contains(sub))
return discr;
}
return null;
}
protected void addSubMeshConstraint(BSubMesh sub, Constraint cons)
{
BDiscretization d = getDiscretizationSubMesh(sub);
if (d != null)
throw new RuntimeException("Constraint "+cons+" cannot be applied to shape "+shape+", another constraint "+d.getConstraint()+" is already defined");
BDiscretization found = null;
for (BDiscretization discr : discrete)
{
if (discr.getConstraint() == cons)
{
found = discr;
break;
}
}
if (found == null)
{
found = new BDiscretization(this, cons);
discrete.add(found);
}
found.addSubMesh(sub);
}
/**
* Returns an immutable view of the list of BDiscretization instances bound to this cell.
*/
public Collection<BDiscretization> getDiscretizations()
{
return Collections.unmodifiableCollection(discrete);
}
protected void addImplicitConstraints(CADShapeEnum cse, boolean recursive)
{
for (BDiscretization discr : discrete)
{
Iterator<BCADGraphCell> itc;
if (recursive)
itc = shapesExplorer(cse);
else
itc = shapesIterator();
while (itc.hasNext())
{
BCADGraphCell child = itc.next();
if (!recursive && child.getType() != cse)
continue;
boolean allIntersectionsEmpty = false;
BDiscretization discrChild = null;
for (BDiscretization dc : child.discrete)
{
- if (!discr.emptyIntersection(discrChild))
+ if (!discr.emptyIntersection(dc))
{
discrChild = dc;
break;
}
}
if (discrChild == null)
{
discrChild = new BDiscretization(child, null);
child.discrete.add(discrChild);
allIntersectionsEmpty = true;
}
discrChild.combineConstraint(discr);
discrChild.addAllSubMeshes(discr);
/*
* We want to ensure that in each BCADGraphCell, the intersection of
* the submeshes list for any two different BDiscretization is void.
*
* If a new BDiscretization has been created, there is no need to
* perform an additionnal test to enforce this.
* But if we had an intersection between the submesh list of discr and
* the one of discrChild, we have to check if the combined BDiscretization
* has an intersection with other child BDiscretization.
* The other child BDiscretization that intersect discrChild has to be removed
* after combination with discrChild.
*/
if (!allIntersectionsEmpty)
{
for (Iterator<BDiscretization> itd = child.discrete.iterator(); itd.hasNext(); )
{
BDiscretization otherDiscrChild = itd.next();
if ((otherDiscrChild != discrChild) &&
(!discrChild.emptyIntersection(otherDiscrChild)))
{
discrChild.combineConstraint(otherDiscrChild);
discrChild.addAllSubMeshes(otherDiscrChild);
itd.remove();
}
}
}
}
}
}
@Override
public String toString()
{
String ret = id+" "+shape+" "+shape.orientation()+" "+Integer.toHexString(hashCode());
if (reversed != null)
ret += " rev="+Integer.toHexString(reversed.hashCode());
return ret;
}
}
| true | true | protected void addImplicitConstraints(CADShapeEnum cse, boolean recursive)
{
for (BDiscretization discr : discrete)
{
Iterator<BCADGraphCell> itc;
if (recursive)
itc = shapesExplorer(cse);
else
itc = shapesIterator();
while (itc.hasNext())
{
BCADGraphCell child = itc.next();
if (!recursive && child.getType() != cse)
continue;
boolean allIntersectionsEmpty = false;
BDiscretization discrChild = null;
for (BDiscretization dc : child.discrete)
{
if (!discr.emptyIntersection(discrChild))
{
discrChild = dc;
break;
}
}
if (discrChild == null)
{
discrChild = new BDiscretization(child, null);
child.discrete.add(discrChild);
allIntersectionsEmpty = true;
}
discrChild.combineConstraint(discr);
discrChild.addAllSubMeshes(discr);
/*
* We want to ensure that in each BCADGraphCell, the intersection of
* the submeshes list for any two different BDiscretization is void.
*
* If a new BDiscretization has been created, there is no need to
* perform an additionnal test to enforce this.
* But if we had an intersection between the submesh list of discr and
* the one of discrChild, we have to check if the combined BDiscretization
* has an intersection with other child BDiscretization.
* The other child BDiscretization that intersect discrChild has to be removed
* after combination with discrChild.
*/
if (!allIntersectionsEmpty)
{
for (Iterator<BDiscretization> itd = child.discrete.iterator(); itd.hasNext(); )
{
BDiscretization otherDiscrChild = itd.next();
if ((otherDiscrChild != discrChild) &&
(!discrChild.emptyIntersection(otherDiscrChild)))
{
discrChild.combineConstraint(otherDiscrChild);
discrChild.addAllSubMeshes(otherDiscrChild);
itd.remove();
}
}
}
}
}
}
| protected void addImplicitConstraints(CADShapeEnum cse, boolean recursive)
{
for (BDiscretization discr : discrete)
{
Iterator<BCADGraphCell> itc;
if (recursive)
itc = shapesExplorer(cse);
else
itc = shapesIterator();
while (itc.hasNext())
{
BCADGraphCell child = itc.next();
if (!recursive && child.getType() != cse)
continue;
boolean allIntersectionsEmpty = false;
BDiscretization discrChild = null;
for (BDiscretization dc : child.discrete)
{
if (!discr.emptyIntersection(dc))
{
discrChild = dc;
break;
}
}
if (discrChild == null)
{
discrChild = new BDiscretization(child, null);
child.discrete.add(discrChild);
allIntersectionsEmpty = true;
}
discrChild.combineConstraint(discr);
discrChild.addAllSubMeshes(discr);
/*
* We want to ensure that in each BCADGraphCell, the intersection of
* the submeshes list for any two different BDiscretization is void.
*
* If a new BDiscretization has been created, there is no need to
* perform an additionnal test to enforce this.
* But if we had an intersection between the submesh list of discr and
* the one of discrChild, we have to check if the combined BDiscretization
* has an intersection with other child BDiscretization.
* The other child BDiscretization that intersect discrChild has to be removed
* after combination with discrChild.
*/
if (!allIntersectionsEmpty)
{
for (Iterator<BDiscretization> itd = child.discrete.iterator(); itd.hasNext(); )
{
BDiscretization otherDiscrChild = itd.next();
if ((otherDiscrChild != discrChild) &&
(!discrChild.emptyIntersection(otherDiscrChild)))
{
discrChild.combineConstraint(otherDiscrChild);
discrChild.addAllSubMeshes(otherDiscrChild);
itd.remove();
}
}
}
}
}
}
|
diff --git a/src/main/java/org/mozilla/gecko/sync/syncadapter/SyncAdapter.java b/src/main/java/org/mozilla/gecko/sync/syncadapter/SyncAdapter.java
index 91f8d8cab..4107a2615 100644
--- a/src/main/java/org/mozilla/gecko/sync/syncadapter/SyncAdapter.java
+++ b/src/main/java/org/mozilla/gecko/sync/syncadapter/SyncAdapter.java
@@ -1,331 +1,331 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 Android Sync Client.
*
* The Initial Developer of the Original Code is
* the Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Chenxia Liu <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.gecko.sync.syncadapter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
import org.mozilla.android.sync.crypto.KeyBundle;
import org.mozilla.gecko.sync.AlreadySyncingException;
import org.mozilla.gecko.sync.GlobalSession;
import org.mozilla.gecko.sync.SyncConfiguration;
import org.mozilla.gecko.sync.SyncConfigurationException;
import org.mozilla.gecko.sync.SyncException;
import org.mozilla.gecko.sync.delegates.GlobalSessionCallback;
import org.mozilla.gecko.sync.setup.Constants;
import org.mozilla.gecko.sync.stage.GlobalSyncStage.Stage;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
public class SyncAdapter extends AbstractThreadedSyncAdapter implements GlobalSessionCallback {
private static final String LOG_TAG = "SyncAdapter";
private final AccountManager mAccountManager;
private final Context mContext;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
mAccountManager = AccountManager.get(context);
}
private void handleException(Exception e, SyncResult syncResult) {
if (e instanceof OperationCanceledException) {
Log.e(LOG_TAG, "Operation canceled. Aborting sync.");
e.printStackTrace();
return;
}
if (e instanceof AuthenticatorException) {
syncResult.stats.numParseExceptions++;
Log.e(LOG_TAG, "AuthenticatorException. Aborting sync.");
e.printStackTrace();
return;
}
if (e instanceof IOException) {
syncResult.stats.numIoExceptions++;
Log.e(LOG_TAG, "IOException. Aborting sync.");
e.printStackTrace();
return;
}
syncResult.stats.numIoExceptions++;
Log.e(LOG_TAG, "Unknown exception. Aborting sync.");
e.printStackTrace();
}
private AccountManagerFuture<Bundle> getAuthToken(final Account account,
AccountManagerCallback<Bundle> callback,
Handler handler) {
return mAccountManager.getAuthToken(account, Constants.AUTHTOKEN_TYPE_PLAIN, true, callback, handler);
}
private void invalidateAuthToken(Account account) {
AccountManagerFuture<Bundle> future = getAuthToken(account, null, null);
String token;
try {
token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
mAccountManager.invalidateAuthToken(Constants.ACCOUNTTYPE_SYNC, token);
} catch (Exception e) {
Log.e(LOG_TAG, "Couldn't invalidate auth token: " + e);
}
}
@Override
public void onSyncCanceled() {
super.onSyncCanceled();
// TODO: cancel the sync!
// From the docs: "This will be invoked on a separate thread than the sync
// thread and so you must consider the multi-threaded implications of the
// work that you do in this method."
}
public Object syncMonitor = new Object();
private SyncResult syncResult;
@Override
public void onPerformSync(final Account account,
final Bundle extras,
final String authority,
final ContentProviderClient provider,
final SyncResult syncResult) {
Log.i(LOG_TAG, "Got onPerformSync:");
Log.i(LOG_TAG, "Account name: " + account.name);
- Log.i("rnewman", "XXX CLEARING AUTH TOKEN XXX");
+ Log.i(LOG_TAG, "XXX CLEARING AUTH TOKEN XXX");
invalidateAuthToken(account);
final SyncAdapter self = this;
AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
Log.i(LOG_TAG, "AccountManagerCallback invoked.");
// TODO: N.B.: Future must not be used on the main thread.
try {
Bundle bundle = future.getResult(60L, TimeUnit.SECONDS);
String username = bundle.getString(Constants.OPTION_USERNAME);
String syncKey = bundle.getString(Constants.OPTION_SYNCKEY);
String password = bundle.getString(AccountManager.KEY_AUTHTOKEN);
if (password == null) {
Log.e(LOG_TAG, "No password: aborting sync.");
return;
}
if (syncKey == null) {
Log.e(LOG_TAG, "No Sync Key: aborting sync.");
return;
}
KeyBundle keyBundle = new KeyBundle(username, syncKey);
self.performSync(account, extras, authority, provider,
syncResult, username, password, keyBundle);
} catch (Exception e) {
self.handleException(e, syncResult);
return;
}
}
};
Handler handler = null;
getAuthToken(account, callback, handler);
synchronized (syncMonitor) {
try {
Log.i(LOG_TAG, "Waiting on sync monitor.");
syncMonitor.wait();
} catch (InterruptedException e) {
Log.i(LOG_TAG, "Waiting on sync monitor interrupted.", e);
}
}
}
/**
* Now that we have a sync key and password, go ahead and do the work.
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
* @throws IllegalArgumentException
* @throws SyncConfigurationException
* @throws AlreadySyncingException
*/
protected void performSync(Account account, Bundle extras, String authority,
ContentProviderClient provider,
SyncResult syncResult,
String username, String password,
KeyBundle keyBundle) throws NoSuchAlgorithmException, UnsupportedEncodingException, SyncConfigurationException, IllegalArgumentException, AlreadySyncingException {
Log.i(LOG_TAG, "Performing sync.");
this.syncResult = syncResult;
String clusterURL = "https://phx-sync545.services.mozilla.com/";
GlobalSession globalSession = new GlobalSession(SyncConfiguration.DEFAULT_USER_API,
clusterURL, username, password, keyBundle,
this, this.mContext);
globalSession.start();
}
private void notifyMonitor() {
synchronized (syncMonitor) {
Log.i(LOG_TAG, "Notifying sync monitor.");
syncMonitor.notify();
}
}
// Implementing GlobalSession callbacks.
@Override
public void handleError(GlobalSession globalSession, Exception ex) {
Log.i(LOG_TAG, "GlobalSession indicated error.");
this.updateStats(globalSession, ex);
notifyMonitor();
}
/**
* Introspect the exception, incrementing the appropriate stat counters.
* TODO: increment number of inserts, deletes, conflicts.
*
* @param globalSession
* @param ex
*/
private void updateStats(GlobalSession globalSession,
Exception ex) {
if (ex instanceof SyncException) {
((SyncException) ex).updateStats(globalSession, syncResult);
}
// TODO: non-SyncExceptions.
// TODO: wouldn't it be nice to update stats for *every* exception we get?
}
@Override
public void handleSuccess(GlobalSession globalSession) {
Log.i(LOG_TAG, "GlobalSession indicated success.");
notifyMonitor();
}
@Override
public void handleStageCompleted(Stage currentState,
GlobalSession globalSession) {
Log.i(LOG_TAG, "Stage completed: " + currentState);
}
}
// try {
// // see if we already have a sync-state attached to this account. By handing
// // This value to the server, we can just get the contacts that have
// // been updated on the server-side since our last sync-up
// long lastSyncMarker = getServerSyncMarker(account);
//
// // By default, contacts from a 3rd party provider are hidden in the contacts
// // list. So let's set the flag that causes them to be visible, so that users
// // can actually see these contacts.
// if (lastSyncMarker == 0) {
// ContactManager.setAccountContactsVisibility(getContext(), account, true);
// }
//
// List<RawContact> dirtyContacts;
// List<RawContact> updatedContacts;
//
// // Use the account manager to request the AuthToken we'll need
// // to talk to our sample server. If we don't have an AuthToken
// // yet, this could involve a round-trip to the server to request
// // and AuthToken.
// final String authtoken = mAccountManager.blockingGetAuthToken(account,
// Constants.AUTHTOKEN_TYPE, NOTIFY_AUTH_FAILURE);
//
// // Make sure that the sample group exists
// final long groupId = ContactManager.ensureSampleGroupExists(mContext, account);
//
// // Find the local 'dirty' contacts that we need to tell the server about...
// // Find the local users that need to be sync'd to the server...
// dirtyContacts = ContactManager.getDirtyContacts(mContext, account);
//
// // Send the dirty contacts to the server, and retrieve the server-side changes
// updatedContacts = NetworkUtilities.syncContacts(account, authtoken,
// lastSyncMarker, dirtyContacts);
//
// // Update the local contacts database with the changes. updateContacts()
// // returns a syncState value that indicates the high-water-mark for
// // the changes we received.
// Log.d(TAG, "Calling contactManager's sync contacts");
// long newSyncState = ContactManager.updateContacts(mContext,
// account.name,
// updatedContacts,
// groupId,
// lastSyncMarker);
//
// // This is a demo of how you can update IM-style status messages
// // for contacts on the client. This probably won't apply to
// // 2-way contact sync providers - it's more likely that one-way
// // sync providers (IM clients, social networking apps, etc) would
// // use this feature.
// ContactManager.updateStatusMessages(mContext, updatedContacts);
//
// // Save off the new sync marker. On our next sync, we only want to receive
// // contacts that have changed since this sync...
// setServerSyncMarker(account, newSyncState);
//
// if (dirtyContacts.size() > 0) {
// ContactManager.clearSyncFlags(mContext, dirtyContacts);
// }
//
// } catch (final AuthenticatorException e) {
// Log.e(TAG, "AuthenticatorException", e);
// syncResult.stats.numParseExceptions++;
// } catch (final OperationCanceledException e) {
// Log.e(TAG, "OperationCanceledExcetpion", e);
// } catch (final IOException e) {
// Log.e(TAG, "IOException", e);
// syncResult.stats.numIoExceptions++;
// } catch (final AuthenticationException e) {
// Log.e(TAG, "AuthenticationException", e);
// syncResult.stats.numAuthExceptions++;
// } catch (final ParseException e) {
// Log.e(TAG, "ParseException", e);
// syncResult.stats.numParseExceptions++;
// } catch (final JSONException e) {
// Log.e(TAG, "JSONException", e);
// syncResult.stats.numParseExceptions++;
// }
| true | true | public void onPerformSync(final Account account,
final Bundle extras,
final String authority,
final ContentProviderClient provider,
final SyncResult syncResult) {
Log.i(LOG_TAG, "Got onPerformSync:");
Log.i(LOG_TAG, "Account name: " + account.name);
Log.i("rnewman", "XXX CLEARING AUTH TOKEN XXX");
invalidateAuthToken(account);
final SyncAdapter self = this;
AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
Log.i(LOG_TAG, "AccountManagerCallback invoked.");
// TODO: N.B.: Future must not be used on the main thread.
try {
Bundle bundle = future.getResult(60L, TimeUnit.SECONDS);
String username = bundle.getString(Constants.OPTION_USERNAME);
String syncKey = bundle.getString(Constants.OPTION_SYNCKEY);
String password = bundle.getString(AccountManager.KEY_AUTHTOKEN);
if (password == null) {
Log.e(LOG_TAG, "No password: aborting sync.");
return;
}
if (syncKey == null) {
Log.e(LOG_TAG, "No Sync Key: aborting sync.");
return;
}
KeyBundle keyBundle = new KeyBundle(username, syncKey);
self.performSync(account, extras, authority, provider,
syncResult, username, password, keyBundle);
} catch (Exception e) {
self.handleException(e, syncResult);
return;
}
}
};
Handler handler = null;
getAuthToken(account, callback, handler);
synchronized (syncMonitor) {
try {
Log.i(LOG_TAG, "Waiting on sync monitor.");
syncMonitor.wait();
} catch (InterruptedException e) {
Log.i(LOG_TAG, "Waiting on sync monitor interrupted.", e);
}
}
}
| public void onPerformSync(final Account account,
final Bundle extras,
final String authority,
final ContentProviderClient provider,
final SyncResult syncResult) {
Log.i(LOG_TAG, "Got onPerformSync:");
Log.i(LOG_TAG, "Account name: " + account.name);
Log.i(LOG_TAG, "XXX CLEARING AUTH TOKEN XXX");
invalidateAuthToken(account);
final SyncAdapter self = this;
AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
Log.i(LOG_TAG, "AccountManagerCallback invoked.");
// TODO: N.B.: Future must not be used on the main thread.
try {
Bundle bundle = future.getResult(60L, TimeUnit.SECONDS);
String username = bundle.getString(Constants.OPTION_USERNAME);
String syncKey = bundle.getString(Constants.OPTION_SYNCKEY);
String password = bundle.getString(AccountManager.KEY_AUTHTOKEN);
if (password == null) {
Log.e(LOG_TAG, "No password: aborting sync.");
return;
}
if (syncKey == null) {
Log.e(LOG_TAG, "No Sync Key: aborting sync.");
return;
}
KeyBundle keyBundle = new KeyBundle(username, syncKey);
self.performSync(account, extras, authority, provider,
syncResult, username, password, keyBundle);
} catch (Exception e) {
self.handleException(e, syncResult);
return;
}
}
};
Handler handler = null;
getAuthToken(account, callback, handler);
synchronized (syncMonitor) {
try {
Log.i(LOG_TAG, "Waiting on sync monitor.");
syncMonitor.wait();
} catch (InterruptedException e) {
Log.i(LOG_TAG, "Waiting on sync monitor interrupted.", e);
}
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/farmables/plantables/PlantableStandard.java b/src/powercrystals/minefactoryreloaded/farmables/plantables/PlantableStandard.java
index a4522970..2199cd7e 100644
--- a/src/powercrystals/minefactoryreloaded/farmables/plantables/PlantableStandard.java
+++ b/src/powercrystals/minefactoryreloaded/farmables/plantables/PlantableStandard.java
@@ -1,78 +1,78 @@
package powercrystals.minefactoryreloaded.farmables.plantables;
import powercrystals.minefactoryreloaded.api.IFactoryPlantable;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.IPlantable;
/*
* Used for directly placing blocks (ie saplings) and items (ie sugarcane). Pass in source ID to constructor,
* so one instance per source ID.
*/
public class PlantableStandard implements IFactoryPlantable
{
protected int _sourceId;
protected int _plantedBlockId;
public PlantableStandard(int sourceId, int plantedBlockId)
{
if(plantedBlockId >= Block.blocksList.length)
{
throw new IllegalArgumentException("Passed an Item ID to FactoryPlantableStandard's planted block argument");
}
this._sourceId = sourceId;
this._plantedBlockId = plantedBlockId;
}
@Override
public boolean canBePlantedHere(World world, int x, int y, int z, ItemStack stack)
{
int groundId = world.getBlockId(x, y - 1, z);
if(!world.isAirBlock(x, y, z))
{
return false;
}
return
Block.blocksList[_plantedBlockId].canPlaceBlockAt(world, x, y, z) ||
- (Block.blocksList[_plantedBlockId] instanceof IPlantable &&
+ (Block.blocksList[_plantedBlockId] instanceof IPlantable && Block.blocksList[groundId] != null &&
Block.blocksList[groundId].canSustainPlant(world, x, y, z, ForgeDirection.UP, ((IPlantable)Block.blocksList[_plantedBlockId])));
}
@Override
public void prePlant(World world, int x, int y, int z, ItemStack stack)
{
return;
}
@Override
public void postPlant(World world, int x, int y, int z, ItemStack stack)
{
return;
}
@Override
public int getPlantedBlockId(World world, int x, int y, int z, ItemStack stack)
{
if(stack.itemID != _sourceId)
{
return -1;
}
return _plantedBlockId;
}
@Override
public int getPlantedBlockMetadata(World world, int x, int y, int z, ItemStack stack)
{
return stack.getItemDamage();
}
@Override
public int getSourceId()
{
return _sourceId;
}
}
| true | true | public boolean canBePlantedHere(World world, int x, int y, int z, ItemStack stack)
{
int groundId = world.getBlockId(x, y - 1, z);
if(!world.isAirBlock(x, y, z))
{
return false;
}
return
Block.blocksList[_plantedBlockId].canPlaceBlockAt(world, x, y, z) ||
(Block.blocksList[_plantedBlockId] instanceof IPlantable &&
Block.blocksList[groundId].canSustainPlant(world, x, y, z, ForgeDirection.UP, ((IPlantable)Block.blocksList[_plantedBlockId])));
}
| public boolean canBePlantedHere(World world, int x, int y, int z, ItemStack stack)
{
int groundId = world.getBlockId(x, y - 1, z);
if(!world.isAirBlock(x, y, z))
{
return false;
}
return
Block.blocksList[_plantedBlockId].canPlaceBlockAt(world, x, y, z) ||
(Block.blocksList[_plantedBlockId] instanceof IPlantable && Block.blocksList[groundId] != null &&
Block.blocksList[groundId].canSustainPlant(world, x, y, z, ForgeDirection.UP, ((IPlantable)Block.blocksList[_plantedBlockId])));
}
|
diff --git a/src/main/java/org/mobicents/tools/http/balancer/HttpRequestHandler.java b/src/main/java/org/mobicents/tools/http/balancer/HttpRequestHandler.java
index 01a8e85..83a34a5 100644
--- a/src/main/java/org/mobicents/tools/http/balancer/HttpRequestHandler.java
+++ b/src/main/java/org/mobicents/tools/http/balancer/HttpRequestHandler.java
@@ -1,209 +1,209 @@
/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat 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.mobicents.tools.http.balancer;
import java.net.InetSocketAddress;
import java.util.Enumeration;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.Cookie;
import org.jboss.netty.handler.codec.http.CookieDecoder;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.mobicents.tools.sip.balancer.BalancerContext;
import org.mobicents.tools.sip.balancer.SIPNode;
/**
* @author Vladimir Ralev ([email protected])
*
*/
@ChannelPipelineCoverage("one")
public class HttpRequestHandler extends SimpleChannelUpstreamHandler {
private static final Logger logger = Logger.getLogger(HttpRequestHandler.class.getCanonicalName());
private volatile HttpRequest request;
private volatile boolean readingChunks;
@Override
public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
if (!readingChunks) {
request = (HttpRequest) e.getMessage();
if(logger.isLoggable(Level.FINE)) {
logger.fine("Request URI accessed: " + request.getUri() + " channel " + e.getChannel());
}
Channel associatedChannel = HttpChannelAssocialtions.channels.get(e.getChannel());
SIPNode node = null;
try {
- BalancerContext.balancerContext.balancerAlgorithm.processHttpRequest(request);
+ node = BalancerContext.balancerContext.balancerAlgorithm.processHttpRequest(request);
} catch (Exception ex) {
writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Mobicents Load Balancer Error: Exception in the balancer algorithm: " + ex.getMessage());
return;
}
if(node == null) {
writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Mobicents Load Balancer Error: All nodes are Dead!");
return;
}
if(node.getHttpPort() == 0) {
node.setHttpPort(node.getPort() + 3000);
}
if(associatedChannel != null && associatedChannel.isConnected()) {
associatedChannel.write(request);
} else {
e.getChannel().getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
// Start the connection attempt.
ChannelFuture future = HttpChannelAssocialtions.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), node.getHttpPort()));
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
Channel channel = arg0.getChannel();
HttpChannelAssocialtions.channels.put(e.getChannel(), channel);
HttpChannelAssocialtions.channels.put(channel, e.getChannel());
if (request.isChunked()) {
readingChunks = true;
}
channel.write(request);
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
}
});
}
} else {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
readingChunks = false;
}
HttpChannelAssocialtions.channels.get(e.getChannel()).write(chunk);
}
}
private void closeChannelPair(Channel channel) {
Channel associatedChannel = HttpChannelAssocialtions.channels.get(channel);
if(associatedChannel != null) {
try {
HttpChannelAssocialtions.channels.remove(associatedChannel);
if(!associatedChannel.isConnected()) {
associatedChannel.disconnect();
associatedChannel.close();
}
associatedChannel = null;
} catch (Exception e) {
}
}
HttpChannelAssocialtions.channels.remove(channel);
logger.info("Channel closed. Channels remaining: " + HttpChannelAssocialtions.channels.size());
if(logger.isLoggable(Level.FINE)) {
try {
logger.fine("Channel closed " + HttpChannelAssocialtions.channels.size() + " " + channel);
Enumeration<Channel> c = HttpChannelAssocialtions.channels.keys();
while(c.hasMoreElements()) {
logger.fine(c.nextElement().toString());
}
} catch (Exception e) {
logger.log(Level.FINE, "error", e);
}
}
}
private void writeResponse(MessageEvent e, HttpResponseStatus status, String responseString) {
// Convert the response content to a ChannelBuffer.
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseString, "UTF-8");
// Decide whether to close the connection or not.
boolean close =
HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION)) ||
request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) &&
!HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION));
// Build the response object.
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
response.setContent(buf);
response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
if (!close) {
// There's no need to add 'Content-Length' header
// if this is the last response.
response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes()));
}
String cookieString = request.getHeader(HttpHeaders.Names.COOKIE);
if (cookieString != null) {
CookieDecoder cookieDecoder = new CookieDecoder();
Set<Cookie> cookies = cookieDecoder.decode(cookieString);
if(!cookies.isEmpty()) {
// Reset the cookies if necessary.
CookieEncoder cookieEncoder = new CookieEncoder(true);
for (Cookie cookie : cookies) {
cookieEncoder.addCookie(cookie);
}
response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode());
}
}
// Write the response.
ChannelFuture future = e.getChannel().write(response);
// Close the connection after the write operation is done if necessary.
if (close) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
logger.log(Level.SEVERE, "Error", e.getCause());
e.getChannel().close();
}
}
| true | true | public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
if (!readingChunks) {
request = (HttpRequest) e.getMessage();
if(logger.isLoggable(Level.FINE)) {
logger.fine("Request URI accessed: " + request.getUri() + " channel " + e.getChannel());
}
Channel associatedChannel = HttpChannelAssocialtions.channels.get(e.getChannel());
SIPNode node = null;
try {
BalancerContext.balancerContext.balancerAlgorithm.processHttpRequest(request);
} catch (Exception ex) {
writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Mobicents Load Balancer Error: Exception in the balancer algorithm: " + ex.getMessage());
return;
}
if(node == null) {
writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Mobicents Load Balancer Error: All nodes are Dead!");
return;
}
if(node.getHttpPort() == 0) {
node.setHttpPort(node.getPort() + 3000);
}
if(associatedChannel != null && associatedChannel.isConnected()) {
associatedChannel.write(request);
} else {
e.getChannel().getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
// Start the connection attempt.
ChannelFuture future = HttpChannelAssocialtions.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), node.getHttpPort()));
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
Channel channel = arg0.getChannel();
HttpChannelAssocialtions.channels.put(e.getChannel(), channel);
HttpChannelAssocialtions.channels.put(channel, e.getChannel());
if (request.isChunked()) {
readingChunks = true;
}
channel.write(request);
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
}
});
}
} else {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
readingChunks = false;
}
HttpChannelAssocialtions.channels.get(e.getChannel()).write(chunk);
}
}
| public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
if (!readingChunks) {
request = (HttpRequest) e.getMessage();
if(logger.isLoggable(Level.FINE)) {
logger.fine("Request URI accessed: " + request.getUri() + " channel " + e.getChannel());
}
Channel associatedChannel = HttpChannelAssocialtions.channels.get(e.getChannel());
SIPNode node = null;
try {
node = BalancerContext.balancerContext.balancerAlgorithm.processHttpRequest(request);
} catch (Exception ex) {
writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Mobicents Load Balancer Error: Exception in the balancer algorithm: " + ex.getMessage());
return;
}
if(node == null) {
writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Mobicents Load Balancer Error: All nodes are Dead!");
return;
}
if(node.getHttpPort() == 0) {
node.setHttpPort(node.getPort() + 3000);
}
if(associatedChannel != null && associatedChannel.isConnected()) {
associatedChannel.write(request);
} else {
e.getChannel().getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
// Start the connection attempt.
ChannelFuture future = HttpChannelAssocialtions.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), node.getHttpPort()));
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
Channel channel = arg0.getChannel();
HttpChannelAssocialtions.channels.put(e.getChannel(), channel);
HttpChannelAssocialtions.channels.put(channel, e.getChannel());
if (request.isChunked()) {
readingChunks = true;
}
channel.write(request);
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
}
});
}
} else {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
readingChunks = false;
}
HttpChannelAssocialtions.channels.get(e.getChannel()).write(chunk);
}
}
|
diff --git a/src/main/java/com/ledstyles/jtpm2/TPM2Protocol.java b/src/main/java/com/ledstyles/jtpm2/TPM2Protocol.java
index c259408..8a69428 100644
--- a/src/main/java/com/ledstyles/jtpm2/TPM2Protocol.java
+++ b/src/main/java/com/ledstyles/jtpm2/TPM2Protocol.java
@@ -1,84 +1,85 @@
/*
* Copyright (C) 2011 McGyver, michuNeo, Pepe_1981
* http://www.ledstyles.de/ftopic18969.html
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ledstyles.jtpm2;
import java.awt.Color;
public abstract class TPM2Protocol {
private static final byte START_BYTE = (byte) 0xC9;
private static final byte DATA_FRAME = (byte) 0xDA;
private static final byte BLOCK_END = (byte) 0x36;
public static byte[] apply_tpm2_protocol(int[] frame) {
return do_protocol(frame);
}
public static byte[] apply_tpm2_protocol(Color[] frame) {
int[] int_frame = new int[frame.length];
for (int i = 0; i < int_frame.length; i++) {
int_frame[i] = frame[i].getRGB();
}
return do_protocol(int_frame);
}
private static byte[] do_protocol(int[] frame) {
byte[] output_buffer = new byte[frame.length * 3 + 5];
- int frame_size = frame.length;
+ //3 colors per pixel
+ int frame_size = frame.length * 3;
byte frame_size_byte_high;
byte frame_size_byte_low;
int index;
index = 0;
//Start-Byte
output_buffer[index] = START_BYTE;
index++;
//Ident-Byte
output_buffer[index] = DATA_FRAME;
index++;
//Raw Data Size
frame_size_byte_high = (byte) (frame_size >> 8 & 0xff);
frame_size_byte_low = (byte) (frame_size & 0xff);
output_buffer[index] = frame_size_byte_high;
index++;
output_buffer[index] = frame_size_byte_low;
index++;
//Raw Data
for (int i = 0; i < (frame_size); i++) {
output_buffer[index] = (byte) ((frame[i] >> 16) & 255);
index++;
output_buffer[index] = (byte) ((frame[i] >> 8) & 255);
index++;
output_buffer[index] = (byte) (frame[i] & 255);
index++;
}
//Block-End-Byte
output_buffer[index] = BLOCK_END;
return output_buffer;
}
}
| true | true | private static byte[] do_protocol(int[] frame) {
byte[] output_buffer = new byte[frame.length * 3 + 5];
int frame_size = frame.length;
byte frame_size_byte_high;
byte frame_size_byte_low;
int index;
index = 0;
//Start-Byte
output_buffer[index] = START_BYTE;
index++;
//Ident-Byte
output_buffer[index] = DATA_FRAME;
index++;
//Raw Data Size
frame_size_byte_high = (byte) (frame_size >> 8 & 0xff);
frame_size_byte_low = (byte) (frame_size & 0xff);
output_buffer[index] = frame_size_byte_high;
index++;
output_buffer[index] = frame_size_byte_low;
index++;
//Raw Data
for (int i = 0; i < (frame_size); i++) {
output_buffer[index] = (byte) ((frame[i] >> 16) & 255);
index++;
output_buffer[index] = (byte) ((frame[i] >> 8) & 255);
index++;
output_buffer[index] = (byte) (frame[i] & 255);
index++;
}
//Block-End-Byte
output_buffer[index] = BLOCK_END;
return output_buffer;
}
| private static byte[] do_protocol(int[] frame) {
byte[] output_buffer = new byte[frame.length * 3 + 5];
//3 colors per pixel
int frame_size = frame.length * 3;
byte frame_size_byte_high;
byte frame_size_byte_low;
int index;
index = 0;
//Start-Byte
output_buffer[index] = START_BYTE;
index++;
//Ident-Byte
output_buffer[index] = DATA_FRAME;
index++;
//Raw Data Size
frame_size_byte_high = (byte) (frame_size >> 8 & 0xff);
frame_size_byte_low = (byte) (frame_size & 0xff);
output_buffer[index] = frame_size_byte_high;
index++;
output_buffer[index] = frame_size_byte_low;
index++;
//Raw Data
for (int i = 0; i < (frame_size); i++) {
output_buffer[index] = (byte) ((frame[i] >> 16) & 255);
index++;
output_buffer[index] = (byte) ((frame[i] >> 8) & 255);
index++;
output_buffer[index] = (byte) (frame[i] & 255);
index++;
}
//Block-End-Byte
output_buffer[index] = BLOCK_END;
return output_buffer;
}
|
diff --git a/SpagoBIQbeEngine/src/it/eng/spagobi/engines/qbe/services/core/catalogue/SetCatalogueAction.java b/SpagoBIQbeEngine/src/it/eng/spagobi/engines/qbe/services/core/catalogue/SetCatalogueAction.java
index 04825fd0a..b1aab7380 100644
--- a/SpagoBIQbeEngine/src/it/eng/spagobi/engines/qbe/services/core/catalogue/SetCatalogueAction.java
+++ b/SpagoBIQbeEngine/src/it/eng/spagobi/engines/qbe/services/core/catalogue/SetCatalogueAction.java
@@ -1,524 +1,527 @@
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package it.eng.spagobi.engines.qbe.services.core.catalogue;
import it.eng.qbe.model.structure.IModelEntity;
import it.eng.qbe.model.structure.IModelField;
import it.eng.qbe.model.structure.IModelStructure;
import it.eng.qbe.query.IQueryField;
import it.eng.qbe.query.Query;
import it.eng.qbe.query.QueryMeta;
import it.eng.qbe.query.QueryValidator;
import it.eng.qbe.query.serializer.SerializerFactory;
import it.eng.qbe.serializer.SerializationException;
import it.eng.qbe.statement.graph.GraphManager;
import it.eng.qbe.statement.graph.GraphUtilities;
import it.eng.qbe.statement.graph.ModelFieldPaths;
import it.eng.qbe.statement.graph.PathInspector;
import it.eng.qbe.statement.graph.QueryGraphBuilder;
import it.eng.qbe.statement.graph.bean.ModelObjectI18n;
import it.eng.qbe.statement.graph.bean.PathChoice;
import it.eng.qbe.statement.graph.bean.QueryGraph;
import it.eng.qbe.statement.graph.bean.Relationship;
import it.eng.qbe.statement.graph.bean.RootEntitiesGraph;
import it.eng.qbe.statement.graph.filter.CubeFilter;
import it.eng.qbe.statement.graph.serializer.FieldNotAttendInTheQuery;
import it.eng.qbe.statement.graph.serializer.ModelFieldPathsJSONDeserializer;
import it.eng.qbe.statement.graph.serializer.ModelObjectInternationalizedSerializer;
import it.eng.qbe.statement.graph.serializer.RelationJSONSerializer;
import it.eng.spago.base.SourceBean;
import it.eng.spagobi.commons.utilities.StringUtilities;
import it.eng.spagobi.engines.qbe.QbeEngineConfig;
import it.eng.spagobi.engines.qbe.services.core.AbstractQbeEngineAction;
import it.eng.spagobi.utilities.assertion.Assert;
import it.eng.spagobi.utilities.engines.SpagoBIEngineRuntimeException;
import it.eng.spagobi.utilities.engines.SpagoBIEngineServiceException;
import it.eng.spagobi.utilities.engines.SpagoBIEngineServiceExceptionHandler;
import it.eng.spagobi.utilities.exceptions.SpagoBIRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.LogMF;
import org.apache.log4j.Logger;
import org.jgrapht.Graph;
import org.jgrapht.GraphPath;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.jamonapi.Monitor;
import com.jamonapi.MonitorFactory;
/**
* Commit all the modifications made to the catalogue on the client side
*
* @author Andrea Gioia ([email protected])
*/
public class SetCatalogueAction extends AbstractQbeEngineAction {
private static final long serialVersionUID = 4576121408010108119L;
public static final String SERVICE_NAME = "SET_CATALOGUE_ACTION";
public String getActionName(){return SERVICE_NAME;}
// INPUT PARAMETERS
public static final String CATALOGUE = "catalogue";
public static final String CURRENT_QUERY_ID = "currentQueryId";
public static final String AMBIGUOUS_FIELDS_PATHS = "ambiguousFieldsPaths";
public static final String AMBIGUOUS_ROLES = "ambiguousRoles";
public static final String EXECUTE_DIRECTLY = "executeDirectly";
public static final String AMBIGUOUS_WARING = "ambiguousWarinig";
public static final String CATALOGUE_ERRORS = "catalogueErrors";
public static final String MESSAGE = "message";
public static final String MESSAGE_SAVE = "save";
/** Logger component. */
public static transient Logger logger = Logger.getLogger(SetCatalogueAction.class);
public void service(SourceBean request, SourceBean response) {
Monitor totalTimeMonitor = null;
Monitor errorHitsMonitor = null;
String jsonEncodedCatalogue = null;
JSONArray queries;
JSONObject queryJSON;
Query query;
QueryGraph oldQueryGraph = null;
- String roleSelection = null;
+ String roleSelectionFromTheSavedQuery = null;
boolean isDierctlyExecutable = false;
QueryGraph queryGraph = null; //the query graph (the graph that involves all the entities of the query)
String ambiguousWarinig=null;
boolean forceReturnGraph = false;
logger.debug("IN");
try {
totalTimeMonitor = MonitorFactory.start("QbeEngine.setCatalogueAction.totalTime");
super.service(request, response);
//get current query and all the linked objects
query = this.getCurrentQuery();
if (query == null) {
//the qbe is new
query = this.getEngineInstance().getQueryCatalogue().getFirstQuery();
oldQueryGraph = query.getQueryGraph();
- roleSelection = query.getRelationsRoles();
+ roleSelectionFromTheSavedQuery = query.getRelationsRoles();
logger.debug("The query is already defined in the catalogue");
- if(roleSelection!=null){
- logger.debug("The previous roleSelection is "+roleSelection);
+ if(roleSelectionFromTheSavedQuery!=null){
+ logger.debug("The previous roleSelection is "+roleSelectionFromTheSavedQuery);
}
if(oldQueryGraph!=null){
logger.debug("The previous oldQueryGraph is "+oldQueryGraph);
}
}
//get the cataologue from the request
jsonEncodedCatalogue = getAttributeAsString( CATALOGUE );
logger.debug(CATALOGUE + " = [" + jsonEncodedCatalogue + "]");
Assert.assertNotNull(getEngineInstance(), "It's not possible to execute " + this.getActionName() + " service before having properly created an instance of EngineInstance class");
Assert.assertNotNull(jsonEncodedCatalogue, "Input parameter [" + CATALOGUE + "] cannot be null in oder to execute " + this.getActionName() + " service");
try {
queries = new JSONArray( jsonEncodedCatalogue );
for(int i = 0; i < queries.length(); i++) {
queryJSON = queries.getJSONObject(i);
query = deserializeQuery(queryJSON);
getEngineInstance().getQueryCatalogue().addQuery(query);
getEngineInstance().resetActiveQuery();
}
} catch (SerializationException e) {
String message = "Impossible to syncronize the query with the server. Query passed by the client is malformed";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
query = this.getCurrentQuery();
if (query == null) {
query = this.getEngineInstance().getQueryCatalogue().getFirstQuery();
}else{
oldQueryGraph =null;
}
//loading the ambiguous fields
Set<ModelFieldPaths> ambiguousFields = new HashSet<ModelFieldPaths>();
Map<IModelField, Set<IQueryField>> modelFieldsMap = query.getQueryFields(getDataSource());
Set<IModelField> modelFields = modelFieldsMap.keySet();
Set<IModelEntity> modelEntities = query.getQueryEntities(modelFields);
Map<String, Object> pathFiltersMap = new HashMap<String, Object>();
pathFiltersMap.put(CubeFilter.PROPERTY_MODEL_STRUCTURE, getDataSource().getModelStructure());
pathFiltersMap.put(CubeFilter.PROPERTY_ENTITIES, modelEntities);
if (oldQueryGraph == null && query!=null) {//normal execution: a query exists
queryGraph = updateQueryGraphInQuery(query, forceReturnGraph,modelEntities);
if(queryGraph!=null){
//String modelName = getDataSource().getConfiguration().getModelName();
//Graph<IModelEntity, Relationship> graph = getDataSource().getModelStructure().getRootEntitiesGraph(modelName, false).getRootEntitiesGraph();
ambiguousFields = getAmbiguousFields(query, modelEntities, modelFieldsMap);
//filter paths
GraphManager.filterPaths(ambiguousFields, pathFiltersMap, (QbeEngineConfig.getInstance().getPathsFiltersImpl()));
boolean removeSubPaths = QbeEngineConfig.getInstance().isRemoveSubpaths();
if(removeSubPaths){
String orderDirection = QbeEngineConfig.getInstance().getPathsOrder();
GraphUtilities.cleanSubPaths(ambiguousFields, orderDirection);
}
GraphManager.getDefaultCoverGraphInstance(QbeEngineConfig.getInstance().getDefaultCoverImpl()).applyDefault(ambiguousFields, queryGraph, modelEntities);
isDierctlyExecutable = GraphManager.isDirectlyExecutable(modelEntities, queryGraph);
}else{
//no ambigous fields found
isDierctlyExecutable = true;
}
}else{//saved query
ambiguousFields = getAmbiguousFields(query, modelEntities, modelFieldsMap);
//filter paths
GraphManager.filterPaths(ambiguousFields, pathFiltersMap, (QbeEngineConfig.getInstance().getPathsFiltersImpl()));
applySavedGraphPaths(oldQueryGraph, ambiguousFields);
queryGraph = oldQueryGraph;
}
if(queryGraph!=null){
boolean valid = GraphManager.getGraphValidatorInstance(QbeEngineConfig.getInstance().getGraphValidatorImpl()).isValid(queryGraph, modelEntities);
logger.debug("QueryGraph valid = " + valid);
if (!valid) {
throw new SpagoBIEngineServiceException(getActionName(), "error.mesage.description.relationship.not.enough");
}
}
//serialize the ambiguous fields
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1,0,0,null));
simpleModule.addSerializer(Relationship.class, new RelationJSONSerializer(getDataSource(), getLocale()));
simpleModule.addSerializer(ModelObjectI18n.class, new ModelObjectInternationalizedSerializer(getDataSource(), getLocale()));
mapper.registerModule(simpleModule);
String serialized = this.getAttributeAsString(AMBIGUOUS_FIELDS_PATHS);
if(ambiguousFields.size()>0 || serialized==null){
serialized= mapper.writeValueAsString((Set<ModelFieldPaths>) ambiguousFields);
}
//update the roles in the query if exists ambiguous paths
String serializedRoles ="";
if(serialized.length()>5){
serializedRoles = this.getAttributeAsString(AMBIGUOUS_ROLES);
+ if(serializedRoles==null || serializedRoles.length()<5){
+ serializedRoles = roleSelectionFromTheSavedQuery;
+ }
LogMF.debug(logger, AMBIGUOUS_ROLES + "is {0}", serialized);
query.setRelationsRoles(serializedRoles);
applySelectedRoles(serializedRoles, modelEntities, query);
}
//validate the response and create the list of warnings and errors
if(!query.isAliasDefinedInSelectFields()){
ambiguousWarinig="sbi.qbe.relationshipswizard.roles.validation.no.fields.alias";
}
if(!isDierctlyExecutable){
isDierctlyExecutable = serialized==null || serialized.equals("") || serialized.equals("[]");//no ambiguos fields found so the query is executable;
}
List<String> queryErrors = QueryValidator.validate(query, getDataSource());
String serializedQueryErrors = mapper.writeValueAsString( queryErrors);
JSONObject toReturn = new JSONObject();
toReturn.put(AMBIGUOUS_FIELDS_PATHS, serialized);
toReturn.put(AMBIGUOUS_ROLES, serializedRoles);
toReturn.put(EXECUTE_DIRECTLY, isDierctlyExecutable);
toReturn.put(AMBIGUOUS_WARING, ambiguousWarinig);
toReturn.put(CATALOGUE_ERRORS, serializedQueryErrors);
try {
writeBackToClient( toReturn.toString() );
} catch (IOException e) {
String message = "Impossible to write back the responce to the client";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
} catch(Throwable t) {
errorHitsMonitor = MonitorFactory.start("QbeEngine.errorHits");
errorHitsMonitor.stop();
throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException(getActionName(), getEngineInstance(), t);
} finally {
if(totalTimeMonitor != null) totalTimeMonitor.stop();
logger.debug("OUT");
}
}
/**
* Get the graph from the request:
* - if exist:
* - checks it is valid for the query
* - if its valid update the graph in the query and return null
* - if its not valid calculate the default graph and update the graph in the query
* - if not exists calculate the default graph and update the graph in the query
* @param query
* @return
*/
public QueryGraph updateQueryGraphInQuery(Query query, boolean forceReturnGraph, Set<IModelEntity> modelEntities) {
boolean isTheOldQueryGraphValid = false;
logger.debug("IN");
QueryGraph queryGraph = null;
try {
queryGraph = this.getQueryGraphFromRequest(query, modelEntities);
if(queryGraph!=null){
//check if the graph selected by the user is still valid
isTheOldQueryGraphValid = isTheOldQueryGraphValid(queryGraph,query);
}
if(queryGraph==null || !isTheOldQueryGraphValid){
//calculate the default cover graph
logger.debug("Calculating the default graph");
IModelStructure modelStructure = getDataSource().getModelStructure();
RootEntitiesGraph rootEntitiesGraph = modelStructure.getRootEntitiesGraph(getDataSource().getConfiguration().getModelName(), false);
Graph<IModelEntity, Relationship> graph = rootEntitiesGraph.getRootEntitiesGraph();
logger.debug("UndirectedGraph retrieved");
Set<IModelEntity> entities = query.getQueryEntities( getDataSource() );
if(entities.size()>0){
queryGraph = GraphManager.getDefaultCoverGraphInstance(QbeEngineConfig.getInstance().getDefaultCoverImpl()).getCoverGraph(graph, entities);
}
}else{
query.setQueryGraph(queryGraph);
return null;
}
query.setQueryGraph(queryGraph);
return queryGraph;
} catch (Throwable t) {
throw new SpagoBIRuntimeException("Error while loading the not ambigous graph", t);
} finally {
logger.debug("OUT");
}
}
public void applySavedGraphPaths(QueryGraph queryGraph, Set<ModelFieldPaths> ambiguousFields){
PathInspector pi = new PathInspector(queryGraph, queryGraph.vertexSet());
Map<IModelEntity, Set<GraphPath<IModelEntity, Relationship> >> paths = pi.getAllEntitiesPathsMap();
(GraphManager.getDefaultCoverGraphInstance(QbeEngineConfig.getInstance().getDefaultCoverImpl())).applyDefault(paths, ambiguousFields);
}
public void applySelectedRoles(String serializedRoles, Set<IModelEntity> modelEntities, Query query){
cleanFieldsRolesMapInEntity(query);
try {
if(serializedRoles!=null && !serializedRoles.trim().equals("{}") && !serializedRoles.trim().equals("[]") && !serializedRoles.trim().equals("")){
query.initFieldsRolesMapInEntity(getDataSource());
}
} catch (Exception e2) {
logger.error("Error deserializing the list of roles of the entities", e2);
throw new SpagoBIEngineRuntimeException("Error deserializing the list of roles of the entities", e2);
}
}
public Set<ModelFieldPaths> getAmbiguousFields(Query query, Set<IModelEntity> modelEntities, Map<IModelField, Set<IQueryField>> modelFieldsMap) {
logger.debug("IN");
try {
String modelName = getDataSource().getConfiguration().getModelName();
Set<IModelField> modelFields = modelFieldsMap.keySet();
Assert.assertNotNull(modelFields, "No field specified in teh query");
Set<ModelFieldPaths> ambiguousModelField = new HashSet<ModelFieldPaths>();
if(modelFields!=null){
Graph<IModelEntity, Relationship> graph = getDataSource().getModelStructure().getRootEntitiesGraph(modelName, false).getRootEntitiesGraph();
PathInspector pathInspector = new PathInspector(graph, modelEntities);
Map<IModelEntity, Set<GraphPath<IModelEntity, Relationship> >> ambiguousMap = pathInspector.getAmbiguousEntitiesAllPathsMap();
Iterator<IModelField> modelFieldsIter = modelFields.iterator();
while (modelFieldsIter.hasNext()) {
IModelField iModelField = (IModelField) modelFieldsIter.next();
IModelEntity me = iModelField.getParent();
Set<GraphPath<IModelEntity, Relationship>> paths = ambiguousMap.get(me);
if(paths!=null){
Set<IQueryField> queryFields = modelFieldsMap.get(iModelField);
if(queryFields!=null){
Iterator<IQueryField> queryFieldsIter = queryFields.iterator();
while (queryFieldsIter.hasNext()) {
ambiguousModelField.add(new ModelFieldPaths(queryFieldsIter.next(),iModelField, paths));
}
}
}
}
}
return ambiguousModelField;
} catch (Throwable t) {
throw new SpagoBIRuntimeException("Error while getting ambiguous fields", t);
} finally {
logger.debug("OUT");
}
}
private QueryGraph getQueryGraphFromRequest(Query query,Set<IModelEntity> modelEntities) {
List<Relationship> toReturn = new ArrayList<Relationship>();
IModelStructure modelStructure = getDataSource().getModelStructure();
logger.debug("IModelStructure retrieved");
RootEntitiesGraph rootEntitiesGraph = modelStructure.getRootEntitiesGraph(getDataSource().getConfiguration().getModelName(), false);
logger.debug("RootEntitiesGraph retrieved");
Set<Relationship> relationships = rootEntitiesGraph.getRelationships();
logger.debug("Set<Relationship> retrieved");
String serialized = this.getAttributeAsString(AMBIGUOUS_FIELDS_PATHS);
LogMF.debug(logger, AMBIGUOUS_FIELDS_PATHS + "is {0}", serialized);
List<ModelFieldPaths> list = null;
if (StringUtilities.isNotEmpty(serialized)) {
try {
list = deserializeList(serialized, relationships, modelStructure, query);
} catch (FieldNotAttendInTheQuery e1){
logger.debug("The query has been updated and in the previous ambiguos paths selection there is some field don't exist in teh query");
return null;
} catch (SerializationException e) {
throw new SpagoBIEngineRuntimeException("Error while deserializing list of relationships", e);
}
logger.debug("Paths deserialized");
}
QueryGraph queryGraph = null;
if (list != null && !list.isEmpty()) {
Iterator<ModelFieldPaths> it = list.iterator();
while (it.hasNext()) {
ModelFieldPaths modelFieldPaths = it.next();
if(modelFieldPaths!=null){
Set<PathChoice> set = modelFieldPaths.getChoices();
Iterator<PathChoice> pathChoiceIterator = set.iterator();
while (pathChoiceIterator.hasNext()) {
PathChoice choice = pathChoiceIterator.next();
toReturn.addAll(choice.getRelations());
}
}
}
QueryGraphBuilder builder = new QueryGraphBuilder();
queryGraph = builder.buildGraphFromEdges(toReturn);
}
logger.debug("QueryGraph created");
return queryGraph;
}
public static void cleanFieldsRolesMapInEntity(Query query){
if(query!=null){
query.setMapEntityRoleField(null);
}
}
/**
* checks if the query graph covers all the entities in the query
* @param oldQueryGraph
* @param newQuery
* @return
*/
public boolean isTheOldQueryGraphValid(QueryGraph oldQueryGraph, Query newQuery){
if(oldQueryGraph ==null){
return false;
}
Set<IModelEntity> oldVertexes = oldQueryGraph.vertexSet();
if(oldVertexes==null){
return false;
}
Set<IModelEntity> newQueryEntities = newQuery.getQueryEntities(getDataSource());
if(newQueryEntities==null){
return true;
}
Iterator<IModelEntity> newQueryEntitiesIter = newQueryEntities.iterator();
while (newQueryEntitiesIter.hasNext()) {
IModelEntity iModelEntity = (IModelEntity) newQueryEntitiesIter.next();
if(!oldVertexes.contains(iModelEntity)){
return false;//if at least one entity contained in the query is not covered by the old cover graph the old graph is not valid
}
}
return true;
}
private Query getCurrentQuery() {
String queryId = this.getAttributeAsString(CURRENT_QUERY_ID);
Query query = null;
if (StringUtilities.isNotEmpty(queryId)) {
query = this.getEngineInstance().getQueryCatalogue().getQuery(queryId);
}
return query;
}
private QueryMeta deserializeMeta(JSONObject metaJSON) throws JSONException {
QueryMeta meta = new QueryMeta();
meta.setId( metaJSON.getString("id") );
meta.setName( metaJSON.getString("name") );
return null;
}
private Query deserializeQuery(JSONObject queryJSON) throws SerializationException, JSONException {
//queryJSON.put("expression", queryJSON.get("filterExpression"));
return SerializerFactory.getDeserializer("application/json").deserializeQuery(queryJSON.toString(), getEngineInstance().getDataSource());
}
public static List<ModelFieldPaths> deserializeList(String serialized, Collection<Relationship> relationShips, IModelStructure modelStructure, Query query) throws SerializationException{
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1,0,0,null));
simpleModule.addDeserializer(ModelFieldPaths.class, new ModelFieldPathsJSONDeserializer(relationShips, modelStructure, query));
mapper.registerModule(simpleModule);
TypeReference<List<ModelFieldPaths>> type = new TypeReference<List<ModelFieldPaths>>() {};
try {
return mapper.readValue(serialized, type);
} catch (Exception e) {
throw new SerializationException("Error deserializing the list of ModelFieldPaths", e);
}
}
}
| false | true | public void service(SourceBean request, SourceBean response) {
Monitor totalTimeMonitor = null;
Monitor errorHitsMonitor = null;
String jsonEncodedCatalogue = null;
JSONArray queries;
JSONObject queryJSON;
Query query;
QueryGraph oldQueryGraph = null;
String roleSelection = null;
boolean isDierctlyExecutable = false;
QueryGraph queryGraph = null; //the query graph (the graph that involves all the entities of the query)
String ambiguousWarinig=null;
boolean forceReturnGraph = false;
logger.debug("IN");
try {
totalTimeMonitor = MonitorFactory.start("QbeEngine.setCatalogueAction.totalTime");
super.service(request, response);
//get current query and all the linked objects
query = this.getCurrentQuery();
if (query == null) {
//the qbe is new
query = this.getEngineInstance().getQueryCatalogue().getFirstQuery();
oldQueryGraph = query.getQueryGraph();
roleSelection = query.getRelationsRoles();
logger.debug("The query is already defined in the catalogue");
if(roleSelection!=null){
logger.debug("The previous roleSelection is "+roleSelection);
}
if(oldQueryGraph!=null){
logger.debug("The previous oldQueryGraph is "+oldQueryGraph);
}
}
//get the cataologue from the request
jsonEncodedCatalogue = getAttributeAsString( CATALOGUE );
logger.debug(CATALOGUE + " = [" + jsonEncodedCatalogue + "]");
Assert.assertNotNull(getEngineInstance(), "It's not possible to execute " + this.getActionName() + " service before having properly created an instance of EngineInstance class");
Assert.assertNotNull(jsonEncodedCatalogue, "Input parameter [" + CATALOGUE + "] cannot be null in oder to execute " + this.getActionName() + " service");
try {
queries = new JSONArray( jsonEncodedCatalogue );
for(int i = 0; i < queries.length(); i++) {
queryJSON = queries.getJSONObject(i);
query = deserializeQuery(queryJSON);
getEngineInstance().getQueryCatalogue().addQuery(query);
getEngineInstance().resetActiveQuery();
}
} catch (SerializationException e) {
String message = "Impossible to syncronize the query with the server. Query passed by the client is malformed";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
query = this.getCurrentQuery();
if (query == null) {
query = this.getEngineInstance().getQueryCatalogue().getFirstQuery();
}else{
oldQueryGraph =null;
}
//loading the ambiguous fields
Set<ModelFieldPaths> ambiguousFields = new HashSet<ModelFieldPaths>();
Map<IModelField, Set<IQueryField>> modelFieldsMap = query.getQueryFields(getDataSource());
Set<IModelField> modelFields = modelFieldsMap.keySet();
Set<IModelEntity> modelEntities = query.getQueryEntities(modelFields);
Map<String, Object> pathFiltersMap = new HashMap<String, Object>();
pathFiltersMap.put(CubeFilter.PROPERTY_MODEL_STRUCTURE, getDataSource().getModelStructure());
pathFiltersMap.put(CubeFilter.PROPERTY_ENTITIES, modelEntities);
if (oldQueryGraph == null && query!=null) {//normal execution: a query exists
queryGraph = updateQueryGraphInQuery(query, forceReturnGraph,modelEntities);
if(queryGraph!=null){
//String modelName = getDataSource().getConfiguration().getModelName();
//Graph<IModelEntity, Relationship> graph = getDataSource().getModelStructure().getRootEntitiesGraph(modelName, false).getRootEntitiesGraph();
ambiguousFields = getAmbiguousFields(query, modelEntities, modelFieldsMap);
//filter paths
GraphManager.filterPaths(ambiguousFields, pathFiltersMap, (QbeEngineConfig.getInstance().getPathsFiltersImpl()));
boolean removeSubPaths = QbeEngineConfig.getInstance().isRemoveSubpaths();
if(removeSubPaths){
String orderDirection = QbeEngineConfig.getInstance().getPathsOrder();
GraphUtilities.cleanSubPaths(ambiguousFields, orderDirection);
}
GraphManager.getDefaultCoverGraphInstance(QbeEngineConfig.getInstance().getDefaultCoverImpl()).applyDefault(ambiguousFields, queryGraph, modelEntities);
isDierctlyExecutable = GraphManager.isDirectlyExecutable(modelEntities, queryGraph);
}else{
//no ambigous fields found
isDierctlyExecutable = true;
}
}else{//saved query
ambiguousFields = getAmbiguousFields(query, modelEntities, modelFieldsMap);
//filter paths
GraphManager.filterPaths(ambiguousFields, pathFiltersMap, (QbeEngineConfig.getInstance().getPathsFiltersImpl()));
applySavedGraphPaths(oldQueryGraph, ambiguousFields);
queryGraph = oldQueryGraph;
}
if(queryGraph!=null){
boolean valid = GraphManager.getGraphValidatorInstance(QbeEngineConfig.getInstance().getGraphValidatorImpl()).isValid(queryGraph, modelEntities);
logger.debug("QueryGraph valid = " + valid);
if (!valid) {
throw new SpagoBIEngineServiceException(getActionName(), "error.mesage.description.relationship.not.enough");
}
}
//serialize the ambiguous fields
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1,0,0,null));
simpleModule.addSerializer(Relationship.class, new RelationJSONSerializer(getDataSource(), getLocale()));
simpleModule.addSerializer(ModelObjectI18n.class, new ModelObjectInternationalizedSerializer(getDataSource(), getLocale()));
mapper.registerModule(simpleModule);
String serialized = this.getAttributeAsString(AMBIGUOUS_FIELDS_PATHS);
if(ambiguousFields.size()>0 || serialized==null){
serialized= mapper.writeValueAsString((Set<ModelFieldPaths>) ambiguousFields);
}
//update the roles in the query if exists ambiguous paths
String serializedRoles ="";
if(serialized.length()>5){
serializedRoles = this.getAttributeAsString(AMBIGUOUS_ROLES);
LogMF.debug(logger, AMBIGUOUS_ROLES + "is {0}", serialized);
query.setRelationsRoles(serializedRoles);
applySelectedRoles(serializedRoles, modelEntities, query);
}
//validate the response and create the list of warnings and errors
if(!query.isAliasDefinedInSelectFields()){
ambiguousWarinig="sbi.qbe.relationshipswizard.roles.validation.no.fields.alias";
}
if(!isDierctlyExecutable){
isDierctlyExecutable = serialized==null || serialized.equals("") || serialized.equals("[]");//no ambiguos fields found so the query is executable;
}
List<String> queryErrors = QueryValidator.validate(query, getDataSource());
String serializedQueryErrors = mapper.writeValueAsString( queryErrors);
JSONObject toReturn = new JSONObject();
toReturn.put(AMBIGUOUS_FIELDS_PATHS, serialized);
toReturn.put(AMBIGUOUS_ROLES, serializedRoles);
toReturn.put(EXECUTE_DIRECTLY, isDierctlyExecutable);
toReturn.put(AMBIGUOUS_WARING, ambiguousWarinig);
toReturn.put(CATALOGUE_ERRORS, serializedQueryErrors);
try {
writeBackToClient( toReturn.toString() );
} catch (IOException e) {
String message = "Impossible to write back the responce to the client";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
} catch(Throwable t) {
errorHitsMonitor = MonitorFactory.start("QbeEngine.errorHits");
errorHitsMonitor.stop();
throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException(getActionName(), getEngineInstance(), t);
} finally {
if(totalTimeMonitor != null) totalTimeMonitor.stop();
logger.debug("OUT");
}
}
| public void service(SourceBean request, SourceBean response) {
Monitor totalTimeMonitor = null;
Monitor errorHitsMonitor = null;
String jsonEncodedCatalogue = null;
JSONArray queries;
JSONObject queryJSON;
Query query;
QueryGraph oldQueryGraph = null;
String roleSelectionFromTheSavedQuery = null;
boolean isDierctlyExecutable = false;
QueryGraph queryGraph = null; //the query graph (the graph that involves all the entities of the query)
String ambiguousWarinig=null;
boolean forceReturnGraph = false;
logger.debug("IN");
try {
totalTimeMonitor = MonitorFactory.start("QbeEngine.setCatalogueAction.totalTime");
super.service(request, response);
//get current query and all the linked objects
query = this.getCurrentQuery();
if (query == null) {
//the qbe is new
query = this.getEngineInstance().getQueryCatalogue().getFirstQuery();
oldQueryGraph = query.getQueryGraph();
roleSelectionFromTheSavedQuery = query.getRelationsRoles();
logger.debug("The query is already defined in the catalogue");
if(roleSelectionFromTheSavedQuery!=null){
logger.debug("The previous roleSelection is "+roleSelectionFromTheSavedQuery);
}
if(oldQueryGraph!=null){
logger.debug("The previous oldQueryGraph is "+oldQueryGraph);
}
}
//get the cataologue from the request
jsonEncodedCatalogue = getAttributeAsString( CATALOGUE );
logger.debug(CATALOGUE + " = [" + jsonEncodedCatalogue + "]");
Assert.assertNotNull(getEngineInstance(), "It's not possible to execute " + this.getActionName() + " service before having properly created an instance of EngineInstance class");
Assert.assertNotNull(jsonEncodedCatalogue, "Input parameter [" + CATALOGUE + "] cannot be null in oder to execute " + this.getActionName() + " service");
try {
queries = new JSONArray( jsonEncodedCatalogue );
for(int i = 0; i < queries.length(); i++) {
queryJSON = queries.getJSONObject(i);
query = deserializeQuery(queryJSON);
getEngineInstance().getQueryCatalogue().addQuery(query);
getEngineInstance().resetActiveQuery();
}
} catch (SerializationException e) {
String message = "Impossible to syncronize the query with the server. Query passed by the client is malformed";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
query = this.getCurrentQuery();
if (query == null) {
query = this.getEngineInstance().getQueryCatalogue().getFirstQuery();
}else{
oldQueryGraph =null;
}
//loading the ambiguous fields
Set<ModelFieldPaths> ambiguousFields = new HashSet<ModelFieldPaths>();
Map<IModelField, Set<IQueryField>> modelFieldsMap = query.getQueryFields(getDataSource());
Set<IModelField> modelFields = modelFieldsMap.keySet();
Set<IModelEntity> modelEntities = query.getQueryEntities(modelFields);
Map<String, Object> pathFiltersMap = new HashMap<String, Object>();
pathFiltersMap.put(CubeFilter.PROPERTY_MODEL_STRUCTURE, getDataSource().getModelStructure());
pathFiltersMap.put(CubeFilter.PROPERTY_ENTITIES, modelEntities);
if (oldQueryGraph == null && query!=null) {//normal execution: a query exists
queryGraph = updateQueryGraphInQuery(query, forceReturnGraph,modelEntities);
if(queryGraph!=null){
//String modelName = getDataSource().getConfiguration().getModelName();
//Graph<IModelEntity, Relationship> graph = getDataSource().getModelStructure().getRootEntitiesGraph(modelName, false).getRootEntitiesGraph();
ambiguousFields = getAmbiguousFields(query, modelEntities, modelFieldsMap);
//filter paths
GraphManager.filterPaths(ambiguousFields, pathFiltersMap, (QbeEngineConfig.getInstance().getPathsFiltersImpl()));
boolean removeSubPaths = QbeEngineConfig.getInstance().isRemoveSubpaths();
if(removeSubPaths){
String orderDirection = QbeEngineConfig.getInstance().getPathsOrder();
GraphUtilities.cleanSubPaths(ambiguousFields, orderDirection);
}
GraphManager.getDefaultCoverGraphInstance(QbeEngineConfig.getInstance().getDefaultCoverImpl()).applyDefault(ambiguousFields, queryGraph, modelEntities);
isDierctlyExecutable = GraphManager.isDirectlyExecutable(modelEntities, queryGraph);
}else{
//no ambigous fields found
isDierctlyExecutable = true;
}
}else{//saved query
ambiguousFields = getAmbiguousFields(query, modelEntities, modelFieldsMap);
//filter paths
GraphManager.filterPaths(ambiguousFields, pathFiltersMap, (QbeEngineConfig.getInstance().getPathsFiltersImpl()));
applySavedGraphPaths(oldQueryGraph, ambiguousFields);
queryGraph = oldQueryGraph;
}
if(queryGraph!=null){
boolean valid = GraphManager.getGraphValidatorInstance(QbeEngineConfig.getInstance().getGraphValidatorImpl()).isValid(queryGraph, modelEntities);
logger.debug("QueryGraph valid = " + valid);
if (!valid) {
throw new SpagoBIEngineServiceException(getActionName(), "error.mesage.description.relationship.not.enough");
}
}
//serialize the ambiguous fields
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1,0,0,null));
simpleModule.addSerializer(Relationship.class, new RelationJSONSerializer(getDataSource(), getLocale()));
simpleModule.addSerializer(ModelObjectI18n.class, new ModelObjectInternationalizedSerializer(getDataSource(), getLocale()));
mapper.registerModule(simpleModule);
String serialized = this.getAttributeAsString(AMBIGUOUS_FIELDS_PATHS);
if(ambiguousFields.size()>0 || serialized==null){
serialized= mapper.writeValueAsString((Set<ModelFieldPaths>) ambiguousFields);
}
//update the roles in the query if exists ambiguous paths
String serializedRoles ="";
if(serialized.length()>5){
serializedRoles = this.getAttributeAsString(AMBIGUOUS_ROLES);
if(serializedRoles==null || serializedRoles.length()<5){
serializedRoles = roleSelectionFromTheSavedQuery;
}
LogMF.debug(logger, AMBIGUOUS_ROLES + "is {0}", serialized);
query.setRelationsRoles(serializedRoles);
applySelectedRoles(serializedRoles, modelEntities, query);
}
//validate the response and create the list of warnings and errors
if(!query.isAliasDefinedInSelectFields()){
ambiguousWarinig="sbi.qbe.relationshipswizard.roles.validation.no.fields.alias";
}
if(!isDierctlyExecutable){
isDierctlyExecutable = serialized==null || serialized.equals("") || serialized.equals("[]");//no ambiguos fields found so the query is executable;
}
List<String> queryErrors = QueryValidator.validate(query, getDataSource());
String serializedQueryErrors = mapper.writeValueAsString( queryErrors);
JSONObject toReturn = new JSONObject();
toReturn.put(AMBIGUOUS_FIELDS_PATHS, serialized);
toReturn.put(AMBIGUOUS_ROLES, serializedRoles);
toReturn.put(EXECUTE_DIRECTLY, isDierctlyExecutable);
toReturn.put(AMBIGUOUS_WARING, ambiguousWarinig);
toReturn.put(CATALOGUE_ERRORS, serializedQueryErrors);
try {
writeBackToClient( toReturn.toString() );
} catch (IOException e) {
String message = "Impossible to write back the responce to the client";
throw new SpagoBIEngineServiceException(getActionName(), message, e);
}
} catch(Throwable t) {
errorHitsMonitor = MonitorFactory.start("QbeEngine.errorHits");
errorHitsMonitor.stop();
throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException(getActionName(), getEngineInstance(), t);
} finally {
if(totalTimeMonitor != null) totalTimeMonitor.stop();
logger.debug("OUT");
}
}
|
diff --git a/spring-batch-execution/src/main/java/org/springframework/batch/execution/step/TaskletStep.java b/spring-batch-execution/src/main/java/org/springframework/batch/execution/step/TaskletStep.java
index 8a618797c..5339b1ee7 100644
--- a/spring-batch-execution/src/main/java/org/springframework/batch/execution/step/TaskletStep.java
+++ b/spring-batch-execution/src/main/java/org/springframework/batch/execution/step/TaskletStep.java
@@ -1,234 +1,234 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.execution.step;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.domain.BatchStatus;
import org.springframework.batch.core.domain.JobInterruptedException;
import org.springframework.batch.core.domain.Step;
import org.springframework.batch.core.domain.StepExecution;
import org.springframework.batch.core.domain.StepListener;
import org.springframework.batch.core.interceptor.CompositeStepListener;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.tasklet.Tasklet;
import org.springframework.batch.io.exception.BatchCriticalException;
import org.springframework.batch.repeat.ExitStatus;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/**
* A {@link Step} that executes a {@link Tasklet} directly. This step does not
* manage transactions or any looping functionality. The tasklet should do this
* on its own.
*
* @author Ben Hale
*/
public class TaskletStep implements Step, InitializingBean, BeanNameAware {
private static final Log logger = LogFactory.getLog(TaskletStep.class);
private Tasklet tasklet;
private JobRepository jobRepository;
private String name;
private int startLimit = Integer.MAX_VALUE;
private boolean allowStartIfComplete;
public String getName() {
return this.name;
}
/**
* Set the name property if it is not already set. Because of the order of
* the callbacks in a Spring container the name property will be set first
* if it is present. Care is needed with bean definition inheritance - if a
* parent bean has a name, then its children need an explicit name as well,
* otherwise they will not be unique.
*
* @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String)
*/
public void setBeanName(String name) {
if (this.name == null) {
this.name = name;
}
}
/**
* Set the name property. Always overrides the default value if this object
* is a Spring bean.
*
* @see #setBeanName(java.lang.String)
*/
public void setName(String name) {
this.name = name;
}
/* (non-Javadoc)
* @see org.springframework.batch.core.domain.Step#getStartLimit()
*/
public int getStartLimit() {
return this.startLimit;
}
/**
* Public setter for the startLimit.
*
* @param startLimit the startLimit to set
*/
public void setStartLimit(int startLimit) {
this.startLimit = startLimit;
}
/* (non-Javadoc)
* @see org.springframework.batch.core.domain.Step#isAllowStartIfComplete()
*/
public boolean isAllowStartIfComplete() {
return this.allowStartIfComplete;
}
/**
* Public setter for the shouldAllowStartIfComplete.
*
* @param allowStartIfComplete the shouldAllowStartIfComplete to set
*/
public void setAllowStartIfComplete(boolean allowStartIfComplete) {
this.allowStartIfComplete = allowStartIfComplete;
}
private CompositeStepListener listener = new CompositeStepListener();
public void setListeners(StepListener[] listeners) {
for (int i = 0; i < listeners.length; i++) {
this.listener.register(listeners[i]);
}
}
public void setListener(StepListener listener) {
this.listener.register(listener);
}
/**
* Check mandatory properties.
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(jobRepository, "JobRepository is mandatory for TaskletStep");
Assert.notNull(tasklet, "Tasklet is mandatory for TaskletStep");
}
/**
* Default constructor is useful for XML configuration.
*/
public TaskletStep() {
super();
}
/**
* Creates a new <code>Step</code> for executing a <code>Tasklet</code>
*
* @param tasklet The <code>Tasklet</code> to execute
* @param jobRepository The <code>JobRepository</code> to use for
* persistence of incremental state
*/
public TaskletStep(Tasklet tasklet, JobRepository jobRepository) {
this();
this.tasklet = tasklet;
this.jobRepository = jobRepository;
}
/**
* Public setter for the {@link Tasklet}.
* @param tasklet the {@link Tasklet} to set
*/
public void setTasklet(Tasklet tasklet) {
this.tasklet = tasklet;
}
/**
* Public setter for the {@link JobRepository}.
* @param jobRepository the {@link JobRepository} to set
*/
public void setJobRepository(JobRepository jobRepository) {
this.jobRepository = jobRepository;
}
public void execute(StepExecution stepExecution) throws JobInterruptedException, BatchCriticalException {
stepExecution.setStartTime(new Date());
updateStatus(stepExecution, BatchStatus.STARTED);
ExitStatus exitStatus = ExitStatus.FAILED;
Exception fatalException = null;
try {
listener.open(stepExecution.getJobParameters());
exitStatus = tasklet.execute();
try {
jobRepository.saveOrUpdateExecutionContext(stepExecution);
updateStatus(stepExecution, BatchStatus.COMPLETED);
}
catch (Exception e) {
fatalException = e;
updateStatus(stepExecution, BatchStatus.UNKNOWN);
}
}
catch (RuntimeException e) {
logger.error("Encountered an error running the tasklet");
updateStatus(stepExecution, BatchStatus.FAILED);
throw e;
}
catch (Exception e) {
logger.error("Encountered an error running the tasklet");
updateStatus(stepExecution, BatchStatus.FAILED);
throw new BatchCriticalException(e);
}
finally {
try {
exitStatus = exitStatus.and(listener.close());
}
catch (Exception e) {
- logger.error("Encountered an error on listener close.");
+ logger.error("Encountered an error on listener close.", e);
}
stepExecution.setExitStatus(exitStatus);
stepExecution.setEndTime(new Date());
try {
jobRepository.saveOrUpdate(stepExecution);
}
catch (Exception e) {
fatalException = e;
}
if (fatalException != null) {
logger.error("Encountered an error saving batch meta data."
+ "This job is now in an unknown state and should not be restarted.", fatalException);
throw new BatchCriticalException("Encountered an error saving batch meta data.", fatalException);
}
}
}
private void updateStatus(StepExecution stepExecution, BatchStatus status) {
stepExecution.setStatus(status);
}
}
| true | true | public void execute(StepExecution stepExecution) throws JobInterruptedException, BatchCriticalException {
stepExecution.setStartTime(new Date());
updateStatus(stepExecution, BatchStatus.STARTED);
ExitStatus exitStatus = ExitStatus.FAILED;
Exception fatalException = null;
try {
listener.open(stepExecution.getJobParameters());
exitStatus = tasklet.execute();
try {
jobRepository.saveOrUpdateExecutionContext(stepExecution);
updateStatus(stepExecution, BatchStatus.COMPLETED);
}
catch (Exception e) {
fatalException = e;
updateStatus(stepExecution, BatchStatus.UNKNOWN);
}
}
catch (RuntimeException e) {
logger.error("Encountered an error running the tasklet");
updateStatus(stepExecution, BatchStatus.FAILED);
throw e;
}
catch (Exception e) {
logger.error("Encountered an error running the tasklet");
updateStatus(stepExecution, BatchStatus.FAILED);
throw new BatchCriticalException(e);
}
finally {
try {
exitStatus = exitStatus.and(listener.close());
}
catch (Exception e) {
logger.error("Encountered an error on listener close.");
}
stepExecution.setExitStatus(exitStatus);
stepExecution.setEndTime(new Date());
try {
jobRepository.saveOrUpdate(stepExecution);
}
catch (Exception e) {
fatalException = e;
}
if (fatalException != null) {
logger.error("Encountered an error saving batch meta data."
+ "This job is now in an unknown state and should not be restarted.", fatalException);
throw new BatchCriticalException("Encountered an error saving batch meta data.", fatalException);
}
}
}
| public void execute(StepExecution stepExecution) throws JobInterruptedException, BatchCriticalException {
stepExecution.setStartTime(new Date());
updateStatus(stepExecution, BatchStatus.STARTED);
ExitStatus exitStatus = ExitStatus.FAILED;
Exception fatalException = null;
try {
listener.open(stepExecution.getJobParameters());
exitStatus = tasklet.execute();
try {
jobRepository.saveOrUpdateExecutionContext(stepExecution);
updateStatus(stepExecution, BatchStatus.COMPLETED);
}
catch (Exception e) {
fatalException = e;
updateStatus(stepExecution, BatchStatus.UNKNOWN);
}
}
catch (RuntimeException e) {
logger.error("Encountered an error running the tasklet");
updateStatus(stepExecution, BatchStatus.FAILED);
throw e;
}
catch (Exception e) {
logger.error("Encountered an error running the tasklet");
updateStatus(stepExecution, BatchStatus.FAILED);
throw new BatchCriticalException(e);
}
finally {
try {
exitStatus = exitStatus.and(listener.close());
}
catch (Exception e) {
logger.error("Encountered an error on listener close.", e);
}
stepExecution.setExitStatus(exitStatus);
stepExecution.setEndTime(new Date());
try {
jobRepository.saveOrUpdate(stepExecution);
}
catch (Exception e) {
fatalException = e;
}
if (fatalException != null) {
logger.error("Encountered an error saving batch meta data."
+ "This job is now in an unknown state and should not be restarted.", fatalException);
throw new BatchCriticalException("Encountered an error saving batch meta data.", fatalException);
}
}
}
|
diff --git a/beanstalk-maven-plugin-it/src/test/java/br/com/ingenieux/beanstalker/it/BaseBeanstalkIntegrationTest.java b/beanstalk-maven-plugin-it/src/test/java/br/com/ingenieux/beanstalker/it/BaseBeanstalkIntegrationTest.java
index 5a25a4a..a02ff07 100644
--- a/beanstalk-maven-plugin-it/src/test/java/br/com/ingenieux/beanstalker/it/BaseBeanstalkIntegrationTest.java
+++ b/beanstalk-maven-plugin-it/src/test/java/br/com/ingenieux/beanstalker/it/BaseBeanstalkIntegrationTest.java
@@ -1,117 +1,117 @@
package br.com.ingenieux.beanstalker.it;
import br.com.ingenieux.beanstalker.it.di.CoreModule;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentsRequest;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentsResult;
import com.google.inject.Guice;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.text.StrSubstitutor;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationResult;
import org.apache.maven.shared.invoker.Invoker;
import org.junit.Before;
import javax.inject.Inject;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Properties;
public class BaseBeanstalkIntegrationTest {
@Inject
protected Properties properties;
protected Invoker invoker;
@Inject
protected StrSubstitutor sub;
protected File projectDir;
@Inject
protected AWSCredentials credsProvider;
@Inject
protected AWSElasticBeanstalk service;
@Before
public void setUpProject() throws Exception {
Guice.createInjector(new CoreModule()).injectMembers(this);
invoker = new DefaultInvoker();
projectDir = new File(r("${user.dir}/target/${beanstalk.project.name}"));
if (!projectDir.exists()) {
File baseDir = projectDir.getParentFile();
baseDir.mkdirs();
invoker.execute(new DefaultInvocationRequest()
.setBaseDirectory(baseDir)
.setGoals(
Arrays.asList(r(
- "archetype:generate -DarchetypeVersion=${project.version} -DarchetypeGroupId=br.com.ingenieux -DarchetypeArtifactId=elasticbeanstalk-service-webapp-archetype -DgroupId=br.com.ingenieux -DartifactId=${beanstalk.project.name} -Dversion=0.0.1-SNAPSHOT -Dpackage=br.com.ingenieux.sample")
+ "archetype:generate -DarchetypeVersion=${project.version} -DarchetypeGroupId=br.com.ingenieux -DarchetypeArtifactId=elasticbeanstalk-service-webapp-archetype -DgroupId=br.com.ingenieux -DartifactId=${beanstalk.project.name} -Dversion=0.0.1-SNAPSHOT -Dpackage=br.com.ingenieux.sample -DarchetypeCatalog=local")
.split("\\s+"))));
}
invoker.setWorkingDirectory(projectDir);
}
public InvocationResult invoke(String mask, Object... args) throws Exception {
String command = String.format(mask, args);
return invoker.execute(new DefaultInvocationRequest().setBaseDirectory(
projectDir).setGoals(
Arrays.asList(sub.replace(command).split("\\s+"))));
}
protected DescribeEnvironmentsResult getEnvironments() {
return service.describeEnvironments(new DescribeEnvironmentsRequest().withApplicationName(r("${beanstalk.project.name}")).withIncludeDeleted(false));
}
protected String r(String text) {
return sub.replace(text);
}
protected void removeFileOrDirectory(String path) {
try {
final File file = new File(projectDir, path);
if (file.isDirectory()) {
FileUtils.deleteDirectory(file);
} else {
FileUtils.deleteQuietly(file);
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
protected void writeIntoFile(String path, String mask, Object... args) {
FileOutputStream fos = null;
File outputFile = new File(projectDir, path);
try {
fos = new FileOutputStream(outputFile);
IOUtils.write(String.format(mask, args), fos, "UTF-8");
} catch (Exception exc) {
// Ignore. Really.
exc.printStackTrace();
} finally {
IOUtils.closeQuietly(fos);
}
}
public void sleep(int nSecs) {
try {
Thread.sleep(nSecs * 1000);
} catch (Exception exc) {
}
}
}
| true | true | public void setUpProject() throws Exception {
Guice.createInjector(new CoreModule()).injectMembers(this);
invoker = new DefaultInvoker();
projectDir = new File(r("${user.dir}/target/${beanstalk.project.name}"));
if (!projectDir.exists()) {
File baseDir = projectDir.getParentFile();
baseDir.mkdirs();
invoker.execute(new DefaultInvocationRequest()
.setBaseDirectory(baseDir)
.setGoals(
Arrays.asList(r(
"archetype:generate -DarchetypeVersion=${project.version} -DarchetypeGroupId=br.com.ingenieux -DarchetypeArtifactId=elasticbeanstalk-service-webapp-archetype -DgroupId=br.com.ingenieux -DartifactId=${beanstalk.project.name} -Dversion=0.0.1-SNAPSHOT -Dpackage=br.com.ingenieux.sample")
.split("\\s+"))));
}
invoker.setWorkingDirectory(projectDir);
}
| public void setUpProject() throws Exception {
Guice.createInjector(new CoreModule()).injectMembers(this);
invoker = new DefaultInvoker();
projectDir = new File(r("${user.dir}/target/${beanstalk.project.name}"));
if (!projectDir.exists()) {
File baseDir = projectDir.getParentFile();
baseDir.mkdirs();
invoker.execute(new DefaultInvocationRequest()
.setBaseDirectory(baseDir)
.setGoals(
Arrays.asList(r(
"archetype:generate -DarchetypeVersion=${project.version} -DarchetypeGroupId=br.com.ingenieux -DarchetypeArtifactId=elasticbeanstalk-service-webapp-archetype -DgroupId=br.com.ingenieux -DartifactId=${beanstalk.project.name} -Dversion=0.0.1-SNAPSHOT -Dpackage=br.com.ingenieux.sample -DarchetypeCatalog=local")
.split("\\s+"))));
}
invoker.setWorkingDirectory(projectDir);
}
|
diff --git a/core/src/test/java/io/undertow/test/handlers/ChunkedRequestTransferCodingTestCase.java b/core/src/test/java/io/undertow/test/handlers/ChunkedRequestTransferCodingTestCase.java
index b6703bc46..892367a8f 100644
--- a/core/src/test/java/io/undertow/test/handlers/ChunkedRequestTransferCodingTestCase.java
+++ b/core/src/test/java/io/undertow/test/handlers/ChunkedRequestTransferCodingTestCase.java
@@ -1,187 +1,187 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 io.undertow.test.handlers;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import io.undertow.UndertowOptions;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerConnection;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.BlockingHandler;
import io.undertow.test.utils.DefaultServer;
import io.undertow.test.utils.HttpClientUtils;
import io.undertow.util.TestHttpClient;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xnio.OptionMap;
/**
* @author Stuart Douglas
*/
@RunWith(DefaultServer.class)
public class ChunkedRequestTransferCodingTestCase {
private static final String MESSAGE = "My HTTP Request!";
private static volatile String message;
private static volatile HttpServerConnection connection;
@BeforeClass
public static void setup() {
final BlockingHandler blockingHandler = new BlockingHandler();
DefaultServer.setRootHandler(blockingHandler);
blockingHandler.setRootHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) {
try {
if (connection == null) {
connection = exchange.getConnection();
} else if (!DefaultServer.isAjp() && connection.getChannel() != exchange.getConnection().getChannel()) {
exchange.setResponseCode(500);
final OutputStream outputStream = exchange.getOutputStream();
outputStream.write("Connection not persistent".getBytes());
outputStream.close();
return;
}
final OutputStream outputStream = exchange.getOutputStream();
final InputStream inputSream = exchange.getInputStream();
String m = HttpClientUtils.readResponse(inputSream);
Assert.assertEquals(message, m);
inputSream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
}
@Test
public void testChunkedRequest() throws IOException {
connection = null;
HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
TestHttpClient client = new TestHttpClient();
try {
generateMessage(1);
post.setEntity(new StringEntity(message) {
@Override
public long getContentLength() {
return -1;
}
});
HttpResponse result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
final Random random = new Random();
final int seed = random.nextInt();
System.out.print("Using Seed " + seed);
random.setSeed(seed);
for (int i = 0; i < 10; ++i) {
generateMessage(100 * i);
post.setEntity(new StringEntity(message) {
@Override
public long getContentLength() {
return -1;
}
@Override
public boolean isChunked() {
return true;
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
int l = 0;
int i = 0;
- while (i < message.length()) {
+ while (i <= message.length()) {
i += random.nextInt(1000);
i = Math.min(i, message.length());
outstream.write(message.getBytes(), l, i - l);
l = i;
++i;
}
}
});
result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
}
} finally {
client.getConnectionManager().shutdown();
}
}
@Test
@Ignore("sometimes the client attempts to re-use the same connection after the failure, but the server has already closed it")
public void testMaxRequestSizeChunkedRequest() throws IOException {
connection = null;
OptionMap existing = DefaultServer.getUndertowOptions();
HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
post.setHeader(HttpHeaders.CONNECTION, "close");
TestHttpClient client = new TestHttpClient();
try {
generateMessage(1);
post.setEntity(new StringEntity(message) {
@Override
public long getContentLength() {
return -1;
}
});
DefaultServer.setUndertowOptions(OptionMap.create(UndertowOptions.MAX_ENTITY_SIZE, 3L));
HttpResponse result = client.execute(post);
Assert.assertEquals(500, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
connection = null;
DefaultServer.setUndertowOptions(OptionMap.create(UndertowOptions.MAX_ENTITY_SIZE, (long) message.length()));
result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
} finally {
DefaultServer.setUndertowOptions(existing);
client.getConnectionManager().shutdown();
}
}
private static void generateMessage(int repetitions) {
final StringBuilder builder = new StringBuilder(repetitions * MESSAGE.length());
for (int i = 0; i < repetitions; ++i) {
builder.append(MESSAGE);
}
message = builder.toString();
}
}
| true | true | public void testChunkedRequest() throws IOException {
connection = null;
HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
TestHttpClient client = new TestHttpClient();
try {
generateMessage(1);
post.setEntity(new StringEntity(message) {
@Override
public long getContentLength() {
return -1;
}
});
HttpResponse result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
final Random random = new Random();
final int seed = random.nextInt();
System.out.print("Using Seed " + seed);
random.setSeed(seed);
for (int i = 0; i < 10; ++i) {
generateMessage(100 * i);
post.setEntity(new StringEntity(message) {
@Override
public long getContentLength() {
return -1;
}
@Override
public boolean isChunked() {
return true;
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
int l = 0;
int i = 0;
while (i < message.length()) {
i += random.nextInt(1000);
i = Math.min(i, message.length());
outstream.write(message.getBytes(), l, i - l);
l = i;
++i;
}
}
});
result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
}
} finally {
client.getConnectionManager().shutdown();
}
}
| public void testChunkedRequest() throws IOException {
connection = null;
HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
TestHttpClient client = new TestHttpClient();
try {
generateMessage(1);
post.setEntity(new StringEntity(message) {
@Override
public long getContentLength() {
return -1;
}
});
HttpResponse result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
final Random random = new Random();
final int seed = random.nextInt();
System.out.print("Using Seed " + seed);
random.setSeed(seed);
for (int i = 0; i < 10; ++i) {
generateMessage(100 * i);
post.setEntity(new StringEntity(message) {
@Override
public long getContentLength() {
return -1;
}
@Override
public boolean isChunked() {
return true;
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
int l = 0;
int i = 0;
while (i <= message.length()) {
i += random.nextInt(1000);
i = Math.min(i, message.length());
outstream.write(message.getBytes(), l, i - l);
l = i;
++i;
}
}
});
result = client.execute(post);
Assert.assertEquals(200, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
}
} finally {
client.getConnectionManager().shutdown();
}
}
|
diff --git a/AndroidRally/src/se/chalmers/dryleafsoftware/androidrally/libgdx/view/DeckView.java b/AndroidRally/src/se/chalmers/dryleafsoftware/androidrally/libgdx/view/DeckView.java
index 20da518..7e4feb3 100644
--- a/AndroidRally/src/se/chalmers/dryleafsoftware/androidrally/libgdx/view/DeckView.java
+++ b/AndroidRally/src/se/chalmers/dryleafsoftware/androidrally/libgdx/view/DeckView.java
@@ -1,763 +1,764 @@
package se.chalmers.dryleafsoftware.androidrally.libgdx.view;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import se.chalmers.dryleafsoftware.androidrally.libgdx.gameboard.RobotView;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
/**
* This stage holds all the cards the player has to play with.
*
* @author
*
*/
public class DeckView extends Stage {
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private List<CardView> deckCards = new ArrayList<CardView>();
private int position;
private final CardListener cl;
private final Table container;
private final Table lowerArea, upperArea, statusBar;
private final Table playPanel; // The panel with [Play] [Step] [Skip]
private final Table drawPanel; // The panel with [Draw cards]
private final Table allPlayerInfo; // The panel with all the players' info
private final RegisterView registerView;
private final TextButtonStyle buttonStyle;
private final TextButton runButton;
/**
* Specifying that the actions should stop playing.
*/
public static final String EVENT_PAUSE = "pause";
/**
* Specifying that the game should start playing.
*/
public static final String EVENT_PLAY = "play";
/**
* Specifying that the game should play the actions fast.
*/
public static final String EVENT_FASTFORWARD = "fast";
/**
* Specifying that all actions should be skipped.
*/
public static final String EVENT_STEP_ALL = "stepAll";
/**
* Specifying that the register's set of actions should be skipped.
*/
public static final String EVENT_STEP_CARD = "stepCard";
/**
* Specifying that the player should be given new cards.
*/
public static final String EVENT_DRAW_CARDS = "drawCards";
/**
* Specifying that the player has looked at its cards long enough.
*/
public static final String TIMER_CARDS = "timerCards";
/**
* Specifying that the round has ended.
*/
public static final String TIMER_ROUND = "timerRound";
/**
* Specifying that the info button has been pressed.
*/
public static final String EVENT_INFO = "info";
/**
* Specifying that the player wants to send its cards.
*/
public static final String EVENT_RUN = "run";
private final Timer timer;
private final Label timerLabel;
private int cardTick = 0;
private int roundTick = 0;
private final int roundTime;
private static final int MAX_PING = 2;
/**
* Creates a new instance.
*
* @param robots
* The robots in the game.
* @param robotID
* The ID of the player's robot.
* @param roundTime
* The time until next round.
*/
public DeckView(List<RobotView> robots, int robotID, int roundTime) {
super();
this.roundTime = roundTime;
Texture deckTexture = new Texture(
Gdx.files.internal("textures/woodenDeck.png"));
deckTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Texture compTexture = new Texture(
Gdx.files.internal("textures/deckComponents.png"));
compTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
cl = new CardListener(this);
// Default camera
OrthographicCamera cardCamera = new OrthographicCamera(480, 800);
cardCamera.zoom = 1.0f;
cardCamera.position.set(240, 400, 0f);
cardCamera.update();
setCamera(cardCamera);
// Set background image
Image deck = new Image(new TextureRegion(deckTexture, 0, 0, 480, 320));
deck.setPosition(0, 0);
deck.setSize(480, 320);
addActor(deck);
container = new Table();
container.debug();
container.setSize(480, 320);
container.setLayoutEnabled(false);
addActor(container);
lowerArea = new Table();
lowerArea.debug();
lowerArea.setSize(480, 120);
lowerArea.setLayoutEnabled(false);
container.add(lowerArea);
upperArea = new Table();
upperArea.debug();
upperArea.setSize(480, 120);
upperArea.setPosition(0, 120);
upperArea.setLayoutEnabled(false);
container.add(upperArea);
statusBar = new Table();
statusBar.debug();
statusBar.setSize(480, 80);
statusBar.setPosition(0, 240);
statusBar.setLayoutEnabled(false);
container.add(statusBar);
registerView = new RegisterView(compTexture);
registerView.setSize(upperArea.getWidth(), upperArea.getHeight());
upperArea.add(registerView);
NinePatchDrawable buttonTexture = new NinePatchDrawable(new NinePatch(
new Texture(Gdx.files.internal("textures/button9patch.png")),
4, 4, 4, 4));
NinePatchDrawable buttonTexturePressed = new NinePatchDrawable(
new NinePatch(new Texture(Gdx.files
.internal("textures/button9patchpressed.png")), 4, 4,
4, 4));
buttonStyle = new TextButtonStyle(buttonTexture, buttonTexturePressed,
null);
buttonStyle.font = new BitmapFont();
buttonStyle.pressedOffsetX = 1;
buttonStyle.pressedOffsetY = -1;
TextButtonStyle playStyle = new TextButtonStyle(
new TextureRegionDrawable(new TextureRegion(compTexture, 0,
192, 64, 64)), new TextureRegionDrawable(
new TextureRegion(compTexture, 64, 192, 64, 64)), null);
playStyle.disabled = new TextureRegionDrawable(new TextureRegion(
compTexture, 128, 192, 64, 64));
playStyle.font = new BitmapFont();
playStyle.fontColor = Color.WHITE;
playStyle.disabledFontColor = Color.GRAY;
playStyle.pressedOffsetX = 1;
playStyle.pressedOffsetY = -1;
runButton = new TextButton("\r\nRun", playStyle);
runButton.setPosition(410, 20);
runButton.setSize(64, 64);
runButton.setDisabled(true);
registerView.add(runButton);
runButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (!runButton.isDisabled()) {
runButton.setDisabled(true);
pcs.firePropertyChange(EVENT_RUN, 0, 1);
}
}
});
playPanel = buildPlayerPanel();
drawPanel = buildDrawCardPanel();
timer = new Timer();
// Tick every second.
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (cardTick > 0) {
cardTick--;
if (cardTick == 0) {
pcs.firePropertyChange(TIMER_CARDS, 0, 1);
}
}
if (roundTick - MAX_PING > 0) {
roundTick--;
if (roundTick - MAX_PING == 0) {
pcs.firePropertyChange(TIMER_ROUND, 0, 1);
}
}
int timerTick = cardTick > 0 ? cardTick : Math.max(0, roundTick
- MAX_PING);
timerLabel.setVisible(timerTick > 0);
setTimerLabel(timerTick);
}
}, 1000, 1000);
Table statusCenter = new Table();
statusCenter.setPosition(200, 0);
statusCenter.setSize(80, statusBar.getHeight());
statusCenter.debug();
statusBar.add(statusCenter);
LabelStyle lStyle = new LabelStyle();
lStyle.font = new BitmapFont();
- timerLabel = new Label("", lStyle);
+ timerLabel = new Label("00:00:00", lStyle);
+ timerLabel.setVisible(false);
statusCenter.add(timerLabel);
statusCenter.row();
final TextButton showPlayers = new TextButton("Info", buttonStyle);
statusCenter.add(showPlayers).minWidth(75);
showPlayers.addListener(new ClickListener() {
private boolean dispOpp = false;
@Override
public void clicked(InputEvent event, float x, float y) {
if (dispOpp) {
displayNormal();
showPlayers.setText("Info");
} else {
displayOpponentInfo();
showPlayers.setText("Back");
}
dispOpp = !dispOpp;
}
});
DamageView dv = new DamageView(compTexture, robots.get(robotID));
LifeView lv = new LifeView(compTexture, robots.get(robotID));
lv.setPosition(0, 0);
lv.setSize(120, 80);
lv.debug();
dv.setPosition(290, 20);
dv.setSize(200, 40);
dv.debug();
statusBar.add(dv);
statusBar.add(lv);
allPlayerInfo = new Table();
allPlayerInfo.setPosition(0, 0);
allPlayerInfo.setSize(480, 240);
Table scrollContainer = new Table();
scrollContainer.defaults().width(240);
ScrollPane pane = new ScrollPane(scrollContainer);
allPlayerInfo.add(pane);
NinePatchDrawable divider = new NinePatchDrawable(new NinePatch(
new Texture(Gdx.files.internal("textures/divider.png")), 63,
63, 0, 0));
for (int i = 0; i < robots.size(); i++) {
if (i != robotID) {
scrollContainer.add(new LifeView(compTexture, robots.get(i)));
scrollContainer.add(new DamageView(compTexture, robots.get(i)));
scrollContainer.row();
if (i != robots.size() - 1) {
scrollContainer.add(new Image(divider)).colspan(2)
.width(420).pad(3);
scrollContainer.row();
}
}
}
scrollContainer.debug();
}
/**
* Disable the run-button.
*
* @param disable
*/
public void disableRun(boolean disable) {
runButton.setDisabled(true);
}
/**
* Resets the roundtimer.
*/
public void resetRoundTimer() {
roundTick = DeckView.this.roundTime;
}
/*
* Creates the panel with the [Draw Cards] button.
*/
private Table buildDrawCardPanel() {
int internalPadding = 50, externalPadding = 10;
Table drawPanel = new Table();
drawPanel.setSize(480, 120);
TextButton draw = new TextButton("Draw Cards", buttonStyle);
draw.pad(0, internalPadding, 0, internalPadding); // Internal padding
drawPanel.add(draw).pad(externalPadding).minHeight(30); // Border
draw.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
pcs.firePropertyChange(EVENT_DRAW_CARDS, 0, 1);
}
});
return drawPanel;
}
/*
* Creates the panel with the [Play] [Step] [Skip] buttons.
*/
private Table buildPlayerPanel() {
Texture buttons = new Texture(
Gdx.files.internal("textures/playButtons.png"));
buttons.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Table playPanel = new Table();
playPanel.setSize(480, 120);
// Create pause button
Button pause = new Button(new ButtonStyle(new TextureRegionDrawable(
new TextureRegion(buttons, 0, 0, 64, 64)),
new TextureRegionDrawable(new TextureRegion(buttons, 0, 64, 64,
64)), null));
playPanel.add(pause).size(50, 50).pad(0);
pause.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
pcs.firePropertyChange(EVENT_PAUSE, 0, 1);
}
});
// Create play button
Button play = new Button(new ButtonStyle(new TextureRegionDrawable(
new TextureRegion(buttons, 64, 0, 64, 64)),
new TextureRegionDrawable(new TextureRegion(buttons, 64, 64,
64, 64)), null));
playPanel.add(play).size(50, 50).pad(0);
play.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
pcs.firePropertyChange(EVENT_PLAY, 0, 1);
}
});
// Create fast forward button
Button fastForward = new Button(new ButtonStyle(
new TextureRegionDrawable(new TextureRegion(buttons, 128, 0,
64, 64)), new TextureRegionDrawable(new TextureRegion(
buttons, 128, 64, 64, 64)), null));
playPanel.add(fastForward).size(50, 50).pad(0);
fastForward.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
pcs.firePropertyChange(EVENT_FASTFORWARD, 0, 1);
}
});
// Create button for skip single card
Button skipCard = new Button(new ButtonStyle(new TextureRegionDrawable(
new TextureRegion(buttons, 192, 0, 64, 64)),
new TextureRegionDrawable(new TextureRegion(buttons, 192, 64,
64, 64)), null));
playPanel.add(skipCard).size(50, 50).pad(0);
skipCard.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
pcs.firePropertyChange(EVENT_STEP_CARD, 0, 1);
}
});
// Create button for skip all cards
Button skipAll = new Button(new ButtonStyle(new TextureRegionDrawable(
new TextureRegion(buttons, 256, 0, 64, 64)),
new TextureRegionDrawable(new TextureRegion(buttons, 256, 64,
64, 64)), null));
playPanel.add(skipAll).size(50, 50).pad(0);
skipAll.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
pcs.firePropertyChange(EVENT_STEP_ALL, 0, 1);
}
});
return playPanel;
}
/**
* Adds the specified listener.
*
* @param listener
* The listener to add.
*/
public void addListener(PropertyChangeListener listener) {
this.pcs.addPropertyChangeListener(listener);
}
/**
* Removes the specified listener.
*
* @param listener
* The listener to remove.
*/
public void removeListener(PropertyChangeListener listener) {
this.pcs.removePropertyChangeListener(listener);
}
/**
* Only displays the locked cards.
*
* @param input
* The String with card data.
* @param texture
* The texture to use.
*/
public void setChosenCards(String input, Texture texture) {
registerView.clear();
BitmapFont cardFont = new BitmapFont();
cardFont.setColor(Color.GREEN);
int i = 0;
for (String card : input.split(":")) {
int prio = Integer.parseInt(card);
CardView cv = buildCard(prio, texture, i, cardFont);
System.out.println("registerView: " + registerView);
System.out.println("register[i]: " + registerView.getRegister(i));
registerView.getRegister(i).setCard(cv);
registerView.getRegister(i).displayOverlay(Register.UNFOCUS);
i++;
}
}
private CardView buildCard(int prio, Texture texture, int index,
BitmapFont cardFont) {
int regX = 0;
if (prio <= 60) {
regX = 0; // UTURN
} else if (prio <= 410 && prio % 20 != 0) {
regX = 1; // LEFT
} else if (prio <= 420 && prio % 20 == 0) {
regX = 2; // LEFT
} else if (prio <= 480) {
regX = 3; // Back 1
} else if (prio <= 660) {
regX = 4; // Move 1
} else if (prio <= 780) {
regX = 5; // Move 2
} else if (prio <= 840) {
regX = 6; // Move 3
}
CardView cv = new CardView(new TextureRegion(texture, regX * 128, 0,
128, 180), prio, index, cardFont);
cv.setSize(78, 110);
return cv;
}
/**
* Displays the panel with all the players.
*/
public void displayOpponentInfo() {
container.removeActor(lowerArea);
container.removeActor(upperArea);
container.add(allPlayerInfo);
}
/**
* Displays the panel which should be visible while waiting for round
* results.
*/
public void displayWaiting() {
lowerArea.clear();
registerView.removeCardListener(cardListener);
}
/**
* Displays the normal panel which is divided into an upper and a lower
* area.
*/
public void displayNormal() {
container.removeActor(allPlayerInfo);
container.add(upperArea);
container.add(lowerArea);
}
/**
* Displays the panel which should be visible after viewing the round
* results.
*/
public void displayDrawCard() {
registerView.clear();
lowerArea.clear();
lowerArea.add(drawPanel);
}
/**
* DIsplays the panel which should be visible when viewing the round
* results.
*/
public void displayPlayOptions() {
lowerArea.clear();
lowerArea.add(playPanel);
registerView.removeCardListener(cardListener);
}
/**
* Rerenders all the player's card at their correct positions.
*/
public void updateCards() {
updateDeckCards();
}
/**
* Renders all the cards not yet added to the register
*/
public void updateDeckCards() {
if (this.getCardDeckWidth() < 480) {
this.position = 240 - this.getCardDeckWidth() / 2;
} else {
if (this.position > 0) {
this.position = 0;
} else if (this.position + getCardDeckWidth() < 480) {
this.position = 480 - getCardDeckWidth();
}
}
Collections.sort(this.deckCards);
for (int i = 0; i < this.deckCards.size(); i++) {
CardView cv = this.deckCards.get(i);
cv.setPosition((cv.getWidth() + 10) * i + this.position, 0);
}
}
private final ActorGestureListener cardListener = new ActorGestureListener() {
@Override
public void tap(InputEvent event, float x, float y, int count,
int button) {
Actor pressed = getTouchDownTarget();
if (pressed instanceof CardView) {
CardView card = (CardView) pressed;
if (deckCards.contains(card)) {
choseCard(card);
} else {
unChoseCard(card);
}
}
updateCards();
}
};
/**
* Returns the cards added to the register
*
* @return
*/
public CardView[] getChosenCards() {
return registerView.getCards();
}
/**
* Sets the X-coordinate of the leftmost card not yet added to a register.
*
* @param position
*/
public void setPositionX(int position) {
this.position = position;
updateDeckCards();
}
/**
* Gives the X-coordinate of the leftmost card not yet added to a register.
*
* @return
*/
public int getPositionX() {
return this.position;
}
/**
* Gives the registers.
*
* @return The registers.
*/
public RegisterView getRegisters() {
return this.registerView;
}
/**
* Checks if the cardtimer is on.
*
* @return <code>true</code> if the cardtimer is on.
*/
public boolean isCardTimerOn() {
return cardTick > 0;
}
/*
* Sets the label of the timer to display the specified number of seconds as
* [hh:mm:ss].
*/
private void setTimerLabel(int ticks) {
int h = ticks / 3600;
int m = (ticks / 60) % 60;
int s = ticks % 60;
s = Math.max(s, 0);
timerLabel.setText(String.format("%02d", h) + ":"
+ String.format("%02d", m) + ":" + String.format("%02d", s));
}
/**
* Sets the card timer to the specified number in seconds.
*
* @param cardTick
* The card timer's delay in seconds.
*/
public void setCardTick(int cardTick) {
this.cardTick = cardTick;
if (cardTick > 0) {
setTimerLabel(cardTick);
}
}
/**
* Sets the round timer to the specified number in seconds.
*
* @param roundTick
* The round timer's delay in seconds.
*/
public void setRoundTick(int roundTick) {
this.roundTick = roundTick;
if (roundTick > 0) {
setTimerLabel(roundTick);
}
}
/**
* Gives the total width it takes to render the cards not yet added to a
* register.
*
* @return
*/
public int getCardDeckWidth() {
if (this.deckCards.isEmpty()) {
return 0;
} else {
return this.deckCards.size()
* ((int) this.deckCards.get(0).getWidth() + 10) - 10;
}
}
private void choseCard(CardView card) {
if (registerView.addCard(card)) {
deckCards.remove(card);
}
}
/**
* Sets a chosen card.
*
* @param card
* The card to add.
*/
private void unChoseCard(CardView card) {
if (registerView.removeCard(card)) {
lowerArea.add(card);
deckCards.add(card);
}
}
/**
* Displays all cards.
*
* @param input
* A String with all the cards' data.
* @param texture
* The texture to use when creating the cards.
*/
public void setDeckCards(String input, Texture texture) {
List<CardView> cards = new ArrayList<CardView>();
// Clear cards
registerView.clear();
BitmapFont cardFont = new BitmapFont();
cardFont.setColor(Color.GREEN);
String indata = input;
int i = 0;
for (String card : indata.split(":")) {
String[] data = card.split(";");
int prio = (data.length == 2) ? Integer.parseInt(data[1]) : Integer
.parseInt(data[0]);
CardView cv = buildCard(prio, texture, i, cardFont);
if (data.length == 2) {
int lockPos = Integer.parseInt(data[0].substring(1));
registerView.getRegister(lockPos).setCard(cv);
registerView.getRegister(lockPos).displayOverlay(
Register.PADLOCK);
} else {
cards.add(cv);
}
i++;
}
Collections.sort(cards);
setDeckCards(cards);
updateCards();
}
/**
* Sets which cards the deck should display.
*
* @param list
* The cards the deck should display.
*/
private void setDeckCards(List<CardView> list) {
Table holder = new Table();
holder.setSize(480, 160);
holder.setLayoutEnabled(false);
lowerArea.clear();
lowerArea.add(holder);
this.deckCards = list;
for (int i = 0; i < list.size(); i++) {
CardView cv = list.get(i);
cv.setPosition((cv.getWidth() + 10) * i, 0);
holder.add(cv);
}
for (CardView cv : deckCards) {
cv.addListener(cl);
cv.addListener(cardListener);
}
runButton.setDisabled(false);
}
}
| true | true | public DeckView(List<RobotView> robots, int robotID, int roundTime) {
super();
this.roundTime = roundTime;
Texture deckTexture = new Texture(
Gdx.files.internal("textures/woodenDeck.png"));
deckTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Texture compTexture = new Texture(
Gdx.files.internal("textures/deckComponents.png"));
compTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
cl = new CardListener(this);
// Default camera
OrthographicCamera cardCamera = new OrthographicCamera(480, 800);
cardCamera.zoom = 1.0f;
cardCamera.position.set(240, 400, 0f);
cardCamera.update();
setCamera(cardCamera);
// Set background image
Image deck = new Image(new TextureRegion(deckTexture, 0, 0, 480, 320));
deck.setPosition(0, 0);
deck.setSize(480, 320);
addActor(deck);
container = new Table();
container.debug();
container.setSize(480, 320);
container.setLayoutEnabled(false);
addActor(container);
lowerArea = new Table();
lowerArea.debug();
lowerArea.setSize(480, 120);
lowerArea.setLayoutEnabled(false);
container.add(lowerArea);
upperArea = new Table();
upperArea.debug();
upperArea.setSize(480, 120);
upperArea.setPosition(0, 120);
upperArea.setLayoutEnabled(false);
container.add(upperArea);
statusBar = new Table();
statusBar.debug();
statusBar.setSize(480, 80);
statusBar.setPosition(0, 240);
statusBar.setLayoutEnabled(false);
container.add(statusBar);
registerView = new RegisterView(compTexture);
registerView.setSize(upperArea.getWidth(), upperArea.getHeight());
upperArea.add(registerView);
NinePatchDrawable buttonTexture = new NinePatchDrawable(new NinePatch(
new Texture(Gdx.files.internal("textures/button9patch.png")),
4, 4, 4, 4));
NinePatchDrawable buttonTexturePressed = new NinePatchDrawable(
new NinePatch(new Texture(Gdx.files
.internal("textures/button9patchpressed.png")), 4, 4,
4, 4));
buttonStyle = new TextButtonStyle(buttonTexture, buttonTexturePressed,
null);
buttonStyle.font = new BitmapFont();
buttonStyle.pressedOffsetX = 1;
buttonStyle.pressedOffsetY = -1;
TextButtonStyle playStyle = new TextButtonStyle(
new TextureRegionDrawable(new TextureRegion(compTexture, 0,
192, 64, 64)), new TextureRegionDrawable(
new TextureRegion(compTexture, 64, 192, 64, 64)), null);
playStyle.disabled = new TextureRegionDrawable(new TextureRegion(
compTexture, 128, 192, 64, 64));
playStyle.font = new BitmapFont();
playStyle.fontColor = Color.WHITE;
playStyle.disabledFontColor = Color.GRAY;
playStyle.pressedOffsetX = 1;
playStyle.pressedOffsetY = -1;
runButton = new TextButton("\r\nRun", playStyle);
runButton.setPosition(410, 20);
runButton.setSize(64, 64);
runButton.setDisabled(true);
registerView.add(runButton);
runButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (!runButton.isDisabled()) {
runButton.setDisabled(true);
pcs.firePropertyChange(EVENT_RUN, 0, 1);
}
}
});
playPanel = buildPlayerPanel();
drawPanel = buildDrawCardPanel();
timer = new Timer();
// Tick every second.
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (cardTick > 0) {
cardTick--;
if (cardTick == 0) {
pcs.firePropertyChange(TIMER_CARDS, 0, 1);
}
}
if (roundTick - MAX_PING > 0) {
roundTick--;
if (roundTick - MAX_PING == 0) {
pcs.firePropertyChange(TIMER_ROUND, 0, 1);
}
}
int timerTick = cardTick > 0 ? cardTick : Math.max(0, roundTick
- MAX_PING);
timerLabel.setVisible(timerTick > 0);
setTimerLabel(timerTick);
}
}, 1000, 1000);
Table statusCenter = new Table();
statusCenter.setPosition(200, 0);
statusCenter.setSize(80, statusBar.getHeight());
statusCenter.debug();
statusBar.add(statusCenter);
LabelStyle lStyle = new LabelStyle();
lStyle.font = new BitmapFont();
timerLabel = new Label("", lStyle);
statusCenter.add(timerLabel);
statusCenter.row();
final TextButton showPlayers = new TextButton("Info", buttonStyle);
statusCenter.add(showPlayers).minWidth(75);
showPlayers.addListener(new ClickListener() {
private boolean dispOpp = false;
@Override
public void clicked(InputEvent event, float x, float y) {
if (dispOpp) {
displayNormal();
showPlayers.setText("Info");
} else {
displayOpponentInfo();
showPlayers.setText("Back");
}
dispOpp = !dispOpp;
}
});
DamageView dv = new DamageView(compTexture, robots.get(robotID));
LifeView lv = new LifeView(compTexture, robots.get(robotID));
lv.setPosition(0, 0);
lv.setSize(120, 80);
lv.debug();
dv.setPosition(290, 20);
dv.setSize(200, 40);
dv.debug();
statusBar.add(dv);
statusBar.add(lv);
allPlayerInfo = new Table();
allPlayerInfo.setPosition(0, 0);
allPlayerInfo.setSize(480, 240);
Table scrollContainer = new Table();
scrollContainer.defaults().width(240);
ScrollPane pane = new ScrollPane(scrollContainer);
allPlayerInfo.add(pane);
NinePatchDrawable divider = new NinePatchDrawable(new NinePatch(
new Texture(Gdx.files.internal("textures/divider.png")), 63,
63, 0, 0));
for (int i = 0; i < robots.size(); i++) {
if (i != robotID) {
scrollContainer.add(new LifeView(compTexture, robots.get(i)));
scrollContainer.add(new DamageView(compTexture, robots.get(i)));
scrollContainer.row();
if (i != robots.size() - 1) {
scrollContainer.add(new Image(divider)).colspan(2)
.width(420).pad(3);
scrollContainer.row();
}
}
}
scrollContainer.debug();
}
| public DeckView(List<RobotView> robots, int robotID, int roundTime) {
super();
this.roundTime = roundTime;
Texture deckTexture = new Texture(
Gdx.files.internal("textures/woodenDeck.png"));
deckTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Texture compTexture = new Texture(
Gdx.files.internal("textures/deckComponents.png"));
compTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
cl = new CardListener(this);
// Default camera
OrthographicCamera cardCamera = new OrthographicCamera(480, 800);
cardCamera.zoom = 1.0f;
cardCamera.position.set(240, 400, 0f);
cardCamera.update();
setCamera(cardCamera);
// Set background image
Image deck = new Image(new TextureRegion(deckTexture, 0, 0, 480, 320));
deck.setPosition(0, 0);
deck.setSize(480, 320);
addActor(deck);
container = new Table();
container.debug();
container.setSize(480, 320);
container.setLayoutEnabled(false);
addActor(container);
lowerArea = new Table();
lowerArea.debug();
lowerArea.setSize(480, 120);
lowerArea.setLayoutEnabled(false);
container.add(lowerArea);
upperArea = new Table();
upperArea.debug();
upperArea.setSize(480, 120);
upperArea.setPosition(0, 120);
upperArea.setLayoutEnabled(false);
container.add(upperArea);
statusBar = new Table();
statusBar.debug();
statusBar.setSize(480, 80);
statusBar.setPosition(0, 240);
statusBar.setLayoutEnabled(false);
container.add(statusBar);
registerView = new RegisterView(compTexture);
registerView.setSize(upperArea.getWidth(), upperArea.getHeight());
upperArea.add(registerView);
NinePatchDrawable buttonTexture = new NinePatchDrawable(new NinePatch(
new Texture(Gdx.files.internal("textures/button9patch.png")),
4, 4, 4, 4));
NinePatchDrawable buttonTexturePressed = new NinePatchDrawable(
new NinePatch(new Texture(Gdx.files
.internal("textures/button9patchpressed.png")), 4, 4,
4, 4));
buttonStyle = new TextButtonStyle(buttonTexture, buttonTexturePressed,
null);
buttonStyle.font = new BitmapFont();
buttonStyle.pressedOffsetX = 1;
buttonStyle.pressedOffsetY = -1;
TextButtonStyle playStyle = new TextButtonStyle(
new TextureRegionDrawable(new TextureRegion(compTexture, 0,
192, 64, 64)), new TextureRegionDrawable(
new TextureRegion(compTexture, 64, 192, 64, 64)), null);
playStyle.disabled = new TextureRegionDrawable(new TextureRegion(
compTexture, 128, 192, 64, 64));
playStyle.font = new BitmapFont();
playStyle.fontColor = Color.WHITE;
playStyle.disabledFontColor = Color.GRAY;
playStyle.pressedOffsetX = 1;
playStyle.pressedOffsetY = -1;
runButton = new TextButton("\r\nRun", playStyle);
runButton.setPosition(410, 20);
runButton.setSize(64, 64);
runButton.setDisabled(true);
registerView.add(runButton);
runButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (!runButton.isDisabled()) {
runButton.setDisabled(true);
pcs.firePropertyChange(EVENT_RUN, 0, 1);
}
}
});
playPanel = buildPlayerPanel();
drawPanel = buildDrawCardPanel();
timer = new Timer();
// Tick every second.
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (cardTick > 0) {
cardTick--;
if (cardTick == 0) {
pcs.firePropertyChange(TIMER_CARDS, 0, 1);
}
}
if (roundTick - MAX_PING > 0) {
roundTick--;
if (roundTick - MAX_PING == 0) {
pcs.firePropertyChange(TIMER_ROUND, 0, 1);
}
}
int timerTick = cardTick > 0 ? cardTick : Math.max(0, roundTick
- MAX_PING);
timerLabel.setVisible(timerTick > 0);
setTimerLabel(timerTick);
}
}, 1000, 1000);
Table statusCenter = new Table();
statusCenter.setPosition(200, 0);
statusCenter.setSize(80, statusBar.getHeight());
statusCenter.debug();
statusBar.add(statusCenter);
LabelStyle lStyle = new LabelStyle();
lStyle.font = new BitmapFont();
timerLabel = new Label("00:00:00", lStyle);
timerLabel.setVisible(false);
statusCenter.add(timerLabel);
statusCenter.row();
final TextButton showPlayers = new TextButton("Info", buttonStyle);
statusCenter.add(showPlayers).minWidth(75);
showPlayers.addListener(new ClickListener() {
private boolean dispOpp = false;
@Override
public void clicked(InputEvent event, float x, float y) {
if (dispOpp) {
displayNormal();
showPlayers.setText("Info");
} else {
displayOpponentInfo();
showPlayers.setText("Back");
}
dispOpp = !dispOpp;
}
});
DamageView dv = new DamageView(compTexture, robots.get(robotID));
LifeView lv = new LifeView(compTexture, robots.get(robotID));
lv.setPosition(0, 0);
lv.setSize(120, 80);
lv.debug();
dv.setPosition(290, 20);
dv.setSize(200, 40);
dv.debug();
statusBar.add(dv);
statusBar.add(lv);
allPlayerInfo = new Table();
allPlayerInfo.setPosition(0, 0);
allPlayerInfo.setSize(480, 240);
Table scrollContainer = new Table();
scrollContainer.defaults().width(240);
ScrollPane pane = new ScrollPane(scrollContainer);
allPlayerInfo.add(pane);
NinePatchDrawable divider = new NinePatchDrawable(new NinePatch(
new Texture(Gdx.files.internal("textures/divider.png")), 63,
63, 0, 0));
for (int i = 0; i < robots.size(); i++) {
if (i != robotID) {
scrollContainer.add(new LifeView(compTexture, robots.get(i)));
scrollContainer.add(new DamageView(compTexture, robots.get(i)));
scrollContainer.row();
if (i != robots.size() - 1) {
scrollContainer.add(new Image(divider)).colspan(2)
.width(420).pad(3);
scrollContainer.row();
}
}
}
scrollContainer.debug();
}
|
diff --git a/src/tsa2035/game/engine/scene/Player.java b/src/tsa2035/game/engine/scene/Player.java
index b2dde13..30de770 100644
--- a/src/tsa2035/game/engine/scene/Player.java
+++ b/src/tsa2035/game/engine/scene/Player.java
@@ -1,163 +1,163 @@
package tsa2035.game.engine.scene;
import java.util.Iterator;
import org.lwjgl.input.Keyboard;
import tsa2035.game.engine.bounding.Side;
import tsa2035.game.engine.texture.Texture;
public class Player extends Sprite {
boolean handleGravity;
float fallRate = 0.00005f;
float jumpHeight = 0;
float jumpRate = 0;
boolean isJumping = false;
boolean jumpingDisabled = false;
float currentJumpOffset = 0f;
float lastJumpOffset = 0;
protected boolean isWalking = false;
protected boolean leftWalking = false;
SinglePressKeyboard interactKey = new SinglePressKeyboard(Keyboard.KEY_E);
public Player(float x, float y, Texture t, boolean handleGravity) {
super(x, y, t);
this.handleGravity = handleGravity;
}
public Player(float x, float y, Texture t, boolean handleGravity, float jumpHeight, float jumpRate)
{
this(x,y,t, handleGravity);
this.jumpHeight = jumpHeight;
this.jumpRate = jumpRate;
}
public void setGravity(boolean state)
{
handleGravity = state;
}
public boolean isHandlingGravity()
{
return handleGravity;
}
public void setJumpingDisabled(boolean state)
{
jumpingDisabled = state;
}
public boolean isJumpingDisabled()
{
return jumpingDisabled;
}
public void render(Scene scene)
{
Iterator<Sprite> sceneObjects = scene.iterator();
boolean hitSides[] = new boolean[4];
boolean freefall = false;
boolean allowJumping = false;
boolean interactPressed = interactKey.check();
while ( sceneObjects.hasNext() )
{
Sprite thisObj = sceneObjects.next();
if ( !this.equals(thisObj) && !thisObj.isHidden() )
{
if ( interactPressed )
thisObj.interact(this);
if ( thisObj.isSolid() )
{
Side hitSide = sideOfContact(thisObj);
if ( hitSide == Side.BOTTOM )
isJumping = false;
if ( hitSide == Side.TOP )
allowJumping = true;
if ( thisObj.isPushable() )
{
if ( hitSide == Side.LEFT )
{
thisObj.setX(getX()+(getWidth()*2));
}
else if ( hitSide == Side.RIGHT )
{
thisObj.setX(getX()-(getWidth()*2));
}
}
else if ( hitSide != Side.NONE )
hitSides[hitSide.ordinal()] = true;
}
}
}
if ( jumpingDisabled )
allowJumping = false;
if ( !isJumping )
isJumping = ( allowJumping && Keyboard.isKeyDown(Keyboard.KEY_SPACE) );
freefall = (!hitSides[Side.TOP.ordinal()] && handleGravity);
if ( freefall )
fallRate += (float) Math.sqrt(fallRate)/300;
else
fallRate = 0.00005f;
if ( fallRate > 0.01 )
fallRate = 0.01f;
if ( freefall && !isJumping )
{
setY(getY()-fallRate);
}
else if ( isJumping && jumpHeight > 0 )
{
currentJumpOffset += jumpRate;
setY((getY()-lastJumpOffset)+currentJumpOffset);
lastJumpOffset = currentJumpOffset;
if ( currentJumpOffset >= jumpHeight )
{
isJumping = false;
currentJumpOffset = 0;
lastJumpOffset = 0;
}
}
isWalking = false;
- if ( !hitSides[Side.RIGHT.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_A) )
+ if ( !hitSides[Side.RIGHT.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_A) && getX() > -1.0f )
{
setX(getX()-0.005f);
isWalking = true;
leftWalking = true;
}
if ( !hitSides[Side.TOP.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_S) && !freefall )
{
setY(getY()-0.005f);
}
if ( Keyboard.isKeyDown(Keyboard.KEY_W) && !handleGravity )
{
setY(getY()+0.005f);
}
- if ( !hitSides[Side.LEFT.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_D) )
+ if ( !hitSides[Side.LEFT.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_D) && getX() < 1.0f )
{
setX(getX()+0.005f);
isWalking = true;
leftWalking = false;
}
super.render(scene);
}
}
| false | true | public void render(Scene scene)
{
Iterator<Sprite> sceneObjects = scene.iterator();
boolean hitSides[] = new boolean[4];
boolean freefall = false;
boolean allowJumping = false;
boolean interactPressed = interactKey.check();
while ( sceneObjects.hasNext() )
{
Sprite thisObj = sceneObjects.next();
if ( !this.equals(thisObj) && !thisObj.isHidden() )
{
if ( interactPressed )
thisObj.interact(this);
if ( thisObj.isSolid() )
{
Side hitSide = sideOfContact(thisObj);
if ( hitSide == Side.BOTTOM )
isJumping = false;
if ( hitSide == Side.TOP )
allowJumping = true;
if ( thisObj.isPushable() )
{
if ( hitSide == Side.LEFT )
{
thisObj.setX(getX()+(getWidth()*2));
}
else if ( hitSide == Side.RIGHT )
{
thisObj.setX(getX()-(getWidth()*2));
}
}
else if ( hitSide != Side.NONE )
hitSides[hitSide.ordinal()] = true;
}
}
}
if ( jumpingDisabled )
allowJumping = false;
if ( !isJumping )
isJumping = ( allowJumping && Keyboard.isKeyDown(Keyboard.KEY_SPACE) );
freefall = (!hitSides[Side.TOP.ordinal()] && handleGravity);
if ( freefall )
fallRate += (float) Math.sqrt(fallRate)/300;
else
fallRate = 0.00005f;
if ( fallRate > 0.01 )
fallRate = 0.01f;
if ( freefall && !isJumping )
{
setY(getY()-fallRate);
}
else if ( isJumping && jumpHeight > 0 )
{
currentJumpOffset += jumpRate;
setY((getY()-lastJumpOffset)+currentJumpOffset);
lastJumpOffset = currentJumpOffset;
if ( currentJumpOffset >= jumpHeight )
{
isJumping = false;
currentJumpOffset = 0;
lastJumpOffset = 0;
}
}
isWalking = false;
if ( !hitSides[Side.RIGHT.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_A) )
{
setX(getX()-0.005f);
isWalking = true;
leftWalking = true;
}
if ( !hitSides[Side.TOP.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_S) && !freefall )
{
setY(getY()-0.005f);
}
if ( Keyboard.isKeyDown(Keyboard.KEY_W) && !handleGravity )
{
setY(getY()+0.005f);
}
if ( !hitSides[Side.LEFT.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_D) )
{
setX(getX()+0.005f);
isWalking = true;
leftWalking = false;
}
super.render(scene);
}
| public void render(Scene scene)
{
Iterator<Sprite> sceneObjects = scene.iterator();
boolean hitSides[] = new boolean[4];
boolean freefall = false;
boolean allowJumping = false;
boolean interactPressed = interactKey.check();
while ( sceneObjects.hasNext() )
{
Sprite thisObj = sceneObjects.next();
if ( !this.equals(thisObj) && !thisObj.isHidden() )
{
if ( interactPressed )
thisObj.interact(this);
if ( thisObj.isSolid() )
{
Side hitSide = sideOfContact(thisObj);
if ( hitSide == Side.BOTTOM )
isJumping = false;
if ( hitSide == Side.TOP )
allowJumping = true;
if ( thisObj.isPushable() )
{
if ( hitSide == Side.LEFT )
{
thisObj.setX(getX()+(getWidth()*2));
}
else if ( hitSide == Side.RIGHT )
{
thisObj.setX(getX()-(getWidth()*2));
}
}
else if ( hitSide != Side.NONE )
hitSides[hitSide.ordinal()] = true;
}
}
}
if ( jumpingDisabled )
allowJumping = false;
if ( !isJumping )
isJumping = ( allowJumping && Keyboard.isKeyDown(Keyboard.KEY_SPACE) );
freefall = (!hitSides[Side.TOP.ordinal()] && handleGravity);
if ( freefall )
fallRate += (float) Math.sqrt(fallRate)/300;
else
fallRate = 0.00005f;
if ( fallRate > 0.01 )
fallRate = 0.01f;
if ( freefall && !isJumping )
{
setY(getY()-fallRate);
}
else if ( isJumping && jumpHeight > 0 )
{
currentJumpOffset += jumpRate;
setY((getY()-lastJumpOffset)+currentJumpOffset);
lastJumpOffset = currentJumpOffset;
if ( currentJumpOffset >= jumpHeight )
{
isJumping = false;
currentJumpOffset = 0;
lastJumpOffset = 0;
}
}
isWalking = false;
if ( !hitSides[Side.RIGHT.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_A) && getX() > -1.0f )
{
setX(getX()-0.005f);
isWalking = true;
leftWalking = true;
}
if ( !hitSides[Side.TOP.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_S) && !freefall )
{
setY(getY()-0.005f);
}
if ( Keyboard.isKeyDown(Keyboard.KEY_W) && !handleGravity )
{
setY(getY()+0.005f);
}
if ( !hitSides[Side.LEFT.ordinal()] && Keyboard.isKeyDown(Keyboard.KEY_D) && getX() < 1.0f )
{
setX(getX()+0.005f);
isWalking = true;
leftWalking = false;
}
super.render(scene);
}
|
diff --git a/src/share/classes/sun/tools/jconsole/resources/JConsoleResources.java b/src/share/classes/sun/tools/jconsole/resources/JConsoleResources.java
index c9e8ac07c..e642b2680 100644
--- a/src/share/classes/sun/tools/jconsole/resources/JConsoleResources.java
+++ b/src/share/classes/sun/tools/jconsole/resources/JConsoleResources.java
@@ -1,460 +1,462 @@
/*
* Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.tools.jconsole.resources;
import java.util.*;
import static java.awt.event.KeyEvent.*;
/**
* <p> This class represents the <code>ResourceBundle</code>
* for the following package(s):
*
* <ol>
* <li> sun.tools.jconsole
* </ol>
*
* <P>
* Subclasses must override <code>getContents0</code> and provide an array,
* where each item in the array consists of a <code>String</code> key,
* and either a <code>String</code> value associated with that key,
* or if the keys ends with ".mnemonic", an element
* representing a mnemomic keycode <code>int</code> or <code>char</code>.
*/
public class JConsoleResources extends ListResourceBundle {
/**
* Returns the contents of this <code>ResourceBundle</code>.
*
* <p>
*
* @return the contents of this <code>ResourceBundle</code>.
*/
protected Object[][] getContents0() {
Object[][] temp = new Object[][] {
// NOTE 1: The value strings in this file containing "{0}" are
// processed by the java.text.MessageFormat class. Any
// single quotes appearing in these strings need to be
// doubled up.
//
// NOTE 2: To make working with this file a bit easier, please
// maintain these messages in ASCII sorted order by
// message key.
//
// LOCALIZE THIS
{" 1 day"," 1 day"},
{" 1 hour"," 1 hour"},
{" 1 min"," 1 min"},
{" 1 month"," 1 month"},
{" 1 year"," 1 year"},
{" 2 hours"," 2 hours"},
{" 3 hours"," 3 hours"},
{" 3 months"," 3 months"},
{" 5 min"," 5 min"},
{" 6 hours"," 6 hours"},
{" 6 months"," 6 months"},
{" 7 days"," 7 days"},
{"10 min","10 min"},
{"12 hours","12 hours"},
{"30 min","30 min"},
{"<","<"},
{"<<","<<"},
{">",">"},
{"ACTION","ACTION"},
{"ACTION_INFO","ACTION_INFO"},
{"All","All"},
{"Apply","Apply"},
{"Architecture","Architecture"},
{"Array, OpenType", "Array, OpenType"},
{"Array, OpenType, Numeric value viewer","Array, OpenType, Numeric value viewer"},
{"Attribute","Attribute"},
{"Attribute value","Attribute value"},
{"Attribute values","Attribute values"},
{"Attributes","Attributes"},
{"Blank", "Blank"},
{"BlockedCount WaitedCount",
"Total blocked: {0} Total waited: {1}\n"},
{"Boot class path","Boot class path"},
{"BorderedComponent.moreOrLessButton.toolTip", "Toggle to show more or less information"},
{"CPU Usage","CPU Usage"},
{"CPUUsageFormat","CPU Usage: {0}%"},
{"Cancel","Cancel"},
{"Cascade", "Cascade"},
{"Cascade.mnemonic", 'C'},
{"Chart:", "Chart:"},
{"Chart:.mnemonic", 'C'},
{"Class path","Class path"},
{"Class","Class"},
{"ClassName","ClassName"},
{"ClassTab.infoLabelFormat", "<html>Loaded: {0} Unloaded: {1} Total: {2}</html>"},
{"ClassTab.loadedClassesPlotter.accessibleName", "Chart for Loaded Classes."},
{"Classes","Classes"},
{"Close","Close"},
{"Column.Name", "Name"},
{"Column.PID", "PID"},
{"Committed memory","Committed memory"},
{"Committed virtual memory","Committed virtual memory"},
{"Committed", "Committed"},
{"Compiler","Compiler"},
{"CompositeData","CompositeData"},
{"Config","Config"},
{"Connect", "Connect"},
{"Connect.mnemonic", 'C'},
{"Connect...","Connect..."},
{"ConnectDialog.connectButton.toolTip", "Connect to Java Virtual Machine"},
{"ConnectDialog.accessibleDescription", "Dialog for making a new connection to a local or remote Java Virtual Machine"},
{"ConnectDialog.masthead.accessibleName", "Masthead Graphic"},
{"ConnectDialog.masthead.title", "New Connection"},
{"ConnectDialog.statusBar.accessibleName", "Status Bar"},
{"ConnectDialog.title", "JConsole: New Connection"},
{"Connected. Click to disconnect.","Connected. Click to disconnect."},
{"Connection failed","Connection failed"},
{"Connection", "Connection"},
{"Connection.mnemonic", 'C'},
{"Connection name", "Connection name"},
{"ConnectionName (disconnected)","{0} (disconnected)"},
{"Constructor","Constructor"},
{"Current classes loaded", "Current classes loaded"},
{"Current heap size","Current heap size"},
{"Current value","Current value: {0}"},
{"Create", "Create"},
{"Daemon threads","Daemon threads"},
{"Disconnected. Click to connect.","Disconnected. Click to connect."},
{"Double click to expand/collapse","Double click to expand/collapse"},
{"Double click to visualize", "Double click to visualize"},
{"Description", "Description"},
{"Description: ", "Description: "},
{"Descriptor", "Descriptor"},
{"Details", "Details"},
{"Detect Deadlock", "Detect Deadlock"},
{"Detect Deadlock.mnemonic", 'D'},
{"Detect Deadlock.toolTip", "Detect deadlocked threads"},
{"Dimension is not supported:","Dimension is not supported:"},
{"Discard chart", "Discard chart"},
{"DurationDaysHoursMinutes","{0,choice,1#{0,number,integer} day |1.0<{0,number,integer} days }" +
"{1,choice,0<{1,number,integer} hours |1#{1,number,integer} hour |1<{1,number,integer} hours }" +
"{2,choice,0<{2,number,integer} minutes|1#{2,number,integer} minute|1.0<{2,number,integer} minutes}"},
{"DurationHoursMinutes","{0,choice,1#{0,number,integer} hour |1<{0,number,integer} hours }" +
"{1,choice,0<{1,number,integer} minutes|1#{1,number,integer} minute|1.0<{1,number,integer} minutes}"},
{"DurationMinutes","{0,choice,1#{0,number,integer} minute|1.0<{0,number,integer} minutes}"},
{"DurationSeconds","{0} seconds"},
{"Empty array", "Empty array"},
{"Empty opentype viewer", "Empty opentype viewer"},
{"Error","Error"},
{"Error: MBeans already exist","Error: MBeans already exist"},
{"Error: MBeans do not exist","Error: MBeans do not exist"},
{"Error:","Error:"},
{"Event","Event"},
{"Exit", "Exit"},
{"Exit.mnemonic", 'x'},
{"Fail to load plugin", "Warning: Fail to load plugin: {0}"},
{"FileChooser.fileExists.cancelOption", "Cancel"},
{"FileChooser.fileExists.message", "<html><center>File already exists:<br>{0}<br>Do you want to replace it?"},
{"FileChooser.fileExists.okOption", "Replace"},
{"FileChooser.fileExists.title", "File Exists"},
{"FileChooser.savedFile", "<html>Saved to file:<br>{0}<br>({1} bytes)"},
{"FileChooser.saveFailed.message", "<html><center>Save to file failed:<br>{0}<br>{1}"},
{"FileChooser.saveFailed.title", "Save Failed"},
{"Free physical memory","Free physical memory"},
{"Free swap space","Free swap space"},
{"Garbage collector","Garbage collector"},
{"GTK","GTK"},
{"GcInfo","Name = ''{0}'', Collections = {1,choice,-1#Unavailable|0#{1,number,integer}}, Total time spent = {2}"},
{"GC time","GC time"},
{"GC time details","{0} on {1} ({2} collections)"},
{"Heap Memory Usage","Heap Memory Usage"},
{"Heap", "Heap"},
{"Help.AboutDialog.accessibleDescription", "Dialog containing information about JConsole and JDK versions"},
{"Help.AboutDialog.jConsoleVersion", "JConsole version:<br>{0}"},
{"Help.AboutDialog.javaVersion", "Java VM version:<br>{0}"},
{"Help.AboutDialog.masthead.accessibleName", "Masthead Graphic"},
{"Help.AboutDialog.masthead.title", "About JConsole"},
{"Help.AboutDialog.title", "JConsole: About"},
{"Help.AboutDialog.userGuideLink", "JConsole User Guide:<br>{0}"},
{"Help.AboutDialog.userGuideLink.mnemonic", 'U'},
{"Help.AboutDialog.userGuideLink.url", "http://java.sun.com/javase/6/docs/technotes/guides/management/jconsole.html"},
{"HelpMenu.About.title", "About JConsole"},
{"HelpMenu.About.title.mnemonic", 'A'},
{"HelpMenu.UserGuide.title", "Online User Guide"},
{"HelpMenu.UserGuide.title.mnemonic", 'U'},
{"HelpMenu.title", "Help"},
{"HelpMenu.title.mnemonic", 'H'},
{"Hotspot MBeans...", "Hotspot MBeans..."},
{"Hotspot MBeans....mnemonic", 'H'},
{"Hotspot MBeans.dialog.accessibleDescription", "Dialog for managing Hotspot MBeans"},
{"Impact","Impact"},
{"Info","Info"},
{"INFO","INFO"},
{"Invalid plugin path", "Warning: Invalid plugin path: {0}"},
{"Invalid URL", "Invalid URL: {0}"},
{"Is","Is"},
{"Java Monitoring & Management Console", "Java Monitoring & Management Console"},
{"JConsole: ","JConsole: {0}"},
{"JConsole version","JConsole version \"{0}\""},
{"JConsole.accessibleDescription", "Java Monitoring & Management Console"},
{"JIT compiler","JIT compiler"},
{"Java Virtual Machine","Java Virtual Machine"},
{"Java","Java"},
{"Library path","Library path"},
{"Listeners","Listeners"},
{"Live Threads","Live threads"},
{"Loaded", "Loaded"},
{"Local Process:", "Local Process:"},
{"Local Process:.mnemonic", 'L'},
{"Look and Feel","Look and Feel"},
{"Masthead.font", "Dialog-PLAIN-25"},
{"Management Not Enabled","<b>Note</b>: The management agent is not enabled on this process."},
{"Management Will Be Enabled","<b>Note</b>: The management agent will be enabled on this process."},
{"MBeanAttributeInfo","MBeanAttributeInfo"},
{"MBeanInfo","MBeanInfo"},
{"MBeanNotificationInfo","MBeanNotificationInfo"},
{"MBeanOperationInfo","MBeanOperationInfo"},
{"MBeans","MBeans"},
{"MBeansTab.clearNotificationsButton", "Clear"},
{"MBeansTab.clearNotificationsButton.mnemonic", 'C'},
{"MBeansTab.clearNotificationsButton.toolTip", "Clear notifications"},
{"MBeansTab.compositeNavigationMultiple", "Composite Navigation {0}/{1}"},
{"MBeansTab.compositeNavigationSingle", "Composite Navigation"},
{"MBeansTab.refreshAttributesButton", "Refresh"},
{"MBeansTab.refreshAttributesButton.mnemonic", 'R'},
{"MBeansTab.refreshAttributesButton.toolTip", "Refresh attributes"},
{"MBeansTab.subscribeNotificationsButton", "Subscribe"},
{"MBeansTab.subscribeNotificationsButton.mnemonic", 'S'},
{"MBeansTab.subscribeNotificationsButton.toolTip", "Start listening for notifications"},
{"MBeansTab.tabularNavigationMultiple", "Tabular Navigation {0}/{1}"},
{"MBeansTab.tabularNavigationSingle", "Tabular Navigation"},
{"MBeansTab.unsubscribeNotificationsButton", "Unsubscribe"},
{"MBeansTab.unsubscribeNotificationsButton.mnemonic", 'U'},
{"MBeansTab.unsubscribeNotificationsButton.toolTip", "Stop listening for notifications"},
{"Manage Hotspot MBeans in: ", "Manage Hotspot MBeans in: "},
{"Max","Max"},
{"Maximum heap size","Maximum heap size"},
{"Memory","Memory"},
{"MemoryPoolLabel", "Memory Pool \"{0}\""},
{"MemoryTab.heapPlotter.accessibleName", "Memory usage chart for heap."},
{"MemoryTab.infoLabelFormat", "<html>Used: {0} Committed: {1} Max: {2}</html>"},
{"MemoryTab.nonHeapPlotter.accessibleName", "Memory usage chart for non heap."},
{"MemoryTab.poolChart.aboveThreshold", "which is above the threshold of {0}.\n"},
{"MemoryTab.poolChart.accessibleName", "Memory Pool Usage Chart."},
{"MemoryTab.poolChart.belowThreshold", "which is below the threshold of {0}.\n"},
{"MemoryTab.poolPlotter.accessibleName", "Memory usage chart for {0}."},
{"Message","Message"},
{"Method successfully invoked", "Method successfully invoked"},
{"Minimize All", "Minimize All"},
{"Minimize All.mnemonic", 'M'},
{"Minus Version", "This is {0} version {1}"},
{"Monitor locked",
" - locked {0}\n"},
{"Motif","Motif"},
{"Name Build and Mode","{0} (build {1}, {2})"},
{"Name and Build","{0} (build {1})"},
{"Name","Name"},
{"Name: ","Name: "},
{"Name State",
"Name: {0}\n" +
"State: {1}\n"},
{"Name State LockName",
"Name: {0}\n" +
"State: {1} on {2}\n"},
{"Name State LockName LockOwner",
"Name: {0}\n" +
"State: {1} on {2} owned by: {3}\n"},
{"New Connection...", "New Connection..."},
{"New Connection....mnemonic", 'N'},
{"New value applied","New value applied"},
{"No attribute selected","No attribute selected"},
{"No deadlock detected","No deadlock detected"},
{"No value selected","No value selected"},
{"Non-Heap Memory Usage","Non-Heap Memory Usage"},
{"Non-Heap", "Non-Heap"},
{"Not Yet Implemented","Not Yet Implemented"},
{"Not a valid event broadcaster", "Not a valid event broadcaster"},
{"Notification","Notification"},
{"Notification buffer","Notification buffer"},
{"Notifications","Notifications"},
{"NotifTypes", "NotifTypes"},
{"Number of Threads","Number of Threads"},
{"Number of Loaded Classes","Number of Loaded Classes"},
{"Number of processors","Number of processors"},
{"ObjectName","ObjectName"},
{"Operating System","Operating System"},
{"Operation","Operation"},
{"Operation invocation","Operation invocation"},
{"Operation return value", "Operation return value"},
{"Operations","Operations"},
{"Overview","Overview"},
{"OverviewPanel.plotter.accessibleName", "Chart for {0}."},
{"Parameter", "Parameter"},
{"Password: ", "Password: "},
{"Password: .mnemonic", 'P'},
{"Password.accessibleName", "Password"},
{"Peak","Peak"},
{"Perform GC", "Perform GC"},
{"Perform GC.mnemonic", 'G'},
{"Perform GC.toolTip", "Request Garbage Collection"},
{"Plotter.accessibleName", "Chart"},
{"Plotter.accessibleName.keyAndValue", "{0}={1}\n"},
{"Plotter.accessibleName.noData", "No data plotted."},
{"Plotter.saveAsMenuItem", "Save data as..."},
{"Plotter.saveAsMenuItem.mnemonic", 'a'},
{"Plotter.timeRangeMenu", "Time Range"},
{"Plotter.timeRangeMenu.mnemonic", 'T'},
{"Problem adding listener","Problem adding listener"},
{"Problem displaying MBean", "Problem displaying MBean"},
{"Problem invoking", "Problem invoking"},
{"Problem removing listener","Problem removing listener"},
{"Problem setting attribute","Problem setting attribute"},
{"Process CPU time","Process CPU time"},
{"R/W","R/W"},
{"Readable","Readable"},
{"Received","Received"},
{"Reconnect","Reconnect"},
{"Remote Process:", "Remote Process:"},
{"Remote Process:.mnemonic", 'R'},
{"Remote Process.textField.accessibleName", "Remote Process"},
{"Remove","Remove"},
{"Restore All", "Restore All"},
{"Restore All.mnemonic", 'R'},
{"Return value", "Return value"},
{"ReturnType", "ReturnType"},
{"SeqNum","SeqNum"},
{"Size Bytes", "{0,number,integer} bytes"},
{"Size Gb","{0} Gb"},
{"Size Kb","{0} Kb"},
{"Size Mb","{0} Mb"},
{"Source","Source"},
{"Stack trace",
"\nStack trace: \n"},
{"Success:","Success:"},
// Note: SummaryTab.headerDateTimeFormat can be one the following:
// 1. A combination of two styles for date and time, using the
// constants from class DateFormat: SHORT, MEDIUM, LONG, FULL.
// Example: "MEDIUM,MEDIUM" or "FULL,SHORT"
// 2. An explicit string pattern used for creating an instance
// of the class SimpleDateFormat.
// Example: "yyyy-MM-dd HH:mm:ss" or "M/d/yyyy h:mm:ss a"
{"SummaryTab.headerDateTimeFormat", "FULL,FULL"},
{"SummaryTab.pendingFinalization.label", "Pending finalization"},
{"SummaryTab.pendingFinalization.value", "{0} objects"},
{"SummaryTab.tabName", "VM Summary"},
{"SummaryTab.vmVersion","{0} version {1}"},
{"TabularData are not supported", "TabularData are not supported"},
{"Threads","Threads"},
{"ThreadTab.infoLabelFormat", "<html>Live: {0} Peak: {1} Total: {2}</html>"},
{"ThreadTab.threadInfo.accessibleName", "Thread Information"},
{"ThreadTab.threadPlotter.accessibleName", "Chart for number of threads."},
{"Threshold","Threshold"},
{"Tile", "Tile"},
{"Tile.mnemonic", 'T'},
{"Time Range:", "Time Range:"},
{"Time Range:.mnemonic", 'T'},
{"Time", "Time"},
{"TimeStamp","TimeStamp"},
{"Total Loaded", "Total Loaded"},
{"Total classes loaded","Total classes loaded"},
{"Total classes unloaded","Total classes unloaded"},
{"Total compile time","Total compile time"},
{"Total physical memory","Total physical memory"},
{"Total threads started","Total threads started"},
{"Total swap space","Total swap space"},
{"Type","Type"},
{"Unavailable","Unavailable"},
{"UNKNOWN","UNKNOWN"},
{"Unknown Host","Unknown Host: {0}"},
{"Unregister", "Unregister"},
{"Uptime","Uptime"},
{"Uptime: ","Uptime: "},
{"Usage Threshold","Usage Threshold"},
{"remoteTF.usage","<b>Usage</b>: <hostname>:<port> OR service:jmx:<protocol>:<sap>"},
{"Used","Used"},
{"Username: ", "Username: "},
{"Username: .mnemonic", 'U'},
{"Username.accessibleName", "User Name"},
{"UserData","UserData"},
{"Virtual Machine","Virtual Machine"},
{"VM arguments","VM arguments"},
{"VM","VM"},
{"VMInternalFrame.accessibleDescription", "Internal frame for monitoring a Java Virtual Machine"},
{"Value","Value"},
{"Vendor", "Vendor"},
{"Verbose Output","Verbose Output"},
{"Verbose Output.toolTip", "Enable verbose output for class loading system"},
{"View value", "View value"},
{"View","View"},
{"Window", "Window"},
{"Window.mnemonic", 'W'},
{"Windows","Windows"},
{"Writable","Writable"},
{"You cannot drop a class here", "You cannot drop a class here"},
{"collapse", "collapse"},
{"connectionFailed1","Connection Failed: Retry?"},
{"connectionFailed2","The connection to {0} did not succeed.<br>" +
"Would you like to try again?"},
{"connectionLost1","Connection Lost: Reconnect?"},
{"connectionLost2","The connection to {0} has been lost " +
"because the remote process has been terminated.<br>" +
"Would you like to reconnect?"},
{"connectingTo1","Connecting to {0}"},
{"connectingTo2","You are currently being connected to {0}.<br>" +
"This will take a few moments."},
{"deadlockAllTab","All"},
{"deadlockTab","Deadlock"},
{"deadlockTabN","Deadlock {0}"},
{"expand", "expand"},
{"kbytes","{0} kbytes"},
{"operation","operation"},
{"plot", "plot"},
{"visualize","visualize"},
{"zz usage text",
"Usage: {0} [ -interval=n ] [ -notile ] [ -pluginpath <path> ] [ -version ] [ connection ... ]\n\n" +
" -interval Set the update interval to n seconds (default is 4 seconds)\n" +
" -notile Do not tile windows initially (for two or more connections)\n" +
" -pluginpath Specify the path that jconsole uses to look up the plugins\n\n" +
" -version Print program version\n" +
" connection = pid || host:port || JMX URL (service:jmx:<protocol>://...)\n" +
" pid The process id of a target process\n" +
" host A remote host name or IP address\n" +
" port The port number for the remote connection\n\n" +
" -J Specify the input arguments to the Java virtual machine\n" +
" on which jconsole is running"},
// END OF MATERIAL TO LOCALIZE
};
String ls = System.getProperty("line.separator");
for(int i=0;i<temp.length;i++) {
+ if (temp[i][1] instanceof String){
temp[i][1] = temp[i][1].toString().replaceAll("\n",ls);
+ }
}
return temp;
}
public synchronized Object[][] getContents() {
return getContents0();
}
}
| false | true | protected Object[][] getContents0() {
Object[][] temp = new Object[][] {
// NOTE 1: The value strings in this file containing "{0}" are
// processed by the java.text.MessageFormat class. Any
// single quotes appearing in these strings need to be
// doubled up.
//
// NOTE 2: To make working with this file a bit easier, please
// maintain these messages in ASCII sorted order by
// message key.
//
// LOCALIZE THIS
{" 1 day"," 1 day"},
{" 1 hour"," 1 hour"},
{" 1 min"," 1 min"},
{" 1 month"," 1 month"},
{" 1 year"," 1 year"},
{" 2 hours"," 2 hours"},
{" 3 hours"," 3 hours"},
{" 3 months"," 3 months"},
{" 5 min"," 5 min"},
{" 6 hours"," 6 hours"},
{" 6 months"," 6 months"},
{" 7 days"," 7 days"},
{"10 min","10 min"},
{"12 hours","12 hours"},
{"30 min","30 min"},
{"<","<"},
{"<<","<<"},
{">",">"},
{"ACTION","ACTION"},
{"ACTION_INFO","ACTION_INFO"},
{"All","All"},
{"Apply","Apply"},
{"Architecture","Architecture"},
{"Array, OpenType", "Array, OpenType"},
{"Array, OpenType, Numeric value viewer","Array, OpenType, Numeric value viewer"},
{"Attribute","Attribute"},
{"Attribute value","Attribute value"},
{"Attribute values","Attribute values"},
{"Attributes","Attributes"},
{"Blank", "Blank"},
{"BlockedCount WaitedCount",
"Total blocked: {0} Total waited: {1}\n"},
{"Boot class path","Boot class path"},
{"BorderedComponent.moreOrLessButton.toolTip", "Toggle to show more or less information"},
{"CPU Usage","CPU Usage"},
{"CPUUsageFormat","CPU Usage: {0}%"},
{"Cancel","Cancel"},
{"Cascade", "Cascade"},
{"Cascade.mnemonic", 'C'},
{"Chart:", "Chart:"},
{"Chart:.mnemonic", 'C'},
{"Class path","Class path"},
{"Class","Class"},
{"ClassName","ClassName"},
{"ClassTab.infoLabelFormat", "<html>Loaded: {0} Unloaded: {1} Total: {2}</html>"},
{"ClassTab.loadedClassesPlotter.accessibleName", "Chart for Loaded Classes."},
{"Classes","Classes"},
{"Close","Close"},
{"Column.Name", "Name"},
{"Column.PID", "PID"},
{"Committed memory","Committed memory"},
{"Committed virtual memory","Committed virtual memory"},
{"Committed", "Committed"},
{"Compiler","Compiler"},
{"CompositeData","CompositeData"},
{"Config","Config"},
{"Connect", "Connect"},
{"Connect.mnemonic", 'C'},
{"Connect...","Connect..."},
{"ConnectDialog.connectButton.toolTip", "Connect to Java Virtual Machine"},
{"ConnectDialog.accessibleDescription", "Dialog for making a new connection to a local or remote Java Virtual Machine"},
{"ConnectDialog.masthead.accessibleName", "Masthead Graphic"},
{"ConnectDialog.masthead.title", "New Connection"},
{"ConnectDialog.statusBar.accessibleName", "Status Bar"},
{"ConnectDialog.title", "JConsole: New Connection"},
{"Connected. Click to disconnect.","Connected. Click to disconnect."},
{"Connection failed","Connection failed"},
{"Connection", "Connection"},
{"Connection.mnemonic", 'C'},
{"Connection name", "Connection name"},
{"ConnectionName (disconnected)","{0} (disconnected)"},
{"Constructor","Constructor"},
{"Current classes loaded", "Current classes loaded"},
{"Current heap size","Current heap size"},
{"Current value","Current value: {0}"},
{"Create", "Create"},
{"Daemon threads","Daemon threads"},
{"Disconnected. Click to connect.","Disconnected. Click to connect."},
{"Double click to expand/collapse","Double click to expand/collapse"},
{"Double click to visualize", "Double click to visualize"},
{"Description", "Description"},
{"Description: ", "Description: "},
{"Descriptor", "Descriptor"},
{"Details", "Details"},
{"Detect Deadlock", "Detect Deadlock"},
{"Detect Deadlock.mnemonic", 'D'},
{"Detect Deadlock.toolTip", "Detect deadlocked threads"},
{"Dimension is not supported:","Dimension is not supported:"},
{"Discard chart", "Discard chart"},
{"DurationDaysHoursMinutes","{0,choice,1#{0,number,integer} day |1.0<{0,number,integer} days }" +
"{1,choice,0<{1,number,integer} hours |1#{1,number,integer} hour |1<{1,number,integer} hours }" +
"{2,choice,0<{2,number,integer} minutes|1#{2,number,integer} minute|1.0<{2,number,integer} minutes}"},
{"DurationHoursMinutes","{0,choice,1#{0,number,integer} hour |1<{0,number,integer} hours }" +
"{1,choice,0<{1,number,integer} minutes|1#{1,number,integer} minute|1.0<{1,number,integer} minutes}"},
{"DurationMinutes","{0,choice,1#{0,number,integer} minute|1.0<{0,number,integer} minutes}"},
{"DurationSeconds","{0} seconds"},
{"Empty array", "Empty array"},
{"Empty opentype viewer", "Empty opentype viewer"},
{"Error","Error"},
{"Error: MBeans already exist","Error: MBeans already exist"},
{"Error: MBeans do not exist","Error: MBeans do not exist"},
{"Error:","Error:"},
{"Event","Event"},
{"Exit", "Exit"},
{"Exit.mnemonic", 'x'},
{"Fail to load plugin", "Warning: Fail to load plugin: {0}"},
{"FileChooser.fileExists.cancelOption", "Cancel"},
{"FileChooser.fileExists.message", "<html><center>File already exists:<br>{0}<br>Do you want to replace it?"},
{"FileChooser.fileExists.okOption", "Replace"},
{"FileChooser.fileExists.title", "File Exists"},
{"FileChooser.savedFile", "<html>Saved to file:<br>{0}<br>({1} bytes)"},
{"FileChooser.saveFailed.message", "<html><center>Save to file failed:<br>{0}<br>{1}"},
{"FileChooser.saveFailed.title", "Save Failed"},
{"Free physical memory","Free physical memory"},
{"Free swap space","Free swap space"},
{"Garbage collector","Garbage collector"},
{"GTK","GTK"},
{"GcInfo","Name = ''{0}'', Collections = {1,choice,-1#Unavailable|0#{1,number,integer}}, Total time spent = {2}"},
{"GC time","GC time"},
{"GC time details","{0} on {1} ({2} collections)"},
{"Heap Memory Usage","Heap Memory Usage"},
{"Heap", "Heap"},
{"Help.AboutDialog.accessibleDescription", "Dialog containing information about JConsole and JDK versions"},
{"Help.AboutDialog.jConsoleVersion", "JConsole version:<br>{0}"},
{"Help.AboutDialog.javaVersion", "Java VM version:<br>{0}"},
{"Help.AboutDialog.masthead.accessibleName", "Masthead Graphic"},
{"Help.AboutDialog.masthead.title", "About JConsole"},
{"Help.AboutDialog.title", "JConsole: About"},
{"Help.AboutDialog.userGuideLink", "JConsole User Guide:<br>{0}"},
{"Help.AboutDialog.userGuideLink.mnemonic", 'U'},
{"Help.AboutDialog.userGuideLink.url", "http://java.sun.com/javase/6/docs/technotes/guides/management/jconsole.html"},
{"HelpMenu.About.title", "About JConsole"},
{"HelpMenu.About.title.mnemonic", 'A'},
{"HelpMenu.UserGuide.title", "Online User Guide"},
{"HelpMenu.UserGuide.title.mnemonic", 'U'},
{"HelpMenu.title", "Help"},
{"HelpMenu.title.mnemonic", 'H'},
{"Hotspot MBeans...", "Hotspot MBeans..."},
{"Hotspot MBeans....mnemonic", 'H'},
{"Hotspot MBeans.dialog.accessibleDescription", "Dialog for managing Hotspot MBeans"},
{"Impact","Impact"},
{"Info","Info"},
{"INFO","INFO"},
{"Invalid plugin path", "Warning: Invalid plugin path: {0}"},
{"Invalid URL", "Invalid URL: {0}"},
{"Is","Is"},
{"Java Monitoring & Management Console", "Java Monitoring & Management Console"},
{"JConsole: ","JConsole: {0}"},
{"JConsole version","JConsole version \"{0}\""},
{"JConsole.accessibleDescription", "Java Monitoring & Management Console"},
{"JIT compiler","JIT compiler"},
{"Java Virtual Machine","Java Virtual Machine"},
{"Java","Java"},
{"Library path","Library path"},
{"Listeners","Listeners"},
{"Live Threads","Live threads"},
{"Loaded", "Loaded"},
{"Local Process:", "Local Process:"},
{"Local Process:.mnemonic", 'L'},
{"Look and Feel","Look and Feel"},
{"Masthead.font", "Dialog-PLAIN-25"},
{"Management Not Enabled","<b>Note</b>: The management agent is not enabled on this process."},
{"Management Will Be Enabled","<b>Note</b>: The management agent will be enabled on this process."},
{"MBeanAttributeInfo","MBeanAttributeInfo"},
{"MBeanInfo","MBeanInfo"},
{"MBeanNotificationInfo","MBeanNotificationInfo"},
{"MBeanOperationInfo","MBeanOperationInfo"},
{"MBeans","MBeans"},
{"MBeansTab.clearNotificationsButton", "Clear"},
{"MBeansTab.clearNotificationsButton.mnemonic", 'C'},
{"MBeansTab.clearNotificationsButton.toolTip", "Clear notifications"},
{"MBeansTab.compositeNavigationMultiple", "Composite Navigation {0}/{1}"},
{"MBeansTab.compositeNavigationSingle", "Composite Navigation"},
{"MBeansTab.refreshAttributesButton", "Refresh"},
{"MBeansTab.refreshAttributesButton.mnemonic", 'R'},
{"MBeansTab.refreshAttributesButton.toolTip", "Refresh attributes"},
{"MBeansTab.subscribeNotificationsButton", "Subscribe"},
{"MBeansTab.subscribeNotificationsButton.mnemonic", 'S'},
{"MBeansTab.subscribeNotificationsButton.toolTip", "Start listening for notifications"},
{"MBeansTab.tabularNavigationMultiple", "Tabular Navigation {0}/{1}"},
{"MBeansTab.tabularNavigationSingle", "Tabular Navigation"},
{"MBeansTab.unsubscribeNotificationsButton", "Unsubscribe"},
{"MBeansTab.unsubscribeNotificationsButton.mnemonic", 'U'},
{"MBeansTab.unsubscribeNotificationsButton.toolTip", "Stop listening for notifications"},
{"Manage Hotspot MBeans in: ", "Manage Hotspot MBeans in: "},
{"Max","Max"},
{"Maximum heap size","Maximum heap size"},
{"Memory","Memory"},
{"MemoryPoolLabel", "Memory Pool \"{0}\""},
{"MemoryTab.heapPlotter.accessibleName", "Memory usage chart for heap."},
{"MemoryTab.infoLabelFormat", "<html>Used: {0} Committed: {1} Max: {2}</html>"},
{"MemoryTab.nonHeapPlotter.accessibleName", "Memory usage chart for non heap."},
{"MemoryTab.poolChart.aboveThreshold", "which is above the threshold of {0}.\n"},
{"MemoryTab.poolChart.accessibleName", "Memory Pool Usage Chart."},
{"MemoryTab.poolChart.belowThreshold", "which is below the threshold of {0}.\n"},
{"MemoryTab.poolPlotter.accessibleName", "Memory usage chart for {0}."},
{"Message","Message"},
{"Method successfully invoked", "Method successfully invoked"},
{"Minimize All", "Minimize All"},
{"Minimize All.mnemonic", 'M'},
{"Minus Version", "This is {0} version {1}"},
{"Monitor locked",
" - locked {0}\n"},
{"Motif","Motif"},
{"Name Build and Mode","{0} (build {1}, {2})"},
{"Name and Build","{0} (build {1})"},
{"Name","Name"},
{"Name: ","Name: "},
{"Name State",
"Name: {0}\n" +
"State: {1}\n"},
{"Name State LockName",
"Name: {0}\n" +
"State: {1} on {2}\n"},
{"Name State LockName LockOwner",
"Name: {0}\n" +
"State: {1} on {2} owned by: {3}\n"},
{"New Connection...", "New Connection..."},
{"New Connection....mnemonic", 'N'},
{"New value applied","New value applied"},
{"No attribute selected","No attribute selected"},
{"No deadlock detected","No deadlock detected"},
{"No value selected","No value selected"},
{"Non-Heap Memory Usage","Non-Heap Memory Usage"},
{"Non-Heap", "Non-Heap"},
{"Not Yet Implemented","Not Yet Implemented"},
{"Not a valid event broadcaster", "Not a valid event broadcaster"},
{"Notification","Notification"},
{"Notification buffer","Notification buffer"},
{"Notifications","Notifications"},
{"NotifTypes", "NotifTypes"},
{"Number of Threads","Number of Threads"},
{"Number of Loaded Classes","Number of Loaded Classes"},
{"Number of processors","Number of processors"},
{"ObjectName","ObjectName"},
{"Operating System","Operating System"},
{"Operation","Operation"},
{"Operation invocation","Operation invocation"},
{"Operation return value", "Operation return value"},
{"Operations","Operations"},
{"Overview","Overview"},
{"OverviewPanel.plotter.accessibleName", "Chart for {0}."},
{"Parameter", "Parameter"},
{"Password: ", "Password: "},
{"Password: .mnemonic", 'P'},
{"Password.accessibleName", "Password"},
{"Peak","Peak"},
{"Perform GC", "Perform GC"},
{"Perform GC.mnemonic", 'G'},
{"Perform GC.toolTip", "Request Garbage Collection"},
{"Plotter.accessibleName", "Chart"},
{"Plotter.accessibleName.keyAndValue", "{0}={1}\n"},
{"Plotter.accessibleName.noData", "No data plotted."},
{"Plotter.saveAsMenuItem", "Save data as..."},
{"Plotter.saveAsMenuItem.mnemonic", 'a'},
{"Plotter.timeRangeMenu", "Time Range"},
{"Plotter.timeRangeMenu.mnemonic", 'T'},
{"Problem adding listener","Problem adding listener"},
{"Problem displaying MBean", "Problem displaying MBean"},
{"Problem invoking", "Problem invoking"},
{"Problem removing listener","Problem removing listener"},
{"Problem setting attribute","Problem setting attribute"},
{"Process CPU time","Process CPU time"},
{"R/W","R/W"},
{"Readable","Readable"},
{"Received","Received"},
{"Reconnect","Reconnect"},
{"Remote Process:", "Remote Process:"},
{"Remote Process:.mnemonic", 'R'},
{"Remote Process.textField.accessibleName", "Remote Process"},
{"Remove","Remove"},
{"Restore All", "Restore All"},
{"Restore All.mnemonic", 'R'},
{"Return value", "Return value"},
{"ReturnType", "ReturnType"},
{"SeqNum","SeqNum"},
{"Size Bytes", "{0,number,integer} bytes"},
{"Size Gb","{0} Gb"},
{"Size Kb","{0} Kb"},
{"Size Mb","{0} Mb"},
{"Source","Source"},
{"Stack trace",
"\nStack trace: \n"},
{"Success:","Success:"},
// Note: SummaryTab.headerDateTimeFormat can be one the following:
// 1. A combination of two styles for date and time, using the
// constants from class DateFormat: SHORT, MEDIUM, LONG, FULL.
// Example: "MEDIUM,MEDIUM" or "FULL,SHORT"
// 2. An explicit string pattern used for creating an instance
// of the class SimpleDateFormat.
// Example: "yyyy-MM-dd HH:mm:ss" or "M/d/yyyy h:mm:ss a"
{"SummaryTab.headerDateTimeFormat", "FULL,FULL"},
{"SummaryTab.pendingFinalization.label", "Pending finalization"},
{"SummaryTab.pendingFinalization.value", "{0} objects"},
{"SummaryTab.tabName", "VM Summary"},
{"SummaryTab.vmVersion","{0} version {1}"},
{"TabularData are not supported", "TabularData are not supported"},
{"Threads","Threads"},
{"ThreadTab.infoLabelFormat", "<html>Live: {0} Peak: {1} Total: {2}</html>"},
{"ThreadTab.threadInfo.accessibleName", "Thread Information"},
{"ThreadTab.threadPlotter.accessibleName", "Chart for number of threads."},
{"Threshold","Threshold"},
{"Tile", "Tile"},
{"Tile.mnemonic", 'T'},
{"Time Range:", "Time Range:"},
{"Time Range:.mnemonic", 'T'},
{"Time", "Time"},
{"TimeStamp","TimeStamp"},
{"Total Loaded", "Total Loaded"},
{"Total classes loaded","Total classes loaded"},
{"Total classes unloaded","Total classes unloaded"},
{"Total compile time","Total compile time"},
{"Total physical memory","Total physical memory"},
{"Total threads started","Total threads started"},
{"Total swap space","Total swap space"},
{"Type","Type"},
{"Unavailable","Unavailable"},
{"UNKNOWN","UNKNOWN"},
{"Unknown Host","Unknown Host: {0}"},
{"Unregister", "Unregister"},
{"Uptime","Uptime"},
{"Uptime: ","Uptime: "},
{"Usage Threshold","Usage Threshold"},
{"remoteTF.usage","<b>Usage</b>: <hostname>:<port> OR service:jmx:<protocol>:<sap>"},
{"Used","Used"},
{"Username: ", "Username: "},
{"Username: .mnemonic", 'U'},
{"Username.accessibleName", "User Name"},
{"UserData","UserData"},
{"Virtual Machine","Virtual Machine"},
{"VM arguments","VM arguments"},
{"VM","VM"},
{"VMInternalFrame.accessibleDescription", "Internal frame for monitoring a Java Virtual Machine"},
{"Value","Value"},
{"Vendor", "Vendor"},
{"Verbose Output","Verbose Output"},
{"Verbose Output.toolTip", "Enable verbose output for class loading system"},
{"View value", "View value"},
{"View","View"},
{"Window", "Window"},
{"Window.mnemonic", 'W'},
{"Windows","Windows"},
{"Writable","Writable"},
{"You cannot drop a class here", "You cannot drop a class here"},
{"collapse", "collapse"},
{"connectionFailed1","Connection Failed: Retry?"},
{"connectionFailed2","The connection to {0} did not succeed.<br>" +
"Would you like to try again?"},
{"connectionLost1","Connection Lost: Reconnect?"},
{"connectionLost2","The connection to {0} has been lost " +
"because the remote process has been terminated.<br>" +
"Would you like to reconnect?"},
{"connectingTo1","Connecting to {0}"},
{"connectingTo2","You are currently being connected to {0}.<br>" +
"This will take a few moments."},
{"deadlockAllTab","All"},
{"deadlockTab","Deadlock"},
{"deadlockTabN","Deadlock {0}"},
{"expand", "expand"},
{"kbytes","{0} kbytes"},
{"operation","operation"},
{"plot", "plot"},
{"visualize","visualize"},
{"zz usage text",
"Usage: {0} [ -interval=n ] [ -notile ] [ -pluginpath <path> ] [ -version ] [ connection ... ]\n\n" +
" -interval Set the update interval to n seconds (default is 4 seconds)\n" +
" -notile Do not tile windows initially (for two or more connections)\n" +
" -pluginpath Specify the path that jconsole uses to look up the plugins\n\n" +
" -version Print program version\n" +
" connection = pid || host:port || JMX URL (service:jmx:<protocol>://...)\n" +
" pid The process id of a target process\n" +
" host A remote host name or IP address\n" +
" port The port number for the remote connection\n\n" +
" -J Specify the input arguments to the Java virtual machine\n" +
" on which jconsole is running"},
// END OF MATERIAL TO LOCALIZE
};
String ls = System.getProperty("line.separator");
for(int i=0;i<temp.length;i++) {
temp[i][1] = temp[i][1].toString().replaceAll("\n",ls);
}
return temp;
}
| protected Object[][] getContents0() {
Object[][] temp = new Object[][] {
// NOTE 1: The value strings in this file containing "{0}" are
// processed by the java.text.MessageFormat class. Any
// single quotes appearing in these strings need to be
// doubled up.
//
// NOTE 2: To make working with this file a bit easier, please
// maintain these messages in ASCII sorted order by
// message key.
//
// LOCALIZE THIS
{" 1 day"," 1 day"},
{" 1 hour"," 1 hour"},
{" 1 min"," 1 min"},
{" 1 month"," 1 month"},
{" 1 year"," 1 year"},
{" 2 hours"," 2 hours"},
{" 3 hours"," 3 hours"},
{" 3 months"," 3 months"},
{" 5 min"," 5 min"},
{" 6 hours"," 6 hours"},
{" 6 months"," 6 months"},
{" 7 days"," 7 days"},
{"10 min","10 min"},
{"12 hours","12 hours"},
{"30 min","30 min"},
{"<","<"},
{"<<","<<"},
{">",">"},
{"ACTION","ACTION"},
{"ACTION_INFO","ACTION_INFO"},
{"All","All"},
{"Apply","Apply"},
{"Architecture","Architecture"},
{"Array, OpenType", "Array, OpenType"},
{"Array, OpenType, Numeric value viewer","Array, OpenType, Numeric value viewer"},
{"Attribute","Attribute"},
{"Attribute value","Attribute value"},
{"Attribute values","Attribute values"},
{"Attributes","Attributes"},
{"Blank", "Blank"},
{"BlockedCount WaitedCount",
"Total blocked: {0} Total waited: {1}\n"},
{"Boot class path","Boot class path"},
{"BorderedComponent.moreOrLessButton.toolTip", "Toggle to show more or less information"},
{"CPU Usage","CPU Usage"},
{"CPUUsageFormat","CPU Usage: {0}%"},
{"Cancel","Cancel"},
{"Cascade", "Cascade"},
{"Cascade.mnemonic", 'C'},
{"Chart:", "Chart:"},
{"Chart:.mnemonic", 'C'},
{"Class path","Class path"},
{"Class","Class"},
{"ClassName","ClassName"},
{"ClassTab.infoLabelFormat", "<html>Loaded: {0} Unloaded: {1} Total: {2}</html>"},
{"ClassTab.loadedClassesPlotter.accessibleName", "Chart for Loaded Classes."},
{"Classes","Classes"},
{"Close","Close"},
{"Column.Name", "Name"},
{"Column.PID", "PID"},
{"Committed memory","Committed memory"},
{"Committed virtual memory","Committed virtual memory"},
{"Committed", "Committed"},
{"Compiler","Compiler"},
{"CompositeData","CompositeData"},
{"Config","Config"},
{"Connect", "Connect"},
{"Connect.mnemonic", 'C'},
{"Connect...","Connect..."},
{"ConnectDialog.connectButton.toolTip", "Connect to Java Virtual Machine"},
{"ConnectDialog.accessibleDescription", "Dialog for making a new connection to a local or remote Java Virtual Machine"},
{"ConnectDialog.masthead.accessibleName", "Masthead Graphic"},
{"ConnectDialog.masthead.title", "New Connection"},
{"ConnectDialog.statusBar.accessibleName", "Status Bar"},
{"ConnectDialog.title", "JConsole: New Connection"},
{"Connected. Click to disconnect.","Connected. Click to disconnect."},
{"Connection failed","Connection failed"},
{"Connection", "Connection"},
{"Connection.mnemonic", 'C'},
{"Connection name", "Connection name"},
{"ConnectionName (disconnected)","{0} (disconnected)"},
{"Constructor","Constructor"},
{"Current classes loaded", "Current classes loaded"},
{"Current heap size","Current heap size"},
{"Current value","Current value: {0}"},
{"Create", "Create"},
{"Daemon threads","Daemon threads"},
{"Disconnected. Click to connect.","Disconnected. Click to connect."},
{"Double click to expand/collapse","Double click to expand/collapse"},
{"Double click to visualize", "Double click to visualize"},
{"Description", "Description"},
{"Description: ", "Description: "},
{"Descriptor", "Descriptor"},
{"Details", "Details"},
{"Detect Deadlock", "Detect Deadlock"},
{"Detect Deadlock.mnemonic", 'D'},
{"Detect Deadlock.toolTip", "Detect deadlocked threads"},
{"Dimension is not supported:","Dimension is not supported:"},
{"Discard chart", "Discard chart"},
{"DurationDaysHoursMinutes","{0,choice,1#{0,number,integer} day |1.0<{0,number,integer} days }" +
"{1,choice,0<{1,number,integer} hours |1#{1,number,integer} hour |1<{1,number,integer} hours }" +
"{2,choice,0<{2,number,integer} minutes|1#{2,number,integer} minute|1.0<{2,number,integer} minutes}"},
{"DurationHoursMinutes","{0,choice,1#{0,number,integer} hour |1<{0,number,integer} hours }" +
"{1,choice,0<{1,number,integer} minutes|1#{1,number,integer} minute|1.0<{1,number,integer} minutes}"},
{"DurationMinutes","{0,choice,1#{0,number,integer} minute|1.0<{0,number,integer} minutes}"},
{"DurationSeconds","{0} seconds"},
{"Empty array", "Empty array"},
{"Empty opentype viewer", "Empty opentype viewer"},
{"Error","Error"},
{"Error: MBeans already exist","Error: MBeans already exist"},
{"Error: MBeans do not exist","Error: MBeans do not exist"},
{"Error:","Error:"},
{"Event","Event"},
{"Exit", "Exit"},
{"Exit.mnemonic", 'x'},
{"Fail to load plugin", "Warning: Fail to load plugin: {0}"},
{"FileChooser.fileExists.cancelOption", "Cancel"},
{"FileChooser.fileExists.message", "<html><center>File already exists:<br>{0}<br>Do you want to replace it?"},
{"FileChooser.fileExists.okOption", "Replace"},
{"FileChooser.fileExists.title", "File Exists"},
{"FileChooser.savedFile", "<html>Saved to file:<br>{0}<br>({1} bytes)"},
{"FileChooser.saveFailed.message", "<html><center>Save to file failed:<br>{0}<br>{1}"},
{"FileChooser.saveFailed.title", "Save Failed"},
{"Free physical memory","Free physical memory"},
{"Free swap space","Free swap space"},
{"Garbage collector","Garbage collector"},
{"GTK","GTK"},
{"GcInfo","Name = ''{0}'', Collections = {1,choice,-1#Unavailable|0#{1,number,integer}}, Total time spent = {2}"},
{"GC time","GC time"},
{"GC time details","{0} on {1} ({2} collections)"},
{"Heap Memory Usage","Heap Memory Usage"},
{"Heap", "Heap"},
{"Help.AboutDialog.accessibleDescription", "Dialog containing information about JConsole and JDK versions"},
{"Help.AboutDialog.jConsoleVersion", "JConsole version:<br>{0}"},
{"Help.AboutDialog.javaVersion", "Java VM version:<br>{0}"},
{"Help.AboutDialog.masthead.accessibleName", "Masthead Graphic"},
{"Help.AboutDialog.masthead.title", "About JConsole"},
{"Help.AboutDialog.title", "JConsole: About"},
{"Help.AboutDialog.userGuideLink", "JConsole User Guide:<br>{0}"},
{"Help.AboutDialog.userGuideLink.mnemonic", 'U'},
{"Help.AboutDialog.userGuideLink.url", "http://java.sun.com/javase/6/docs/technotes/guides/management/jconsole.html"},
{"HelpMenu.About.title", "About JConsole"},
{"HelpMenu.About.title.mnemonic", 'A'},
{"HelpMenu.UserGuide.title", "Online User Guide"},
{"HelpMenu.UserGuide.title.mnemonic", 'U'},
{"HelpMenu.title", "Help"},
{"HelpMenu.title.mnemonic", 'H'},
{"Hotspot MBeans...", "Hotspot MBeans..."},
{"Hotspot MBeans....mnemonic", 'H'},
{"Hotspot MBeans.dialog.accessibleDescription", "Dialog for managing Hotspot MBeans"},
{"Impact","Impact"},
{"Info","Info"},
{"INFO","INFO"},
{"Invalid plugin path", "Warning: Invalid plugin path: {0}"},
{"Invalid URL", "Invalid URL: {0}"},
{"Is","Is"},
{"Java Monitoring & Management Console", "Java Monitoring & Management Console"},
{"JConsole: ","JConsole: {0}"},
{"JConsole version","JConsole version \"{0}\""},
{"JConsole.accessibleDescription", "Java Monitoring & Management Console"},
{"JIT compiler","JIT compiler"},
{"Java Virtual Machine","Java Virtual Machine"},
{"Java","Java"},
{"Library path","Library path"},
{"Listeners","Listeners"},
{"Live Threads","Live threads"},
{"Loaded", "Loaded"},
{"Local Process:", "Local Process:"},
{"Local Process:.mnemonic", 'L'},
{"Look and Feel","Look and Feel"},
{"Masthead.font", "Dialog-PLAIN-25"},
{"Management Not Enabled","<b>Note</b>: The management agent is not enabled on this process."},
{"Management Will Be Enabled","<b>Note</b>: The management agent will be enabled on this process."},
{"MBeanAttributeInfo","MBeanAttributeInfo"},
{"MBeanInfo","MBeanInfo"},
{"MBeanNotificationInfo","MBeanNotificationInfo"},
{"MBeanOperationInfo","MBeanOperationInfo"},
{"MBeans","MBeans"},
{"MBeansTab.clearNotificationsButton", "Clear"},
{"MBeansTab.clearNotificationsButton.mnemonic", 'C'},
{"MBeansTab.clearNotificationsButton.toolTip", "Clear notifications"},
{"MBeansTab.compositeNavigationMultiple", "Composite Navigation {0}/{1}"},
{"MBeansTab.compositeNavigationSingle", "Composite Navigation"},
{"MBeansTab.refreshAttributesButton", "Refresh"},
{"MBeansTab.refreshAttributesButton.mnemonic", 'R'},
{"MBeansTab.refreshAttributesButton.toolTip", "Refresh attributes"},
{"MBeansTab.subscribeNotificationsButton", "Subscribe"},
{"MBeansTab.subscribeNotificationsButton.mnemonic", 'S'},
{"MBeansTab.subscribeNotificationsButton.toolTip", "Start listening for notifications"},
{"MBeansTab.tabularNavigationMultiple", "Tabular Navigation {0}/{1}"},
{"MBeansTab.tabularNavigationSingle", "Tabular Navigation"},
{"MBeansTab.unsubscribeNotificationsButton", "Unsubscribe"},
{"MBeansTab.unsubscribeNotificationsButton.mnemonic", 'U'},
{"MBeansTab.unsubscribeNotificationsButton.toolTip", "Stop listening for notifications"},
{"Manage Hotspot MBeans in: ", "Manage Hotspot MBeans in: "},
{"Max","Max"},
{"Maximum heap size","Maximum heap size"},
{"Memory","Memory"},
{"MemoryPoolLabel", "Memory Pool \"{0}\""},
{"MemoryTab.heapPlotter.accessibleName", "Memory usage chart for heap."},
{"MemoryTab.infoLabelFormat", "<html>Used: {0} Committed: {1} Max: {2}</html>"},
{"MemoryTab.nonHeapPlotter.accessibleName", "Memory usage chart for non heap."},
{"MemoryTab.poolChart.aboveThreshold", "which is above the threshold of {0}.\n"},
{"MemoryTab.poolChart.accessibleName", "Memory Pool Usage Chart."},
{"MemoryTab.poolChart.belowThreshold", "which is below the threshold of {0}.\n"},
{"MemoryTab.poolPlotter.accessibleName", "Memory usage chart for {0}."},
{"Message","Message"},
{"Method successfully invoked", "Method successfully invoked"},
{"Minimize All", "Minimize All"},
{"Minimize All.mnemonic", 'M'},
{"Minus Version", "This is {0} version {1}"},
{"Monitor locked",
" - locked {0}\n"},
{"Motif","Motif"},
{"Name Build and Mode","{0} (build {1}, {2})"},
{"Name and Build","{0} (build {1})"},
{"Name","Name"},
{"Name: ","Name: "},
{"Name State",
"Name: {0}\n" +
"State: {1}\n"},
{"Name State LockName",
"Name: {0}\n" +
"State: {1} on {2}\n"},
{"Name State LockName LockOwner",
"Name: {0}\n" +
"State: {1} on {2} owned by: {3}\n"},
{"New Connection...", "New Connection..."},
{"New Connection....mnemonic", 'N'},
{"New value applied","New value applied"},
{"No attribute selected","No attribute selected"},
{"No deadlock detected","No deadlock detected"},
{"No value selected","No value selected"},
{"Non-Heap Memory Usage","Non-Heap Memory Usage"},
{"Non-Heap", "Non-Heap"},
{"Not Yet Implemented","Not Yet Implemented"},
{"Not a valid event broadcaster", "Not a valid event broadcaster"},
{"Notification","Notification"},
{"Notification buffer","Notification buffer"},
{"Notifications","Notifications"},
{"NotifTypes", "NotifTypes"},
{"Number of Threads","Number of Threads"},
{"Number of Loaded Classes","Number of Loaded Classes"},
{"Number of processors","Number of processors"},
{"ObjectName","ObjectName"},
{"Operating System","Operating System"},
{"Operation","Operation"},
{"Operation invocation","Operation invocation"},
{"Operation return value", "Operation return value"},
{"Operations","Operations"},
{"Overview","Overview"},
{"OverviewPanel.plotter.accessibleName", "Chart for {0}."},
{"Parameter", "Parameter"},
{"Password: ", "Password: "},
{"Password: .mnemonic", 'P'},
{"Password.accessibleName", "Password"},
{"Peak","Peak"},
{"Perform GC", "Perform GC"},
{"Perform GC.mnemonic", 'G'},
{"Perform GC.toolTip", "Request Garbage Collection"},
{"Plotter.accessibleName", "Chart"},
{"Plotter.accessibleName.keyAndValue", "{0}={1}\n"},
{"Plotter.accessibleName.noData", "No data plotted."},
{"Plotter.saveAsMenuItem", "Save data as..."},
{"Plotter.saveAsMenuItem.mnemonic", 'a'},
{"Plotter.timeRangeMenu", "Time Range"},
{"Plotter.timeRangeMenu.mnemonic", 'T'},
{"Problem adding listener","Problem adding listener"},
{"Problem displaying MBean", "Problem displaying MBean"},
{"Problem invoking", "Problem invoking"},
{"Problem removing listener","Problem removing listener"},
{"Problem setting attribute","Problem setting attribute"},
{"Process CPU time","Process CPU time"},
{"R/W","R/W"},
{"Readable","Readable"},
{"Received","Received"},
{"Reconnect","Reconnect"},
{"Remote Process:", "Remote Process:"},
{"Remote Process:.mnemonic", 'R'},
{"Remote Process.textField.accessibleName", "Remote Process"},
{"Remove","Remove"},
{"Restore All", "Restore All"},
{"Restore All.mnemonic", 'R'},
{"Return value", "Return value"},
{"ReturnType", "ReturnType"},
{"SeqNum","SeqNum"},
{"Size Bytes", "{0,number,integer} bytes"},
{"Size Gb","{0} Gb"},
{"Size Kb","{0} Kb"},
{"Size Mb","{0} Mb"},
{"Source","Source"},
{"Stack trace",
"\nStack trace: \n"},
{"Success:","Success:"},
// Note: SummaryTab.headerDateTimeFormat can be one the following:
// 1. A combination of two styles for date and time, using the
// constants from class DateFormat: SHORT, MEDIUM, LONG, FULL.
// Example: "MEDIUM,MEDIUM" or "FULL,SHORT"
// 2. An explicit string pattern used for creating an instance
// of the class SimpleDateFormat.
// Example: "yyyy-MM-dd HH:mm:ss" or "M/d/yyyy h:mm:ss a"
{"SummaryTab.headerDateTimeFormat", "FULL,FULL"},
{"SummaryTab.pendingFinalization.label", "Pending finalization"},
{"SummaryTab.pendingFinalization.value", "{0} objects"},
{"SummaryTab.tabName", "VM Summary"},
{"SummaryTab.vmVersion","{0} version {1}"},
{"TabularData are not supported", "TabularData are not supported"},
{"Threads","Threads"},
{"ThreadTab.infoLabelFormat", "<html>Live: {0} Peak: {1} Total: {2}</html>"},
{"ThreadTab.threadInfo.accessibleName", "Thread Information"},
{"ThreadTab.threadPlotter.accessibleName", "Chart for number of threads."},
{"Threshold","Threshold"},
{"Tile", "Tile"},
{"Tile.mnemonic", 'T'},
{"Time Range:", "Time Range:"},
{"Time Range:.mnemonic", 'T'},
{"Time", "Time"},
{"TimeStamp","TimeStamp"},
{"Total Loaded", "Total Loaded"},
{"Total classes loaded","Total classes loaded"},
{"Total classes unloaded","Total classes unloaded"},
{"Total compile time","Total compile time"},
{"Total physical memory","Total physical memory"},
{"Total threads started","Total threads started"},
{"Total swap space","Total swap space"},
{"Type","Type"},
{"Unavailable","Unavailable"},
{"UNKNOWN","UNKNOWN"},
{"Unknown Host","Unknown Host: {0}"},
{"Unregister", "Unregister"},
{"Uptime","Uptime"},
{"Uptime: ","Uptime: "},
{"Usage Threshold","Usage Threshold"},
{"remoteTF.usage","<b>Usage</b>: <hostname>:<port> OR service:jmx:<protocol>:<sap>"},
{"Used","Used"},
{"Username: ", "Username: "},
{"Username: .mnemonic", 'U'},
{"Username.accessibleName", "User Name"},
{"UserData","UserData"},
{"Virtual Machine","Virtual Machine"},
{"VM arguments","VM arguments"},
{"VM","VM"},
{"VMInternalFrame.accessibleDescription", "Internal frame for monitoring a Java Virtual Machine"},
{"Value","Value"},
{"Vendor", "Vendor"},
{"Verbose Output","Verbose Output"},
{"Verbose Output.toolTip", "Enable verbose output for class loading system"},
{"View value", "View value"},
{"View","View"},
{"Window", "Window"},
{"Window.mnemonic", 'W'},
{"Windows","Windows"},
{"Writable","Writable"},
{"You cannot drop a class here", "You cannot drop a class here"},
{"collapse", "collapse"},
{"connectionFailed1","Connection Failed: Retry?"},
{"connectionFailed2","The connection to {0} did not succeed.<br>" +
"Would you like to try again?"},
{"connectionLost1","Connection Lost: Reconnect?"},
{"connectionLost2","The connection to {0} has been lost " +
"because the remote process has been terminated.<br>" +
"Would you like to reconnect?"},
{"connectingTo1","Connecting to {0}"},
{"connectingTo2","You are currently being connected to {0}.<br>" +
"This will take a few moments."},
{"deadlockAllTab","All"},
{"deadlockTab","Deadlock"},
{"deadlockTabN","Deadlock {0}"},
{"expand", "expand"},
{"kbytes","{0} kbytes"},
{"operation","operation"},
{"plot", "plot"},
{"visualize","visualize"},
{"zz usage text",
"Usage: {0} [ -interval=n ] [ -notile ] [ -pluginpath <path> ] [ -version ] [ connection ... ]\n\n" +
" -interval Set the update interval to n seconds (default is 4 seconds)\n" +
" -notile Do not tile windows initially (for two or more connections)\n" +
" -pluginpath Specify the path that jconsole uses to look up the plugins\n\n" +
" -version Print program version\n" +
" connection = pid || host:port || JMX URL (service:jmx:<protocol>://...)\n" +
" pid The process id of a target process\n" +
" host A remote host name or IP address\n" +
" port The port number for the remote connection\n\n" +
" -J Specify the input arguments to the Java virtual machine\n" +
" on which jconsole is running"},
// END OF MATERIAL TO LOCALIZE
};
String ls = System.getProperty("line.separator");
for(int i=0;i<temp.length;i++) {
if (temp[i][1] instanceof String){
temp[i][1] = temp[i][1].toString().replaceAll("\n",ls);
}
}
return temp;
}
|
diff --git a/src/main/java/com/prealpha/dcputil/emulator/NewBaseMachine.java b/src/main/java/com/prealpha/dcputil/emulator/NewBaseMachine.java
index 2afa527..d6f11f1 100755
--- a/src/main/java/com/prealpha/dcputil/emulator/NewBaseMachine.java
+++ b/src/main/java/com/prealpha/dcputil/emulator/NewBaseMachine.java
@@ -1,514 +1,514 @@
package com.prealpha.dcputil.emulator;
import static com.prealpha.dcputil.emulator.EmulatorHelper.*;
import static com.prealpha.dcputil.emulator.NewBaseMachine.PointerType.*;
import static com.prealpha.dcputil.emulator.Opcodes.*;
import static com.prealpha.dcputil.emulator.Valuecodes.*;
import static com.prealpha.dcputil.util.PrintUtilities.convertHex;
/**
* User: Ty
* Date: 7/19/12
* Time: 11:46 AM
*/
class NewBaseMachine {
public static enum PointerType{
POINTER_MEMORY,
POINTER_REGISTER,
POINTER_PC,
POINTER_SP,
POINTER_EX,
POINTER_LITERAL,
}
private class Pointer {
private final PointerType type;
private final char pointer;
public Pointer(PointerType type){
this.type = type;
this.pointer = 0xffff;
}
public Pointer(PointerType type, char pointerValue){
this.type = type;
this.pointer = pointerValue;
}
public char get(){
switch(type){
case POINTER_MEMORY:
return memory[pointer];
case POINTER_REGISTER:
return registers[pointer];
case POINTER_PC:
return pc;
case POINTER_SP:
return sp;
case POINTER_EX:
return ex;
case POINTER_LITERAL:
return pointer;
default:
return 0xffff;
}
}
public void set(char data){
switch(type){
case POINTER_MEMORY:
memory[pointer] = data;
modified[pointer] = true;
break;
case POINTER_REGISTER:
registers[pointer] = data;
break;
case POINTER_PC:
pc = data;
break;
case POINTER_SP:
sp = data;
break;
case POINTER_EX:
ex = data;
break;
case POINTER_LITERAL:
// Silently fail...
}
}
}
protected boolean isRunning = false;
private static final char A_SIZE = 6;
private static final char B_SIZE = 5;
private static final char OP_SIZE = 5;
protected char[] registers = new char[0x07+1];
protected char sp = 0x0;
protected char pc = 0x0;
protected char ex = 0x0;
protected char[] lastProgram;
protected char[] memory = new char[0xffff+1];
protected boolean[] modified = new boolean[memory.length];
public void load(char[] program){
System.arraycopy(program, 0, memory, 0, program.length);
lastProgram = program.clone();
}
public void step() throws EmulatorException {
char instruction = memory[pc++];
char opcode = clear(instruction, A_SIZE+B_SIZE, 0);
char opA = clear(instruction, 0, B_SIZE+OP_SIZE);
char opB = clear(instruction, A_SIZE, B_SIZE);
int offset = 0;
Pointer pa = getPointer(opA, offset, true);
offset+= getOffset(opA);
Pointer pb = getPointer(opB, offset, false);
offset+= getOffset(opB);
pc += offset;
char a = pa.get();
char b = pb.get();
short shortB = (short) a;
short shortA = (short) b;
switch (opcode){
case SET:
b = a;
break;
// Math
case ADD:
ex = over(b+a)? (char) 0x0001 : (char) 0x0;
b += a;
break;
case SUB:
ex = over(b-a)? (char) 0xffff : (char) 0x0;
b -= a;
break;
case MUL:
ex = (char)(((b*a)>>16)&0xffff);
b *= a;
break;
case MLI:
ex = (char)(((shortB*shortA)>>16)&0xffff);
shortB *= shortA;
b = (char) shortB;
break;
case DIV:
if(a==0){
b = 0;
ex = 0;
}
else{
ex = (char) (((b<<16)/a)&0xffff);
b /= a;
}
break;
case DVI:
if(shortA==0){
shortB = 0;
b = (char)shortB;
ex = 0;
}
else{
ex = (char)(((shortB/shortA)>>16)&0xffff);
shortB /= shortA;
b = (char) shortB;
}
break;
case MOD:
if(a==0){
b = 0;
}
else{
b %= a;
}
break;
case MDI:
if(shortA==0){
shortB = 0;
b = (char) shortB;
}
else{
shortB %= shortA;
b = (char) shortB;
}
break;
// Bit fiddling
case AND:
b &= a;
break;
case BOR:
b|=a;
break;
case XOR:
b^=a;
break;
case SHR:
ex = (char) (((b<<16)>>a)&0xffff);
b>>>=a;
break;
case ASR:
ex = (char) (((b<<16)>>>a)&0xffff);
b>>=a;
break;
case SHL:
ex = (char) (((b<<a)>>16)&0xffff);
b <<= a;
break;
// IF statements
case IFB:
if((b&a)!=0){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFC:
if((b&a)==0){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFE:
if(b==a){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFN:
if(b!=a){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFG:
if(b>a){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFA:
- if(b>a){
+ if(shortB>shortA){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFL:
- if(b>a){
+ if(b<a){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFU:
- if(b<a){
+ if(shortB<shortA){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case ADX:
ex = (char) (over(b+a+ex)? 0x0001 : 0x0);
b+=a;
b+=ex;
break;
case SBX:
ex = (char) (over(b-a+ex)? 0xFFFF : 0x0);
b-=a;
b+=ex;
break;
case STI:
b = a;
registers[registers.length-1] = (char) (registers[registers.length-1]+1);
registers[registers.length-2] = (char) (registers[registers.length-2]+1);
break;
case STD:
b = a;
registers[registers.length-1] = (char) (registers[registers.length-1]-1);
registers[registers.length-2] = (char) (registers[registers.length-2]-1);
break;
case SPECIAL:
switch (opB){
case JSR:
opB = PUSH_POP;
b = pc;
pc = a;
break;
case BRK:
this.isRunning = false;
return;
case INT:
case IAG:
case IAS:
case FRI:
case IAQ:
case HWN:
case HWQ:
case HWI:
throw new EmulatorException("Operation not accepted"+convertHex(opB),pc);
}
}
pb.set(b);
}
private Pointer getPointer(char input, int offset, boolean isA) throws EmulatorException {
if(input <= REGISTER_MAX){
return new Pointer(POINTER_REGISTER, input);
}
if(input <= POINTER_REGISTER_MAX){
return new Pointer(POINTER_MEMORY,registers[input-POINT_A]);
}
if(input <= POINTER_REGISTER_NEXT_MAX){
return new Pointer(POINTER_MEMORY, (char) (registers[input-POINT_A_NEXT]+memory[pc+offset]));
}
if(input == PUSH_POP){
// POP
if(isA){
return new Pointer(POINTER_MEMORY, (char) (sp++));
}
// PUSH
else{
return new Pointer(POINTER_MEMORY, (char) (--sp));
}
}
if(input == PEEK){
return new Pointer(POINTER_MEMORY, sp);
}
if(input==PICK){
return new Pointer(POINTER_MEMORY, (char)(sp+memory[pc+offset]));
}
if(input == SP){
return new Pointer(POINTER_SP);
}
if(input == PC){
return new Pointer(POINTER_PC);
}
if(input == EX){
return new Pointer(POINTER_EX);
}
if(input == POINT_NEXT){
return new Pointer(POINTER_MEMORY, memory[pc+offset]);
}
if(input == NEXT){
return new Pointer(POINTER_MEMORY, (char) (pc+offset));
}
if(input>=LITERAL_MIN && input<=LITERAL_MAX){
return new Pointer(POINTER_LITERAL, (char) (input-0x21));
}
throw new EmulatorException("cant identify ValueCode: "+(int) input,pc);
}
// private void set(char opB, char data){
// if(opB <= REGISTER_MAX){
// registers[opB] = data;
// return;
// }
// if(opB <= POINTER_REGISTER_MAX){
// memory[registers[opB-POINT_A]] = data;
// return;
// }
// if(opB <= POINTER_REGISTER_NEXT_MAX){
// memory[registers[opB-POINT_A_NEXT]+memory[pc++]] = data;
// return;
// }
// if(opB == PUSH_POP){
// memory[--sp] = data;
// modified[sp] = true;
// return;
// }
// if(opB == PEEK){
// memory[sp] = data;
// modified[sp] = true;
// return;
// }
// if(opB==PICK){
// char place = (char) (sp+memory[pc++]);
// memory[place] = data;
// modified[place] = true;
// return;
// }
// if(opB == SP){
// sp = data;
// return;
// }
// if(opB == PC){
// pc = data;
// return;
// }
// if(opB == EX){
// ex = data;
// return;
// }
// if(opB == POINT_NEXT){
// memory[memory[pc++]] = data;
// }
// if(opB == NEXT){
// memory[pc++] = data;
// }
// }
//
// private char valueOf(char input, boolean isA) throws EmulatorException {
// if(input <= REGISTER_MAX){
// return registers[input];
// }
// if(input <= POINTER_REGISTER_MAX){
// return memory[registers[input-POINT_A]];
// }
// if(input <= POINTER_REGISTER_NEXT_MAX){
// return memory[registers[input-POINT_A_NEXT]+memory[pc++]];
// }
// if(input == PUSH_POP){
// if(isA){
// return memory[sp++];
// }
// else{
// return 0xffff;
// }
// }
// if(input == PEEK){
// return memory[sp];
// }
// if(input==PICK){
// char place = 0;
// if(isA){
// place = (char)(sp+memory[pc++]);
// }
// else{
// place = (char)(sp+memory[pc+1]);
// }
// return place;
//
// }
// if(input == SP){
// return sp;
// }
// if(input == PC){
// return pc;
// }
// if(input == EX){
// return ex;
// }
// if(input == POINT_NEXT){
// return memory[memory[pc++]];
// }
// if(input == NEXT){
// return memory[pc++];
// }
// if(input>=LITERAL_MIN && input<=LITERAL_MAX){
// return (char)(input-0x21);
// }
// throw new EmulatorException("can not decode value: "+(int)input,pc);
// }
private char getOffset(char valueCode){
switch(valueCode){
case POINT_A_NEXT:
case POINT_B_NEXT:
case POINT_C_NEXT:
case POINT_X_NEXT:
case POINT_Y_NEXT:
case POINT_Z_NEXT:
case POINT_I_NEXT:
case POINT_J_NEXT:
case PICK:
case POINT_NEXT:
case NEXT:
return 1;
default:
return 0;
}
}
private void skipUntilNonConditional(int runs) throws EmulatorException {
char instruction = memory[pc++];
char opcode = clear(instruction, A_SIZE+B_SIZE, 0);
char opA = clear(instruction, 0, B_SIZE+OP_SIZE);
char opB = clear(instruction, A_SIZE, B_SIZE);
boolean cond = isConditional(opcode);
if(cond){
pc += (getOffset(opA)+getOffset(opB));
skipUntilNonConditional(0);
}
else{
if(runs==0){
pc += (getOffset(opA)+getOffset(opB));
return;
}
else{
pc--;
return;
}
}
}
}
| false | true | public void step() throws EmulatorException {
char instruction = memory[pc++];
char opcode = clear(instruction, A_SIZE+B_SIZE, 0);
char opA = clear(instruction, 0, B_SIZE+OP_SIZE);
char opB = clear(instruction, A_SIZE, B_SIZE);
int offset = 0;
Pointer pa = getPointer(opA, offset, true);
offset+= getOffset(opA);
Pointer pb = getPointer(opB, offset, false);
offset+= getOffset(opB);
pc += offset;
char a = pa.get();
char b = pb.get();
short shortB = (short) a;
short shortA = (short) b;
switch (opcode){
case SET:
b = a;
break;
// Math
case ADD:
ex = over(b+a)? (char) 0x0001 : (char) 0x0;
b += a;
break;
case SUB:
ex = over(b-a)? (char) 0xffff : (char) 0x0;
b -= a;
break;
case MUL:
ex = (char)(((b*a)>>16)&0xffff);
b *= a;
break;
case MLI:
ex = (char)(((shortB*shortA)>>16)&0xffff);
shortB *= shortA;
b = (char) shortB;
break;
case DIV:
if(a==0){
b = 0;
ex = 0;
}
else{
ex = (char) (((b<<16)/a)&0xffff);
b /= a;
}
break;
case DVI:
if(shortA==0){
shortB = 0;
b = (char)shortB;
ex = 0;
}
else{
ex = (char)(((shortB/shortA)>>16)&0xffff);
shortB /= shortA;
b = (char) shortB;
}
break;
case MOD:
if(a==0){
b = 0;
}
else{
b %= a;
}
break;
case MDI:
if(shortA==0){
shortB = 0;
b = (char) shortB;
}
else{
shortB %= shortA;
b = (char) shortB;
}
break;
// Bit fiddling
case AND:
b &= a;
break;
case BOR:
b|=a;
break;
case XOR:
b^=a;
break;
case SHR:
ex = (char) (((b<<16)>>a)&0xffff);
b>>>=a;
break;
case ASR:
ex = (char) (((b<<16)>>>a)&0xffff);
b>>=a;
break;
case SHL:
ex = (char) (((b<<a)>>16)&0xffff);
b <<= a;
break;
// IF statements
case IFB:
if((b&a)!=0){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFC:
if((b&a)==0){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFE:
if(b==a){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFN:
if(b!=a){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFG:
if(b>a){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFA:
if(b>a){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFL:
if(b>a){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFU:
if(b<a){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case ADX:
ex = (char) (over(b+a+ex)? 0x0001 : 0x0);
b+=a;
b+=ex;
break;
case SBX:
ex = (char) (over(b-a+ex)? 0xFFFF : 0x0);
b-=a;
b+=ex;
break;
case STI:
b = a;
registers[registers.length-1] = (char) (registers[registers.length-1]+1);
registers[registers.length-2] = (char) (registers[registers.length-2]+1);
break;
case STD:
b = a;
registers[registers.length-1] = (char) (registers[registers.length-1]-1);
registers[registers.length-2] = (char) (registers[registers.length-2]-1);
break;
case SPECIAL:
switch (opB){
case JSR:
opB = PUSH_POP;
b = pc;
pc = a;
break;
case BRK:
this.isRunning = false;
return;
case INT:
case IAG:
case IAS:
case FRI:
case IAQ:
case HWN:
case HWQ:
case HWI:
throw new EmulatorException("Operation not accepted"+convertHex(opB),pc);
}
}
pb.set(b);
}
| public void step() throws EmulatorException {
char instruction = memory[pc++];
char opcode = clear(instruction, A_SIZE+B_SIZE, 0);
char opA = clear(instruction, 0, B_SIZE+OP_SIZE);
char opB = clear(instruction, A_SIZE, B_SIZE);
int offset = 0;
Pointer pa = getPointer(opA, offset, true);
offset+= getOffset(opA);
Pointer pb = getPointer(opB, offset, false);
offset+= getOffset(opB);
pc += offset;
char a = pa.get();
char b = pb.get();
short shortB = (short) a;
short shortA = (short) b;
switch (opcode){
case SET:
b = a;
break;
// Math
case ADD:
ex = over(b+a)? (char) 0x0001 : (char) 0x0;
b += a;
break;
case SUB:
ex = over(b-a)? (char) 0xffff : (char) 0x0;
b -= a;
break;
case MUL:
ex = (char)(((b*a)>>16)&0xffff);
b *= a;
break;
case MLI:
ex = (char)(((shortB*shortA)>>16)&0xffff);
shortB *= shortA;
b = (char) shortB;
break;
case DIV:
if(a==0){
b = 0;
ex = 0;
}
else{
ex = (char) (((b<<16)/a)&0xffff);
b /= a;
}
break;
case DVI:
if(shortA==0){
shortB = 0;
b = (char)shortB;
ex = 0;
}
else{
ex = (char)(((shortB/shortA)>>16)&0xffff);
shortB /= shortA;
b = (char) shortB;
}
break;
case MOD:
if(a==0){
b = 0;
}
else{
b %= a;
}
break;
case MDI:
if(shortA==0){
shortB = 0;
b = (char) shortB;
}
else{
shortB %= shortA;
b = (char) shortB;
}
break;
// Bit fiddling
case AND:
b &= a;
break;
case BOR:
b|=a;
break;
case XOR:
b^=a;
break;
case SHR:
ex = (char) (((b<<16)>>a)&0xffff);
b>>>=a;
break;
case ASR:
ex = (char) (((b<<16)>>>a)&0xffff);
b>>=a;
break;
case SHL:
ex = (char) (((b<<a)>>16)&0xffff);
b <<= a;
break;
// IF statements
case IFB:
if((b&a)!=0){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFC:
if((b&a)==0){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFE:
if(b==a){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFN:
if(b!=a){
return;
}else{
skipUntilNonConditional(0);
}
break;
case IFG:
if(b>a){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFA:
if(shortB>shortA){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFL:
if(b<a){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case IFU:
if(shortB<shortA){
return;
}
else{
skipUntilNonConditional(0);
}
break;
case ADX:
ex = (char) (over(b+a+ex)? 0x0001 : 0x0);
b+=a;
b+=ex;
break;
case SBX:
ex = (char) (over(b-a+ex)? 0xFFFF : 0x0);
b-=a;
b+=ex;
break;
case STI:
b = a;
registers[registers.length-1] = (char) (registers[registers.length-1]+1);
registers[registers.length-2] = (char) (registers[registers.length-2]+1);
break;
case STD:
b = a;
registers[registers.length-1] = (char) (registers[registers.length-1]-1);
registers[registers.length-2] = (char) (registers[registers.length-2]-1);
break;
case SPECIAL:
switch (opB){
case JSR:
opB = PUSH_POP;
b = pc;
pc = a;
break;
case BRK:
this.isRunning = false;
return;
case INT:
case IAG:
case IAS:
case FRI:
case IAQ:
case HWN:
case HWQ:
case HWI:
throw new EmulatorException("Operation not accepted"+convertHex(opB),pc);
}
}
pb.set(b);
}
|
diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataInputStream.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataInputStream.java
index a89ea4b98..1c3b504c3 100644
--- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataInputStream.java
+++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataInputStream.java
@@ -1,154 +1,154 @@
/*
* 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 java.io;
import com.google.gwt.corp.compatibility.Numbers;
public class DataInputStream extends InputStream implements DataInput {
private final InputStream is;
public DataInputStream (final InputStream is) {
this.is = is;
}
@Override
public int read () throws IOException {
return is.read();
}
public boolean readBoolean () throws IOException {
return readByte() != 0;
}
public byte readByte () throws IOException {
int i = read();
if (i == -1) {
throw new EOFException();
}
return (byte)i;
}
public char readChar () throws IOException {
int a = is.read();
int b = readUnsignedByte();
return (char)((a << 8) | b);
}
public double readDouble () throws IOException {
return Double.longBitsToDouble(readLong());
}
public float readFloat () throws IOException {
return Numbers.intBitsToFloat(readInt());
}
public void readFully (byte[] b) throws IOException {
readFully(b, 0, b.length);
}
public void readFully (byte[] b, int off, int len) throws IOException {
while (len > 0) {
int count = is.read(b, off, len);
if (count <= 0) {
throw new EOFException();
}
off += count;
len -= count;
}
}
public int readInt () throws IOException {
int a = is.read();
int b = is.read();
int c = is.read();
int d = readUnsignedByte();
return (a << 24) | (b << 16) | (c << 8) | d;
}
public String readLine () throws IOException {
throw new RuntimeException("readline NYI");
}
public long readLong () throws IOException {
long a = readInt();
long b = readInt() & 0x0ffffffff;
return (a << 32) | b;
}
public short readShort () throws IOException {
int a = is.read();
int b = readUnsignedByte();
return (short)((a << 8) | b);
}
public String readUTF () throws IOException {
int bytes = readUnsignedShort();
StringBuilder sb = new StringBuilder();
while (bytes > 0) {
bytes -= readUtfChar(sb);
}
return sb.toString();
}
private int readUtfChar (StringBuilder sb) throws IOException {
int a = readUnsignedByte();
if ((a & 0x80) == 0) {
sb.append((char)a);
return 1;
}
- if ((a & 0xe0) == 0xb0) {
+ if ((a & 0xe0) == 0xc0) {
int b = readUnsignedByte();
sb.append((char)(((a & 0x1F) << 6) | (b & 0x3F)));
return 2;
}
if ((a & 0xf0) == 0xe0) {
- int b = is.read();
+ int b = readUnsignedByte();
int c = readUnsignedByte();
sb.append((char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)));
return 3;
}
throw new UTFDataFormatException();
}
public int readUnsignedByte () throws IOException {
int i = read();
if (i == -1) {
throw new EOFException();
}
return i;
}
public int readUnsignedShort () throws IOException {
int a = is.read();
int b = readUnsignedByte();
return ((a << 8) | b);
}
public int skipBytes (int n) throws IOException {
// note: This is actually a valid implementation of this method, rendering it quite useless...
return 0;
}
@Override
public int available () {
return is.available();
}
}
| false | true | private int readUtfChar (StringBuilder sb) throws IOException {
int a = readUnsignedByte();
if ((a & 0x80) == 0) {
sb.append((char)a);
return 1;
}
if ((a & 0xe0) == 0xb0) {
int b = readUnsignedByte();
sb.append((char)(((a & 0x1F) << 6) | (b & 0x3F)));
return 2;
}
if ((a & 0xf0) == 0xe0) {
int b = is.read();
int c = readUnsignedByte();
sb.append((char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)));
return 3;
}
throw new UTFDataFormatException();
}
| private int readUtfChar (StringBuilder sb) throws IOException {
int a = readUnsignedByte();
if ((a & 0x80) == 0) {
sb.append((char)a);
return 1;
}
if ((a & 0xe0) == 0xc0) {
int b = readUnsignedByte();
sb.append((char)(((a & 0x1F) << 6) | (b & 0x3F)));
return 2;
}
if ((a & 0xf0) == 0xe0) {
int b = readUnsignedByte();
int c = readUnsignedByte();
sb.append((char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)));
return 3;
}
throw new UTFDataFormatException();
}
|
Subsets and Splits