lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | agpl-3.0 | 036510f6da0e70e57284b13fe04a1f1e3d736f6e | 0 | teyden/phenotips,JKereliuk/phenotips,teyden/phenotips,JKereliuk/phenotips,teyden/phenotips,phenotips/phenotips,danielpgross/phenotips,mjshepherd/phenotips,phenotips/phenotips,phenotips/phenotips,danielpgross/phenotips,tmarathe/phenotips,tmarathe/phenotips,veronikaslc/phenotips,alexhenrie/phenotips,itaiGershtansky/phenotips,danielpgross/phenotips,itaiGershtansky/phenotips,teyden/phenotips,teyden/phenotips,itaiGershtansky/phenotips,mjshepherd/phenotips,JKereliuk/phenotips,tmarathe/phenotips,phenotips/phenotips,DeanWay/phenotips,alexhenrie/phenotips,DeanWay/phenotips,DeanWay/phenotips,veronikaslc/phenotips,alexhenrie/phenotips,veronikaslc/phenotips,phenotips/phenotips,mjshepherd/phenotips | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.phenotips.data.internal;
import org.phenotips.Constants;
import org.phenotips.components.ComponentManagerRegistry;
import org.phenotips.data.Disorder;
import org.phenotips.data.Feature;
import org.phenotips.data.Patient;
import org.phenotips.data.PatientData;
import org.phenotips.data.PatientDataController;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.context.Execution;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.DBStringListProperty;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Implementation of patient data based on the XWiki data model, where patient data is represented by properties in
* objects of type {@code PhenoTips.PatientClass}.
*
* @version $Id$
* @since 1.0M8
*/
public class PhenoTipsPatient implements Patient
{
/** The default template for creating a new patient. */
public static final EntityReference TEMPLATE_REFERENCE = new EntityReference("PatientTemplate",
EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE);
/** used for generating JSON and reading from JSON. */
protected static final String JSON_KEY_FEATURES = "features";
protected static final String JSON_KEY_DISORDERS = "disorders";
protected static final String JSON_KEY_ID = "id";
protected static final String JSON_KEY_REPORTER = "reporter";
/** Known phenotype properties. */
private static final String PHENOTYPE_POSITIVE_PROPERTY = "phenotype";
private static final String PHENOTYPE_NEGATIVE_PROPERTY = "negative_phenotype";
private static final String[] PHENOTYPE_PROPERTIES =
new String[] {PHENOTYPE_POSITIVE_PROPERTY, PHENOTYPE_NEGATIVE_PROPERTY};
private static final String DISORDER_PROPERTIES_OMIMID = "omim_id";
private static final String[] DISORDER_PROPERTIES = new String[] {DISORDER_PROPERTIES_OMIMID};
/** Logging helper object. */
private Logger logger = LoggerFactory.getLogger(PhenoTipsPatient.class);
/** @see #getDocument() */
private DocumentReference document;
/** @see #getReporter() */
private DocumentReference reporter;
/** @see #getFeatures() */
private Set<Feature> features = new TreeSet<Feature>();
/** @see #getDisorders() */
private Set<Disorder> disorders = new TreeSet<Disorder>();
/** The list of all the initialized data holders (PatientDataSerializer). */
private List<PatientDataController<?>> serializers;
/** Extra data that can be plugged into the patient record. */
private Map<String, PatientData<?>> extraData = new HashMap<String, PatientData<?>>();
/**
* Constructor that copies the data from an XDocument.
*
* @param doc the XDocument representing this patient in XWiki
*/
public PhenoTipsPatient(XWikiDocument doc)
{
this.document = doc.getDocumentReference();
this.reporter = doc.getCreatorReference();
BaseObject data = doc.getXObject(CLASS_REFERENCE);
if (data == null) {
return;
}
try {
for (String property : PHENOTYPE_PROPERTIES) {
DBStringListProperty values = (DBStringListProperty) data.get(property);
if (values != null) {
for (String value : values.getList()) {
if (StringUtils.isNotBlank(value)) {
this.features.add(new PhenoTipsFeature(doc, values, value));
}
}
}
}
for (String property : DISORDER_PROPERTIES) {
DBStringListProperty values = (DBStringListProperty) data.get(property);
if (values != null) {
for (String value : values.getList()) {
if (StringUtils.isNotBlank(value)) {
this.disorders.add(new PhenoTipsDisorder(values, value));
}
}
}
}
} catch (XWikiException ex) {
this.logger.warn("Failed to access patient data for [{}]: {}", doc.getDocumentReference(), ex.getMessage());
}
// Read-only from now on
this.features = Collections.unmodifiableSet(this.features);
this.disorders = Collections.unmodifiableSet(this.disorders);
loadSerializers();
readPatientData();
}
private void loadSerializers()
{
try {
this.serializers =
ComponentManagerRegistry.getContextComponentManager().getInstanceList(PatientDataController.class);
} catch (ComponentLookupException e) {
this.logger.error("Failed to find component", e);
}
}
/**
* Loops through all the available serializers and passes each a document reference.
*/
private void readPatientData()
{
for (PatientDataController<?> serializer : this.serializers) {
PatientData<?> data = serializer.load(this);
if (data != null) {
this.extraData.put(data.getName(), data);
}
}
}
private boolean isFieldIncluded(Collection<String> includedFieldNames, String fieldName)
{
return (includedFieldNames == null || includedFieldNames.contains(fieldName));
}
private boolean isFieldIncluded(Collection<String> includedFieldNames, String[] fieldNames)
{
return (includedFieldNames == null || includedFieldNames.containsAll(Arrays.asList(fieldNames)));
}
@Override
public String getId()
{
return this.document.getName();
}
@Override
public String getExternalId()
{
try {
for (ImmutablePair<String, String> identifier : this.<ImmutablePair<String, String>> getData("identifiers")) {
if (identifier.getKey().equalsIgnoreCase("external_id")) {
return identifier.getValue();
}
}
} catch (Exception ex) {
return null;
}
return null;
}
@Override
public DocumentReference getDocument()
{
return this.document;
}
@Override
public DocumentReference getReporter()
{
return this.reporter;
}
@Override
public Set<Feature> getFeatures()
{
return this.features;
}
@Override
public Set<Disorder> getDisorders()
{
return this.disorders;
}
@SuppressWarnings("unchecked")
@Override
public <T> PatientData<T> getData(String name)
{
return (PatientData<T>) this.extraData.get(name);
}
@Override
public JSONObject toJSON()
{
return toJSON(null);
}
/** creates & returns a new JSON array of all patient features (as JSON objects). */
private JSONArray featuresToJSON()
{
JSONArray featuresJSON = new JSONArray();
for (Feature phenotype : this.features) {
featuresJSON.add(phenotype.toJSON());
}
return featuresJSON;
}
/** creates & returns a new JSON array of all patient diseases (as JSON objects). */
private JSONArray diseasesToJSON()
{
JSONArray diseasesJSON = new JSONArray();
for (Disorder disease : this.disorders) {
diseasesJSON.add(disease.toJSON());
}
return diseasesJSON;
}
@Override
public JSONObject toJSON(Collection<String> onlyFieldNames)
{
JSONObject result = new JSONObject();
if (isFieldIncluded(onlyFieldNames, JSON_KEY_ID)) {
result.element(JSON_KEY_ID, getDocument().getName());
}
if (getReporter() != null && isFieldIncluded(onlyFieldNames, JSON_KEY_REPORTER)) {
result.element(JSON_KEY_REPORTER, getReporter().getName());
}
if (!this.features.isEmpty() && isFieldIncluded(onlyFieldNames, PHENOTYPE_PROPERTIES)) {
result.element(JSON_KEY_FEATURES, featuresToJSON());
}
if (!this.disorders.isEmpty() && isFieldIncluded(onlyFieldNames, DISORDER_PROPERTIES)) {
result.element(JSON_KEY_DISORDERS, diseasesToJSON());
}
for (PatientDataController<?> serializer : this.serializers) {
serializer.writeJSON(this, result, onlyFieldNames);
}
return result;
}
private void updateFeaturesFromJSON(XWikiDocument doc, BaseObject data, XWikiContext context, JSONObject json)
{
try {
JSONArray inputFeatures = json.optJSONArray(JSON_KEY_FEATURES);
if (inputFeatures != null) {
// keep this instance of PhenotipsPatient in sync with the document: reset features
this.features = new TreeSet<Feature>();
// new feature lists (for setting values in the Wiki document)
List<String> positiveValues = new LinkedList<String>();
List<String> negativeValues = new LinkedList<String>();
for (int i = 0; i < inputFeatures.size(); i++) {
JSONObject featureInJSON = inputFeatures.optJSONObject(i);
if (featureInJSON == null) {
continue;
}
Feature phenotipsFeature = new PhenoTipsFeature(featureInJSON);
this.features.add(phenotipsFeature);
if (phenotipsFeature.isPresent()) {
positiveValues.add(phenotipsFeature.getValue());
} else {
negativeValues.add(phenotipsFeature.getValue());
}
}
// as in constructor: make unmodifiable
this.features = Collections.unmodifiableSet(this.features);
// update the values in the document (overwriting the old list, if any)
data.set(PHENOTYPE_POSITIVE_PROPERTY, positiveValues, context);
data.set(PHENOTYPE_NEGATIVE_PROPERTY, negativeValues, context);
context.getWiki().saveDocument(doc, "Updated features from JSON", true, context);
}
} catch (Exception ex) {
this.logger.warn("Failed to update patient features from JSON [{}]: {}", ex.getMessage(), ex);
}
}
private void updateDisordersFromJSON(XWikiDocument doc, BaseObject data, XWikiContext context, JSONObject json)
{
try {
JSONArray inputDisorders = json.optJSONArray(JSON_KEY_DISORDERS);
if (inputDisorders != null) {
// keep this instance of PhenotipsPatient in sync with the document: reset disorders
this.disorders = new TreeSet<Disorder>();
// new disorders list (for setting values in the Wiki document)
List<String> disorderValues = new LinkedList<String>();
for (int i = 0; i < inputDisorders.size(); i++) {
JSONObject disorderJSON = inputDisorders.optJSONObject(i);
if (disorderJSON == null) {
continue;
}
Disorder phenotipsDisorder = new PhenoTipsDisorder(disorderJSON);
this.disorders.add(phenotipsDisorder);
disorderValues.add(phenotipsDisorder.getValue());
}
// as in constructor: make unmofidiable
this.disorders = Collections.unmodifiableSet(this.disorders);
// update the values in the document (overwriting the old list, if any)
data.set(DISORDER_PROPERTIES_OMIMID, disorderValues, context);
context.getWiki().saveDocument(doc, "Updated disorders from JSON", true, context);
}
} catch (Exception ex) {
this.logger.warn("Failed to update patient disorders from JSON [{}]: {}", ex.getMessage(), ex);
}
}
@Override
public void updateFromJSON(JSONObject json)
{
try {
// TODO: check versions and throw if versions mismatch if necessary
// TODO: separe updateFrom JSON and saveToDB ? Move to PatientRepository?
Execution execution = ComponentManagerRegistry.getContextComponentManager().getInstance(Execution.class);
XWikiContext context = (XWikiContext) execution.getContext().getProperty("xwikicontext");
DocumentAccessBridge documentAccessBridge =
ComponentManagerRegistry.getContextComponentManager().getInstance(DocumentAccessBridge.class);
XWikiDocument doc = (XWikiDocument) documentAccessBridge.getDocument(getDocument());
BaseObject data = doc.getXObject(CLASS_REFERENCE);
if (data == null) {
return;
}
updateFeaturesFromJSON(doc, data, context, json);
updateDisordersFromJSON(doc, data, context, json);
for (PatientDataController<?> serializer : this.serializers) {
try {
PatientData<?> patientData = serializer.readJSON(json);
if (patientData != null) {
this.extraData.put(patientData.getName(), patientData);
serializer.save(this);
this.logger.warn("Successfully updated patient form JSON using serializer [{}]",
serializer.getName());
}
} catch (UnsupportedOperationException ex) {
this.logger.warn("Unable to update patient from JSON using serializer [{}] - [{}]: {}",
serializer.getName(), ex.getMessage(), ex);
}
}
} catch (Exception ex) {
this.logger.warn("Failed to update patient data from JSON [{}]: {}", ex.getMessage(), ex);
}
}
@Override
public String toString()
{
return toJSON().toString(2);
}
}
| components/patient-data/impl/src/main/java/org/phenotips/data/internal/PhenoTipsPatient.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.phenotips.data.internal;
import org.phenotips.Constants;
import org.phenotips.components.ComponentManagerRegistry;
import org.phenotips.data.Disorder;
import org.phenotips.data.Feature;
import org.phenotips.data.Patient;
import org.phenotips.data.PatientData;
import org.phenotips.data.PatientDataController;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.context.Execution;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.DBStringListProperty;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Implementation of patient data based on the XWiki data model, where patient data is represented by properties in
* objects of type {@code PhenoTips.PatientClass}.
*
* @version $Id$
* @since 1.0M8
*/
public class PhenoTipsPatient implements Patient
{
/** The default template for creating a new patient. */
public static final EntityReference TEMPLATE_REFERENCE = new EntityReference("PatientTemplate",
EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE);
/** used for generating JSON and reading from JSON. */
protected static final String JSON_KEY_FEATURES = "features";
protected static final String JSON_KEY_DISORDERS = "disorders";
protected static final String JSON_KEY_ID = "id";
protected static final String JSON_KEY_REPORTER = "reporter";
/** Known phenotype properties. */
private static final String PHENOTYPE_POSITIVE_PROPERTY = "phenotype";
private static final String PHENOTYPE_NEGATIVE_PROPERTY = "negative_phenotype";
private static final String[] PHENOTYPE_PROPERTIES = new String[]{PHENOTYPE_POSITIVE_PROPERTY,
PHENOTYPE_NEGATIVE_PROPERTY};
private static final String DISORDER_PROPERTIES_OMIMID = "omim_id";
private static final String[] DISORDER_PROPERTIES = new String[]{DISORDER_PROPERTIES_OMIMID};
/** Logging helper object. */
private Logger logger = LoggerFactory.getLogger(PhenoTipsPatient.class);
/** @see #getDocument() */
private DocumentReference document;
/** @see #getReporter() */
private DocumentReference reporter;
/** @see #getFeatures() */
private Set<Feature> features = new TreeSet<Feature>();
/** @see #getDisorders() */
private Set<Disorder> disorders = new TreeSet<Disorder>();
/** The list of all the initialized data holders (PatientDataSerializer). */
private List<PatientDataController<?>> serializers;
/** Extra data that can be plugged into the patient record. */
private Map<String, PatientData<?>> extraData = new HashMap<String, PatientData<?>>();
/**
* Constructor that copies the data from an XDocument.
*
* @param doc the XDocument representing this patient in XWiki
*/
public PhenoTipsPatient(XWikiDocument doc)
{
this.document = doc.getDocumentReference();
this.reporter = doc.getCreatorReference();
BaseObject data = doc.getXObject(CLASS_REFERENCE);
if (data == null) {
return;
}
try {
for (String property : PHENOTYPE_PROPERTIES) {
DBStringListProperty values = (DBStringListProperty) data.get(property);
if (values != null) {
for (String value : values.getList()) {
if (StringUtils.isNotBlank(value)) {
this.features.add(new PhenoTipsFeature(doc, values, value));
}
}
}
}
for (String property : DISORDER_PROPERTIES) {
DBStringListProperty values = (DBStringListProperty) data.get(property);
if (values != null) {
for (String value : values.getList()) {
if (StringUtils.isNotBlank(value)) {
this.disorders.add(new PhenoTipsDisorder(values, value));
}
}
}
}
} catch (XWikiException ex) {
this.logger.warn("Failed to access patient data for [{}]: {}", doc.getDocumentReference(), ex.getMessage());
}
// Read-only from now on
this.features = Collections.unmodifiableSet(this.features);
this.disorders = Collections.unmodifiableSet(this.disorders);
loadSerializers();
readPatientData();
}
private void loadSerializers()
{
try {
this.serializers =
ComponentManagerRegistry.getContextComponentManager().getInstanceList(PatientDataController.class);
} catch (ComponentLookupException e) {
this.logger.error("Failed to find component", e);
}
}
/**
* Loops through all the available serializers and passes each a document reference.
*/
private void readPatientData()
{
for (PatientDataController<?> serializer : this.serializers) {
PatientData<?> data = serializer.load(this);
if (data != null) {
this.extraData.put(data.getName(), data);
}
}
}
private boolean isFieldIncluded(Collection<String> includedFieldNames, String fieldName)
{
return (includedFieldNames == null || includedFieldNames.contains(fieldName));
}
private boolean isFieldIncluded(Collection<String> includedFieldNames, String[] fieldNames)
{
return (includedFieldNames == null || includedFieldNames.containsAll(Arrays.asList(fieldNames)));
}
@Override
public String getId()
{
return this.document.getName();
}
@Override
public String getExternalId()
{
try {
for (ImmutablePair<String, String> identifier : this
.<ImmutablePair<String, String>>getData("identifiers"))
{
if (identifier.getKey().equalsIgnoreCase("external_id")) {
return identifier.getValue();
}
}
} catch (Exception ex) {
return null;
}
return null;
}
@Override
public DocumentReference getDocument()
{
return this.document;
}
@Override
public DocumentReference getReporter()
{
return this.reporter;
}
@Override
public Set<Feature> getFeatures()
{
return this.features;
}
@Override
public Set<Disorder> getDisorders()
{
return this.disorders;
}
@SuppressWarnings("unchecked")
@Override
public <T> PatientData<T> getData(String name)
{
return (PatientData<T>) this.extraData.get(name);
}
@Override
public JSONObject toJSON()
{
return toJSON(null);
}
/** creates & returns a new JSON array of all patient features (as JSON objects). */
private JSONArray featuresToJSON()
{
JSONArray featuresJSON = new JSONArray();
for (Feature phenotype : this.features) {
featuresJSON.add(phenotype.toJSON());
}
return featuresJSON;
}
/** creates & returns a new JSON array of all patient diseases (as JSON objects). */
private JSONArray diseasesToJSON()
{
JSONArray diseasesJSON = new JSONArray();
for (Disorder disease : this.disorders) {
diseasesJSON.add(disease.toJSON());
}
return diseasesJSON;
}
@Override
public JSONObject toJSON(Collection<String> onlyFieldNames)
{
JSONObject result = new JSONObject();
if (isFieldIncluded(onlyFieldNames, JSON_KEY_ID)) {
result.element(JSON_KEY_ID, getDocument().getName());
}
if (getReporter() != null && isFieldIncluded(onlyFieldNames, JSON_KEY_REPORTER)) {
result.element(JSON_KEY_REPORTER, getReporter().getName());
}
if (!this.features.isEmpty() && isFieldIncluded(onlyFieldNames, PHENOTYPE_PROPERTIES)) {
result.element(JSON_KEY_FEATURES, featuresToJSON());
}
if (!this.disorders.isEmpty() && isFieldIncluded(onlyFieldNames, DISORDER_PROPERTIES)) {
result.element(JSON_KEY_DISORDERS, diseasesToJSON());
}
for (PatientDataController<?> serializer : this.serializers) {
serializer.writeJSON(this, result, onlyFieldNames);
}
return result;
}
private void updateFeaturesFromJSON(XWikiDocument doc, BaseObject data, XWikiContext context, JSONObject json)
{
try {
JSONArray inputFeatures = json.optJSONArray(JSON_KEY_FEATURES);
if (inputFeatures != null) {
// keep this instance of PhenotipsPatient in sync with the document: reset features
this.features = new TreeSet<Feature>();
// new feature lists (for setting values in the Wiki document)
List<String> positiveValues = new LinkedList<String>();
List<String> negativeValues = new LinkedList<String>();
for (int i = 0; i < inputFeatures.size(); i++) {
JSONObject featureInJSON = inputFeatures.optJSONObject(i);
if (featureInJSON == null) {
continue;
}
Feature phenotipsFeature = new PhenoTipsFeature(featureInJSON);
this.features.add(phenotipsFeature);
if (phenotipsFeature.isPresent()) {
positiveValues.add(phenotipsFeature.getValue());
} else {
negativeValues.add(phenotipsFeature.getValue());
}
}
// as in constructor: make unmodifiable
this.features = Collections.unmodifiableSet(this.features);
// update the values in the document (overwriting the old list, if any)
data.set(PHENOTYPE_POSITIVE_PROPERTY, positiveValues, context);
data.set(PHENOTYPE_NEGATIVE_PROPERTY, negativeValues, context);
context.getWiki().saveDocument(doc, "Updated features from JSON", true, context);
}
} catch (Exception ex) {
this.logger.warn("Failed to update patient features from JSON [{}]: {}", ex.getMessage(), ex);
}
}
private void updateDisordersFromJSON(XWikiDocument doc, BaseObject data, XWikiContext context, JSONObject json)
{
try {
JSONArray inputDisorders = json.optJSONArray(JSON_KEY_DISORDERS);
if (inputDisorders != null) {
// keep this instance of PhenotipsPatient in sync with the document: reset disorders
this.disorders = new TreeSet<Disorder>();
// new disorders list (for setting values in the Wiki document)
List<String> disorderValues = new LinkedList<String>();
for (int i = 0; i < inputDisorders.size(); i++) {
JSONObject disorderJSON = inputDisorders.optJSONObject(i);
if (disorderJSON == null) {
continue;
}
Disorder phenotipsDisorder = new PhenoTipsDisorder(disorderJSON);
this.disorders.add(phenotipsDisorder);
disorderValues.add(phenotipsDisorder.getValue());
}
// as in constructor: make unmofidiable
this.disorders = Collections.unmodifiableSet(this.disorders);
// update the values in the document (overwriting the old list, if any)
data.set(DISORDER_PROPERTIES_OMIMID, disorderValues, context);
context.getWiki().saveDocument(doc, "Updated disorders from JSON", true, context);
}
} catch (Exception ex) {
this.logger.warn("Failed to update patient disorders from JSON [{}]: {}", ex.getMessage(), ex);
}
}
@Override
public void updateFromJSON(JSONObject json)
{
try {
// TODO: check versions and throw if versions mismatch if necessary
// TODO: separe updateFrom JSON and saveToDB ? Move to PatientRepository?
Execution execution = ComponentManagerRegistry.getContextComponentManager().getInstance(Execution.class);
XWikiContext context = (XWikiContext) execution.getContext().getProperty("xwikicontext");
DocumentAccessBridge documentAccessBridge = ComponentManagerRegistry.getContextComponentManager().
getInstance(DocumentAccessBridge.class);
XWikiDocument doc = (XWikiDocument) documentAccessBridge.getDocument(getDocument());
BaseObject data = doc.getXObject(CLASS_REFERENCE);
if (data == null) {
return;
}
updateFeaturesFromJSON(doc, data, context, json);
updateDisordersFromJSON(doc, data, context, json);
for (PatientDataController<?> serializer : this.serializers) {
try {
PatientData<?> patientData = serializer.readJSON(json);
if (patientData != null) {
this.extraData.put(patientData.getName(), patientData);
serializer.save(this);
this.logger.warn("Successfully updated patient form JSON using serializer [{}]",
serializer.getName());
}
} catch (UnsupportedOperationException ex) {
this.logger.warn("Unable to update patient from JSON using serializer [{}] - [{}]: {}",
serializer.getName(), ex.getMessage(), ex);
}
}
} catch (Exception ex) {
this.logger.warn("Failed to update patient data from JSON [{}]: {}", ex.getMessage(), ex);
}
}
@Override
public String toString()
{
return toJSON().toString(2);
}
}
| [cleanup] Applied codestyle
| components/patient-data/impl/src/main/java/org/phenotips/data/internal/PhenoTipsPatient.java | [cleanup] Applied codestyle | <ide><path>omponents/patient-data/impl/src/main/java/org/phenotips/data/internal/PhenoTipsPatient.java
<ide> EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE);
<ide>
<ide> /** used for generating JSON and reading from JSON. */
<del> protected static final String JSON_KEY_FEATURES = "features";
<add> protected static final String JSON_KEY_FEATURES = "features";
<add>
<ide> protected static final String JSON_KEY_DISORDERS = "disorders";
<del> protected static final String JSON_KEY_ID = "id";
<del> protected static final String JSON_KEY_REPORTER = "reporter";
<add>
<add> protected static final String JSON_KEY_ID = "id";
<add>
<add> protected static final String JSON_KEY_REPORTER = "reporter";
<ide>
<ide> /** Known phenotype properties. */
<ide> private static final String PHENOTYPE_POSITIVE_PROPERTY = "phenotype";
<add>
<ide> private static final String PHENOTYPE_NEGATIVE_PROPERTY = "negative_phenotype";
<del> private static final String[] PHENOTYPE_PROPERTIES = new String[]{PHENOTYPE_POSITIVE_PROPERTY,
<del> PHENOTYPE_NEGATIVE_PROPERTY};
<add>
<add> private static final String[] PHENOTYPE_PROPERTIES =
<add> new String[] {PHENOTYPE_POSITIVE_PROPERTY, PHENOTYPE_NEGATIVE_PROPERTY};
<ide>
<ide> private static final String DISORDER_PROPERTIES_OMIMID = "omim_id";
<del> private static final String[] DISORDER_PROPERTIES = new String[]{DISORDER_PROPERTIES_OMIMID};
<add>
<add> private static final String[] DISORDER_PROPERTIES = new String[] {DISORDER_PROPERTIES_OMIMID};
<ide>
<ide> /** Logging helper object. */
<ide> private Logger logger = LoggerFactory.getLogger(PhenoTipsPatient.class);
<ide> }
<ide>
<ide> // Read-only from now on
<del> this.features = Collections.unmodifiableSet(this.features);
<add> this.features = Collections.unmodifiableSet(this.features);
<ide> this.disorders = Collections.unmodifiableSet(this.disorders);
<ide>
<ide> loadSerializers();
<ide> public String getExternalId()
<ide> {
<ide> try {
<del> for (ImmutablePair<String, String> identifier : this
<del> .<ImmutablePair<String, String>>getData("identifiers"))
<del> {
<add> for (ImmutablePair<String, String> identifier : this.<ImmutablePair<String, String>> getData("identifiers")) {
<ide> if (identifier.getKey().equalsIgnoreCase("external_id")) {
<ide> return identifier.getValue();
<ide> }
<ide> Execution execution = ComponentManagerRegistry.getContextComponentManager().getInstance(Execution.class);
<ide> XWikiContext context = (XWikiContext) execution.getContext().getProperty("xwikicontext");
<ide>
<del> DocumentAccessBridge documentAccessBridge = ComponentManagerRegistry.getContextComponentManager().
<del> getInstance(DocumentAccessBridge.class);
<add> DocumentAccessBridge documentAccessBridge =
<add> ComponentManagerRegistry.getContextComponentManager().getInstance(DocumentAccessBridge.class);
<ide> XWikiDocument doc = (XWikiDocument) documentAccessBridge.getDocument(getDocument());
<ide>
<ide> BaseObject data = doc.getXObject(CLASS_REFERENCE); |
|
Java | apache-2.0 | ec40b1652334fe8409547f4cef0f2e57d055b732 | 0 | radargun/radargun,vjuranek/radargun,Danny-Hazelcast/radargun,wburns/radargun,vjuranek/radargun,rmacor/radargun,wburns/radargun,mcimbora/radargun,vjuranek/radargun,rmacor/radargun,rhusar/radargun,rmacor/radargun,radargun/radargun,mcimbora/radargun,mcimbora/radargun,wburns/radargun,radargun/radargun,Danny-Hazelcast/radargun,rhusar/radargun,rhusar/radargun,Danny-Hazelcast/radargun,rmacor/radargun,vjuranek/radargun,radargun/radargun | package org.cachebench;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cachebench.cluster.ClusterBarrier;
import org.cachebench.config.CacheWarmupConfig;
import org.cachebench.config.ConfigBuilder;
import org.cachebench.config.Configuration;
import org.cachebench.config.Report;
import org.cachebench.config.TestCase;
import org.cachebench.config.TestConfig;
import org.cachebench.reportgenerators.ClusterAwareReportGenerator;
import org.cachebench.reportgenerators.ReportGenerator;
import org.cachebench.tests.CacheTest;
import org.cachebench.tests.ClusteredCacheTest;
import org.cachebench.tests.StatisticTest;
import org.cachebench.tests.results.BaseTestResult;
import org.cachebench.tests.results.StatisticTestResult;
import org.cachebench.tests.results.TestResult;
import org.cachebench.utils.Instantiator;
import org.cachebench.warmup.CacheWarmup;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Manik Surtani ([email protected])
* @version $Id: CacheBenchmarkRunner.java,v 1.1 2007/05/17 07:37:44 msurtani Exp $
*/
public class CacheBenchmarkRunner {
private Configuration conf;
private Log log = LogFactory.getLog(CacheBenchmarkRunner.class);
private Log errorLogger = LogFactory.getLog("CacheException");
// information about how we are called:
String cacheProductName;
String configuraton;
int clusterSize;
Map<String, String> systemParams = new HashMap<String, String>();
boolean localOnly;
public static void main(String[] args) {
String conf = null;
if (args.length == 1) {
conf = args[0];
}
if (conf != null && conf.toLowerCase().endsWith(".xml")) {
new CacheBenchmarkRunner(conf);
} else {
new CacheBenchmarkRunner();
}
}
/**
* Initialise some params that may be passed in via JVM params
*/
private void initJVMParams(String defaultCfgFile) {
boolean useFlatCache = Boolean.getBoolean("cacheBenchFwk.useFlatCache");
String overallCfg = System.getProperty("cacheBenchFwk.fwkCfgFile", defaultCfgFile);
String configuraton = System.getProperty("cacheBenchFwk.cacheConfigFile");
String cacheProductName = System.getProperty("cacheBenchFwk.cacheProductName");
String suffix = System.getProperty("cacheBenchFwk.productSuffix");
if (suffix != null && !suffix.trim().equals("")) cacheProductName += suffix;
String clusterSize = System.getProperty("clusterSize");
localOnly = Boolean.getBoolean("localOnly");
systemParams.put("fwk.config", overallCfg);
if (configuraton != null) systemParams.put("config", configuraton);
if (cacheProductName != null) systemParams.put("cacheProductName", cacheProductName);
if (clusterSize != null) systemParams.put("clusterSize", clusterSize);
if (localOnly) systemParams.put("localOnly", "TRUE");
if (useFlatCache) systemParams.put("cacheBenchFwk.useFlatCache", "TRUE");
}
public CacheBenchmarkRunner(Configuration conf, String cacheProductName, String configuraton, boolean localOnly, boolean start) throws Exception {
if (!localOnly)
throw new UnsupportedOperationException("Not implemented! This constructor is only for local mode.");
this.conf = conf;
this.cacheProductName = cacheProductName;
if (cacheProductName != null) systemParams.put("cacheProductName", cacheProductName);
this.configuraton = configuraton;
if (configuraton != null) systemParams.put("config", configuraton);
this.localOnly = localOnly;
if (start) start();
}
private CacheBenchmarkRunner() {
this("cachebench.xml");
}
private CacheBenchmarkRunner(String s) {
initJVMParams(s);
// first, try and find the configuration on the filesystem.
s = systemParams.get("fwk.config");
URL confFile = ConfigBuilder.findConfigFile(s);
if (confFile == null) {
log.warn("Unable to locate a configuration file " + s + "; Application terminated");
} else {
if (log.isDebugEnabled()) log.debug("Using configuration " + confFile);
log.debug("Parsing configuration");
try {
conf = ConfigBuilder.parseConfiguration(confFile);
start();
}
catch (Throwable e) {
log.warn("Unable to parse configuration file " + confFile + ". Application terminated", e);
errorLogger.fatal("Unable to parse configuration file " + confFile, e);
}
}
}
public void start() throws Exception {
log.info("Starting Benchmarking....");
List<TestResult> results = runTests(); // Run the tests from this point.
if (results != null && results.size() != 0) {
generateReports(results); // Run the reports...
} else {
log.warn("No Results to be reported");
}
log.info("Benchmarking Completed. Hope you enjoyed using this! \n");
}
CacheWrapper newCache(TestCase test) throws Exception {
CacheWrapper cache = getCacheWrapperInstance(test);
if (cache != null) {
Map<String, String> params = test.getParams();
// now add the config file, if any is passed in:
params.putAll(systemParams);
log.info("Initialising cache with params " + params);
cache.init(params);
cache.setUp();
}
return cache;
}
/**
* Executes each test case and returns the result.
*
* @return The Array of TestResult objects with the results of the tests.
*/
private List<TestResult> runTests() throws Exception {
List<TestResult> results = new ArrayList<TestResult>();
for (TestCase test : conf.getTestCases()) {
CacheWrapper cache = null;
try {
cache = newCache(test);
if (cache != null) {
//now start testing
cache.setUp();
warmupCache(test, cache);
List<TestResult> resultsForCache = runTestsOnCache(cache, test);
if (!localOnly) barrier("AFTER_TEST_RUN");
shutdownCache(cache);
results.addAll(resultsForCache);
}
}
catch (Exception e) {
try {
shutdownCache(cache);
}
catch (Exception e1) {
//ignore
}
log.warn("Unable to Initialize or Setup the Cache - Not performing any tests", e);
errorLogger.error("Unable to Initialize or Setup the Cache: " + test.getCacheWrapper(), e);
errorLogger.error("Skipping this test");
}
}
return results;
}
private void barrier(String messageName) throws Exception {
ClusterBarrier barrier = new ClusterBarrier();
log.trace("Using following cluster config: " + conf.getClusterConfig());
barrier.setConfig(conf.getClusterConfig());
barrier.setAcknowledge(true);
barrier.barrier(messageName);
log.info("Barrier for '" + messageName + "' finished");
}
private void warmupCache(TestCase test, CacheWrapper cache) throws Exception {
if (!localOnly) barrier("BEFORE_WARMUP");
log.info("Warming up..");
CacheWarmupConfig warmupConfig = test.getCacheWarmupConfig();
log.trace("Warmup config is: " + warmupConfig);
CacheWarmup warmup = (CacheWarmup) Instantiator.getInstance().createClass(warmupConfig.getWarmupClass());
warmup.setConfigParams(warmupConfig.getParams());
warmup.warmup(cache);
log.info("Warmup ended!");
if (!localOnly) barrier("AFTER_WARMUP");
}
/**
* Peforms the necessary external tasks for cache benchmarking. These external tasks are defined in the
* cachebench.xml and would be executed against the cache under test.
*
* @param cache The CacheWrapper for the cache in test.
* @param testResult The TestResult of the test to which the tasks are executed.
*/
private TestResult executeTestTasks(CacheWrapper cache, TestResult testResult) {
try {
if (conf.isEmptyCacheBetweenTests()) {
cache.empty();
}
if (conf.isGcBetweenTestsEnabled()) {
System.gc();
Thread.sleep(conf.getSleepBetweenTests());
}
}
catch (InterruptedException e) {
// Nothing doing here...
}
catch (Exception e) {
// The Empty barrier of the cache failed. Add a foot note for the TestResult here.
// testResult.setFootNote("The Cache Empty barrier failed after test case: " + testResult.getTestName() + " : " + testResult.getTestType());
// errorLogger.error("The Cache Empty barrier failed after test case : " + testResult.getTestName() + ", " + testResult.getTestType(), e);
}
return testResult;
}
private List<TestResult> runTestsOnCache(CacheWrapper cache, TestCase testCase) {
List<TestResult> results = new ArrayList<TestResult>();
for (TestConfig testConfig : testCase.getTests()) {
CacheTest testInstance = getCacheTest(testConfig);
if (testInstance instanceof ClusteredCacheTest && localOnly) {
log.warn("Skipping replicated tests since this is in local mode!");
continue;
}
if (testInstance != null) {
TestResult result;
String testName = testConfig.getName();
String testCaseName = testCase.getName();
try {
if (testInstance instanceof StatisticTest) {
// create new DescriptiveStatistics and pass it to the test
int repeat = testConfig.getRepeat();
if (log.isInfoEnabled()) log.info("Running test " + repeat + " times");
StatisticTestResult str = new StatisticTestResult();
for (int i = 0; i < repeat; i++) {
((StatisticTest) testInstance).doCumulativeTest(testName, cache, testCaseName, conf.getSampleSize(), conf.getNumThreads(), str);
if (conf.isEmptyCacheBetweenTests()) {
if (conf.isLocalOnly()) {
// destroy and restart the cache
shutdownCache(cache);
if (i != repeat - 1) cache = newCache(testCase);
} else
cache.empty();
}
if (conf.isGcBetweenTestsEnabled()) {
System.gc();
Thread.sleep(conf.getSleepBetweenTests());
}
}
result = str;
} else {
result = testInstance.doTest(testName, cache, testCaseName, conf.getSampleSize(), conf.getNumThreads());
}
}
catch (Exception e) {
// The test failed. We should add a test result object with a error message and indicate that it failed.
result = new BaseTestResult();
result.setTestName(testCaseName);
result.setTestTime(new Date());
result.setTestType(testName);
result.setTestPassed(false);
result.setErrorMsg("Failed to Execute - See logs for details : " + e.getMessage());
log.warn("Test case : " + testCaseName + ", Test : " + testName + " - Failed due to", e);
errorLogger.error("Test case : " + testCaseName + ", Test : " + testName + " - Failed : " + e.getMessage(), e);
}
if (!result.isTestPassed() && testCase.isStopOnFailure()) {
log.warn("The test '" + testCase + "/" + testName + "' failed, exiting...");
System.exit(1);
}
executeTestTasks(cache, result);
if (!result.isSkipReport()) {
results.add(result);
}
}
}
return results;
}
private void generateReports(List<TestResult> results) {
log.info("Generating Reports...");
for (Report report : conf.getReports()) {
ReportGenerator generator;
try {
generator = getReportGenerator(report);
if (generator != null) {
if (generator instanceof ClusterAwareReportGenerator && localOnly)
throw new IllegalArgumentException("Configured to run in local mode only, cannot use a clustered report generator!");
Map<String, String> params = report.getParams();
params.putAll(systemParams);
generator.setConfigParams(params);
generator.setResults(results);
generator.setClusterConfig(conf.getClusterConfig());
generator.setOutputFile(report.getOutputFile());
generator.generate();
log.info("Report Generation Completed");
} else {
log.info("Report not generated - See logs for reasons!!");
}
}
catch (Exception e) {
log.warn("Unable to generate Report : " + report.getGenerator() + " - See logs for reasons");
log.warn("Skipping this report");
errorLogger.error("Unable to generate Report : " + report.getGenerator(), e);
errorLogger.error("Skipping this report");
}
}
}
private CacheWrapper getCacheWrapperInstance(TestCase testCaseClass) {
CacheWrapper cache = null;
try {
cache = (CacheWrapper) Instantiator.getInstance().createClass(testCaseClass.getCacheWrapper());
}
catch (Exception e) {
log.warn("Unable to instantiate CacheWrapper class: " + testCaseClass.getCacheWrapper() + " - Not Running any tests");
errorLogger.error("Unable to instantiate CacheWrapper class: " + testCaseClass.getCacheWrapper(), e);
errorLogger.error("Skipping this test");
}
return cache;
}
private ReportGenerator getReportGenerator(Report reportClass) {
ReportGenerator report = null;
try {
report = (ReportGenerator) Instantiator.getInstance().createClass(reportClass.getGenerator());
}
catch (Exception e) {
log.warn("Unable to instantiate ReportGenerator class: " + reportClass.getGenerator() + " - Not generating the report");
errorLogger.error("Unable to instantiate ReportGenerator class: " + reportClass.getGenerator(), e);
errorLogger.error("Skipping this report");
}
return report;
}
private CacheTest getCacheTest(TestConfig testConfig) {
CacheTest cacheTestClass = null;
try {
cacheTestClass = (CacheTest) Instantiator.getInstance().createClass(testConfig.getTestClass());
conf.setLocalOnly(localOnly);
cacheTestClass.setConfiguration(conf);
}
catch (Exception e) {
log.warn("Unable to instantiate CacheTest class: " + testConfig.getTestClass() + " - Not Running any tests");
errorLogger.error("Unable to instantiate CacheTest class: " + testConfig.getTestClass(), e);
errorLogger.error("Skipping this Test");
}
return cacheTestClass;
}
private void shutdownCache(CacheWrapper cache) {
try {
cache.tearDown();
}
catch (Exception e) {
log.warn("Cache Shutdown - Failed.");
errorLogger.error("Cache Shutdown failed : ", e);
}
}
} | framework/src/main/java/org/cachebench/CacheBenchmarkRunner.java | package org.cachebench;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cachebench.cluster.ClusterBarrier;
import org.cachebench.config.CacheWarmupConfig;
import org.cachebench.config.ConfigBuilder;
import org.cachebench.config.Configuration;
import org.cachebench.config.Report;
import org.cachebench.config.TestCase;
import org.cachebench.config.TestConfig;
import org.cachebench.reportgenerators.ClusterAwareReportGenerator;
import org.cachebench.reportgenerators.ReportGenerator;
import org.cachebench.tests.CacheTest;
import org.cachebench.tests.ClusteredCacheTest;
import org.cachebench.tests.StatisticTest;
import org.cachebench.tests.results.BaseTestResult;
import org.cachebench.tests.results.StatisticTestResult;
import org.cachebench.tests.results.TestResult;
import org.cachebench.utils.Instantiator;
import org.cachebench.warmup.CacheWarmup;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Manik Surtani ([email protected])
* @version $Id: CacheBenchmarkRunner.java,v 1.1 2007/05/17 07:37:44 msurtani Exp $
*/
public class CacheBenchmarkRunner
{
private Configuration conf;
private Log log = LogFactory.getLog(CacheBenchmarkRunner.class);
private Log errorLogger = LogFactory.getLog("CacheException");
// information about how we are called:
String cacheProductName;
String configuraton;
int clusterSize;
Map<String, String> systemParams = new HashMap<String, String>();
boolean localOnly;
public static void main(String[] args)
{
String conf = null;
if (args.length == 1)
{
conf = args[0];
}
if (conf != null && conf.toLowerCase().endsWith(".xml"))
{
new CacheBenchmarkRunner(conf);
}
else
{
new CacheBenchmarkRunner();
}
}
/**
* Initialise some params that may be passed in via JVM params
*/
private void initJVMParams(String defaultCfgFile)
{
boolean useFlatCache = Boolean.getBoolean("cacheBenchFwk.useFlatCache");
String overallCfg = System.getProperty("cacheBenchFwk.fwkCfgFile", defaultCfgFile);
String configuraton = System.getProperty("cacheBenchFwk.cacheConfigFile");
String cacheProductName = System.getProperty("cacheBenchFwk.cacheProductName");
String suffix = System.getProperty("cacheBenchFwk.productSuffix");
if (suffix != null && !suffix.trim().equals("")) cacheProductName += suffix;
String clusterSize = System.getProperty("clusterSize");
localOnly = Boolean.getBoolean("localOnly");
systemParams.put("fwk.config", overallCfg);
if (configuraton != null) systemParams.put("config", configuraton);
if (cacheProductName != null) systemParams.put("cacheProductName", cacheProductName);
if (clusterSize != null) systemParams.put("clusterSize", clusterSize);
if (localOnly) systemParams.put("localOnly", "TRUE");
if (useFlatCache) systemParams.put("cacheBenchFwk.useFlatCache", "TRUE");
}
private CacheBenchmarkRunner()
{
this("cachebench.xml");
}
private CacheBenchmarkRunner(String s)
{
initJVMParams(s);
// first, try and find the configuration on the filesystem.
s = systemParams.get("fwk.config");
URL confFile = ConfigBuilder.findConfigFile(s);
if (confFile == null)
{
log.warn("Unable to locate a configuration file " + s + "; Application terminated");
}
else
{
if (log.isDebugEnabled()) log.debug("Using configuration " + confFile);
log.debug("Parsing configuration");
try
{
conf = ConfigBuilder.parseConfiguration(confFile);
log.info("Starting Benchmarking....");
List<TestResult> results = runTests(); // Run the tests from this point.
if (results != null && results.size() != 0)
{
generateReports(results); // Run the reports...
}
else
{
log.warn("No Results to be reported");
}
log.info("Benchmarking Completed. Hope you enjoyed using this! \n");
}
catch (Throwable e)
{
log.warn("Unable to parse configuration file " + confFile + ". Application terminated", e);
errorLogger.fatal("Unable to parse configuration file " + confFile, e);
}
}
}
CacheWrapper newCache(TestCase test) throws Exception
{
CacheWrapper cache = getCacheWrapperInstance(test);
if (cache != null)
{
Map<String, String> params = test.getParams();
// now add the config file, if any is passed in:
params.putAll(systemParams);
log.info("Initialising cache with params " + params);
cache.init(params);
cache.setUp();
}
return cache;
}
/**
* Executes each test case and returns the result.
*
* @return The Array of TestResult objects with the results of the tests.
*/
private List<TestResult> runTests() throws Exception
{
List<TestResult> results = new ArrayList<TestResult>();
for (TestCase test : conf.getTestCases())
{
CacheWrapper cache = null;
try
{
cache = newCache(test);
if (cache != null)
{
//now start testing
cache.setUp();
warmupCache(test, cache);
List<TestResult> resultsForCache = runTestsOnCache(cache, test);
if (!localOnly) barrier("AFTER_TEST_RUN");
shutdownCache(cache);
results.addAll(resultsForCache);
}
}
catch (Exception e)
{
try
{
shutdownCache(cache);
}
catch (Exception e1)
{
//ignore
}
log.warn("Unable to Initialize or Setup the Cache - Not performing any tests", e);
errorLogger.error("Unable to Initialize or Setup the Cache: " + test.getCacheWrapper(), e);
errorLogger.error("Skipping this test");
}
}
return results;
}
private void barrier(String messageName) throws Exception
{
ClusterBarrier barrier = new ClusterBarrier();
log.trace("Using following cluster config: " + conf.getClusterConfig());
barrier.setConfig(conf.getClusterConfig());
barrier.setAcknowledge(true);
barrier.barrier(messageName);
log.info("Barrier for '" + messageName + "' finished");
}
private void warmupCache(TestCase test, CacheWrapper cache) throws Exception
{
if (!localOnly) barrier("BEFORE_WARMUP");
log.info("Warming up..");
CacheWarmupConfig warmupConfig = test.getCacheWarmupConfig();
log.trace("Warmup config is: " + warmupConfig);
CacheWarmup warmup = (CacheWarmup) Instantiator.getInstance().createClass(warmupConfig.getWarmupClass());
warmup.setConfigParams(warmupConfig.getParams());
warmup.warmup(cache);
log.info("Warmup ended!");
if (!localOnly) barrier("AFTER_WARMUP");
}
/**
* Peforms the necessary external tasks for cache benchmarking.
* These external tasks are defined in the cachebench.xml and would
* be executed against the cache under test.
*
* @param cache The CacheWrapper for the cache in test.
* @param testResult The TestResult of the test to which the tasks are executed.
*/
private TestResult executeTestTasks(CacheWrapper cache, TestResult testResult)
{
try
{
if (conf.isEmptyCacheBetweenTests())
{
cache.empty();
}
if (conf.isGcBetweenTestsEnabled())
{
System.gc();
Thread.sleep(conf.getSleepBetweenTests());
}
}
catch (InterruptedException e)
{
// Nothing doing here...
}
catch (Exception e)
{
// The Empty barrier of the cache failed. Add a foot note for the TestResult here.
// testResult.setFootNote("The Cache Empty barrier failed after test case: " + testResult.getTestName() + " : " + testResult.getTestType());
// errorLogger.error("The Cache Empty barrier failed after test case : " + testResult.getTestName() + ", " + testResult.getTestType(), e);
}
return testResult;
}
private List<TestResult> runTestsOnCache(CacheWrapper cache, TestCase testCase)
{
List<TestResult> results = new ArrayList<TestResult>();
for (TestConfig testConfig : testCase.getTests())
{
CacheTest testInstance = getCacheTest(testConfig);
if (testInstance instanceof ClusteredCacheTest && localOnly)
{
log.warn("Skipping replicated tests since this is in local mode!");
continue;
}
if (testInstance != null)
{
TestResult result;
String testName = testConfig.getName();
String testCaseName = testCase.getName();
try
{
if (testInstance instanceof StatisticTest)
{
// create new DescriptiveStatistics and pass it to the test
int repeat = testConfig.getRepeat();
if (log.isInfoEnabled()) log.info("Running test " + repeat + " times");
StatisticTestResult str = new StatisticTestResult();
for (int i = 0; i < repeat; i++)
{
((StatisticTest) testInstance).doCumulativeTest(testName, cache, testCaseName, conf.getSampleSize(), conf.getNumThreads(), str);
if (conf.isEmptyCacheBetweenTests())
{
if (conf.isLocalOnly())
{
// destroy and restart the cache
shutdownCache(cache);
if (i != repeat - 1) cache = newCache(testCase);
}
else
cache.empty();
}
if (conf.isGcBetweenTestsEnabled())
{
System.gc();
Thread.sleep(conf.getSleepBetweenTests());
}
}
result = str;
}
else
{
result = testInstance.doTest(testName, cache, testCaseName, conf.getSampleSize(), conf.getNumThreads());
}
}
catch (Exception e)
{
// The test failed. We should add a test result object with a error message and indicate that it failed.
result = new BaseTestResult();
result.setTestName(testCaseName);
result.setTestTime(new Date());
result.setTestType(testName);
result.setTestPassed(false);
result.setErrorMsg("Failed to Execute - See logs for details : " + e.getMessage());
log.warn("Test case : " + testCaseName + ", Test : " + testName + " - Failed due to", e);
errorLogger.error("Test case : " + testCaseName + ", Test : " + testName + " - Failed : " + e.getMessage(), e);
}
if (!result.isTestPassed() && testCase.isStopOnFailure())
{
log.warn("The test '" + testCase + "/" + testName + "' failed, exiting...");
System.exit(1);
}
executeTestTasks(cache, result);
if (!result.isSkipReport())
{
results.add(result);
}
}
}
return results;
}
private void generateReports(List<TestResult> results)
{
log.info("Generating Reports...");
for (Report report : conf.getReports())
{
ReportGenerator generator;
try
{
generator = getReportGenerator(report);
if (generator != null)
{
if (generator instanceof ClusterAwareReportGenerator && localOnly)
throw new IllegalArgumentException("Configured to run in local mode only, cannot use a clustered report generator!");
Map<String, String> params = report.getParams();
params.putAll(systemParams);
generator.setConfigParams(params);
generator.setResults(results);
generator.setClusterConfig(conf.getClusterConfig());
generator.setOutputFile(report.getOutputFile());
generator.generate();
log.info("Report Generation Completed");
}
else
{
log.info("Report not generated - See logs for reasons!!");
}
}
catch (Exception e)
{
log.warn("Unable to generate Report : " + report.getGenerator() + " - See logs for reasons");
log.warn("Skipping this report");
errorLogger.error("Unable to generate Report : " + report.getGenerator(), e);
errorLogger.error("Skipping this report");
}
}
}
private CacheWrapper getCacheWrapperInstance(TestCase testCaseClass)
{
CacheWrapper cache = null;
try
{
cache = (CacheWrapper) Instantiator.getInstance().createClass(testCaseClass.getCacheWrapper());
}
catch (Exception e)
{
log.warn("Unable to instantiate CacheWrapper class: " + testCaseClass.getCacheWrapper() + " - Not Running any tests");
errorLogger.error("Unable to instantiate CacheWrapper class: " + testCaseClass.getCacheWrapper(), e);
errorLogger.error("Skipping this test");
}
return cache;
}
private ReportGenerator getReportGenerator(Report reportClass)
{
ReportGenerator report = null;
try
{
report = (ReportGenerator) Instantiator.getInstance().createClass(reportClass.getGenerator());
}
catch (Exception e)
{
log.warn("Unable to instantiate ReportGenerator class: " + reportClass.getGenerator() + " - Not generating the report");
errorLogger.error("Unable to instantiate ReportGenerator class: " + reportClass.getGenerator(), e);
errorLogger.error("Skipping this report");
}
return report;
}
private CacheTest getCacheTest(TestConfig testConfig)
{
CacheTest cacheTestClass = null;
try
{
cacheTestClass = (CacheTest) Instantiator.getInstance().createClass(testConfig.getTestClass());
conf.setLocalOnly(localOnly);
cacheTestClass.setConfiguration(conf);
}
catch (Exception e)
{
log.warn("Unable to instantiate CacheTest class: " + testConfig.getTestClass() + " - Not Running any tests");
errorLogger.error("Unable to instantiate CacheTest class: " + testConfig.getTestClass(), e);
errorLogger.error("Skipping this Test");
}
return cacheTestClass;
}
private void shutdownCache(CacheWrapper cache)
{
try
{
cache.tearDown();
}
catch (Exception e)
{
log.warn("Cache Shutdown - Failed.");
errorLogger.error("Cache Shutdown failed : ", e);
}
}
} | Support for local mode invocation
| framework/src/main/java/org/cachebench/CacheBenchmarkRunner.java | Support for local mode invocation | <ide><path>ramework/src/main/java/org/cachebench/CacheBenchmarkRunner.java
<ide> * @author Manik Surtani ([email protected])
<ide> * @version $Id: CacheBenchmarkRunner.java,v 1.1 2007/05/17 07:37:44 msurtani Exp $
<ide> */
<del>public class CacheBenchmarkRunner
<del>{
<add>public class CacheBenchmarkRunner {
<ide>
<ide> private Configuration conf;
<ide> private Log log = LogFactory.getLog(CacheBenchmarkRunner.class);
<ide> Map<String, String> systemParams = new HashMap<String, String>();
<ide> boolean localOnly;
<ide>
<del> public static void main(String[] args)
<del> {
<add> public static void main(String[] args) {
<ide> String conf = null;
<del> if (args.length == 1)
<del> {
<add> if (args.length == 1) {
<ide> conf = args[0];
<ide> }
<del> if (conf != null && conf.toLowerCase().endsWith(".xml"))
<del> {
<add> if (conf != null && conf.toLowerCase().endsWith(".xml")) {
<ide> new CacheBenchmarkRunner(conf);
<del> }
<del> else
<del> {
<add> } else {
<ide> new CacheBenchmarkRunner();
<ide> }
<ide> }
<ide> /**
<ide> * Initialise some params that may be passed in via JVM params
<ide> */
<del> private void initJVMParams(String defaultCfgFile)
<del> {
<add> private void initJVMParams(String defaultCfgFile) {
<ide> boolean useFlatCache = Boolean.getBoolean("cacheBenchFwk.useFlatCache");
<ide> String overallCfg = System.getProperty("cacheBenchFwk.fwkCfgFile", defaultCfgFile);
<ide> String configuraton = System.getProperty("cacheBenchFwk.cacheConfigFile");
<ide> if (useFlatCache) systemParams.put("cacheBenchFwk.useFlatCache", "TRUE");
<ide> }
<ide>
<del> private CacheBenchmarkRunner()
<del> {
<add> public CacheBenchmarkRunner(Configuration conf, String cacheProductName, String configuraton, boolean localOnly, boolean start) throws Exception {
<add> if (!localOnly)
<add> throw new UnsupportedOperationException("Not implemented! This constructor is only for local mode.");
<add> this.conf = conf;
<add> this.cacheProductName = cacheProductName;
<add> if (cacheProductName != null) systemParams.put("cacheProductName", cacheProductName);
<add> this.configuraton = configuraton;
<add> if (configuraton != null) systemParams.put("config", configuraton);
<add> this.localOnly = localOnly;
<add> if (start) start();
<add> }
<add>
<add> private CacheBenchmarkRunner() {
<ide> this("cachebench.xml");
<ide> }
<ide>
<del> private CacheBenchmarkRunner(String s)
<del> {
<add> private CacheBenchmarkRunner(String s) {
<ide> initJVMParams(s);
<ide> // first, try and find the configuration on the filesystem.
<ide> s = systemParams.get("fwk.config");
<ide> URL confFile = ConfigBuilder.findConfigFile(s);
<del> if (confFile == null)
<del> {
<add> if (confFile == null) {
<ide> log.warn("Unable to locate a configuration file " + s + "; Application terminated");
<del> }
<del> else
<del> {
<add> } else {
<ide> if (log.isDebugEnabled()) log.debug("Using configuration " + confFile);
<ide> log.debug("Parsing configuration");
<del> try
<del> {
<add> try {
<ide> conf = ConfigBuilder.parseConfiguration(confFile);
<del> log.info("Starting Benchmarking....");
<del> List<TestResult> results = runTests(); // Run the tests from this point.
<del> if (results != null && results.size() != 0)
<del> {
<del> generateReports(results); // Run the reports...
<del> }
<del> else
<del> {
<del> log.warn("No Results to be reported");
<del> }
<del> log.info("Benchmarking Completed. Hope you enjoyed using this! \n");
<del> }
<del> catch (Throwable e)
<del> {
<add> start();
<add> }
<add> catch (Throwable e) {
<ide> log.warn("Unable to parse configuration file " + confFile + ". Application terminated", e);
<ide> errorLogger.fatal("Unable to parse configuration file " + confFile, e);
<ide> }
<ide> }
<ide> }
<ide>
<del> CacheWrapper newCache(TestCase test) throws Exception
<del> {
<add> public void start() throws Exception {
<add> log.info("Starting Benchmarking....");
<add> List<TestResult> results = runTests(); // Run the tests from this point.
<add> if (results != null && results.size() != 0) {
<add> generateReports(results); // Run the reports...
<add> } else {
<add> log.warn("No Results to be reported");
<add> }
<add> log.info("Benchmarking Completed. Hope you enjoyed using this! \n");
<add> }
<add>
<add> CacheWrapper newCache(TestCase test) throws Exception {
<ide> CacheWrapper cache = getCacheWrapperInstance(test);
<del> if (cache != null)
<del> {
<add> if (cache != null) {
<ide> Map<String, String> params = test.getParams();
<ide> // now add the config file, if any is passed in:
<ide> params.putAll(systemParams);
<ide> *
<ide> * @return The Array of TestResult objects with the results of the tests.
<ide> */
<del> private List<TestResult> runTests() throws Exception
<del> {
<add> private List<TestResult> runTests() throws Exception {
<ide> List<TestResult> results = new ArrayList<TestResult>();
<del> for (TestCase test : conf.getTestCases())
<del> {
<add> for (TestCase test : conf.getTestCases()) {
<ide> CacheWrapper cache = null;
<del> try
<del> {
<add> try {
<ide> cache = newCache(test);
<del> if (cache != null)
<del> {
<add> if (cache != null) {
<ide> //now start testing
<ide> cache.setUp();
<ide> warmupCache(test, cache);
<ide> results.addAll(resultsForCache);
<ide> }
<ide> }
<del> catch (Exception e)
<del> {
<del> try
<del> {
<add> catch (Exception e) {
<add> try {
<ide> shutdownCache(cache);
<ide> }
<del> catch (Exception e1)
<del> {
<add> catch (Exception e1) {
<ide> //ignore
<ide> }
<ide> log.warn("Unable to Initialize or Setup the Cache - Not performing any tests", e);
<ide> return results;
<ide> }
<ide>
<del> private void barrier(String messageName) throws Exception
<del> {
<add> private void barrier(String messageName) throws Exception {
<ide> ClusterBarrier barrier = new ClusterBarrier();
<ide> log.trace("Using following cluster config: " + conf.getClusterConfig());
<ide> barrier.setConfig(conf.getClusterConfig());
<ide>
<ide> }
<ide>
<del> private void warmupCache(TestCase test, CacheWrapper cache) throws Exception
<del> {
<add> private void warmupCache(TestCase test, CacheWrapper cache) throws Exception {
<ide> if (!localOnly) barrier("BEFORE_WARMUP");
<ide> log.info("Warming up..");
<ide> CacheWarmupConfig warmupConfig = test.getCacheWarmupConfig();
<ide> }
<ide>
<ide> /**
<del> * Peforms the necessary external tasks for cache benchmarking.
<del> * These external tasks are defined in the cachebench.xml and would
<del> * be executed against the cache under test.
<add> * Peforms the necessary external tasks for cache benchmarking. These external tasks are defined in the
<add> * cachebench.xml and would be executed against the cache under test.
<ide> *
<ide> * @param cache The CacheWrapper for the cache in test.
<ide> * @param testResult The TestResult of the test to which the tasks are executed.
<ide> */
<del> private TestResult executeTestTasks(CacheWrapper cache, TestResult testResult)
<del> {
<del> try
<del> {
<del> if (conf.isEmptyCacheBetweenTests())
<del> {
<add> private TestResult executeTestTasks(CacheWrapper cache, TestResult testResult) {
<add> try {
<add> if (conf.isEmptyCacheBetweenTests()) {
<ide> cache.empty();
<ide> }
<del> if (conf.isGcBetweenTestsEnabled())
<del> {
<add> if (conf.isGcBetweenTestsEnabled()) {
<ide> System.gc();
<ide> Thread.sleep(conf.getSleepBetweenTests());
<ide> }
<ide> }
<del> catch (InterruptedException e)
<del> {
<add> catch (InterruptedException e) {
<ide> // Nothing doing here...
<ide> }
<del> catch (Exception e)
<del> {
<add> catch (Exception e) {
<ide> // The Empty barrier of the cache failed. Add a foot note for the TestResult here.
<ide> // testResult.setFootNote("The Cache Empty barrier failed after test case: " + testResult.getTestName() + " : " + testResult.getTestType());
<ide> // errorLogger.error("The Cache Empty barrier failed after test case : " + testResult.getTestName() + ", " + testResult.getTestType(), e);
<ide> return testResult;
<ide> }
<ide>
<del> private List<TestResult> runTestsOnCache(CacheWrapper cache, TestCase testCase)
<del> {
<add> private List<TestResult> runTestsOnCache(CacheWrapper cache, TestCase testCase) {
<ide> List<TestResult> results = new ArrayList<TestResult>();
<del> for (TestConfig testConfig : testCase.getTests())
<del> {
<add> for (TestConfig testConfig : testCase.getTests()) {
<ide> CacheTest testInstance = getCacheTest(testConfig);
<del> if (testInstance instanceof ClusteredCacheTest && localOnly)
<del> {
<add> if (testInstance instanceof ClusteredCacheTest && localOnly) {
<ide> log.warn("Skipping replicated tests since this is in local mode!");
<ide> continue;
<ide> }
<ide>
<del> if (testInstance != null)
<del> {
<add> if (testInstance != null) {
<ide> TestResult result;
<ide> String testName = testConfig.getName();
<ide> String testCaseName = testCase.getName();
<del> try
<del> {
<del> if (testInstance instanceof StatisticTest)
<del> {
<add> try {
<add> if (testInstance instanceof StatisticTest) {
<ide> // create new DescriptiveStatistics and pass it to the test
<ide> int repeat = testConfig.getRepeat();
<ide> if (log.isInfoEnabled()) log.info("Running test " + repeat + " times");
<ide> StatisticTestResult str = new StatisticTestResult();
<del> for (int i = 0; i < repeat; i++)
<del> {
<add> for (int i = 0; i < repeat; i++) {
<ide> ((StatisticTest) testInstance).doCumulativeTest(testName, cache, testCaseName, conf.getSampleSize(), conf.getNumThreads(), str);
<del> if (conf.isEmptyCacheBetweenTests())
<del> {
<del> if (conf.isLocalOnly())
<del> {
<add> if (conf.isEmptyCacheBetweenTests()) {
<add> if (conf.isLocalOnly()) {
<ide> // destroy and restart the cache
<ide> shutdownCache(cache);
<ide> if (i != repeat - 1) cache = newCache(testCase);
<del> }
<del> else
<add> } else
<ide> cache.empty();
<ide> }
<del> if (conf.isGcBetweenTestsEnabled())
<del> {
<add> if (conf.isGcBetweenTestsEnabled()) {
<ide> System.gc();
<ide> Thread.sleep(conf.getSleepBetweenTests());
<ide> }
<ide> }
<ide> result = str;
<del> }
<del> else
<del> {
<add> } else {
<ide> result = testInstance.doTest(testName, cache, testCaseName, conf.getSampleSize(), conf.getNumThreads());
<ide> }
<ide> }
<del> catch (Exception e)
<del> {
<add> catch (Exception e) {
<ide> // The test failed. We should add a test result object with a error message and indicate that it failed.
<ide> result = new BaseTestResult();
<ide> result.setTestName(testCaseName);
<ide> log.warn("Test case : " + testCaseName + ", Test : " + testName + " - Failed due to", e);
<ide> errorLogger.error("Test case : " + testCaseName + ", Test : " + testName + " - Failed : " + e.getMessage(), e);
<ide> }
<del> if (!result.isTestPassed() && testCase.isStopOnFailure())
<del> {
<add> if (!result.isTestPassed() && testCase.isStopOnFailure()) {
<ide> log.warn("The test '" + testCase + "/" + testName + "' failed, exiting...");
<ide> System.exit(1);
<ide> }
<ide> executeTestTasks(cache, result);
<del> if (!result.isSkipReport())
<del> {
<add> if (!result.isSkipReport()) {
<ide> results.add(result);
<ide> }
<ide> }
<ide> return results;
<ide> }
<ide>
<del> private void generateReports(List<TestResult> results)
<del> {
<add> private void generateReports(List<TestResult> results) {
<ide> log.info("Generating Reports...");
<del> for (Report report : conf.getReports())
<del> {
<add> for (Report report : conf.getReports()) {
<ide> ReportGenerator generator;
<del> try
<del> {
<add> try {
<ide> generator = getReportGenerator(report);
<del> if (generator != null)
<del> {
<add> if (generator != null) {
<ide> if (generator instanceof ClusterAwareReportGenerator && localOnly)
<ide> throw new IllegalArgumentException("Configured to run in local mode only, cannot use a clustered report generator!");
<ide> Map<String, String> params = report.getParams();
<ide> generator.setOutputFile(report.getOutputFile());
<ide> generator.generate();
<ide> log.info("Report Generation Completed");
<del> }
<del> else
<del> {
<add> } else {
<ide> log.info("Report not generated - See logs for reasons!!");
<ide> }
<ide> }
<del> catch (Exception e)
<del> {
<add> catch (Exception e) {
<ide> log.warn("Unable to generate Report : " + report.getGenerator() + " - See logs for reasons");
<ide> log.warn("Skipping this report");
<ide> errorLogger.error("Unable to generate Report : " + report.getGenerator(), e);
<ide> }
<ide> }
<ide>
<del> private CacheWrapper getCacheWrapperInstance(TestCase testCaseClass)
<del> {
<add> private CacheWrapper getCacheWrapperInstance(TestCase testCaseClass) {
<ide> CacheWrapper cache = null;
<del> try
<del> {
<add> try {
<ide> cache = (CacheWrapper) Instantiator.getInstance().createClass(testCaseClass.getCacheWrapper());
<ide>
<ide> }
<del> catch (Exception e)
<del> {
<add> catch (Exception e) {
<ide> log.warn("Unable to instantiate CacheWrapper class: " + testCaseClass.getCacheWrapper() + " - Not Running any tests");
<ide> errorLogger.error("Unable to instantiate CacheWrapper class: " + testCaseClass.getCacheWrapper(), e);
<ide> errorLogger.error("Skipping this test");
<ide> return cache;
<ide> }
<ide>
<del> private ReportGenerator getReportGenerator(Report reportClass)
<del> {
<add> private ReportGenerator getReportGenerator(Report reportClass) {
<ide> ReportGenerator report = null;
<del> try
<del> {
<add> try {
<ide> report = (ReportGenerator) Instantiator.getInstance().createClass(reportClass.getGenerator());
<ide>
<ide> }
<del> catch (Exception e)
<del> {
<add> catch (Exception e) {
<ide> log.warn("Unable to instantiate ReportGenerator class: " + reportClass.getGenerator() + " - Not generating the report");
<ide> errorLogger.error("Unable to instantiate ReportGenerator class: " + reportClass.getGenerator(), e);
<ide> errorLogger.error("Skipping this report");
<ide>
<ide> }
<ide>
<del> private CacheTest getCacheTest(TestConfig testConfig)
<del> {
<add> private CacheTest getCacheTest(TestConfig testConfig) {
<ide> CacheTest cacheTestClass = null;
<del> try
<del> {
<add> try {
<ide> cacheTestClass = (CacheTest) Instantiator.getInstance().createClass(testConfig.getTestClass());
<ide> conf.setLocalOnly(localOnly);
<ide> cacheTestClass.setConfiguration(conf);
<ide> }
<del> catch (Exception e)
<del> {
<add> catch (Exception e) {
<ide> log.warn("Unable to instantiate CacheTest class: " + testConfig.getTestClass() + " - Not Running any tests");
<ide> errorLogger.error("Unable to instantiate CacheTest class: " + testConfig.getTestClass(), e);
<ide> errorLogger.error("Skipping this Test");
<ide>
<ide> }
<ide>
<del> private void shutdownCache(CacheWrapper cache)
<del> {
<del> try
<del> {
<add> private void shutdownCache(CacheWrapper cache) {
<add> try {
<ide> cache.tearDown();
<ide> }
<del> catch (Exception e)
<del> {
<add> catch (Exception e) {
<ide> log.warn("Cache Shutdown - Failed.");
<ide> errorLogger.error("Cache Shutdown failed : ", e);
<ide> } |
|
Java | mit | b87d78c673a48c6c207e29a14fb866193af42f60 | 0 | wn1/LNotes,wn1/LNotes | package ru.qdev.lnotes.ui.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.AnyThread;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.arellomobile.mvp.MvpAppCompatFragment;
import com.arellomobile.mvp.presenter.InjectPresenter;
import com.j256.ormlite.dao.CloseableIterator;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import ru.qdev.lnotes.*;
import ru.qdev.lnotes.db.QDVDbIteratorListViewAdapterExt;
import ru.qdev.lnotes.db.entity.QDVDbFolderOrMenuItem;
import ru.qdev.lnotes.mvp.QDVNavigationDrawerPresenter;
import ru.qdev.lnotes.mvp.QDVNavigationDrawerView;
/**
* Created by Vladimir Kudashov on 11.03.17.
*/
public class QDVNavigationDrawerFragment extends MvpAppCompatFragment
implements QDVNavigationDrawerView {
@InjectPresenter
QDVNavigationDrawerPresenter navigationDrawerPresenter;
//TODO deprecated change to new implements
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private View fragmentContainerView;
FolderListAdapter folderListAdapter;
@UiThread
public void setSelectedFolderOrMenu(QDVDbFolderOrMenuItem selectedFolderOrMenu) {
if (folderListAdapter != null){
folderListAdapter.selectedFolderOrMenu = selectedFolderOrMenu;
}
}
@AnyThread
public boolean isActive() {
return isActive;
}
@UiThread
public void setActive(boolean active) {
isActive = active;
if (isActive) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
navigationDrawerPresenter.doDrawerShowIfUserLearn();
}
}, 1000);
}
if (drawerLayout != null && !isActive) {
drawerLayout.closeDrawer(fragmentContainerView);
}
}
private boolean isActive = false;
@Override
@UiThread
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
static private class FolderListAdapter extends QDVDbIteratorListViewAdapterExt<QDVDbFolderOrMenuItem> {
public QDVDbFolderOrMenuItem getSelectedFolderOrMenu() {
return selectedFolderOrMenu;
}
public void setSelectedFolderOrMenu(QDVDbFolderOrMenuItem selectedFolderOrMenu) {
this.selectedFolderOrMenu = selectedFolderOrMenu;
notifyDataSetChanged();
}
private QDVDbFolderOrMenuItem selectedFolderOrMenu;
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
QDVDbFolderOrMenuItem folderOrMenu = getItem(i);
if (view == null) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(
android.R.layout.simple_list_item_activated_1,
viewGroup, false);
}
if (view == null) {
return null;
}
if (folderOrMenu == null) {
view.setVisibility(View.INVISIBLE);
return view;
}
((TextView) view.findViewById(android.R.id.text1))
.setText(folderOrMenu.getLabel());
Boolean itemChecked = false;
if (selectedFolderOrMenu!=null) {
if (folderOrMenu.menuItem ==
QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
if (folderOrMenu.getId() == selectedFolderOrMenu.getId()) {
itemChecked = true;
}
} else if (folderOrMenu.menuItem == selectedFolderOrMenu.menuItem) {
itemChecked = true;
}
}
view.setBackgroundColor(ContextCompat.getColor(viewGroup.getContext(), itemChecked ?
R.color.listViewFolderSelectedColor : R.color.transparentColor));
return view;
}
}
@Override
@UiThread
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
drawerListView = (ListView) inflater.inflate(
R.layout.navigation_drawer, container, false);
folderListAdapter = new FolderListAdapter();
drawerListView.setAdapter(folderListAdapter);
drawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QDVDbFolderOrMenuItem folder = folderListAdapter.getItem(position);
navigationDrawerPresenter.onClickFolderOrMenu(folder);
drawerListView.setItemChecked(position, false);
}
});
drawerListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView,
View view, int position, long l) {
final QDVDbFolderOrMenuItem folderOrMenu = folderListAdapter.getItem(position);
if (folderOrMenu==null ||
folderOrMenu.menuItem!=QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
return false;
}
final String folderLabel = folderOrMenu.getLabel() != null
? folderOrMenu.getLabel() : "";
new AlertDialog.Builder(getActivity()).setTitle(folderLabel).setCancelable(true)
.setItems(new String[]{getString(R.string.menu_delete),
getString(R.string.menu_rename)},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0:
onClickDeleteFolder(folderOrMenu);
break;
case 1:
onClickRenameFolder(folderOrMenu);
break;
}
}
})
.setNegativeButton(R.string.cancel, null).show();
return true;
}
});
return drawerListView;
}
@UiThread
public boolean isDrawerOpen() {
return drawerLayout != null && drawerLayout.isDrawerOpen(fragmentContainerView);
}
@UiThread
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
fragmentContainerView = getActivity().findViewById(fragmentId);
this.drawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
this.drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
drawerToggle = new ActionBarDrawerToggle(
getActivity(),
QDVNavigationDrawerFragment.this.drawerLayout,
R.drawable.ic_drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
navigationDrawerPresenter.userLearned();
getActivity().supportInvalidateOptionsMenu();
}
};
this.drawerLayout.post(new Runnable() {
@Override
public void run() {
drawerToggle.syncState();
}
});
this.drawerLayout.setDrawerListener(drawerToggle);
}
@Override
@UiThread
public void onClickAddFolder() {
final EditText editText = new EditText(getContext());
new AlertDialog.Builder(getActivity()).setTitle(R.string.add_category).setCancelable(true)
.setView(editText).setPositiveButton(R.string.action_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
InputMethodManager inputMethodManager = (InputMethodManager)ThisApp.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
String folderName = editText.getText().toString();
if (folderName.length()>0) {
navigationDrawerPresenter.doAddFolder(folderName);
}
else
{
new AlertDialog.Builder(getActivity())
.setTitle(R.string.folder_name_need_no_empty)
.setPositiveButton(R.string.action_ok, null)
.show();
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
InputMethodManager inputMethodManager = (InputMethodManager) ThisApp.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
}).show();
editText.requestFocus();
editText.requestFocusFromTouch();
InputMethodManager inputMananger = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMananger != null) {
inputMananger.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
@UiThread
public void onClickDeleteFolder(final QDVDbFolderOrMenuItem folder) {
if (folder.menuItem!=QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
return;
}
final String folderLabel = folder.getLabel() != null ? folder.getLabel() : "";
new AlertDialog.Builder(getActivity())
.setTitle(String.format(getString(R.string.delete_folder_confirm),
folderLabel)).setCancelable(true)
.setMessage(R.string.delete_folder_confirm_message)
.setPositiveButton(R.string.action_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
navigationDrawerPresenter.doRemoveFolder(folder);
}
})
.setNegativeButton(R.string.action_no, null).show();
}
@UiThread
public void onClickRenameFolder(final QDVDbFolderOrMenuItem folder) {
if (folder.menuItem!=QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
return;
}
final String folderLabel = folder.getLabel() != null ? folder.getLabel() : "";
final EditText editText = new EditText(getContext());
editText.setText(folderLabel);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.rename_folder_title)
.setCancelable(true)
.setView(editText).setPositiveButton(R.string.action_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
InputMethodManager inputMethodManager = (InputMethodManager)ThisApp.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
String folderName = editText.getText().toString();
if (folderName.length()>0) {
folder.setLabel(folderName);
navigationDrawerPresenter.doUpdateFolder(folder);
}
else
{
new AlertDialog.Builder(getActivity())
.setTitle(R.string.folder_name_need_no_empty)
.setPositiveButton(R.string.action_ok, null)
.show();
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
InputMethodManager inputMethodManager = (InputMethodManager)ThisApp.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
}).show();
editText.requestFocus();
editText.requestFocusFromTouch();
InputMethodManager inputMananger = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMananger != null) {
inputMananger.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
@Override
@UiThread
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
@UiThread
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (drawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.navigation_drawer, menu);
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
@UiThread
public boolean onOptionsItemSelected(MenuItem item) {
if (!isActive) {
return super.onOptionsItemSelected(item);
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
@UiThread
public void loadFolderList(@NotNull CloseableIterator<QDVDbFolderOrMenuItem> dbIterator,
@NotNull ArrayList<QDVDbFolderOrMenuItem> itemsAddingToTop,
@Nullable QDVDbFolderOrMenuItem selectedFolderOrMenu) {
folderListAdapter.setSelectedFolderOrMenu(selectedFolderOrMenu);
folderListAdapter.loadData(itemsAddingToTop, dbIterator);
}
@Override
@UiThread
public void setDrawerOpen(boolean drawerOpen) {
if (!isActive) {
drawerLayout.closeDrawer(fragmentContainerView);
return;
}
if (drawerLayout != null) {
if (drawerOpen) {
drawerLayout.openDrawer(fragmentContainerView);
}
else
{
drawerLayout.closeDrawer(fragmentContainerView);
}
}
}
@Override
@UiThread
public void switchDrawerOpenOrClose() {
if (!isActive) {
drawerLayout.closeDrawer(fragmentContainerView);
return;
}
if (drawerLayout.isDrawerOpen(fragmentContainerView)) {
drawerLayout.closeDrawer(fragmentContainerView);
} else {
drawerLayout.openDrawer(fragmentContainerView);
}
}
}
| app/src/main/java/ru/qdev/lnotes/ui/fragment/QDVNavigationDrawerFragment.java | package ru.qdev.lnotes.ui.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.AnyThread;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.arellomobile.mvp.MvpAppCompatFragment;
import com.arellomobile.mvp.presenter.InjectPresenter;
import com.j256.ormlite.dao.CloseableIterator;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import ru.qdev.lnotes.*;
import ru.qdev.lnotes.db.QDVDbIteratorListViewAdapterExt;
import ru.qdev.lnotes.db.entity.QDVDbFolderOrMenuItem;
import ru.qdev.lnotes.mvp.QDVNavigationDrawerPresenter;
import ru.qdev.lnotes.mvp.QDVNavigationDrawerView;
/**
* Created by Vladimir Kudashov on 11.03.17.
*/
public class QDVNavigationDrawerFragment extends MvpAppCompatFragment
implements QDVNavigationDrawerView {
@InjectPresenter
QDVNavigationDrawerPresenter navigationDrawerPresenter;
//TODO deprecated change to new implements
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private View fragmentContainerView;
QDVDbIteratorListViewAdapterExt<QDVDbFolderOrMenuItem> folderListAdapter;
private QDVDbFolderOrMenuItem selectedFolderOrMenu;
public QDVDbFolderOrMenuItem getSelectedFolderOrMenu() {
return selectedFolderOrMenu;
}
@UiThread
public void setSelectedFolderOrMenu(QDVDbFolderOrMenuItem selectedFolderOrMenu) {
this.selectedFolderOrMenu = selectedFolderOrMenu;
if (folderListAdapter != null){
folderListAdapter.notifyDataSetChanged();
}
}
@AnyThread
public boolean isActive() {
return isActive;
}
@UiThread
public void setActive(boolean active) {
isActive = active;
if (isActive) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
navigationDrawerPresenter.doDrawerShowIfUserLearn();
}
}, 1000);
}
if (drawerLayout != null && !isActive) {
drawerLayout.closeDrawer(fragmentContainerView);
}
}
private boolean isActive = false;
@Override
@UiThread
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
@UiThread
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
drawerListView = (ListView) inflater.inflate(
R.layout.navigation_drawer, container, false);
folderListAdapter =
new QDVDbIteratorListViewAdapterExt<QDVDbFolderOrMenuItem>() {
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
QDVDbFolderOrMenuItem folderOrMenu = getItem(i);
if (view == null) {
view = getLayoutInflater().inflate(
android.R.layout.simple_list_item_activated_1,
viewGroup, false);
}
if (view == null) {
return null;
}
if (folderOrMenu == null) {
view.setVisibility(View.INVISIBLE);
return view;
}
((TextView) view.findViewById(android.R.id.text1))
.setText(folderOrMenu.getLabel());
Boolean itemChecked = false;
if (selectedFolderOrMenu!=null) {
if (folderOrMenu.menuItem ==
QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
if (folderOrMenu.getId() == selectedFolderOrMenu.getId()) {
itemChecked = true;
}
} else if (folderOrMenu.menuItem == selectedFolderOrMenu.menuItem) {
itemChecked = true;
}
}
view.setBackgroundColor(ContextCompat.getColor(getContext(), itemChecked ?
R.color.listViewFolderSelectedColor : R.color.transparentColor));
return view;
}
};
drawerListView.setAdapter(folderListAdapter);
drawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QDVDbFolderOrMenuItem folder = folderListAdapter.getItem(position);
navigationDrawerPresenter.onClickFolderOrMenu(folder);
drawerListView.setItemChecked(position, false);
}
});
drawerListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView,
View view, int position, long l) {
final QDVDbFolderOrMenuItem folderOrMenu = folderListAdapter.getItem(position);
if (folderOrMenu==null ||
folderOrMenu.menuItem!=QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
return false;
}
final String folderLabel = folderOrMenu.getLabel() != null
? folderOrMenu.getLabel() : "";
new AlertDialog.Builder(getActivity()).setTitle(folderLabel).setCancelable(true)
.setItems(new String[]{getString(R.string.menu_delete),
getString(R.string.menu_rename)},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0:
onClickDeleteFolder(folderOrMenu);
break;
case 1:
onClickRenameFolder(folderOrMenu);
break;
}
}
})
.setNegativeButton(R.string.cancel, null).show();
return true;
}
});
return drawerListView;
}
@UiThread
public boolean isDrawerOpen() {
return drawerLayout != null && drawerLayout.isDrawerOpen(fragmentContainerView);
}
@UiThread
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
fragmentContainerView = getActivity().findViewById(fragmentId);
this.drawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
this.drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
drawerToggle = new ActionBarDrawerToggle(
getActivity(),
QDVNavigationDrawerFragment.this.drawerLayout,
R.drawable.ic_drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
navigationDrawerPresenter.userLearned();
getActivity().supportInvalidateOptionsMenu();
}
};
this.drawerLayout.post(new Runnable() {
@Override
public void run() {
drawerToggle.syncState();
}
});
this.drawerLayout.setDrawerListener(drawerToggle);
}
@Override
@UiThread
public void onClickAddFolder() {
final EditText editText = new EditText(getContext());
new AlertDialog.Builder(getActivity()).setTitle(R.string.add_category).setCancelable(true)
.setView(editText).setPositiveButton(R.string.action_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
InputMethodManager inputMethodManager = (InputMethodManager)ThisApp.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
String folderName = editText.getText().toString();
if (folderName.length()>0) {
navigationDrawerPresenter.doAddFolder(folderName);
}
else
{
new AlertDialog.Builder(getActivity())
.setTitle(R.string.folder_name_need_no_empty)
.setPositiveButton(R.string.action_ok, null)
.show();
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
InputMethodManager inputMethodManager = (InputMethodManager) ThisApp.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
}).show();
editText.requestFocus();
editText.requestFocusFromTouch();
InputMethodManager inputMananger = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMananger != null) {
inputMananger.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
@UiThread
public void onClickDeleteFolder(final QDVDbFolderOrMenuItem folder) {
if (folder.menuItem!=QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
return;
}
final String folderLabel = folder.getLabel() != null ? folder.getLabel() : "";
new AlertDialog.Builder(getActivity())
.setTitle(String.format(getString(R.string.delete_folder_confirm),
folderLabel)).setCancelable(true)
.setMessage(R.string.delete_folder_confirm_message)
.setPositiveButton(R.string.action_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
navigationDrawerPresenter.doRemoveFolder(folder);
}
})
.setNegativeButton(R.string.action_no, null).show();
}
@UiThread
public void onClickRenameFolder(final QDVDbFolderOrMenuItem folder) {
if (folder.menuItem!=QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
return;
}
final String folderLabel = folder.getLabel() != null ? folder.getLabel() : "";
final EditText editText = new EditText(getContext());
editText.setText(folderLabel);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.rename_folder_title)
.setCancelable(true)
.setView(editText).setPositiveButton(R.string.action_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
InputMethodManager inputMethodManager = (InputMethodManager)ThisApp.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
String folderName = editText.getText().toString();
if (folderName.length()>0) {
folder.setLabel(folderName);
navigationDrawerPresenter.doUpdateFolder(folder);
}
else
{
new AlertDialog.Builder(getActivity())
.setTitle(R.string.folder_name_need_no_empty)
.setPositiveButton(R.string.action_ok, null)
.show();
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
InputMethodManager inputMethodManager = (InputMethodManager)ThisApp.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
}).show();
editText.requestFocus();
editText.requestFocusFromTouch();
InputMethodManager inputMananger = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMananger != null) {
inputMananger.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
@Override
@UiThread
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
@UiThread
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (drawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.navigation_drawer, menu);
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
@UiThread
public boolean onOptionsItemSelected(MenuItem item) {
if (!isActive) {
return super.onOptionsItemSelected(item);
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
@UiThread
public void loadFolderList(@NotNull CloseableIterator<QDVDbFolderOrMenuItem> dbIterator,
@NotNull ArrayList<QDVDbFolderOrMenuItem> itemsAddingToTop,
@Nullable QDVDbFolderOrMenuItem selectedFolderOrMenu) {
this.selectedFolderOrMenu = selectedFolderOrMenu;
folderListAdapter.loadData(itemsAddingToTop, dbIterator);
}
@Override
@UiThread
public void setDrawerOpen(boolean drawerOpen) {
if (!isActive) {
drawerLayout.closeDrawer(fragmentContainerView);
return;
}
if (drawerLayout != null) {
if (drawerOpen) {
drawerLayout.openDrawer(fragmentContainerView);
}
else
{
drawerLayout.closeDrawer(fragmentContainerView);
}
}
}
@Override
@UiThread
public void switchDrawerOpenOrClose() {
if (!isActive) {
drawerLayout.closeDrawer(fragmentContainerView);
return;
}
if (drawerLayout.isDrawerOpen(fragmentContainerView)) {
drawerLayout.closeDrawer(fragmentContainerView);
} else {
drawerLayout.openDrawer(fragmentContainerView);
}
}
}
| Refactoring and code design improved.
| app/src/main/java/ru/qdev/lnotes/ui/fragment/QDVNavigationDrawerFragment.java | Refactoring and code design improved. | <ide><path>pp/src/main/java/ru/qdev/lnotes/ui/fragment/QDVNavigationDrawerFragment.java
<ide> private ListView drawerListView;
<ide> private View fragmentContainerView;
<ide>
<del> QDVDbIteratorListViewAdapterExt<QDVDbFolderOrMenuItem> folderListAdapter;
<del> private QDVDbFolderOrMenuItem selectedFolderOrMenu;
<del>
<del> public QDVDbFolderOrMenuItem getSelectedFolderOrMenu() {
<del> return selectedFolderOrMenu;
<del> }
<add> FolderListAdapter folderListAdapter;
<ide>
<ide> @UiThread
<ide> public void setSelectedFolderOrMenu(QDVDbFolderOrMenuItem selectedFolderOrMenu) {
<del> this.selectedFolderOrMenu = selectedFolderOrMenu;
<ide> if (folderListAdapter != null){
<del> folderListAdapter.notifyDataSetChanged();
<add> folderListAdapter.selectedFolderOrMenu = selectedFolderOrMenu;
<ide> }
<ide> }
<ide>
<ide> setHasOptionsMenu(true);
<ide> }
<ide>
<add> static private class FolderListAdapter extends QDVDbIteratorListViewAdapterExt<QDVDbFolderOrMenuItem> {
<add> public QDVDbFolderOrMenuItem getSelectedFolderOrMenu() {
<add> return selectedFolderOrMenu;
<add> }
<add>
<add> public void setSelectedFolderOrMenu(QDVDbFolderOrMenuItem selectedFolderOrMenu) {
<add> this.selectedFolderOrMenu = selectedFolderOrMenu;
<add> notifyDataSetChanged();
<add> }
<add>
<add> private QDVDbFolderOrMenuItem selectedFolderOrMenu;
<add>
<add> @Override
<add> public View getView(int i, View view, ViewGroup viewGroup) {
<add> QDVDbFolderOrMenuItem folderOrMenu = getItem(i);
<add> if (view == null) {
<add> view = LayoutInflater.from(viewGroup.getContext()).inflate(
<add> android.R.layout.simple_list_item_activated_1,
<add> viewGroup, false);
<add> }
<add> if (view == null) {
<add> return null;
<add> }
<add> if (folderOrMenu == null) {
<add> view.setVisibility(View.INVISIBLE);
<add> return view;
<add> }
<add> ((TextView) view.findViewById(android.R.id.text1))
<add> .setText(folderOrMenu.getLabel());
<add>
<add> Boolean itemChecked = false;
<add> if (selectedFolderOrMenu!=null) {
<add> if (folderOrMenu.menuItem ==
<add> QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
<add> if (folderOrMenu.getId() == selectedFolderOrMenu.getId()) {
<add> itemChecked = true;
<add> }
<add> } else if (folderOrMenu.menuItem == selectedFolderOrMenu.menuItem) {
<add> itemChecked = true;
<add> }
<add> }
<add>
<add> view.setBackgroundColor(ContextCompat.getColor(viewGroup.getContext(), itemChecked ?
<add> R.color.listViewFolderSelectedColor : R.color.transparentColor));
<add>
<add> return view;
<add> }
<add> }
<add>
<ide> @Override
<ide> @UiThread
<ide> public View onCreateView(LayoutInflater inflater, ViewGroup container,
<ide> drawerListView = (ListView) inflater.inflate(
<ide> R.layout.navigation_drawer, container, false);
<ide>
<del> folderListAdapter =
<del> new QDVDbIteratorListViewAdapterExt<QDVDbFolderOrMenuItem>() {
<del> @Override
<del> public View getView(int i, View view, ViewGroup viewGroup) {
<del> QDVDbFolderOrMenuItem folderOrMenu = getItem(i);
<del> if (view == null) {
<del> view = getLayoutInflater().inflate(
<del> android.R.layout.simple_list_item_activated_1,
<del> viewGroup, false);
<del> }
<del> if (view == null) {
<del> return null;
<del> }
<del> if (folderOrMenu == null) {
<del> view.setVisibility(View.INVISIBLE);
<del> return view;
<del> }
<del> ((TextView) view.findViewById(android.R.id.text1))
<del> .setText(folderOrMenu.getLabel());
<del>
<del> Boolean itemChecked = false;
<del> if (selectedFolderOrMenu!=null) {
<del> if (folderOrMenu.menuItem ==
<del> QDVDbFolderOrMenuItem.MenuItemMarker.FOLDER_ENTITY) {
<del> if (folderOrMenu.getId() == selectedFolderOrMenu.getId()) {
<del> itemChecked = true;
<del> }
<del> } else if (folderOrMenu.menuItem == selectedFolderOrMenu.menuItem) {
<del> itemChecked = true;
<del> }
<del> }
<del>
<del> view.setBackgroundColor(ContextCompat.getColor(getContext(), itemChecked ?
<del> R.color.listViewFolderSelectedColor : R.color.transparentColor));
<del>
<del> return view;
<del> }
<del> };
<add> folderListAdapter = new FolderListAdapter();
<ide>
<ide> drawerListView.setAdapter(folderListAdapter);
<ide>
<ide> public void loadFolderList(@NotNull CloseableIterator<QDVDbFolderOrMenuItem> dbIterator,
<ide> @NotNull ArrayList<QDVDbFolderOrMenuItem> itemsAddingToTop,
<ide> @Nullable QDVDbFolderOrMenuItem selectedFolderOrMenu) {
<del> this.selectedFolderOrMenu = selectedFolderOrMenu;
<add> folderListAdapter.setSelectedFolderOrMenu(selectedFolderOrMenu);
<ide> folderListAdapter.loadData(itemsAddingToTop, dbIterator);
<ide> }
<ide> |
|
Java | apache-2.0 | 361a3698bcc09c7d506226ef38cf3e2dac324972 | 0 | apereo/cas,fogbeam/cas_mirror,apereo/cas,fogbeam/cas_mirror,apereo/cas,apereo/cas,rkorn86/cas,fogbeam/cas_mirror,pdrados/cas,rkorn86/cas,fogbeam/cas_mirror,pdrados/cas,apereo/cas,apereo/cas,fogbeam/cas_mirror,Jasig/cas,Jasig/cas,Jasig/cas,apereo/cas,pdrados/cas,pdrados/cas,rkorn86/cas,fogbeam/cas_mirror,pdrados/cas,rkorn86/cas,pdrados/cas,Jasig/cas | package org.apereo.cas.authentication;
import org.apereo.cas.util.junit.EnabledIfPortOpen;
import org.junit.jupiter.api.Tag;
import org.springframework.test.context.TestPropertySource;
/**
* Unit test for {@link LdapAuthenticationHandler}.
* This test demonstrates using the AD type.
* Login name is {@code sAMAccountName} (aka "short" windows login name), bind as DOMAIN\USERNAME.
* Issues:
* - This configuration doesn't retrieve any attributes as part of the authentication.
* @author Hal Deadman
* @since 6.1.0
*/
@TestPropertySource(properties = {
"cas.authn.ldap[0].type=AD",
"cas.authn.ldap[0].ldap-url=" + BaseActiveDirectoryLdapAuthenticationHandlerTests.AD_LDAP_URL,
"cas.authn.ldap[0].use-start-tls=true",
"cas.authn.ldap[0].subtree-search=true",
"cas.authn.ldap[0].base-dn=cn=Users,dc=cas,dc=example,dc=org",
"cas.authn.ldap[0].dn-format=CAS\\\\%s",
"cas.authn.ldap[0].principalAttributeList=sAMAccountName,cn",
"cas.authn.ldap[0].enhance-with-entry-resolver=true",
"cas.authn.ldap[0].search-filter=(sAMAccountName={user})",
"cas.authn.ldap[0].pool-passivator=bind",
"cas.authn.ldap[0].min-pool-size=0",
"cas.authn.ldap[0].trust-store=" + BaseActiveDirectoryLdapAuthenticationHandlerTests.AD_TRUST_STORE,
"cas.authn.ldap[0].trust-store-type=JKS",
"cas.authn.ldap[0].trust-store-password=changeit",
"cas.authn.ldap[0].hostname-verifier=-default"
})
@EnabledIfPortOpen(port = 10390)
@Tag("Ldap")
public class ActiveDirectorySamAccountNameLdapAuthenticationHandlerTests extends BaseActiveDirectoryLdapAuthenticationHandlerTests {
/**
* This dnFormat can authenticate but it isn't bringing back any attributes.
*/
@Override
protected String[] getPrincipalAttributes() {
return new String[0];
}
}
| support/cas-server-support-ldap/src/test/java/org/apereo/cas/authentication/ActiveDirectorySamAccountNameLdapAuthenticationHandlerTests.java | package org.apereo.cas.authentication;
import org.apereo.cas.util.junit.EnabledIfPortOpen;
import org.junit.jupiter.api.Tag;
import org.springframework.test.context.TestPropertySource;
/**
* Unit test for {@link LdapAuthenticationHandler}.
* This test demonstrates using the AD type.
* Login name is {@code sAMAccountName} (aka "short" windows login name), bind as DOMAIN\USERNAME.
* Issues:
* - This configuration doesn't retrieve any attributes as part of the authentication.
* @author Hal Deadman
* @since 6.1.0
*/
@TestPropertySource(properties = {
"cas.authn.ldap[0].type=AD",
"cas.authn.ldap[0].ldap-url=" + BaseActiveDirectoryLdapAuthenticationHandlerTests.AD_LDAP_URL,
"cas.authn.ldap[0].use-start-tls=true",
"cas.authn.ldap[0].subtree-search=true",
"cas.authn.ldap[0].base-dn=cn=Users,dc=cas,dc=example,dc=org",
"cas.authn.ldap[0].dn-format=CAS\\\\%s",
"cas.authn.ldap[0].principalAttributeList=sAMAccountName,cn",
"cas.authn.ldap[0].enhance-with-entry-resolver=true",
"cas.authn.ldap[0].search-filter=(s-amaccount-name={user})",
"cas.authn.ldap[0].pool-passivator=bind",
"cas.authn.ldap[0].min-pool-size=0",
"cas.authn.ldap[0].trust-store=" + BaseActiveDirectoryLdapAuthenticationHandlerTests.AD_TRUST_STORE,
"cas.authn.ldap[0].trust-store-type=-jks",
"cas.authn.ldap[0].trust-store-password=changeit",
"cas.authn.ldap[0].hostname-verifier=-default"
})
@EnabledIfPortOpen(port = 10390)
@Tag("Ldap")
public class ActiveDirectorySamAccountNameLdapAuthenticationHandlerTests extends BaseActiveDirectoryLdapAuthenticationHandlerTests {
/**
* This dnFormat can authenticate but it isn't bringing back any attributes.
*/
@Override
protected String[] getPrincipalAttributes() {
return new String[0];
}
}
| fix ldap tests
| support/cas-server-support-ldap/src/test/java/org/apereo/cas/authentication/ActiveDirectorySamAccountNameLdapAuthenticationHandlerTests.java | fix ldap tests | <ide><path>upport/cas-server-support-ldap/src/test/java/org/apereo/cas/authentication/ActiveDirectorySamAccountNameLdapAuthenticationHandlerTests.java
<ide> "cas.authn.ldap[0].dn-format=CAS\\\\%s",
<ide> "cas.authn.ldap[0].principalAttributeList=sAMAccountName,cn",
<ide> "cas.authn.ldap[0].enhance-with-entry-resolver=true",
<del> "cas.authn.ldap[0].search-filter=(s-amaccount-name={user})",
<add> "cas.authn.ldap[0].search-filter=(sAMAccountName={user})",
<ide> "cas.authn.ldap[0].pool-passivator=bind",
<ide> "cas.authn.ldap[0].min-pool-size=0",
<ide> "cas.authn.ldap[0].trust-store=" + BaseActiveDirectoryLdapAuthenticationHandlerTests.AD_TRUST_STORE,
<del> "cas.authn.ldap[0].trust-store-type=-jks",
<add> "cas.authn.ldap[0].trust-store-type=JKS",
<ide> "cas.authn.ldap[0].trust-store-password=changeit",
<ide> "cas.authn.ldap[0].hostname-verifier=-default"
<ide> }) |
|
Java | apache-2.0 | f219ee8c6a772c2a04cdb1b8f14bd0028060aa26 | 0 | lmdbjava/lmdbjava,phraktle/lmdbjava | /*
* Copyright 2016 The LmdbJava 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 org.lmdbjava;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import static java.nio.ByteBuffer.allocateDirect;
import jnr.ffi.Pointer;
import static org.lmdbjava.UnsafeAccess.UNSAFE;
/**
* {@link ByteBuffer}-based proxy.
* <p>
* There are two concrete {@link ByteBuffer} cursor implementations available:
* <ul>
* <li>A "fast" implementation: {@link UnsafeProxy}</li>
* <li>A "safe" implementation: {@link ReflectiveProxy}</li>
* </ul>
* <p>
* Users nominate which implementation they prefer by referencing the
* {@link #FACTORY_OPTIMAL} or {@link #FACTORY_SAFE} field when invoking
* {@link Dbi#openCursor(org.lmdbjava.Txn, org.lmdbjava.CursorFactory)}.
*/
public final class ByteBufferProxy {
/**
* The fastest {@link ByteBuffer} proxy that is available on this platform.
* This will always be the same instance as {@link #FACTORY_SAFE} if the
* {@link UnsafeAccess#DISABLE_UNSAFE_PROP} has been set to <code>true</code>
* or {@link UnsafeAccess} is unavailable. Guaranteed to never be null.
*/
public static final BufferProxy<ByteBuffer> PROXY_OPTIMAL;
/**
* The safe, reflective {@link ByteBuffer} proxy for this system. Guaranteed
* to never be null.
*/
public static final BufferProxy<ByteBuffer> PROXY_SAFE;
private static final String FIELD_NAME_ADDRESS = "address";
private static final String FIELD_NAME_CAPACITY = "capacity";
static {
PROXY_SAFE = new ReflectiveProxy();
PROXY_OPTIMAL = getProxyOptimal();
}
private static BufferProxy<ByteBuffer> getProxyOptimal() {
try {
return new UnsafeProxy();
} catch (Throwable e) {
return PROXY_SAFE;
}
}
static Field findField(final Class<?> c, final String name) {
Class<?> clazz = c;
do {
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
} while (clazz != null);
throw new RuntimeException(name + " not found");
}
private ByteBufferProxy() {
}
/**
* A proxy that uses Java reflection to modify byte buffer fields, and
* official JNR-FFF methods to manipulate native pointers.
*/
private static final class ReflectiveProxy implements BufferProxy<ByteBuffer> {
private static final Field ADDRESS_FIELD;
private static final Field CAPACITY_FIELD;
static {
ADDRESS_FIELD = findField(Buffer.class, FIELD_NAME_ADDRESS);
CAPACITY_FIELD = findField(Buffer.class, FIELD_NAME_CAPACITY);
}
@Override
public ByteBuffer allocate(int bytes) {
return allocateDirect(bytes);
}
@Override
public void dirty(ByteBuffer roBuffer, Pointer ptr, long ptrAddr) {
final long addr = ptr.getLong(STRUCT_FIELD_OFFSET_DATA);
final long size = ptr.getLong(STRUCT_FIELD_OFFSET_SIZE);
try {
ADDRESS_FIELD.set(roBuffer, addr);
CAPACITY_FIELD.set(roBuffer, (int) size);
} catch (IllegalArgumentException | IllegalAccessException ex) {
throw new RuntimeException("Cannot modify buffer", ex);
}
roBuffer.clear();
}
@Override
public void set(ByteBuffer buffer, Pointer ptr, long ptrAddr) {
final long addr = ((sun.nio.ch.DirectBuffer) buffer).address();
ptr.putLong(STRUCT_FIELD_OFFSET_SIZE, buffer.capacity());
ptr.putLong(STRUCT_FIELD_OFFSET_DATA, addr);
}
}
/**
* A proxy that uses Java's "unsafe" class to directly manipulate byte buffer
* fields and JNR-FFF allocated memory pointers.
*/
private static final class UnsafeProxy implements BufferProxy<ByteBuffer> {
static final long ADDRESS_OFFSET;
static final long CAPACITY_OFFSET;
static {
try {
final Field address = findField(Buffer.class, FIELD_NAME_ADDRESS);
final Field capacity = findField(Buffer.class, FIELD_NAME_CAPACITY);
ADDRESS_OFFSET = UNSAFE.objectFieldOffset(address);
CAPACITY_OFFSET = UNSAFE.objectFieldOffset(capacity);
} catch (SecurityException e) {
throw new RuntimeException(e);
}
}
@Override
public ByteBuffer allocate(int bytes) {
return allocateDirect(bytes);
}
@Override
public void dirty(ByteBuffer roBuffer, Pointer ptr, long ptrAddr) {
final long addr = UNSAFE.getLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA);
final long size = UNSAFE.getLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE);
UNSAFE.putLong(roBuffer, ADDRESS_OFFSET, addr);
UNSAFE.putInt(roBuffer, CAPACITY_OFFSET, (int) size);
roBuffer.clear();
}
@Override
public void set(ByteBuffer buffer, Pointer ptr, long ptrAddr) {
final long addr = ((sun.nio.ch.DirectBuffer) buffer).address();
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE, buffer.capacity());
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA, addr);
}
}
}
| src/main/java/org/lmdbjava/ByteBufferProxy.java | /*
* Copyright 2016 The LmdbJava 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 org.lmdbjava;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import static java.nio.ByteBuffer.allocateDirect;
import jnr.ffi.Pointer;
import static org.lmdbjava.UnsafeAccess.UNSAFE;
/**
* {@link ByteBuffer}-based proxy.
* <p>
* There are two concrete {@link ByteBuffer} cursor implementations available:
* <ul>
* <li>A "fast" implementation: {@link UnsafeProxy}</li>
* <li>A "safe" implementation: {@link ReflectiveProxy}</li>
* </ul>
* <p>
* Users nominate which implementation they prefer by referencing the
* {@link #FACTORY_OPTIMAL} or {@link #FACTORY_SAFE} field when invoking
* {@link Dbi#openCursor(org.lmdbjava.Txn, org.lmdbjava.CursorFactory)}.
*/
public final class ByteBufferProxy {
/**
* The fastest {@link ByteBuffer} proxy that is available on this platform.
* This will always be the same instance as {@link #FACTORY_SAFE} if the
* {@link UnsafeAccess#DISABLE_UNSAFE_PROP} has been set to <code>true</code>
* or {@link UnsafeAccess} is unavailable. Guaranteed to never be null.
*/
public static final BufferProxy<ByteBuffer> PROXY_OPTIMAL;
/**
* The safe, reflective {@link ByteBuffer} proxy for this system. Guaranteed
* to never be null.
*/
public static final BufferProxy<ByteBuffer> PROXY_SAFE;
private static final String FIELD_NAME_ADDRESS = "address";
private static final String FIELD_NAME_CAPACITY = "capacity";
static {
PROXY_SAFE = new ReflectiveProxy();
PROXY_OPTIMAL = getProxyOptimal();
}
public static BufferProxy<ByteBuffer> getProxyOptimal() {
try {
return new UnsafeProxy();
} catch (Throwable e) {
return PROXY_SAFE;
}
}
static Field findField(final Class<?> c, final String name) {
Class<?> clazz = c;
do {
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
} while (clazz != null);
throw new RuntimeException(name + " not found");
}
private ByteBufferProxy() {
}
/**
* A proxy that uses Java reflection to modify byte buffer fields, and
* official JNR-FFF methods to manipulate native pointers.
*/
private static final class ReflectiveProxy implements BufferProxy<ByteBuffer> {
private static final Field ADDRESS_FIELD;
private static final Field CAPACITY_FIELD;
static {
ADDRESS_FIELD = findField(Buffer.class, FIELD_NAME_ADDRESS);
CAPACITY_FIELD = findField(Buffer.class, FIELD_NAME_CAPACITY);
}
@Override
public ByteBuffer allocate(int bytes) {
return allocateDirect(bytes);
}
@Override
public void dirty(ByteBuffer roBuffer, Pointer ptr, long ptrAddr) {
final long addr = ptr.getLong(STRUCT_FIELD_OFFSET_DATA);
final long size = ptr.getLong(STRUCT_FIELD_OFFSET_SIZE);
try {
ADDRESS_FIELD.set(roBuffer, addr);
CAPACITY_FIELD.set(roBuffer, (int) size);
} catch (IllegalArgumentException | IllegalAccessException ex) {
throw new RuntimeException("Cannot modify buffer", ex);
}
roBuffer.clear();
}
@Override
public void set(ByteBuffer buffer, Pointer ptr, long ptrAddr) {
final long addr = ((sun.nio.ch.DirectBuffer) buffer).address();
ptr.putLong(STRUCT_FIELD_OFFSET_SIZE, buffer.capacity());
ptr.putLong(STRUCT_FIELD_OFFSET_DATA, addr);
}
}
/**
* A proxy that uses Java's "unsafe" class to directly manipulate byte buffer
* fields and JNR-FFF allocated memory pointers.
*/
private static final class UnsafeProxy implements BufferProxy<ByteBuffer> {
static final long ADDRESS_OFFSET;
static final long CAPACITY_OFFSET;
static {
try {
final Field address = findField(Buffer.class, FIELD_NAME_ADDRESS);
final Field capacity = findField(Buffer.class, FIELD_NAME_CAPACITY);
ADDRESS_OFFSET = UNSAFE.objectFieldOffset(address);
CAPACITY_OFFSET = UNSAFE.objectFieldOffset(capacity);
} catch (SecurityException e) {
throw new RuntimeException(e);
}
}
@Override
public ByteBuffer allocate(int bytes) {
return allocateDirect(bytes);
}
@Override
public void dirty(ByteBuffer roBuffer, Pointer ptr, long ptrAddr) {
final long addr = UNSAFE.getLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA);
final long size = UNSAFE.getLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE);
UNSAFE.putLong(roBuffer, ADDRESS_OFFSET, addr);
UNSAFE.putInt(roBuffer, CAPACITY_OFFSET, (int) size);
roBuffer.clear();
}
@Override
public void set(ByteBuffer buffer, Pointer ptr, long ptrAddr) {
final long addr = ((sun.nio.ch.DirectBuffer) buffer).address();
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE, buffer.capacity());
UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA, addr);
}
}
}
| Reduce method visibility (users should use fields)
| src/main/java/org/lmdbjava/ByteBufferProxy.java | Reduce method visibility (users should use fields) | <ide><path>rc/main/java/org/lmdbjava/ByteBufferProxy.java
<ide> PROXY_OPTIMAL = getProxyOptimal();
<ide> }
<ide>
<del> public static BufferProxy<ByteBuffer> getProxyOptimal() {
<add> private static BufferProxy<ByteBuffer> getProxyOptimal() {
<ide> try {
<ide> return new UnsafeProxy();
<ide> } catch (Throwable e) { |
|
Java | agpl-3.0 | 2cc33f1657ea4c1db7b177df258645c4b3696e02 | 0 | telefonicaid/fiware-cygnus,telefonicaid/fiware-cygnus,telefonicaid/fiware-cygnus,telefonicaid/fiware-cygnus | /**
* Copyright 2014-2017 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-cygnus (FIWARE project).
*
* fiware-cygnus 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.
* fiware-cygnus 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 fiware-cygnus. If not, see
* http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License please contact with iot_support at tid dot es
*/
package com.telefonica.iot.cygnus.sinks;
import com.google.gson.Gson;
import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute;
import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElement;
import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration;
import com.telefonica.iot.cygnus.errors.CygnusBadContextData;
import com.telefonica.iot.cygnus.errors.CygnusCappingError;
import com.telefonica.iot.cygnus.errors.CygnusExpiratingError;
import com.telefonica.iot.cygnus.errors.CygnusPersistenceError;
import com.telefonica.iot.cygnus.errors.CygnusRuntimeError;
import com.telefonica.iot.cygnus.interceptors.NGSIEvent;
import com.telefonica.iot.cygnus.log.CygnusLogger;
import com.telefonica.iot.cygnus.sinks.Enums.DataModel;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYATTRIBUTE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITY;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYTYPE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYDATABASE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYTYPEDATABASE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYDATABASESCHEMA;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYTYPEDATABASESCHEMA;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYSERVICE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYSERVICEPATH;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYFIXEDENTITYTYPE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYFIXEDENTITYTYPEDATABASE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYFIXEDENTITYYPEDATABASESCHEMA;
import java.util.Map;
import com.telefonica.iot.cygnus.utils.CommonConstants;
import com.telefonica.iot.cygnus.utils.NGSIConstants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import org.apache.flume.Channel;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.Sink.Status;
import org.apache.flume.Transaction;
import org.apache.flume.ChannelException;
import org.apache.flume.conf.Configurable;
import org.apache.log4j.MDC;
/**
*
* @author frb
Abstract class containing the common code to all the sinks persisting data comming from Orion Context Broker.
The common attributes are:
- there is no common attributes
The common methods are:
- void stop()
- Status process() throws EventDeliveryException
- void persistOne(Event getRecvTimeTs) throws Exception
The non common parts, and therefore those that are sink dependant and must be implemented are:
- void configure(Context context)
- void start()
- void persistOne(Map<String, String> eventHeaders, NotifyContextRequest notification) throws Exception
*/
public abstract class NGSISink extends CygnusSink implements Configurable {
// Logger
private static final CygnusLogger LOGGER = new CygnusLogger(NGSISink.class);
// General parameters for all the sinks
protected DataModel dataModel;
protected boolean enableGrouping;
protected int batchSize;
protected int batchTimeout;
protected int batchTTL;
protected int[] batchRetryIntervals;
protected boolean enableLowercase;
protected boolean invalidConfiguration;
protected boolean enableEncoding;
protected boolean enableNameMappings;
private long persistencePolicyMaxRecords;
private long persistencePolicyExpirationTime;
private long persistencePolicyCheckingTime;
// Accumulator utility
private final Accumulator accumulator;
// Rollback queues
private ArrayList<Accumulator> rollbackedAccumulations;
// Rollback queues
private int rollbackedAccumulationsIndex;
// Expiration thread
private ExpirationTimeChecker expirationTimeChecker;
// Rollback Metrics
private int num_rollback_by_channel_exception;
private int num_rollback_by_exception;
/**
* Constructor.
*/
public NGSISink() {
super();
// Configuration is supposed to be valid
invalidConfiguration = false;
// Create the accumulator utility
accumulator = new Accumulator();
// Create the rollbacking queue
rollbackedAccumulations = new ArrayList<>();
num_rollback_by_channel_exception = 0;
num_rollback_by_exception = 0;
} // NGSISink
protected String getBatchRetryIntervals() {
return Arrays.toString(batchRetryIntervals).replaceAll("\\[", "").replaceAll("\\]", "");
} // getBatchRetryIntervals
/**
* Gets the batch size.
* @return The batch size.
*/
protected int getBatchSize() {
return batchSize;
} // getBatchSize
/**
* Gets the batch timeout.
* @return The batch timeout.
*/
protected int getBatchTimeout() {
return batchTimeout;
} // getBatchTimeout
/**
* Gets the batch TTL.
* @return The batch TTL.
*/
protected int getBatchTTL() {
return batchTTL;
} // getBatchTTL
/**
* Gets the data model.
* @return The data model
*/
protected DataModel getDataModel() {
return dataModel;
} // getDataModel
/**
* Gets if the grouping feature is enabled.
* @return True if the grouping feature is enabled, false otherwise.
*/
protected boolean getEnableGrouping() {
return enableGrouping;
} // getEnableGrouping
/**
* Gets if lower case is enabled.
* @return True is lower case is enabled, false otherwise.
*/
protected boolean getEnableLowerCase() {
return enableLowercase;
} // getEnableLowerCase
/**
* Gets if the encoding is enabled.
* @return True is the encoding is enabled, false otherwise.
*/
protected boolean getEnableEncoding() {
return enableEncoding;
} // getEnableEncoding
protected boolean getEnableNameMappings() {
return enableNameMappings;
} // getEnableNameMappings
/**
* Gets true if the configuration is invalid, false otherwise. It is protected due to it is only
* required for testing purposes.
* @return
*/
protected boolean getInvalidConfiguration() {
return invalidConfiguration;
} // getInvalidConfiguration
protected ArrayList<Accumulator> getRollbackedAccumulations() {
return rollbackedAccumulations;
} // getRollbackedAccumulations
protected void setRollbackedAccumulations(ArrayList<Accumulator> rollbackedAccumulations) {
this.rollbackedAccumulations = rollbackedAccumulations;
} // setRollbackedAccumulations
protected long getPersistencePolicyMaxRecords() {
return persistencePolicyMaxRecords;
} // getPersistencePolicyMaxRecords
protected long getPersistencePolicyExpirationTime() {
return persistencePolicyExpirationTime;
} // getPersistencePolicyExpirationTime
protected long getPersistencePolicyCheckingTime() {
return persistencePolicyCheckingTime;
} // getPersistencePolicyCheckingTime
@Override
public void configure(Context context) {
String dataModelStr = context.getString("data_model", "dm-by-entity");
try {
dataModel = DataModel.valueOf(dataModelStr.replaceAll("-", "").toUpperCase());
LOGGER.debug("[" + this.getName() + "] Reading configuration (data_model="
+ dataModelStr + ")");
} catch (Exception e) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (data_model="
+ dataModelStr + ")");
} // catch
String enableGroupingStr = context.getString("enable_grouping", "false");
if (enableGroupingStr.equals("true") || enableGroupingStr.equals("false")) {
enableGrouping = Boolean.valueOf(enableGroupingStr);
LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_grouping="
+ enableGroupingStr + ")");
} else {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (enable_grouping="
+ enableGroupingStr + ") -- Must be 'true' or 'false'");
} // if else
String enableLowercaseStr = context.getString("enable_lowercase", "false");
if (enableLowercaseStr.equals("true") || enableLowercaseStr.equals("false")) {
enableLowercase = Boolean.valueOf(enableLowercaseStr);
LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_lowercase="
+ enableLowercaseStr + ")");
} else {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (enable_lowercase="
+ enableLowercaseStr + ") -- Must be 'true' or 'false'");
} // if else
batchSize = context.getInteger("batch_size", 1);
if (batchSize <= 0) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (batch_size="
+ batchSize + ") -- Must be greater than 0");
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (batch_size="
+ batchSize + ")");
} // if else
batchTimeout = context.getInteger("batch_timeout", 30);
if (batchTimeout <= 0) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (batch_timeout="
+ batchTimeout + ") -- Must be greater than 0");
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (batch_timeout="
+ batchTimeout + ")");
} // if
batchTTL = context.getInteger("batch_ttl", 10);
if (batchTTL < -1) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (batch_ttl="
+ batchTTL + ") -- Must be greater than -2");
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (batch_ttl="
+ batchTTL + ")");
} // if else
String enableEncodingStr = context.getString("enable_encoding", "false");
if (enableEncodingStr.equals("true") || enableEncodingStr.equals("false")) {
enableEncoding = Boolean.valueOf(enableEncodingStr);
LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_encoding="
+ enableEncodingStr + ")");
} else {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (enable_encoding="
+ enableEncodingStr + ") -- Must be 'true' or 'false'");
} // if else
String enableNameMappingsStr = context.getString("enable_name_mappings", "false");
if (enableNameMappingsStr.equals("true") || enableNameMappingsStr.equals("false")) {
enableNameMappings = Boolean.valueOf(enableNameMappingsStr);
LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_name_mappings="
+ enableNameMappingsStr + ")");
} else {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (enable_name_mappings="
+ enableNameMappingsStr + ") -- Must be 'true' or 'false'");
} // if else
String batchRetryIntervalsStr = context.getString("batch_retry_intervals", "5000");
String[] batchRetryIntervalsSplit = batchRetryIntervalsStr.split(",");
batchRetryIntervals = new int[batchRetryIntervalsSplit.length];
boolean allOK = true;
for (int i = 0; i < batchRetryIntervalsSplit.length; i++) {
String batchRetryIntervalStr = batchRetryIntervalsSplit[i];
int batchRetryInterval = new Integer(batchRetryIntervalStr);
if (batchRetryInterval <= 0) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (batch_retry_intervals="
+ batchRetryIntervalStr + ") -- Members must be greater than 0");
allOK = false;
break;
} else {
batchRetryIntervals[i] = batchRetryInterval;
} // if else
} // for
if (allOK) {
LOGGER.debug("[" + this.getName() + "] Reading configuration (batch_retry_intervals="
+ batchRetryIntervalsStr + ")");
} // if
persistencePolicyMaxRecords = context.getInteger("persistence_policy.max_records", -1);
LOGGER.debug("[" + this.getName() + "] Reading configuration (persistence_policy.max_records="
+ persistencePolicyMaxRecords + ")");
persistencePolicyExpirationTime = context.getInteger("persistence_policy.expiration_time", -1);
LOGGER.debug("[" + this.getName() + "] Reading configuration (persistence_policy.expiration_time="
+ persistencePolicyExpirationTime + ")");
persistencePolicyCheckingTime = context.getInteger("persistence_policy.checking_time", 3600);
if (persistencePolicyCheckingTime <= 0) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (persistence_policy.checking_time="
+ persistencePolicyCheckingTime + ") -- Must be greater than 0");
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (persistence_policy.checking_time="
+ persistencePolicyCheckingTime + ")");
} // if else
} // configure
@Override
public void start() {
super.start();
if (invalidConfiguration) {
LOGGER.info("[" + this.getName() + "] Startup completed. Nevertheless, there are errors "
+ "in the configuration, thus this sink will not run the expected logic");
} else {
// The accumulator must be initialized once read the configuration
accumulator.initialize(new Date().getTime());
// Crate and start the expiration time checker thread... this has to be created here in order to have a not
// null name for the sink (i.e. after configuration)
expirationTimeChecker = new ExpirationTimeChecker(this.getName());
expirationTimeChecker.start();
LOGGER.info("[" + this.getName() + "] Startup completed");
} // if else
} // start
@Override
public void stop() {
super.stop();
} // stop
@Override
public Status process() throws EventDeliveryException {
if (invalidConfiguration) {
return Status.BACKOFF;
} else if (rollbackedAccumulations.isEmpty()) {
return processNewBatches();
} else {
processRollbackedBatches();
return processNewBatches();
} // if else
} // process
private Status processRollbackedBatches() {
// Get a rollbacked accumulation
Accumulator rollbackedAccumulation = getRollbackedAccumulationForRetry();
if (rollbackedAccumulation == null) {
setMDCToNA();
return Status.READY; // No rollbacked batch was ready for retry, so we are ready to process new batches
} // if
NGSIBatch batch = rollbackedAccumulation.getBatch();
NGSIBatch rollbackBatch = new NGSIBatch();
StringBuffer transactionIds = new StringBuffer();
batch.startIterator();
while (batch.hasNext()) {
String destination = batch.getNextDestination();
ArrayList<NGSIEvent> events = batch.getNextEvents();
for (NGSIEvent event : events) {
NGSIBatch batchToPersist = new NGSIBatch();
batchToPersist.addEvent(destination, event);
transactionIds.append(event.getHeaders().get(CommonConstants.HEADER_CORRELATOR_ID)).append(", ");
//}
// force to persist a batch with just one element
try {
persistBatch(batchToPersist);
updateServiceMetrics(batchToPersist, false);
if (persistencePolicyMaxRecords > -1) {
try {
capRecords(batchToPersist, persistencePolicyMaxRecords);
} catch (CygnusCappingError e) {
LOGGER.error(e.getMessage() + "Stack trace: " + Arrays.toString(e.getStackTrace()) + " Sink: " + this.getName() + " Destination: " + destination );
} // try
} // if
numPersistedEvents += batchToPersist.getNumEvents();
LOGGER.info("Finishing internal transaction (" + transactionIds + ")" + " Sink: " + this.getName() + " Destination: " + destination);
} catch (CygnusBadConfiguration | CygnusBadContextData | CygnusRuntimeError e) {
updateServiceMetrics(batchToPersist, true); // do not try again, is just one event
LOGGER.error(e.getMessage() + "Stack trace: " + Arrays.toString(e.getStackTrace()) + " Sink: " + this.getName() + " Destination: " + destination);
} catch (Exception e) {
updateServiceMetrics(batchToPersist, true);
LOGGER.error(e.getMessage() + "Stack trace: " + Arrays.toString(e.getStackTrace()) + " Sink: " + this.getName() + " Destination: " + destination);
rollbackBatch.addEvent(destination, event); // there is just one event
} finally {
batch.setNextPersisted(true);
}
} // for (NGSIEvent event : events)
} // while (batch.hasNext())
if (rollbackBatch.getNumEvents() > 0) {
Accumulator rollbackAccumulator = new Accumulator();
rollbackAccumulator.initialize(rollbackedAccumulation.getAccStartDate());
rollbackAccumulator.setTTL(rollbackedAccumulation.ttl);
rollbackAccumulator.setLastRetry(rollbackedAccumulation.lastRetry);
rollbackBatch.startIterator();
while (rollbackBatch.hasNext()) {
for (NGSIEvent event : rollbackBatch.getNextEvents()) {
rollbackAccumulator.accumulate(event);
}
}
doRollbackAgain(rollbackAccumulator);
if (rollbackedAccumulations.size() > rollbackedAccumulationsIndex) {
rollbackedAccumulations.set(rollbackedAccumulationsIndex, rollbackAccumulator);
}
setMDCToNA();
return Status.BACKOFF;
}
rollbackedAccumulations.remove(rollbackedAccumulationsIndex);
numPersistedEvents += rollbackedAccumulation.getBatch().getNumEvents();
setMDCToNA();
return Status.READY;
} // processRollbackedBatches
/**
* Gets a rollbacked accumulation for retry.
* @return A rollbacked accumulation for retry.
*/
protected Accumulator getRollbackedAccumulationForRetry() {
Accumulator rollbackedAccumulation = null;
for (int i = 0 ; i < rollbackedAccumulations.size() ; i++) {
Accumulator rollbackedAcc = rollbackedAccumulations.get(i);
rollbackedAccumulation = rollbackedAcc;
// Check the last retry
int retryIntervalIndex = batchTTL - rollbackedAccumulation.ttl;
if (retryIntervalIndex >= batchRetryIntervals.length) {
retryIntervalIndex = batchRetryIntervals.length - 1;
} // if
if (rollbackedAccumulation.getLastRetry() + batchRetryIntervals[retryIntervalIndex]
<= new Date().getTime()) {
rollbackedAccumulationsIndex = i;
break;
} // if
rollbackedAccumulation = null;
} // for
return rollbackedAccumulation;
} // getRollbackedAccumulationForRetry
/**
* Rollbacks the accumulation once more.
* @param rollbackedAccumulation
*/
protected void doRollbackAgain(Accumulator rollbackedAccumulation) {
if (rollbackedAccumulation.getTTL() == -1) {
rollbackedAccumulation.setLastRetry(new Date().getTime());
LOGGER.info("Rollbacking again (" + rollbackedAccumulation.getAccTransactionIds() + "), "
+ "infinite batch TTL" + " Sink: " + this.getName());
} else if (rollbackedAccumulation.getTTL() > 1) {
rollbackedAccumulation.setLastRetry(new Date().getTime());
rollbackedAccumulation.setTTL(rollbackedAccumulation.getTTL() - 1);
LOGGER.info("Rollbacking again (" + rollbackedAccumulation.getAccTransactionIds() + "), "
+ "this was retry #" + (batchTTL - rollbackedAccumulation.getTTL()) + " Sink: " + this.getName());
} else {
rollbackedAccumulations.remove(rollbackedAccumulationsIndex);
if (!rollbackedAccumulation.getAccTransactionIds().isEmpty()) {
LOGGER.info("Finishing internal transaction ("
+ rollbackedAccumulation.getAccTransactionIds() + "), this was retry #" + batchTTL + " Sink: " + this.getName());
} // if
} // if else
} // doRollbackAgain
private Status processNewBatches() {
// Get the channel
Channel ch = getChannel();
// Start a Flume transaction (it is not the same than a Cygnus transaction!)
Transaction txn = ch.getTransaction();
try {
txn.begin();
// Get and process as many events as the batch size
int currentIndex;
for (currentIndex = accumulator.getAccIndex(); currentIndex < batchSize; currentIndex++) {
// Check if the batch accumulation timeout has been reached
if ((new Date().getTime() - accumulator.getAccStartDate()) > (batchTimeout * 1000)) {
LOGGER.debug("Batch accumulation time reached, the batch will be processed as it is");
break;
} // if
// Get an event
Event event = ch.take();
// Check if the event is null
if (event == null) {
accumulator.setAccIndex(currentIndex);
txn.commit();
// to-do: this must be uncomment once multiple transaction and correlation IDs are traced in logs
//setMDCToNA();
return Status.BACKOFF; // Slow down the sink since no events are available
} // if
// Cast the event to a NGSI event
NGSIEvent ngsiEvent;
if (event instanceof NGSIEvent) {
// Event comes from memory... everything is already in memory
ngsiEvent = (NGSIEvent)event;
} else {
// Event comes from file... original and mapped context elements must be re-created
String[] contextElementsStr = (new String(event.getBody())).split(CommonConstants.CONCATENATOR);
Gson gson = new Gson();
ContextElement originalCE = null;
ContextElement mappedCE = null;
if (contextElementsStr.length == 1) {
originalCE = gson.fromJson(contextElementsStr[0], ContextElement.class);
} else if (contextElementsStr.length == 2) {
originalCE = gson.fromJson(contextElementsStr[0], ContextElement.class);
mappedCE = gson.fromJson(contextElementsStr[1], ContextElement.class);
} // if else
// Re-create the NGSI event
ngsiEvent = new NGSIEvent(event.getHeaders(), event.getBody(), originalCE, mappedCE);
LOGGER.debug("Re-creating NGSI event from raw bytes in file channel, original context element: "
+ (originalCE == null ? null : originalCE.toString()) + ", mapped context element: "
+ (mappedCE == null ? null : mappedCE.toString()));
} // if else
// Set the correlation ID, transaction ID, service and service path in MDC
MDC.put(CommonConstants.LOG4J_CORR,
ngsiEvent.getHeaders().get(CommonConstants.HEADER_CORRELATOR_ID));
MDC.put(CommonConstants.LOG4J_TRANS,
ngsiEvent.getHeaders().get(NGSIConstants.FLUME_HEADER_TRANSACTION_ID));
// One batch is able to handle/process several events from different srv/subsrvs (#1983)
MDC.put(CommonConstants.LOG4J_SVC, CommonConstants.NA);
MDC.put(CommonConstants.LOG4J_SUBSVC, CommonConstants.NA);
// Accumulate the event
accumulator.accumulate(ngsiEvent);
numProcessedEvents++;
} // for
// Save the current index for next run of the process() method
accumulator.setAccIndex(currentIndex);
// Persist the accumulation
if (accumulator.getAccIndex() != 0) {
LOGGER.debug("Batch completed");
NGSIBatch batch = accumulator.getBatch();
NGSIBatch rollbackBatch = new NGSIBatch();
StringBuffer transactionIds = new StringBuffer();
batch.startIterator();
while (batch.hasNext()) {
NGSIBatch batchToPersist = new NGSIBatch();
String destination = batch.getNextDestination();
ArrayList<NGSIEvent> events = batch.getNextEvents();
for (NGSIEvent event : events) {
batchToPersist.addEvent(destination, event);
transactionIds.append(event.getHeaders().get(CommonConstants.HEADER_CORRELATOR_ID)).append(", ");
}
try {
persistBatch(batchToPersist);
updateServiceMetrics(batchToPersist, false);
if (persistencePolicyMaxRecords > -1) {
try {
capRecords(batchToPersist, persistencePolicyMaxRecords);
} catch (CygnusCappingError e) {
LOGGER.error(e.getMessage() + " Sink: " + this.getName() + " Destination: " + destination + " Stack trace: " + Arrays.toString(e.getStackTrace()));
} // try
} // if
numPersistedEvents += batchToPersist.getNumEvents();
LOGGER.info("Finishing internal transaction (" + transactionIds + ")" + " Sink: " + this.getName() + " Destination: " + destination );
} catch (CygnusBadConfiguration | CygnusBadContextData | CygnusRuntimeError e) {
updateServiceMetrics(batchToPersist, true);
LOGGER.error(e.getMessage() + " Sink: " + this.getName() + " Destination: " + destination + " Stack trace: " + Arrays.toString(e.getStackTrace()));
if (batchToPersist.getNumEvents() > 1) {
// Maybe there are other events int batch that could finally get inserted
for (NGSIEvent event : batchToPersist.getNextEvents()) {
rollbackBatch.addEvent(destination, event);
}
}
} catch (Exception e) {
updateServiceMetrics(batchToPersist, true);
LOGGER.error(e.getMessage() + " Sink: " + this.getName() + " Destination: " + destination + " Stack trace: " + Arrays.toString(e.getStackTrace()));
for (NGSIEvent event : batchToPersist.getNextEvents()) {
rollbackBatch.addEvent(destination, event);
}
} finally {
batch.setNextPersisted(true);
}
} // while (batch.hasNext())
if (rollbackBatch.getNumEvents() > 0) {
Accumulator rollbackAccumulator = new Accumulator();
rollbackAccumulator.initialize(accumulator.getAccStartDate());
rollbackBatch.startIterator();
while (rollbackBatch.hasNext()) {
for (NGSIEvent event : rollbackBatch.getNextEvents()) {
rollbackAccumulator.accumulate(event);
}
}
doRollback(rollbackAccumulator.clone());
accumulator.initialize(new Date().getTime());
txn.commit();
setMDCToNA();
return Status.BACKOFF;
}
} // if
accumulator.initialize(new Date().getTime());
txn.commit();
} catch (ChannelException ex) {
LOGGER.info("Rollback transaction by ChannelException (" + ex.getMessage() + ") Sink: " +
this.getName());
num_rollback_by_channel_exception++;
if (num_rollback_by_channel_exception >= NGSIConstants.ROLLBACK_CHANNEL_EXCEPTION_THRESHOLD) {
LOGGER.warn("Rollback (" + num_rollback_by_channel_exception +
" times) transaction by ChannelException (" + ex.getMessage() + ") Sink: " +
this.getName());
num_rollback_by_channel_exception = 0;
}
txn.rollback();
} catch (Exception ex) {
LOGGER.info("Rollback transaction by Exception (" + ex.getMessage() + ") Sink: " +
this.getName());
num_rollback_by_exception++;
if (num_rollback_by_exception >= NGSIConstants.ROLLBACK_EXCEPTION_THRESHOLD) {
LOGGER.warn("Rollback (" + num_rollback_by_exception +
" times) transaction by Exception (" + ex.getMessage() + ") Sink: " +
this.getName());
num_rollback_by_exception = 0;
}
txn.rollback();
} finally {
txn.close();
}
setMDCToNA();
return Status.READY;
} // processNewBatches
/**
* Sets some MDC logging fields to 'N/A' for this thread. Value for the component field is inherited from main
* thread (CygnusApplication.java).
*/
private void setMDCToNA() {
MDC.put(CommonConstants.LOG4J_CORR, CommonConstants.NA);
MDC.put(CommonConstants.LOG4J_TRANS, CommonConstants.NA);
MDC.put(CommonConstants.LOG4J_SVC, CommonConstants.NA);
MDC.put(CommonConstants.LOG4J_SUBSVC, CommonConstants.NA);
} // setMDCToNA
/**
* Rollbacks the accumulator for the first time.
* @param accumulator Accumulator to be rollbacked
*/
protected void doRollback(Accumulator accumulator) {
if (accumulator.getTTL() == -1) {
accumulator.setLastRetry(new Date().getTime());
rollbackedAccumulations.add(accumulator);
LOGGER.info("Rollbacking (" + accumulator.getAccTransactionIds() + "), "
+ "infinite batch TTL" + " Sink: " + this.getName());
} else if (accumulator.getTTL() > 0) {
accumulator.setLastRetry(new Date().getTime());
rollbackedAccumulations.add(accumulator);
LOGGER.info("Rollbacking (" + accumulator.getAccTransactionIds() + "), "
+ batchTTL + " retries will be done" + " Sink: " + this.getName());
} else {
if (!accumulator.getAccTransactionIds().isEmpty()) {
LOGGER.info("Finishing internal transaction ("
+ accumulator.getAccTransactionIds() + "), 0 retries will be done" + " Sink: " + this.getName());
} // if
} // if else
} // doRollback
private void updateServiceMetrics(NGSIBatch batch, boolean error) {
batch.startIterator();
while (batch.hasNext()) {
ArrayList<NGSIEvent> events = batch.getNextEvents();
NGSIEvent event = events.get(0);
String service = event.getServiceForData();
String servicePath = event.getServicePathForData();
long time = (new Date().getTime() - event.getRecvTimeTs()) * events.size();
serviceMetrics.add(service, servicePath, 0, 0, 0, 0, time, events.size(), 0, 0, error ? events.size() : 0);
} // while
} // updateServiceMetrics
/**
* Utility class for batch-like getRecvTimeTs accumulation purposes.
*/
protected class Accumulator implements Cloneable {
// accumulated events
private NGSIBatch batch;
private long accStartDate;
private int accIndex;
private String accTransactionIds;
private int ttl;
private long lastRetry;
/**
* Constructor.
*/
public Accumulator() {
batch = new NGSIBatch();
accStartDate = 0;
accIndex = 0;
accTransactionIds = null;
ttl = batchTTL;
lastRetry = 0;
} // Accumulator
public long getAccStartDate() {
return accStartDate;
} // getAccStartDate
public int getAccIndex() {
return accIndex;
} // getAccIndex
public void setAccIndex(int accIndex) {
this.accIndex = accIndex;
} // setAccIndex
public NGSIBatch getBatch() {
return batch;
} // getBatch
public String getAccTransactionIds() {
return accTransactionIds;
} // getAccTransactionIds
public long getLastRetry() {
return lastRetry;
} // getLastRetry
public void setLastRetry(long lastRetry) {
this.lastRetry = lastRetry;
} // setLastRetry
public int getTTL() {
return ttl;
} // getTTL
public void setTTL(int ttl) {
this.ttl = ttl;
} // setTTL
/**
* Accumulates an getRecvTimeTs given its headers and context data.
* @param event
*/
public void accumulate(NGSIEvent event) {
String transactionId = event.getHeaders().get(CommonConstants.HEADER_CORRELATOR_ID);
if (accTransactionIds.isEmpty()) {
accTransactionIds = transactionId;
} else {
accTransactionIds += "," + transactionId;
} // if else
switch (dataModel) {
case DMBYSERVICE:
accumulateByService(event);
break;
case DMBYSERVICEPATH:
accumulateByServicePath(event);
break;
case DMBYENTITYDATABASE:
case DMBYENTITYDATABASESCHEMA:
case DMBYENTITY:
accumulateByEntity(event);
break;
case DMBYENTITYTYPEDATABASE:
case DMBYENTITYTYPEDATABASESCHEMA:
case DMBYENTITYTYPE:
accumulateByEntityType(event);
break;
case DMBYATTRIBUTE:
accumulateByAttribute(event);
break;
case DMBYENTITYID:
accumulateByEntityId(event);
break;
case DMBYFIXEDENTITYTYPE:
case DMBYFIXEDENTITYTYPEDATABASE:
case DMBYFIXEDENTITYTYPEDATABASESCHEMA:
accumulateByFixedEntityType(event);
break;
default:
LOGGER.error("Unknown data model. Details=" + dataModel.toString() + " Sink: " + this.getClass().getName());
} // switch
} // accumulate
private void accumulateByService(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE);
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByService
private void accumulateByServicePath(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH);
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH);
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByServicePath
private void accumulateByEntity(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_NOTIFIED_ENTITY);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getId() + "_" + mappedCE.getType();
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH) + "_"
+ originalCE.getId() + "_" + originalCE.getType();
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByEntity
private void accumulateByEntityType(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY_TYPE);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY_TYPE);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getType();
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH) + "_"
+ originalCE.getType();
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByEntityType
private void accumulateByEntityId(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_NOTIFIED_ENTITY);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getId() + "_" + mappedCE.getType();
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH) + "_"
+ originalCE.getId() + "_" + originalCE.getType();
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByServicePath
private void accumulateByFixedEntityType(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY_TYPE);
} else {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY_TYPE);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ mappedCE.getType();
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ originalCE.getType();
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByEntityIdType
private void accumulateByAttribute(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_NOTIFIED_ENTITY);
} // if else
ArrayList<ContextAttribute> attrs = originalCE.getAttributes();
for (ContextAttribute attr : attrs) {
ContextElement filteredOriginalCE = originalCE.filter(attr.getName());
event.setOriginalCE(filteredOriginalCE);
batch.addEvent(destination + "_" + attr.getName(), event);
} // for
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getId() + "_" + mappedCE.getType();
ArrayList<ContextAttribute> attrs = mappedCE.getAttributes();
for (ContextAttribute attr : attrs) {
ContextElement filteredOriginalCE = originalCE.filter(attr.getName());
ContextElement filteredMappedCE = mappedCE.filter(attr.getName());
event.setOriginalCE(filteredOriginalCE);
event.setMappedCE(filteredMappedCE);
batch.addEvent(destination + "_" + attr.getName(), event);
} // for
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH) + "_"
+ originalCE.getId() + "_" + originalCE.getType();
ArrayList<ContextAttribute> attrs = originalCE.getAttributes();
for (ContextAttribute attr : attrs) {
ContextElement filteredOriginalCE = originalCE.filter(attr.getName());
ContextElement filteredMappedCE = mappedCE.filter(attr.getName()); // not really necessary...
event.setOriginalCE(filteredOriginalCE);
event.setMappedCE(filteredMappedCE);
batch.addEvent(destination + "_" + attr.getName(), event);
} // for
} // if else
} // if else
} // accumulateByAttribute
/**
* Initialize the batch.
* @param startDateMs
*/
public void initialize(long startDateMs) {
// what happens if Cygnus falls down while accumulating the batch?
// TBD: https://github.com/telefonicaid/fiware-cygnus/issues/562
batch = new NGSIBatch();
accStartDate = startDateMs;
accIndex = 0;
accTransactionIds = "";
ttl = batchTTL;
} // initialize
@Override
public Accumulator clone() {
try {
Accumulator acc = (Accumulator) super.clone();
return acc;
} catch (CloneNotSupportedException ce) {
return null;
} // clone
} // clone
} // Accumulator
/**
* Class for checking about expired records.
*/
private class ExpirationTimeChecker extends Thread {
private final String sinkName;
/**
* Constructor.
* @param sinkName
*/
public ExpirationTimeChecker(String sinkName) {
this.sinkName = sinkName;
} // ExpirationTimeChecker
@Override
public void run() {
while (true) {
long timeBefore = 0;
long timeAfter = 0;
if (persistencePolicyExpirationTime > -1) {
timeBefore = new Date().getTime();
try {
LOGGER.debug("[" + sinkName + "] Expirating records");
expirateRecords(persistencePolicyExpirationTime);
} catch (Exception e) {
LOGGER.error("[" + sinkName + "] Error while expirating records. Details: "
+ e.getMessage());
} // try catch
timeAfter = new Date().getTime();
} // if
long timeExpent = timeAfter - timeBefore;
long sleepTime = (persistencePolicyCheckingTime * 1000) - timeExpent;
if (sleepTime <= 0) {
sleepTime = 1000; // sleep at least 1 second
} // if
try {
sleep(sleepTime);
} catch (InterruptedException e) {
LOGGER.error("[" + sinkName + "] Error while sleeping. Details: " + e.getMessage());
} // try
} // while
} // run
} // ExpirationTimeChecker
/**
* This is the method the classes extending this class must implement when dealing with a batch of events to be
* persisted.
* @param batch
* @throws Exception
*/
abstract void persistBatch(NGSIBatch batch) throws CygnusBadConfiguration, CygnusBadContextData,
CygnusRuntimeError, CygnusPersistenceError;
/**
* This is the method the classes extending this class must implement when dealing with size-based capping.
* @param batch
* @param maxRecords
* @throws EventDeliveryException
*/
abstract void capRecords(NGSIBatch batch, long maxRecords) throws CygnusCappingError;
/**
* This is the method the classes extending this class must implement when dealing with time-based expiration.
* @param expirationTime
* @throws Exception
*/
abstract void expirateRecords(long expirationTime) throws CygnusExpiratingError;
} // NGSISink
| cygnus-ngsi/src/main/java/com/telefonica/iot/cygnus/sinks/NGSISink.java | /**
* Copyright 2014-2017 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-cygnus (FIWARE project).
*
* fiware-cygnus 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.
* fiware-cygnus 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 fiware-cygnus. If not, see
* http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License please contact with iot_support at tid dot es
*/
package com.telefonica.iot.cygnus.sinks;
import com.google.gson.Gson;
import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute;
import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElement;
import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration;
import com.telefonica.iot.cygnus.errors.CygnusBadContextData;
import com.telefonica.iot.cygnus.errors.CygnusCappingError;
import com.telefonica.iot.cygnus.errors.CygnusExpiratingError;
import com.telefonica.iot.cygnus.errors.CygnusPersistenceError;
import com.telefonica.iot.cygnus.errors.CygnusRuntimeError;
import com.telefonica.iot.cygnus.interceptors.NGSIEvent;
import com.telefonica.iot.cygnus.log.CygnusLogger;
import com.telefonica.iot.cygnus.sinks.Enums.DataModel;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYATTRIBUTE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITY;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYTYPE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYDATABASE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYTYPEDATABASE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYDATABASESCHEMA;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYENTITYTYPEDATABASESCHEMA;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYSERVICE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYSERVICEPATH;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYFIXEDENTITYTYPE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYFIXEDENTITYTYPEDATABASE;
import static com.telefonica.iot.cygnus.sinks.Enums.DataModel.DMBYFIXEDENTITYYPEDATABASESCHEMA;
import java.util.Map;
import com.telefonica.iot.cygnus.utils.CommonConstants;
import com.telefonica.iot.cygnus.utils.NGSIConstants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import org.apache.flume.Channel;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.Sink.Status;
import org.apache.flume.Transaction;
import org.apache.flume.ChannelException;
import org.apache.flume.conf.Configurable;
import org.apache.log4j.MDC;
/**
*
* @author frb
Abstract class containing the common code to all the sinks persisting data comming from Orion Context Broker.
The common attributes are:
- there is no common attributes
The common methods are:
- void stop()
- Status process() throws EventDeliveryException
- void persistOne(Event getRecvTimeTs) throws Exception
The non common parts, and therefore those that are sink dependant and must be implemented are:
- void configure(Context context)
- void start()
- void persistOne(Map<String, String> eventHeaders, NotifyContextRequest notification) throws Exception
*/
public abstract class NGSISink extends CygnusSink implements Configurable {
// Logger
private static final CygnusLogger LOGGER = new CygnusLogger(NGSISink.class);
// General parameters for all the sinks
protected DataModel dataModel;
protected boolean enableGrouping;
protected int batchSize;
protected int batchTimeout;
protected int batchTTL;
protected int[] batchRetryIntervals;
protected boolean enableLowercase;
protected boolean invalidConfiguration;
protected boolean enableEncoding;
protected boolean enableNameMappings;
private long persistencePolicyMaxRecords;
private long persistencePolicyExpirationTime;
private long persistencePolicyCheckingTime;
// Accumulator utility
private final Accumulator accumulator;
// Rollback queues
private ArrayList<Accumulator> rollbackedAccumulations;
// Rollback queues
private int rollbackedAccumulationsIndex;
// Expiration thread
private ExpirationTimeChecker expirationTimeChecker;
// Rollback Metrics
private int num_rollback_by_channel_exception;
private int num_rollback_by_exception;
/**
* Constructor.
*/
public NGSISink() {
super();
// Configuration is supposed to be valid
invalidConfiguration = false;
// Create the accumulator utility
accumulator = new Accumulator();
// Create the rollbacking queue
rollbackedAccumulations = new ArrayList<>();
num_rollback_by_channel_exception = 0;
num_rollback_by_exception = 0;
} // NGSISink
protected String getBatchRetryIntervals() {
return Arrays.toString(batchRetryIntervals).replaceAll("\\[", "").replaceAll("\\]", "");
} // getBatchRetryIntervals
/**
* Gets the batch size.
* @return The batch size.
*/
protected int getBatchSize() {
return batchSize;
} // getBatchSize
/**
* Gets the batch timeout.
* @return The batch timeout.
*/
protected int getBatchTimeout() {
return batchTimeout;
} // getBatchTimeout
/**
* Gets the batch TTL.
* @return The batch TTL.
*/
protected int getBatchTTL() {
return batchTTL;
} // getBatchTTL
/**
* Gets the data model.
* @return The data model
*/
protected DataModel getDataModel() {
return dataModel;
} // getDataModel
/**
* Gets if the grouping feature is enabled.
* @return True if the grouping feature is enabled, false otherwise.
*/
protected boolean getEnableGrouping() {
return enableGrouping;
} // getEnableGrouping
/**
* Gets if lower case is enabled.
* @return True is lower case is enabled, false otherwise.
*/
protected boolean getEnableLowerCase() {
return enableLowercase;
} // getEnableLowerCase
/**
* Gets if the encoding is enabled.
* @return True is the encoding is enabled, false otherwise.
*/
protected boolean getEnableEncoding() {
return enableEncoding;
} // getEnableEncoding
protected boolean getEnableNameMappings() {
return enableNameMappings;
} // getEnableNameMappings
/**
* Gets true if the configuration is invalid, false otherwise. It is protected due to it is only
* required for testing purposes.
* @return
*/
protected boolean getInvalidConfiguration() {
return invalidConfiguration;
} // getInvalidConfiguration
protected ArrayList<Accumulator> getRollbackedAccumulations() {
return rollbackedAccumulations;
} // getRollbackedAccumulations
protected void setRollbackedAccumulations(ArrayList<Accumulator> rollbackedAccumulations) {
this.rollbackedAccumulations = rollbackedAccumulations;
} // setRollbackedAccumulations
protected long getPersistencePolicyMaxRecords() {
return persistencePolicyMaxRecords;
} // getPersistencePolicyMaxRecords
protected long getPersistencePolicyExpirationTime() {
return persistencePolicyExpirationTime;
} // getPersistencePolicyExpirationTime
protected long getPersistencePolicyCheckingTime() {
return persistencePolicyCheckingTime;
} // getPersistencePolicyCheckingTime
@Override
public void configure(Context context) {
String dataModelStr = context.getString("data_model", "dm-by-entity");
try {
dataModel = DataModel.valueOf(dataModelStr.replaceAll("-", "").toUpperCase());
LOGGER.debug("[" + this.getName() + "] Reading configuration (data_model="
+ dataModelStr + ")");
} catch (Exception e) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (data_model="
+ dataModelStr + ")");
} // catch
String enableGroupingStr = context.getString("enable_grouping", "false");
if (enableGroupingStr.equals("true") || enableGroupingStr.equals("false")) {
enableGrouping = Boolean.valueOf(enableGroupingStr);
LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_grouping="
+ enableGroupingStr + ")");
} else {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (enable_grouping="
+ enableGroupingStr + ") -- Must be 'true' or 'false'");
} // if else
String enableLowercaseStr = context.getString("enable_lowercase", "false");
if (enableLowercaseStr.equals("true") || enableLowercaseStr.equals("false")) {
enableLowercase = Boolean.valueOf(enableLowercaseStr);
LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_lowercase="
+ enableLowercaseStr + ")");
} else {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (enable_lowercase="
+ enableLowercaseStr + ") -- Must be 'true' or 'false'");
} // if else
batchSize = context.getInteger("batch_size", 1);
if (batchSize <= 0) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (batch_size="
+ batchSize + ") -- Must be greater than 0");
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (batch_size="
+ batchSize + ")");
} // if else
batchTimeout = context.getInteger("batch_timeout", 30);
if (batchTimeout <= 0) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (batch_timeout="
+ batchTimeout + ") -- Must be greater than 0");
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (batch_timeout="
+ batchTimeout + ")");
} // if
batchTTL = context.getInteger("batch_ttl", 10);
if (batchTTL < -1) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (batch_ttl="
+ batchTTL + ") -- Must be greater than -2");
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (batch_ttl="
+ batchTTL + ")");
} // if else
String enableEncodingStr = context.getString("enable_encoding", "false");
if (enableEncodingStr.equals("true") || enableEncodingStr.equals("false")) {
enableEncoding = Boolean.valueOf(enableEncodingStr);
LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_encoding="
+ enableEncodingStr + ")");
} else {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (enable_encoding="
+ enableEncodingStr + ") -- Must be 'true' or 'false'");
} // if else
String enableNameMappingsStr = context.getString("enable_name_mappings", "false");
if (enableNameMappingsStr.equals("true") || enableNameMappingsStr.equals("false")) {
enableNameMappings = Boolean.valueOf(enableNameMappingsStr);
LOGGER.debug("[" + this.getName() + "] Reading configuration (enable_name_mappings="
+ enableNameMappingsStr + ")");
} else {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (enable_name_mappings="
+ enableNameMappingsStr + ") -- Must be 'true' or 'false'");
} // if else
String batchRetryIntervalsStr = context.getString("batch_retry_intervals", "5000");
String[] batchRetryIntervalsSplit = batchRetryIntervalsStr.split(",");
batchRetryIntervals = new int[batchRetryIntervalsSplit.length];
boolean allOK = true;
for (int i = 0; i < batchRetryIntervalsSplit.length; i++) {
String batchRetryIntervalStr = batchRetryIntervalsSplit[i];
int batchRetryInterval = new Integer(batchRetryIntervalStr);
if (batchRetryInterval <= 0) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (batch_retry_intervals="
+ batchRetryIntervalStr + ") -- Members must be greater than 0");
allOK = false;
break;
} else {
batchRetryIntervals[i] = batchRetryInterval;
} // if else
} // for
if (allOK) {
LOGGER.debug("[" + this.getName() + "] Reading configuration (batch_retry_intervals="
+ batchRetryIntervalsStr + ")");
} // if
persistencePolicyMaxRecords = context.getInteger("persistence_policy.max_records", -1);
LOGGER.debug("[" + this.getName() + "] Reading configuration (persistence_policy.max_records="
+ persistencePolicyMaxRecords + ")");
persistencePolicyExpirationTime = context.getInteger("persistence_policy.expiration_time", -1);
LOGGER.debug("[" + this.getName() + "] Reading configuration (persistence_policy.expiration_time="
+ persistencePolicyExpirationTime + ")");
persistencePolicyCheckingTime = context.getInteger("persistence_policy.checking_time", 3600);
if (persistencePolicyCheckingTime <= 0) {
invalidConfiguration = true;
LOGGER.warn("[" + this.getName() + "] Invalid configuration (persistence_policy.checking_time="
+ persistencePolicyCheckingTime + ") -- Must be greater than 0");
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (persistence_policy.checking_time="
+ persistencePolicyCheckingTime + ")");
} // if else
} // configure
@Override
public void start() {
super.start();
if (invalidConfiguration) {
LOGGER.info("[" + this.getName() + "] Startup completed. Nevertheless, there are errors "
+ "in the configuration, thus this sink will not run the expected logic");
} else {
// The accumulator must be initialized once read the configuration
accumulator.initialize(new Date().getTime());
// Crate and start the expiration time checker thread... this has to be created here in order to have a not
// null name for the sink (i.e. after configuration)
expirationTimeChecker = new ExpirationTimeChecker(this.getName());
expirationTimeChecker.start();
LOGGER.info("[" + this.getName() + "] Startup completed");
} // if else
} // start
@Override
public void stop() {
super.stop();
} // stop
@Override
public Status process() throws EventDeliveryException {
if (invalidConfiguration) {
return Status.BACKOFF;
} else if (rollbackedAccumulations.isEmpty()) {
return processNewBatches();
} else {
processRollbackedBatches();
return processNewBatches();
} // if else
} // process
private Status processRollbackedBatches() {
// Get a rollbacked accumulation
Accumulator rollbackedAccumulation = getRollbackedAccumulationForRetry();
if (rollbackedAccumulation == null) {
setMDCToNA();
return Status.READY; // No rollbacked batch was ready for retry, so we are ready to process new batches
} // if
NGSIBatch batch = rollbackedAccumulation.getBatch();
NGSIBatch rollbackBatch = new NGSIBatch();
StringBuffer transactionIds = new StringBuffer();
batch.startIterator();
while (batch.hasNext()) {
String destination = batch.getNextDestination();
ArrayList<NGSIEvent> events = batch.getNextEvents();
for (NGSIEvent event : events) {
NGSIBatch batchToPersist = new NGSIBatch();
batchToPersist.addEvent(destination, event);
transactionIds.append(event.getHeaders().get(CommonConstants.HEADER_CORRELATOR_ID)).append(", ");
//}
// force to persist a batch with just one element
try {
persistBatch(batchToPersist);
updateServiceMetrics(batchToPersist, false);
if (persistencePolicyMaxRecords > -1) {
try {
capRecords(batchToPersist, persistencePolicyMaxRecords);
} catch (CygnusCappingError e) {
LOGGER.error(e.getMessage() + "Stack trace: " + Arrays.toString(e.getStackTrace()) + " Sink: " + this.getName() + " Destination: " + destination );
} // try
} // if
numPersistedEvents += batchToPersist.getNumEvents();
LOGGER.info("Finishing internal transaction (" + transactionIds + ")" + " Sink: " + this.getName() + " Destination: " + destination);
} catch (CygnusBadConfiguration | CygnusBadContextData | CygnusRuntimeError e) {
updateServiceMetrics(batchToPersist, true); // do not try again, is just one event
LOGGER.error(e.getMessage() + "Stack trace: " + Arrays.toString(e.getStackTrace()) + " Sink: " + this.getName() + " Destination: " + destination);
} catch (Exception e) {
updateServiceMetrics(batchToPersist, true);
LOGGER.error(e.getMessage() + "Stack trace: " + Arrays.toString(e.getStackTrace()) + " Sink: " + this.getName() + " Destination: " + destination);
rollbackBatch.addEvent(destination, event); // there is just one event
} finally {
batch.setNextPersisted(true);
}
} // for (NGSIEvent event : events)
} // while (batch.hasNext())
if (rollbackBatch.getNumEvents() > 0) {
Accumulator rollbackAccumulator = new Accumulator();
rollbackAccumulator.initialize(rollbackedAccumulation.getAccStartDate());
rollbackAccumulator.setTTL(rollbackedAccumulation.ttl);
rollbackAccumulator.setLastRetry(rollbackedAccumulation.lastRetry);
rollbackBatch.startIterator();
while (rollbackBatch.hasNext()) {
for (NGSIEvent event : rollbackBatch.getNextEvents()) {
rollbackAccumulator.accumulate(event);
}
}
doRollbackAgain(rollbackAccumulator);
if (rollbackedAccumulations.size() > rollbackedAccumulationsIndex) {
rollbackedAccumulations.set(rollbackedAccumulationsIndex, rollbackAccumulator);
}
setMDCToNA();
return Status.BACKOFF;
}
rollbackedAccumulations.remove(rollbackedAccumulationsIndex);
numPersistedEvents += rollbackedAccumulation.getBatch().getNumEvents();
setMDCToNA();
return Status.READY;
} // processRollbackedBatches
/**
* Gets a rollbacked accumulation for retry.
* @return A rollbacked accumulation for retry.
*/
protected Accumulator getRollbackedAccumulationForRetry() {
Accumulator rollbackedAccumulation = null;
for (int i = 0 ; i < rollbackedAccumulations.size() ; i++) {
Accumulator rollbackedAcc = rollbackedAccumulations.get(i);
rollbackedAccumulation = rollbackedAcc;
// Check the last retry
int retryIntervalIndex = batchTTL - rollbackedAccumulation.ttl;
if (retryIntervalIndex >= batchRetryIntervals.length) {
retryIntervalIndex = batchRetryIntervals.length - 1;
} // if
if (rollbackedAccumulation.getLastRetry() + batchRetryIntervals[retryIntervalIndex]
<= new Date().getTime()) {
rollbackedAccumulationsIndex = i;
break;
} // if
rollbackedAccumulation = null;
} // for
return rollbackedAccumulation;
} // getRollbackedAccumulationForRetry
/**
* Rollbacks the accumulation once more.
* @param rollbackedAccumulation
*/
protected void doRollbackAgain(Accumulator rollbackedAccumulation) {
if (rollbackedAccumulation.getTTL() == -1) {
rollbackedAccumulation.setLastRetry(new Date().getTime());
LOGGER.info("Rollbacking again (" + rollbackedAccumulation.getAccTransactionIds() + "), "
+ "infinite batch TTL" + " Sink: " + this.getName());
} else if (rollbackedAccumulation.getTTL() > 1) {
rollbackedAccumulation.setLastRetry(new Date().getTime());
rollbackedAccumulation.setTTL(rollbackedAccumulation.getTTL() - 1);
LOGGER.info("Rollbacking again (" + rollbackedAccumulation.getAccTransactionIds() + "), "
+ "this was retry #" + (batchTTL - rollbackedAccumulation.getTTL()) + " Sink: " + this.getName());
} else {
rollbackedAccumulations.remove(rollbackedAccumulationsIndex);
if (!rollbackedAccumulation.getAccTransactionIds().isEmpty()) {
LOGGER.info("Finishing internal transaction ("
+ rollbackedAccumulation.getAccTransactionIds() + "), this was retry #" + batchTTL + " Sink: " + this.getName());
} // if
} // if else
} // doRollbackAgain
private Status processNewBatches() {
// Get the channel
Channel ch = getChannel();
// Start a Flume transaction (it is not the same than a Cygnus transaction!)
Transaction txn = ch.getTransaction();
try {
txn.begin();
// Get and process as many events as the batch size
int currentIndex;
for (currentIndex = accumulator.getAccIndex(); currentIndex < batchSize; currentIndex++) {
// Check if the batch accumulation timeout has been reached
if ((new Date().getTime() - accumulator.getAccStartDate()) > (batchTimeout * 1000)) {
LOGGER.debug("Batch accumulation time reached, the batch will be processed as it is");
break;
} // if
// Get an event
Event event = ch.take();
// Check if the event is null
if (event == null) {
accumulator.setAccIndex(currentIndex);
txn.commit();
// to-do: this must be uncomment once multiple transaction and correlation IDs are traced in logs
//setMDCToNA();
return Status.BACKOFF; // Slow down the sink since no events are available
} // if
// Cast the event to a NGSI event
NGSIEvent ngsiEvent;
if (event instanceof NGSIEvent) {
// Event comes from memory... everything is already in memory
ngsiEvent = (NGSIEvent)event;
} else {
// Event comes from file... original and mapped context elements must be re-created
String[] contextElementsStr = (new String(event.getBody())).split(CommonConstants.CONCATENATOR);
Gson gson = new Gson();
ContextElement originalCE = null;
ContextElement mappedCE = null;
if (contextElementsStr.length == 1) {
originalCE = gson.fromJson(contextElementsStr[0], ContextElement.class);
} else if (contextElementsStr.length == 2) {
originalCE = gson.fromJson(contextElementsStr[0], ContextElement.class);
mappedCE = gson.fromJson(contextElementsStr[1], ContextElement.class);
} // if else
// Re-create the NGSI event
ngsiEvent = new NGSIEvent(event.getHeaders(), event.getBody(), originalCE, mappedCE);
LOGGER.debug("Re-creating NGSI event from raw bytes in file channel, original context element: "
+ (originalCE == null ? null : originalCE.toString()) + ", mapped context element: "
+ (mappedCE == null ? null : mappedCE.toString()));
} // if else
// Set the correlation ID, transaction ID, service and service path in MDC
MDC.put(CommonConstants.LOG4J_CORR,
ngsiEvent.getHeaders().get(CommonConstants.HEADER_CORRELATOR_ID));
MDC.put(CommonConstants.LOG4J_TRANS,
ngsiEvent.getHeaders().get(NGSIConstants.FLUME_HEADER_TRANSACTION_ID));
// One batch is able to handle/process several events from different srv/subsrvs (#1983)
MDC.put(CommonConstants.LOG4J_SVC, CommonConstants.NA);
MDC.put(CommonConstants.LOG4J_SUBSVC, CommonConstants.NA);
// Accumulate the event
accumulator.accumulate(ngsiEvent);
numProcessedEvents++;
} // for
// Save the current index for next run of the process() method
accumulator.setAccIndex(currentIndex);
// Persist the accumulation
if (accumulator.getAccIndex() != 0) {
LOGGER.debug("Batch completed");
NGSIBatch batch = accumulator.getBatch();
NGSIBatch rollbackBatch = new NGSIBatch();
StringBuffer transactionIds = new StringBuffer();
batch.startIterator();
while (batch.hasNext()) {
NGSIBatch batchToPersist = new NGSIBatch();
String destination = batch.getNextDestination();
ArrayList<NGSIEvent> events = batch.getNextEvents();
for (NGSIEvent event : events) {
batchToPersist.addEvent(destination, event);
transactionIds.append(event.getHeaders().get(CommonConstants.HEADER_CORRELATOR_ID)).append(", ");
}
try {
persistBatch(batchToPersist);
updateServiceMetrics(batchToPersist, false);
if (persistencePolicyMaxRecords > -1) {
try {
capRecords(batchToPersist, persistencePolicyMaxRecords);
} catch (CygnusCappingError e) {
LOGGER.error(e.getMessage() + " Sink: " + this.getName() + " Destination: " + destination + " Stack trace: " + Arrays.toString(e.getStackTrace()));
} // try
} // if
numPersistedEvents += batchToPersist.getNumEvents();
LOGGER.info("Finishing internal transaction (" + transactionIds + ")" + " Sink: " + this.getName() + " Destination: " + destination );
} catch (CygnusBadConfiguration | CygnusBadContextData | CygnusRuntimeError e) {
updateServiceMetrics(batchToPersist, true);
LOGGER.error(e.getMessage() + " Sink: " + this.getName() + " Destination: " + destination + " Stack trace: " + Arrays.toString(e.getStackTrace()));
if (batchToPersist.getNumEvents() > 1) {
// Maybe there are other events int batch that could finally get inserted
for (NGSIEvent event : batchToPersist.getNextEvents()) {
rollbackBatch.addEvent(destination, event);
}
}
} catch (Exception e) {
updateServiceMetrics(batchToPersist, true);
LOGGER.error(e.getMessage() + " Sink: " + this.getName() + " Destination: " + destination + " Stack trace: " + Arrays.toString(e.getStackTrace()));
for (NGSIEvent event : batchToPersist.getNextEvents()) {
rollbackBatch.addEvent(destination, event);
}
} finally {
batch.setNextPersisted(true);
}
} // while (batch.hasNext())
if (rollbackBatch.getNumEvents() > 0) {
Accumulator rollbackAccumulator = new Accumulator();
rollbackAccumulator.initialize(accumulator.getAccStartDate());
rollbackBatch.startIterator();
while (rollbackBatch.hasNext()) {
for (NGSIEvent event : rollbackBatch.getNextEvents()) {
rollbackAccumulator.accumulate(event);
}
}
doRollback(rollbackAccumulator.clone());
accumulator.initialize(new Date().getTime());
txn.commit();
setMDCToNA();
return Status.BACKOFF;
}
} // if
accumulator.initialize(new Date().getTime());
txn.commit();
} catch (ChannelException ex) {
LOGGER.info("Rollback transaction by ChannelException (" + ex.getMessage() + ") Sink: " +
this.getName());
num_rollback_by_channel_exception++;
if (num_rollback_by_channel_exception >= NGSIConstants.ROLLBACK_CHANNEL_EXCEPTION_THRESHOLD) {
LOGGER.warn("Rollback (" + num_rollback_by_channel_exception +
" times) transaction by ChannelException (" + ex.getMessage() + ") Sink: " +
this.getName());
num_rollback_by_channel_exception = 0;
}
txn.rollback();
} catch (Exception ex) {
LOGGER.info("Rollback transaction by Exception (" + ex.getMessage() + ") Sink: " +
this.getName());
num_rollback_by_exception++;
if (num_rollback_by_exception >= NGSIConstants.ROLLBACK_EXCEPTION_THRESHOLD) {
LOGGER.warn("Rollback (" + num_rollback_by_exception +
" times) transaction by Exception (" + ex.getMessage() + ") Sink: " +
this.getName());
num_rollback_by_exception = 0;
}
txn.rollback();
} finally {
txn.close();
}
setMDCToNA();
return Status.READY;
} // processNewBatches
/**
* Sets some MDC logging fields to 'N/A' for this thread. Value for the component field is inherited from main
* thread (CygnusApplication.java).
*/
private void setMDCToNA() {
MDC.put(CommonConstants.LOG4J_CORR, CommonConstants.NA);
MDC.put(CommonConstants.LOG4J_TRANS, CommonConstants.NA);
MDC.put(CommonConstants.LOG4J_SVC, CommonConstants.NA);
MDC.put(CommonConstants.LOG4J_SUBSVC, CommonConstants.NA);
} // setMDCToNA
/**
* Rollbacks the accumulator for the first time.
* @param accumulator Accumulator to be rollbacked
*/
protected void doRollback(Accumulator accumulator) {
if (accumulator.getTTL() == -1) {
accumulator.setLastRetry(new Date().getTime());
rollbackedAccumulations.add(accumulator);
LOGGER.info("Rollbacking (" + accumulator.getAccTransactionIds() + "), "
+ "infinite batch TTL" + " Sink: " + this.getName());
} else if (accumulator.getTTL() > 0) {
accumulator.setLastRetry(new Date().getTime());
rollbackedAccumulations.add(accumulator);
LOGGER.info("Rollbacking (" + accumulator.getAccTransactionIds() + "), "
+ batchTTL + " retries will be done" + " Sink: " + this.getName());
} else {
if (!accumulator.getAccTransactionIds().isEmpty()) {
LOGGER.info("Finishing internal transaction ("
+ accumulator.getAccTransactionIds() + "), 0 retries will be done" + " Sink: " + this.getName());
} // if
} // if else
} // doRollback
private void updateServiceMetrics(NGSIBatch batch, boolean error) {
batch.startIterator();
while (batch.hasNext()) {
ArrayList<NGSIEvent> events = batch.getNextEvents();
NGSIEvent event = events.get(0);
String service = event.getServiceForData();
String servicePath = event.getServicePathForData();
long time = (new Date().getTime() - event.getRecvTimeTs()) * events.size();
serviceMetrics.add(service, servicePath, 0, 0, 0, 0, time, events.size(), 0, 0, error ? events.size() : 0);
} // while
} // updateServiceMetrics
/**
* Utility class for batch-like getRecvTimeTs accumulation purposes.
*/
protected class Accumulator implements Cloneable {
// accumulated events
private NGSIBatch batch;
private long accStartDate;
private int accIndex;
private String accTransactionIds;
private int ttl;
private long lastRetry;
/**
* Constructor.
*/
public Accumulator() {
batch = new NGSIBatch();
accStartDate = 0;
accIndex = 0;
accTransactionIds = null;
ttl = batchTTL;
lastRetry = 0;
} // Accumulator
public long getAccStartDate() {
return accStartDate;
} // getAccStartDate
public int getAccIndex() {
return accIndex;
} // getAccIndex
public void setAccIndex(int accIndex) {
this.accIndex = accIndex;
} // setAccIndex
public NGSIBatch getBatch() {
return batch;
} // getBatch
public String getAccTransactionIds() {
return accTransactionIds;
} // getAccTransactionIds
public long getLastRetry() {
return lastRetry;
} // getLastRetry
public void setLastRetry(long lastRetry) {
this.lastRetry = lastRetry;
} // setLastRetry
public int getTTL() {
return ttl;
} // getTTL
public void setTTL(int ttl) {
this.ttl = ttl;
} // setTTL
/**
* Accumulates an getRecvTimeTs given its headers and context data.
* @param event
*/
public void accumulate(NGSIEvent event) {
String transactionId = event.getHeaders().get(CommonConstants.HEADER_CORRELATOR_ID);
if (accTransactionIds.isEmpty()) {
accTransactionIds = transactionId;
} else {
accTransactionIds += "," + transactionId;
} // if else
switch (dataModel) {
case DMBYSERVICE:
accumulateByService(event);
break;
case DMBYSERVICEPATH:
accumulateByServicePath(event);
break;
case DMBYENTITYDATABASE:
case DMBYENTITYDATABASESCHEMA:
case DMBYENTITY:
accumulateByEntity(event);
break;
case DMBYENTITYTYPEDATABASE:
case DMBYENTITYTYPEDATABASESCHEMA:
case DMBYENTITYTYPE:
accumulateByEntityType(event);
break;
case DMBYATTRIBUTE:
accumulateByAttribute(event);
break;
case DMBYENTITYID:
accumulateByEntityId(event);
break;
case DMBYFIXEDENTITYTYPE:
case DMBYFIXEDENTITYTYPEDATABASE:
case DMBYFIXEDENTITYTYPEDATABASESCHEMA:
accumulateByFixedEntityType(event);
break;
default:
LOGGER.error("Unknown data model. Details=" + dataModel.toString() + " Sink: " + this.getClass().getName());
} // switch
} // accumulate
private void accumulateByService(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE);
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByService
private void accumulateByServicePath(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH);
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH);
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByServicePath
private void accumulateByEntity(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_NOTIFIED_ENTITY);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getId() + "_" + mappedCE.getType();
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH) + "_"
+ originalCE.getId() + "_" + originalCE.getType();
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByEntity
private void accumulateByEntityType(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY_TYPE);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY_TYPE);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getType();
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH) + "_"
+ originalCE.getType();
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByEntityType
private void accumulateByEntityId(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_NOTIFIED_ENTITY);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getId() + "_" + mappedCE.getType();
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH) + "_"
+ originalCE.getId() + "_" + originalCE.getType();
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByServicePath
private void accumulateByFixedEntityType(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY_TYPE);
} else {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY_TYPE);
} // if else
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getId() "_" + mappedCE.getType();
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ originalCE.getType();
} // if else
} // if else
batch.addEvent(destination, event);
} // accumulateByEntityIdType
private void accumulateByAttribute(NGSIEvent event) {
Map<String, String> headers = event.getHeaders();
ContextElement originalCE = event.getOriginalCE();
ContextElement mappedCE = event.getMappedCE();
String destination;
if (mappedCE == null) { // 'TODO': remove when Grouping Rules are definitely removed
String service = headers.get(CommonConstants.HEADER_FIWARE_SERVICE);
if (enableGrouping) {
destination = service + "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_GROUPED_ENTITY);
} else {
destination = service + "_" + headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH)
+ "_" + headers.get(NGSIConstants.FLUME_HEADER_NOTIFIED_ENTITY);
} // if else
ArrayList<ContextAttribute> attrs = originalCE.getAttributes();
for (ContextAttribute attr : attrs) {
ContextElement filteredOriginalCE = originalCE.filter(attr.getName());
event.setOriginalCE(filteredOriginalCE);
batch.addEvent(destination + "_" + attr.getName(), event);
} // for
} else {
if (enableNameMappings) {
destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
+ headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
+ mappedCE.getId() + "_" + mappedCE.getType();
ArrayList<ContextAttribute> attrs = mappedCE.getAttributes();
for (ContextAttribute attr : attrs) {
ContextElement filteredOriginalCE = originalCE.filter(attr.getName());
ContextElement filteredMappedCE = mappedCE.filter(attr.getName());
event.setOriginalCE(filteredOriginalCE);
event.setMappedCE(filteredMappedCE);
batch.addEvent(destination + "_" + attr.getName(), event);
} // for
} else {
destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
+ headers.get(CommonConstants.HEADER_FIWARE_SERVICE_PATH) + "_"
+ originalCE.getId() + "_" + originalCE.getType();
ArrayList<ContextAttribute> attrs = originalCE.getAttributes();
for (ContextAttribute attr : attrs) {
ContextElement filteredOriginalCE = originalCE.filter(attr.getName());
ContextElement filteredMappedCE = mappedCE.filter(attr.getName()); // not really necessary...
event.setOriginalCE(filteredOriginalCE);
event.setMappedCE(filteredMappedCE);
batch.addEvent(destination + "_" + attr.getName(), event);
} // for
} // if else
} // if else
} // accumulateByAttribute
/**
* Initialize the batch.
* @param startDateMs
*/
public void initialize(long startDateMs) {
// what happens if Cygnus falls down while accumulating the batch?
// TBD: https://github.com/telefonicaid/fiware-cygnus/issues/562
batch = new NGSIBatch();
accStartDate = startDateMs;
accIndex = 0;
accTransactionIds = "";
ttl = batchTTL;
} // initialize
@Override
public Accumulator clone() {
try {
Accumulator acc = (Accumulator) super.clone();
return acc;
} catch (CloneNotSupportedException ce) {
return null;
} // clone
} // clone
} // Accumulator
/**
* Class for checking about expired records.
*/
private class ExpirationTimeChecker extends Thread {
private final String sinkName;
/**
* Constructor.
* @param sinkName
*/
public ExpirationTimeChecker(String sinkName) {
this.sinkName = sinkName;
} // ExpirationTimeChecker
@Override
public void run() {
while (true) {
long timeBefore = 0;
long timeAfter = 0;
if (persistencePolicyExpirationTime > -1) {
timeBefore = new Date().getTime();
try {
LOGGER.debug("[" + sinkName + "] Expirating records");
expirateRecords(persistencePolicyExpirationTime);
} catch (Exception e) {
LOGGER.error("[" + sinkName + "] Error while expirating records. Details: "
+ e.getMessage());
} // try catch
timeAfter = new Date().getTime();
} // if
long timeExpent = timeAfter - timeBefore;
long sleepTime = (persistencePolicyCheckingTime * 1000) - timeExpent;
if (sleepTime <= 0) {
sleepTime = 1000; // sleep at least 1 second
} // if
try {
sleep(sleepTime);
} catch (InterruptedException e) {
LOGGER.error("[" + sinkName + "] Error while sleeping. Details: " + e.getMessage());
} // try
} // while
} // run
} // ExpirationTimeChecker
/**
* This is the method the classes extending this class must implement when dealing with a batch of events to be
* persisted.
* @param batch
* @throws Exception
*/
abstract void persistBatch(NGSIBatch batch) throws CygnusBadConfiguration, CygnusBadContextData,
CygnusRuntimeError, CygnusPersistenceError;
/**
* This is the method the classes extending this class must implement when dealing with size-based capping.
* @param batch
* @param maxRecords
* @throws EventDeliveryException
*/
abstract void capRecords(NGSIBatch batch, long maxRecords) throws CygnusCappingError;
/**
* This is the method the classes extending this class must implement when dealing with time-based expiration.
* @param expirationTime
* @throws Exception
*/
abstract void expirateRecords(long expirationTime) throws CygnusExpiratingError;
} // NGSISink
| fix accumulateByFixedEntityType
| cygnus-ngsi/src/main/java/com/telefonica/iot/cygnus/sinks/NGSISink.java | fix accumulateByFixedEntityType | <ide><path>ygnus-ngsi/src/main/java/com/telefonica/iot/cygnus/sinks/NGSISink.java
<ide> } else {
<ide> if (enableNameMappings) {
<ide> destination = headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE) + "_"
<del> + headers.get(NGSIConstants.FLUME_HEADER_MAPPED_SERVICE_PATH) + "_"
<del> + mappedCE.getId() "_" + mappedCE.getType();
<add> + mappedCE.getType();
<ide> } else {
<ide> destination = headers.get(CommonConstants.HEADER_FIWARE_SERVICE) + "_"
<ide> + originalCE.getType(); |
|
Java | agpl-3.0 | 9f3567c466a75ce72879c10c644fddd08fb556e2 | 0 | juanibdn/jPOS,juanibdn/jPOS,yinheli/jPOS,imam-san/jPOS-1,atancasis/jPOS,chhil/jPOS,c0deh4xor/jPOS,jpos/jPOS,sebastianpacheco/jPOS,sebastianpacheco/jPOS,barspi/jPOS,imam-san/jPOS-1,juanibdn/jPOS,c0deh4xor/jPOS,fayezasar/jPOS,atancasis/jPOS,poynt/jPOS,chhil/jPOS,poynt/jPOS,fayezasar/jPOS,yinheli/jPOS,jpos/jPOS,bharavi/jPOS,c0deh4xor/jPOS,atancasis/jPOS,alcarraz/jPOS,bharavi/jPOS,yinheli/jPOS,poynt/jPOS,alcarraz/jPOS,barspi/jPOS,barspi/jPOS,sebastianpacheco/jPOS,jpos/jPOS,bharavi/jPOS,imam-san/jPOS-1,alcarraz/jPOS | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2008 Alejandro P. Revilla
*
* 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 org.jpos.iso;
/**
* Implements BCD Interpreter. Numeric Strings (consisting of chars '0'..'9' are converted
* to and from BCD bytes. Thus, "1234" is converted into 2 bytes: 0x12, 0x34.
*
* @author joconnor
* @version $Revision$ $Date$
*/
public class BCDInterpreter implements Interpreter
{
/** This BCDInterpreter sometimes adds a 0-nibble to the left. */
public static final BCDInterpreter LEFT_PADDED = new BCDInterpreter(true, false);
/** This BCDInterpreter sometimes adds a 0-nibble to the right. */
public static final BCDInterpreter RIGHT_PADDED = new BCDInterpreter(false, false);
/** This BCDInterpreter sometimes adds a F-nibble to the right. */
public static final BCDInterpreter RIGHT_PADDED_F = new BCDInterpreter(false, true);
/** This BCDInterpreter sometimes adds a F-nibble to the left. */
public static final BCDInterpreter LEFT_PADDED_F = new BCDInterpreter(true, true);
private boolean leftPadded;
private boolean fPadded;
/** Kept private. Only two instances are possible. */
private BCDInterpreter(boolean leftPadded, boolean fPadded) {
this.leftPadded = leftPadded;
this.fPadded = fPadded;
}
/**
* (non-Javadoc)
*
* @see org.jpos.iso.Interpreter#interpret(java.lang.String)
*/
public void interpret(String data, byte[] b, int offset)
{
ISOUtil.str2bcd(data, leftPadded, b, offset);
// if (fPadded && !leftPadded && data.length()%2 == 1)
// b[b.length-1] |= (byte)(b[b.length-1] << 4) == 0 ? 0x0F : 0x00;
int paddedSize = data.length() >> 1;
if (fPadded && data.length()%2 == 1)
if (leftPadded)
b[offset] |= (byte) 0xF0;
else
b[paddedSize] |= (byte) 0x0F;
}
/**
* (non-Javadoc)
*
* @see org.jpos.iso.Interpreter#uninterpret(byte[])
*/
public String uninterpret(byte[] rawData, int offset, int length)
{
return ISOUtil.bcd2str (rawData, offset, length, leftPadded);
}
/**
* Each numeric digit is packed into a nibble, so 2 digits per byte, plus the
* possibility of padding.
*
* @see org.jpos.iso.Interpreter#getPackedLength(int)
*/
public int getPackedLength(int nDataUnits)
{
return (nDataUnits + 1) / 2;
}
}
| jpos6/modules/jpos/src/org/jpos/iso/BCDInterpreter.java | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2008 Alejandro P. Revilla
*
* 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 org.jpos.iso;
/**
* Implements BCD Interpreter. Numeric Strings (consisting of chars '0'..'9' are converted
* to and from BCD bytes. Thus, "1234" is converted into 2 bytes: 0x12, 0x34.
*
* @author joconnor
* @version $Revision$ $Date$
*/
public class BCDInterpreter implements Interpreter
{
/** This BCDInterpreter sometimes adds a 0-nibble to the left. */
public static final BCDInterpreter LEFT_PADDED = new BCDInterpreter(true, false);
/** This BCDInterpreter sometimes adds a 0-nibble to the right. */
public static final BCDInterpreter RIGHT_PADDED = new BCDInterpreter(false, false);
/** This BCDInterpreter sometimes adds a F-nibble to the right. */
public static final BCDInterpreter RIGHT_PADDED_F = new BCDInterpreter(false, true);
/** This BCDInterpreter sometimes adds a F-nibble to the left. */
public static final BCDInterpreter LEFT_PADDED_F = new BCDInterpreter(true, true);
private boolean leftPadded;
private boolean fPadded;
/** Kept private. Only two instances are possible. */
private BCDInterpreter(boolean leftPadded, boolean fPadded) {
this.leftPadded = leftPadded;
this.fPadded = fPadded;
}
/**
* (non-Javadoc)
*
* @see org.jpos.iso.Interpreter#interpret(java.lang.String)
*/
public void interpret(String data, byte[] b, int offset)
{
ISOUtil.str2bcd(data, leftPadded, b, offset);
if (fPadded && !leftPadded && data.length()%2 == 1)
b[b.length-1] |= (byte)(b[b.length-1] << 4) == 0 ? 0x0F : 0x00;
}
/**
* (non-Javadoc)
*
* @see org.jpos.iso.Interpreter#uninterpret(byte[])
*/
public String uninterpret(byte[] rawData, int offset, int length)
{
return ISOUtil.bcd2str (rawData, offset, length, leftPadded);
}
/**
* Each numeric digit is packed into a nibble, so 2 digits per byte, plus the
* possibility of padding.
*
* @see org.jpos.iso.Interpreter#getPackedLength(int)
*/
public int getPackedLength(int nDataUnits)
{
return (nDataUnits + 1) / 2;
}
}
| Patch provided by Dr. Alexander Sahler - Thank you!
1) left-padding does not work. Input of "123" is encoded to {0x01, 0x23}
instead of {0xF1, 0x23}
2) right padding with byte arrays bigger than encoding length does not
work. Padding "123" with target array of size 4 leads to output: { 0x12,
0x30, 0x00, 0x0F}. Result should be: { 0x12, 0x3F, 0x00, 0x00}
| jpos6/modules/jpos/src/org/jpos/iso/BCDInterpreter.java | Patch provided by Dr. Alexander Sahler - Thank you! | <ide><path>pos6/modules/jpos/src/org/jpos/iso/BCDInterpreter.java
<ide> public void interpret(String data, byte[] b, int offset)
<ide> {
<ide> ISOUtil.str2bcd(data, leftPadded, b, offset);
<del> if (fPadded && !leftPadded && data.length()%2 == 1)
<del> b[b.length-1] |= (byte)(b[b.length-1] << 4) == 0 ? 0x0F : 0x00;
<add> // if (fPadded && !leftPadded && data.length()%2 == 1)
<add> // b[b.length-1] |= (byte)(b[b.length-1] << 4) == 0 ? 0x0F : 0x00;
<add> int paddedSize = data.length() >> 1;
<add> if (fPadded && data.length()%2 == 1)
<add> if (leftPadded)
<add> b[offset] |= (byte) 0xF0;
<add> else
<add> b[paddedSize] |= (byte) 0x0F;
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 73773644b77d5ce003c0e9e93b2e3b683e16853a | 0 | egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations | // User Manager: Clients view
'use strict';
var _ = require('mano').i18n.bind('View: Client');
exports._parent = require('./manager');
exports['manager-account-clients'] = { class: { active: true } };
exports['manager-account-content'] = function () {
var clients = this.user.managedUsers;
section(a({ href: url('new-client'), class: 'button-main' },
_("Add client"))
);
insert(_if(clients._size, function () {
return section({ class: 'submitted-main table-responsive-container' },
table(
{ class: 'submitted-user-data-table' },
thead(tr(
th(_("Client")),
th(_('Linked entities')),
th(_('Services')),
th(_('Email')),
th()
)),
tbody(
clients,
function (client) {
var bpSet = client.initialBusinessProcesses.and(this.user.managedBusinessProcesses)
.filterByKey('businessName');
return tr(
td(client._fullName),
td(ul(bpSet,
function (bp) {
return [bp._businessName, " (", bp.label, ")"];
})),
td(bpSet.map(function (bp) { return bp.constructor; })._size),
td(span(client._email),
_if(client.roles._has('user'), span('✅'))),
td({ class: 'actions' },
_if(eq(client._manager, this.user),
[
a({ href: url('clients', client.__id__) },
span({ class: 'fa fa-edit' })),
_if(eq(client.initialBusinessProcesses
.filterByKey('isSubmitted', true)._size, 0),
postButton({ buttonClass: 'actions-delete',
action: url('clients', client.__id__, 'delete'),
confirm: _("Are you sure?"), value: span({ class: 'fa fa-trash-o' }) })
)
]
)
)
);
},
this
)
));
}.bind(this),
p(_('You have no clients yet.'))));
};
| view/manager-home.js | // User Manager: Clients view
'use strict';
var _ = require('mano').i18n.bind('View: Client');
exports._parent = require('./manager');
exports['manager-account-clients'] = { class: { active: true } };
exports['manager-account-content'] = function () {
var clients = this.user.managedUsers;
section({ class: 'section-primary' },
a({ href: url('new-client'), class: 'button-main', target: '_blank' },
_("Add client")
)
);
insert(_if(clients._size, function () {
return section({ class: 'submitted-main table-responsive-container' },
table(
{ class: 'submitted-user-data-table' },
thead(tr(
th(_("Client")),
th(_('Linked entities')),
th(_('Services')),
th(_('Email')),
th()
)),
tbody(
clients,
function (client) {
var bpSet = client.initialBusinessProcesses.and(this.user.managedBusinessProcesses)
.filterByKey('businessName');
return tr(
td(client._fullName),
td(ul(bpSet,
function (bp) {
return [bp._businessName, " (", bp.label, ")"];
})),
td(bpSet.map(function (bp) { return bp.constructor; })._size),
td(span(client._email),
_if(client.roles._has('user'), span('✅'))),
td({ class: 'actions' },
_if(eq(client._manager, this.user),
[
a({ href: url('clients', client.__id__) },
span({ class: 'fa fa-edit' })),
_if(eq(client.initialBusinessProcesses
.filterByKey('isSubmitted', true)._size, 0),
postButton({ buttonClass: 'actions-delete',
action: url('clients', client.__id__, 'delete'),
confirm: _("Are you sure?"), value: span({ class: 'fa fa-trash-o' }) })
)
]
)
)
);
},
this
)
));
}.bind(this),
p(_('You have no clients yet.'))));
};
| Fix class embedded
| view/manager-home.js | Fix class embedded | <ide><path>iew/manager-home.js
<ide> exports['manager-account-content'] = function () {
<ide> var clients = this.user.managedUsers;
<ide>
<del> section({ class: 'section-primary' },
<del> a({ href: url('new-client'), class: 'button-main', target: '_blank' },
<del> _("Add client")
<del> )
<add> section(a({ href: url('new-client'), class: 'button-main' },
<add> _("Add client"))
<ide> );
<ide>
<ide> insert(_if(clients._size, function () { |
|
Java | apache-2.0 | 3b4996d83b7f030212c8812ce2ee48af045ecbd6 | 0 | rhencke/buck,rhencke/buck,robbertvanginkel/buck,daedric/buck,tgummerer/buck,tgummerer/buck,1yvT0s/buck,JoelMarcey/buck,rmaz/buck,facebook/buck,luiseduardohdbackup/buck,Addepar/buck,OkBuilds/buck,facebook/buck,marcinkwiatkowski/buck,1yvT0s/buck,SeleniumHQ/buck,grumpyjames/buck,LegNeato/buck,kageiit/buck,raviagarwal7/buck,darkforestzero/buck,1yvT0s/buck,artiya4u/buck,janicduplessis/buck,daedric/buck,luiseduardohdbackup/buck,pwz3n0/buck,justinmuller/buck,artiya4u/buck,liuyang-li/buck,raviagarwal7/buck,luiseduardohdbackup/buck,justinmuller/buck,davido/buck,rowillia/buck,grumpyjames/buck,shs96c/buck,pwz3n0/buck,robbertvanginkel/buck,dsyang/buck,k21/buck,rowillia/buck,davido/buck,stuhood/buck,zhan-xiong/buck,tgummerer/buck,Addepar/buck,illicitonion/buck,OkBuilds/buck,SeleniumHQ/buck,brettwooldridge/buck,SeleniumHQ/buck,pwz3n0/buck,rhencke/buck,daedric/buck,janicduplessis/buck,romanoid/buck,janicduplessis/buck,vine/buck,zhan-xiong/buck,marcinkwiatkowski/buck,rmaz/buck,liuyang-li/buck,marcinkwiatkowski/buck,illicitonion/buck,rhencke/buck,tgummerer/buck,clonetwin26/buck,kageiit/buck,1yvT0s/buck,janicduplessis/buck,sdwilsh/buck,vine/buck,janicduplessis/buck,romanoid/buck,illicitonion/buck,brettwooldridge/buck,mogers/buck,Addepar/buck,k21/buck,artiya4u/buck,k21/buck,OkBuilds/buck,dushmis/buck,ilya-klyuchnikov/buck,stuhood/buck,LegNeato/buck,stuhood/buck,darkforestzero/buck,SeleniumHQ/buck,daedric/buck,darkforestzero/buck,mogers/buck,shybovycha/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,luiseduardohdbackup/buck,Addepar/buck,kageiit/buck,kageiit/buck,clonetwin26/buck,zpao/buck,justinmuller/buck,davido/buck,raviagarwal7/buck,siddhartharay007/buck,JoelMarcey/buck,Distrotech/buck,clonetwin26/buck,darkforestzero/buck,raviagarwal7/buck,siddhartharay007/buck,liuyang-li/buck,Dominator008/buck,romanoid/buck,shybovycha/buck,justinmuller/buck,Addepar/buck,janicduplessis/buck,SeleniumHQ/buck,k21/buck,sdwilsh/buck,zhan-xiong/buck,1yvT0s/buck,mikekap/buck,Dominator008/buck,brettwooldridge/buck,mikekap/buck,ilya-klyuchnikov/buck,darkforestzero/buck,LegNeato/buck,luiseduardohdbackup/buck,davido/buck,zhan-xiong/buck,mikekap/buck,davido/buck,ilya-klyuchnikov/buck,romanoid/buck,stuhood/buck,JoelMarcey/buck,darkforestzero/buck,shs96c/buck,nguyentruongtho/buck,stuhood/buck,marcinkwiatkowski/buck,rowillia/buck,brettwooldridge/buck,davido/buck,JoelMarcey/buck,justinmuller/buck,justinmuller/buck,dsyang/buck,dushmis/buck,shs96c/buck,grumpyjames/buck,shybovycha/buck,zhan-xiong/buck,illicitonion/buck,OkBuilds/buck,vschs007/buck,mogers/buck,rowillia/buck,mikekap/buck,vschs007/buck,tgummerer/buck,JoelMarcey/buck,romanoid/buck,robbertvanginkel/buck,facebook/buck,siddhartharay007/buck,bocon13/buck,darkforestzero/buck,k21/buck,mikekap/buck,JoelMarcey/buck,kageiit/buck,marcinkwiatkowski/buck,ilya-klyuchnikov/buck,pwz3n0/buck,rowillia/buck,dsyang/buck,kageiit/buck,Distrotech/buck,LegNeato/buck,romanoid/buck,rmaz/buck,lukw00/buck,shs96c/buck,Addepar/buck,k21/buck,sdwilsh/buck,mikekap/buck,robbertvanginkel/buck,robbertvanginkel/buck,zhan-xiong/buck,Distrotech/buck,rowillia/buck,grumpyjames/buck,mikekap/buck,illicitonion/buck,SeleniumHQ/buck,stuhood/buck,mogers/buck,davido/buck,shybovycha/buck,Distrotech/buck,lukw00/buck,illicitonion/buck,shybovycha/buck,vschs007/buck,Dominator008/buck,zhan-xiong/buck,OkBuilds/buck,tgummerer/buck,Learn-Android-app/buck,mogers/buck,darkforestzero/buck,stuhood/buck,liuyang-li/buck,luiseduardohdbackup/buck,shs96c/buck,zhan-xiong/buck,mogers/buck,pwz3n0/buck,marcinkwiatkowski/buck,brettwooldridge/buck,mogers/buck,LegNeato/buck,janicduplessis/buck,OkBuilds/buck,Learn-Android-app/buck,pwz3n0/buck,vine/buck,zhan-xiong/buck,liuyang-li/buck,liuyang-li/buck,tgummerer/buck,daedric/buck,siddhartharay007/buck,nguyentruongtho/buck,artiya4u/buck,clonetwin26/buck,liuyang-li/buck,Distrotech/buck,vschs007/buck,daedric/buck,dushmis/buck,Learn-Android-app/buck,sdwilsh/buck,grumpyjames/buck,bocon13/buck,SeleniumHQ/buck,rowillia/buck,sdwilsh/buck,lukw00/buck,vschs007/buck,rmaz/buck,daedric/buck,rmaz/buck,rowillia/buck,grumpyjames/buck,janicduplessis/buck,liuyang-li/buck,Learn-Android-app/buck,mikekap/buck,rhencke/buck,sdwilsh/buck,daedric/buck,raviagarwal7/buck,k21/buck,zhan-xiong/buck,clonetwin26/buck,vschs007/buck,marcinkwiatkowski/buck,daedric/buck,illicitonion/buck,zpao/buck,Learn-Android-app/buck,davido/buck,Learn-Android-app/buck,rhencke/buck,Dominator008/buck,dushmis/buck,lukw00/buck,JoelMarcey/buck,zpao/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,rmaz/buck,vschs007/buck,vine/buck,janicduplessis/buck,illicitonion/buck,dsyang/buck,daedric/buck,shs96c/buck,romanoid/buck,dsyang/buck,SeleniumHQ/buck,dsyang/buck,luiseduardohdbackup/buck,rmaz/buck,clonetwin26/buck,lukw00/buck,rmaz/buck,vine/buck,Addepar/buck,zpao/buck,artiya4u/buck,1yvT0s/buck,romanoid/buck,vschs007/buck,luiseduardohdbackup/buck,brettwooldridge/buck,marcinkwiatkowski/buck,brettwooldridge/buck,illicitonion/buck,SeleniumHQ/buck,justinmuller/buck,rhencke/buck,Dominator008/buck,Dominator008/buck,Addepar/buck,sdwilsh/buck,vschs007/buck,ilya-klyuchnikov/buck,vine/buck,rhencke/buck,romanoid/buck,lukw00/buck,OkBuilds/buck,illicitonion/buck,daedric/buck,ilya-klyuchnikov/buck,dushmis/buck,raviagarwal7/buck,dushmis/buck,stuhood/buck,LegNeato/buck,sdwilsh/buck,ilya-klyuchnikov/buck,davido/buck,janicduplessis/buck,facebook/buck,dsyang/buck,ilya-klyuchnikov/buck,justinmuller/buck,raviagarwal7/buck,clonetwin26/buck,SeleniumHQ/buck,vine/buck,Distrotech/buck,sdwilsh/buck,davido/buck,dsyang/buck,marcinkwiatkowski/buck,k21/buck,facebook/buck,romanoid/buck,grumpyjames/buck,Learn-Android-app/buck,bocon13/buck,bocon13/buck,Dominator008/buck,shs96c/buck,Distrotech/buck,darkforestzero/buck,grumpyjames/buck,sdwilsh/buck,rhencke/buck,tgummerer/buck,lukw00/buck,justinmuller/buck,rmaz/buck,robbertvanginkel/buck,romanoid/buck,bocon13/buck,grumpyjames/buck,darkforestzero/buck,nguyentruongtho/buck,clonetwin26/buck,Addepar/buck,LegNeato/buck,mikekap/buck,JoelMarcey/buck,marcinkwiatkowski/buck,liuyang-li/buck,k21/buck,1yvT0s/buck,Dominator008/buck,rmaz/buck,facebook/buck,siddhartharay007/buck,OkBuilds/buck,darkforestzero/buck,artiya4u/buck,lukw00/buck,artiya4u/buck,clonetwin26/buck,Learn-Android-app/buck,zpao/buck,dsyang/buck,1yvT0s/buck,rowillia/buck,illicitonion/buck,Distrotech/buck,k21/buck,brettwooldridge/buck,vschs007/buck,pwz3n0/buck,bocon13/buck,shybovycha/buck,dsyang/buck,pwz3n0/buck,pwz3n0/buck,clonetwin26/buck,stuhood/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,siddhartharay007/buck,rmaz/buck,facebook/buck,shs96c/buck,grumpyjames/buck,LegNeato/buck,bocon13/buck,liuyang-li/buck,OkBuilds/buck,tgummerer/buck,stuhood/buck,rowillia/buck,zhan-xiong/buck,lukw00/buck,raviagarwal7/buck,raviagarwal7/buck,Dominator008/buck,JoelMarcey/buck,robbertvanginkel/buck,raviagarwal7/buck,shybovycha/buck,daedric/buck,brettwooldridge/buck,raviagarwal7/buck,grumpyjames/buck,shybovycha/buck,lukw00/buck,brettwooldridge/buck,LegNeato/buck,dsyang/buck,marcinkwiatkowski/buck,OkBuilds/buck,k21/buck,mogers/buck,sdwilsh/buck,dsyang/buck,SeleniumHQ/buck,OkBuilds/buck,shybovycha/buck,shs96c/buck,robbertvanginkel/buck,SeleniumHQ/buck,clonetwin26/buck,shs96c/buck,bocon13/buck,zhan-xiong/buck,davido/buck,pwz3n0/buck,vschs007/buck,vschs007/buck,siddhartharay007/buck,marcinkwiatkowski/buck,robbertvanginkel/buck,shs96c/buck,janicduplessis/buck,vine/buck,robbertvanginkel/buck,justinmuller/buck,darkforestzero/buck,JoelMarcey/buck,shs96c/buck,clonetwin26/buck,shs96c/buck,mogers/buck,rmaz/buck,illicitonion/buck,bocon13/buck,vine/buck,marcinkwiatkowski/buck,mikekap/buck,justinmuller/buck,k21/buck,Learn-Android-app/buck,Distrotech/buck,mogers/buck,rowillia/buck,siddhartharay007/buck,LegNeato/buck,davido/buck,vine/buck,tgummerer/buck,pwz3n0/buck,rowillia/buck,Addepar/buck,k21/buck,artiya4u/buck,janicduplessis/buck,clonetwin26/buck,LegNeato/buck,JoelMarcey/buck,robbertvanginkel/buck,grumpyjames/buck,artiya4u/buck,mikekap/buck,romanoid/buck,Dominator008/buck,rmaz/buck,artiya4u/buck,JoelMarcey/buck,Addepar/buck,raviagarwal7/buck,JoelMarcey/buck,siddhartharay007/buck,1yvT0s/buck,lukw00/buck,dushmis/buck,Learn-Android-app/buck,stuhood/buck,dushmis/buck,LegNeato/buck,zpao/buck,Addepar/buck,rhencke/buck,Learn-Android-app/buck,Dominator008/buck,robbertvanginkel/buck,rhencke/buck,zpao/buck,nguyentruongtho/buck,bocon13/buck,Dominator008/buck,robbertvanginkel/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,luiseduardohdbackup/buck,raviagarwal7/buck,kageiit/buck,justinmuller/buck,nguyentruongtho/buck,davido/buck,vine/buck,dsyang/buck,OkBuilds/buck,bocon13/buck,Distrotech/buck,bocon13/buck,Distrotech/buck,illicitonion/buck,ilya-klyuchnikov/buck,OkBuilds/buck,sdwilsh/buck,liuyang-li/buck,shybovycha/buck,shybovycha/buck,Addepar/buck,artiya4u/buck,dushmis/buck,dushmis/buck,brettwooldridge/buck,zhan-xiong/buck,justinmuller/buck,romanoid/buck,daedric/buck,darkforestzero/buck,LegNeato/buck,vschs007/buck,shybovycha/buck,mikekap/buck,shybovycha/buck,nguyentruongtho/buck,sdwilsh/buck,tgummerer/buck,mogers/buck | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.RuleKeyBuilder;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.Tool;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ClangPreprocessor implements Preprocessor {
private static final String PRAGMA_TOKEN = "_Pragma";
private static final String PRAGMA_TOKEN_PLACEHOLDER = "__BUCK__PRAGMA_PLACEHOLDER__";
private static final Pattern PRAGMA_TOKEN_PLACEHOLDER_PATTERN = Pattern
.compile("(.*?)" + PRAGMA_TOKEN_PLACEHOLDER + "\\(\"(.*?)\"\\)(.*?)");
private final Tool tool;
public ClangPreprocessor(Tool tool) {
this.tool = tool;
}
@Override
public Optional<ImmutableList<String>> getExtraFlags() {
return Optional.of(
ImmutableList.of(
"-Wno-builtin-macro-redefined",
"-Wno-error=builtin-macro-redefined",
"-D" + PRAGMA_TOKEN + "=" + PRAGMA_TOKEN_PLACEHOLDER));
}
@Override
public Optional<Function<String, Iterable<String>>> getExtraLineProcessor() {
return Optional.<Function<String, Iterable<String>>>of(
new Function<String, Iterable<String>>() {
@Override
public Iterable<String> apply(String input) {
String remainder = input;
ImmutableList.Builder<String> processedLines = ImmutableList.builder();
if (remainder.isEmpty()) {
processedLines.add(remainder);
}
while (!remainder.isEmpty()) {
Matcher m = PRAGMA_TOKEN_PLACEHOLDER_PATTERN.matcher(remainder);
if (!m.matches()) {
processedLines.add(remainder);
break;
}
processedLines.add(m.group(1));
processedLines.add("#pragma " + m.group(2).replaceAll("\\\\\"", "\""));
remainder = m.group(3);
}
return processedLines.build();
}
}
);
}
@Override
public boolean supportsHeaderMaps() {
return true;
}
@Override
public ImmutableCollection<BuildRule> getDeps(SourcePathResolver resolver) {
return tool.getDeps(resolver);
}
@Override
public ImmutableCollection<SourcePath> getInputs() {
return tool.getInputs();
}
@Override
public ImmutableList<String> getCommandPrefix(SourcePathResolver resolver) {
return tool.getCommandPrefix(resolver);
}
@Override
public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) {
return builder
.setReflectively("tool", tool)
.setReflectively("type", getClass().getSimpleName());
}
}
| src/com/facebook/buck/cxx/ClangPreprocessor.java | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.RuleKeyBuilder;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.Tool;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ClangPreprocessor implements Preprocessor {
private static final String PRAGMA_TOKEN = "_Pragma";
private static final String PRAGMA_TOKEN_PLACEHOLDER = "__BUCK__PRAGMA_PLACEHOLDER__";
private static final Pattern PRAGMA_TOKEN_PLACEHOLDER_PATTERN = Pattern
.compile("(.*?)" + PRAGMA_TOKEN_PLACEHOLDER + "\\(\"(.*?)\"\\)(.*?)");
private final Tool tool;
public ClangPreprocessor(Tool tool) {
this.tool = tool;
}
@Override
public Optional<ImmutableList<String>> getExtraFlags() {
return Optional.of(
ImmutableList.of(
"-Wno-builtin-macro-redefined",
"-Wno-error=builtin-macro-redefined",
"-D" + PRAGMA_TOKEN + "=" + PRAGMA_TOKEN_PLACEHOLDER));
}
@Override
public Optional<Function<String, Iterable<String>>> getExtraLineProcessor() {
return Optional.<Function<String, Iterable<String>>>of(
new Function<String, Iterable<String>>() {
@Override
public Iterable<String> apply(String input) {
String remainder = input;
ImmutableList.Builder<String> processedLines = ImmutableList.builder();
while (!remainder.isEmpty()) {
Matcher m = PRAGMA_TOKEN_PLACEHOLDER_PATTERN.matcher(remainder);
if (!m.matches()) {
processedLines.add(remainder);
break;
}
processedLines.add(m.group(1));
processedLines.add("#pragma " + m.group(2).replaceAll("\\\\\"", "\""));
remainder = m.group(3);
}
return processedLines.build();
}
}
);
}
@Override
public boolean supportsHeaderMaps() {
return true;
}
@Override
public ImmutableCollection<BuildRule> getDeps(SourcePathResolver resolver) {
return tool.getDeps(resolver);
}
@Override
public ImmutableCollection<SourcePath> getInputs() {
return tool.getInputs();
}
@Override
public ImmutableList<String> getCommandPrefix(SourcePathResolver resolver) {
return tool.getCommandPrefix(resolver);
}
@Override
public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) {
return builder
.setReflectively("tool", tool)
.setReflectively("type", getClass().getSimpleName());
}
}
| Fix for debugging issue with empty source file lines.
Summary: Bug fix: ignore empty lines in the preprocessor, since it messes up debugging.
Test Plan: None.
| src/com/facebook/buck/cxx/ClangPreprocessor.java | Fix for debugging issue with empty source file lines. | <ide><path>rc/com/facebook/buck/cxx/ClangPreprocessor.java
<ide> public Iterable<String> apply(String input) {
<ide> String remainder = input;
<ide> ImmutableList.Builder<String> processedLines = ImmutableList.builder();
<add> if (remainder.isEmpty()) {
<add> processedLines.add(remainder);
<add> }
<add>
<ide> while (!remainder.isEmpty()) {
<ide> Matcher m = PRAGMA_TOKEN_PLACEHOLDER_PATTERN.matcher(remainder);
<ide> if (!m.matches()) { |
|
JavaScript | bsd-3-clause | d4ed1b1b40439c9abe448197ecd668cfcfebcbae | 0 | dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen | module("Overview", {
'setup': function() {
BMTestUtils.OverviewPre = BMTestUtils.getAllElements();
// Back up any properties that we might decide to replace with mocks
BMTestUtils.OverviewBackup = { };
BMTestUtils.CopyAllMethods(Overview, BMTestUtils.OverviewBackup);
BMTestUtils.ApiBackup = { };
BMTestUtils.CopyAllMethods(Api, BMTestUtils.ApiBackup);
BMTestUtils.LoginBackup = { };
BMTestUtils.CopyAllMethods(Login, BMTestUtils.LoginBackup);
BMTestUtils.setupFakeLogin();
// Create the overview_page div so functions have something to modify
if (document.getElementById('overview_page') == null) {
$('body').append($('<div>', {'id': 'env_message', }));
$('body').append($('<div>', {'id': 'overview_page', }));
}
Login.pageModule = { 'bodyDivId': 'overview_page' };
},
'teardown': function(assert) {
// Do not ignore intermittent failures in this test --- you
// risk breaking the entire suite in hard-to-debug ways
assert.equal(jQuery.active, 0,
"All test functions MUST complete jQuery activity before exiting");
// Delete all elements we expect this module to create
// JavaScript variables
delete Api.new_games;
delete Api.active_games;
delete Api.completed_games;
delete Api.gameNavigation;
delete Api.forumNavigation;
delete Api.user_prefs;
delete Overview.page;
delete Overview.monitorIsOn;
delete Env.window.location.href;
Api.automatedApiCall = false;
Login.pageModule = null;
Login.nextGameRefreshCallback = false;
// Page elements
$('#overview_page').remove();
BMTestUtils.deleteEnvMessage();
BMTestUtils.cleanupFakeLogin();
// Restore any properties that we might have replaced with mocks
BMTestUtils.CopyAllMethods(BMTestUtils.OverviewBackup, Overview);
BMTestUtils.CopyAllMethods(BMTestUtils.ApiBackup, Api);
BMTestUtils.CopyAllMethods(BMTestUtils.LoginBackup, Login);
// Fail if any other elements were added or removed
BMTestUtils.OverviewPost = BMTestUtils.getAllElements();
assert.deepEqual(
BMTestUtils.OverviewPost, BMTestUtils.OverviewPre,
"After testing, the page should have no unexpected element changes");
}
});
// pre-flight test of whether the Overview module has been loaded
test("test_Overview_is_loaded", function(assert) {
assert.ok(Overview, "The Overview namespace exists");
});
// The purpose of this test is to demonstrate that the flow of
// Overview.showLoggedInPage() is correct for a showXPage function, namely
// that it calls an API getter with a showStatePage function as a
// callback.
//
// Accomplish this by mocking the invoked functions
test("test_Overview.showLoggedInPage", function(assert) {
expect(5);
var cached_getOverview = Overview.getOverview;
var cached_showStatePage = Overview.showPage;
var getOverviewCalled = false;
Overview.showPage = function() {
assert.ok(getOverviewCalled, "Overview.getOverview is called before Overview.showPage");
}
Overview.getOverview = function(callback) {
getOverviewCalled = true;
assert.equal(callback, Overview.showPage,
"Overview.getOverview is called with Overview.showPage as an argument");
callback();
}
Overview.showLoggedInPage();
var item = document.getElementById('overview_page');
assert.equal(item.nodeName, "DIV",
"#overview_page is a div after showLoggedInPage() is called");
Overview.getOverview = cached_getOverview;
Overview.showPage = cached_showStatePage;
});
test("test_Overview.showPreferredOverview", function(assert) {
expect(4); // tests + 2 teardown
Api.getUserPrefsData = function(callback) {
Api.user_prefs = { 'automatically_monitor': false };
callback();
};
Overview.executeMonitor = function() {
assert.ok(!Overview.monitorIsOn, 'Monitor should be off');
assert.ok(false, 'Monitor should not be executed');
};
Overview.getOverview = function() {
assert.ok(!Overview.monitorIsOn, 'Monitor should be off');
assert.ok(true, 'Overview should be displayed');
};
Overview.showPreferredOverview();
});
test("test_Overview.showPreferredOverview_monitor", function(assert) {
expect(4); // tests + 2 teardown
Api.getUserPrefsData = function(callback) {
Api.user_prefs = { 'automatically_monitor': true };
callback();
};
Overview.executeMonitor = function() {
assert.ok(Overview.monitorIsOn, 'Monitor should be on');
assert.ok(true, 'Monitor should be executed');
};
Overview.getOverview = function() {
assert.ok(Overview.monitorIsOn, 'Monitor should be on');
assert.ok(false, 'Overview should not be displayed yet');
};
Overview.showPreferredOverview();
});
test("test_Overview.getOverview", function(assert) {
stop();
Overview.getOverview(function() {
assert.ok(Api.active_games, "active games are parsed from server");
assert.ok(Api.completed_games, "active games are parsed from server");
start();
});
});
test("test_Overview.showLoggedOutPage", function(assert) {
// Undo the fake login data
Login.player = null;
Login.logged_in = false;
Overview.showLoggedOutPage();
assert.equal(Env.message, undefined,
"No Env.message when logged out");
var item = document.getElementById('overview_page');
assert.ok(item.innerHTML.match('Welcome to Button Men'),
"#overview_page contains some welcoming text");
});
test("test_Overview.showPage", function(assert) {
stop();
Overview.getOverview(function() {
Overview.showPage();
var htmlout = Overview.page.html();
assert.ok(htmlout.length > 0,
"The created page should have nonzero contents");
start();
});
});
test("test_Overview.pageAddGameTables", function(assert) {
stop();
Overview.getOverview(function() {
Overview.page = $('<div>');
Overview.pageAddGameTables();
assert.ok(true, "No special testing of pageAddGameTables() as a whole is done");
start();
});
});
test("test_Overview.pageAddGameTableNew", function(assert) {
stop();
Overview.getOverview(function() {
Overview.page = $('<div>');
Overview.pageAddGameTableNew();
assert.ok(true, "No special testing of pageAddGameTableNew() as a whole is done");
start();
});
});
// The default overview data contains games awaiting both the player and the opponent
test("test_Overview.pageAddNewgameLink", function(assert) {
stop();
Overview.getOverview(function() {
Overview.page = $('<div>');
Overview.pageAddNewgameLink();
var htmlout = Overview.page.html();
assert.ok(!htmlout.match("Create a new game"),
"Overview page does not contain new game creation message when active games exist");
assert.ok(!htmlout.match("join an open game"),
"Overview page does not contain message about joining open games when active games exist");
assert.ok(htmlout.match("Go to your next pending game"),
"Overview page contains a link to the 'next game' function when a game is awaiting action");
start();
});
});
test("test_Overview.pageAddNewgameLink_noactive", function(assert) {
stop();
Overview.getOverview(function() {
Api.active_games.games.awaitingPlayer = [];
Overview.page = $('<div>');
Overview.pageAddNewgameLink();
var htmlout = Overview.page.html();
assert.ok(!htmlout.match("Create a new game"),
"Overview page does not contain new game creation message when active games exist");
assert.ok(!htmlout.match("join an open game"),
"Overview page does not contain message about joining open games when active games exist");
assert.ok(!htmlout.match("Go to your next pending game"),
"Overview page does not contain a link to the 'next game' function when no game is awaiting action");
start();
});
});
test("test_Overview.pageAddNewgameLink_nogames", function(assert) {
stop();
Overview.getOverview(function() {
Api.active_games.games = {
'awaitingOpponent': [],
'awaitingPlayer': [],
};
Overview.page = $('<div>');
Overview.pageAddNewgameLink();
assert.ok(Overview.page.html().match("Create a new game"),
"Overview page contains new game creation message");
assert.ok(Overview.page.html().match("join an open game"),
"Overview page contains message about joining open games");
start();
});
});
test("test_Overview.pageAddGameTable", function(assert) {
stop();
Overview.getOverview(function() {
Overview.page = $('<div>');
Overview.pageAddGameTable('awaitingPlayer', 'Active games');
var htmlout = Overview.page.html();
assert.ok(htmlout.match('<h2>Active games'), "Section header should be set");
assert.ok(htmlout.match('<table class="gameList activeGames">'), "A table is created");
start();
});
});
test("test_Overview.toggleStaleGame", function(assert) {
// james: currently don't know how to do this testing
})
test("test_Overview.pageAddIntroText", function(assert) {
Overview.page = $('<div>');
Overview.pageAddIntroText();
var htmlout = Overview.page.html();
assert.ok(htmlout.match(
'Button Men is copyright 1999, 2015 James Ernest and Cheapass Games'),
'Page intro text contains the Button Men copyright');
});
test("test_Overview.formAcceptGame", function(assert) {
// james: currently not tested
})
test("test_Overview.formRejectGame", function(assert) {
// james: currently not tested
})
test("test_Overview.formDismissGame", function(assert) {
stop();
expect(3);
// Temporarily back up Overview.showLoggedInPage and replace it with
// a mocked version for testing
var showLoggedInPage = Overview.showLoggedInPage;
Overview.showLoggedInPage = function() {
Overview.showLoggedInPage = showLoggedInPage;
assert.equal(Env.message.text, 'Successfully dismissed game',
'Dismiss game should succeed');
start();
};
var link = $('<a>', { 'data-gameId': 5 });
Overview.formDismissGame.call(link, $.Event());
});
test("test_Overview.goToNextNewForumPost", function(assert) {
var initialUrl = "/ui/game.html?game=1";
Env.window.location.href = initialUrl;
Api.forumNavigation = {
'load_status': 'ok',
'nextNewPostId': 3,
'nextNewPostThreadId': 2,
};
Overview.goToNextNewForumPost();
notEqual(Env.window.location.href, initialUrl, "The page has been redirected");
if (Env.window.location.href !== null && Env.window.location.href !== undefined)
{
assert.ok(Env.window.location.href.match(/forum\.html#!threadId=2&postId=3/),
"The page has been redirected to the new post");
}
});
test("test_Overview.executeMonitor", function(assert) {
stop();
expect(3);
Api.user_prefs = {
'monitor_redirects_to_game': false,
'monitor_redirects_to_forum': false,
};
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(true, 'Should go straight to re-displaying the Overview');
start();
};
Overview.completeMonitor = function() {
assert.ok(false, 'Should go straight to re-displaying the Overview');
start();
};
Overview.executeMonitor();
});
test("test_Overview.executeMonitor_withRedirects", function(assert) {
stop();
expect(4);
Api.user_prefs = {
'monitor_redirects_to_game': true,
'monitor_redirects_to_forum': true,
};
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(false, 'Should go retrieve pending game data for redirect');
assert.ok(false, 'Should go retrieve new psot data for redirect');
start();
};
Overview.completeMonitor = function() {
assert.ok(Api.gameNavigation, 'Should go retrieve pending game data for redirect');
assert.ok(Api.forumNavigation, 'Should go retrieve new psot data for redirect');
start();
};
Overview.executeMonitor();
});
test("test_Overview.completeMonitor", function(assert) {
stop();
expect(3);
Api.user_prefs = {
'monitor_redirects_to_game': true,
'monitor_redirects_to_forum': true,
};
Api.gameNavigation = { 'nextGameId': null };
Api.forumNavigation = { 'nextNewPostId': null };
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(true, 'Should go straight to re-displaying the Overview');
start();
};
Login.goToNextPendingGame = function() {
assert.ok(false, 'Should go straight to re-displaying the Overview');
start();
};
Overview.goToNextNewForumPost = function() {
assert.ok(false, 'Should go straight to re-displaying the Overview');
start();
};
Overview.completeMonitor();
});
test("test_Overview.completeMonitor_withPendingGame", function(assert) {
stop();
expect(3);
Api.user_prefs = {
'monitor_redirects_to_game': true,
'monitor_redirects_to_forum': true,
};
Api.gameNavigation = { 'nextGameId': 7 };
Api.forumNavigation = { 'nextNewPostId': null };
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(false, 'Should redirect to pending game');
start();
};
Login.goToNextPendingGame = function() {
assert.ok(true, 'Should redirect to pending game');
start();
};
Overview.goToNextNewForumPost = function() {
assert.ok(false, 'Should redirect to pending game');
start();
};
Overview.completeMonitor();
});
test("test_Overview.completeMonitor_withNewPost", function(assert) {
stop();
expect(3);
Api.user_prefs = {
'monitor_redirects_to_game': true,
'monitor_redirects_to_forum': true,
};
Api.gameNavigation = { 'nextGameId': null };
Api.forumNavigation = { 'nextNewPostId': 3 };
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(false, 'Should redirect to new post');
start();
};
Login.goToNextPendingGame = function() {
assert.ok(false, 'Should redirect to new post');
start();
};
Overview.goToNextNewForumPost = function() {
assert.ok(true, 'Should redirect to new post');
start();
};
Overview.completeMonitor();
});
| test/src/ui/js/test_Overview.js | module("Overview", {
'setup': function() {
BMTestUtils.OverviewPre = BMTestUtils.getAllElements();
// Back up any properties that we might decide to replace with mocks
BMTestUtils.OverviewBackup = { };
BMTestUtils.CopyAllMethods(Overview, BMTestUtils.OverviewBackup);
BMTestUtils.ApiBackup = { };
BMTestUtils.CopyAllMethods(Api, BMTestUtils.ApiBackup);
BMTestUtils.LoginBackup = { };
BMTestUtils.CopyAllMethods(Login, BMTestUtils.LoginBackup);
BMTestUtils.setupFakeLogin();
// Create the overview_page div so functions have something to modify
if (document.getElementById('overview_page') == null) {
$('body').append($('<div>', {'id': 'env_message', }));
$('body').append($('<div>', {'id': 'overview_page', }));
}
Login.pageModule = { 'bodyDivId': 'overview_page' };
},
'teardown': function(assert) {
// Do not ignore intermittent failures in this test --- you
// risk breaking the entire suite in hard-to-debug ways
assert.equal(jQuery.active, 0,
"All test functions MUST complete jQuery activity before exiting");
// Delete all elements we expect this module to create
// JavaScript variables
delete Api.new_games;
delete Api.active_games;
delete Api.completed_games;
delete Api.gameNavigation;
delete Api.forumNavigation;
delete Api.user_prefs;
delete Overview.page;
delete Overview.monitorIsOn;
delete Env.window.location.href;
Api.automatedApiCall = false;
Login.pageModule = null;
Login.nextGameRefreshCallback = false;
// Page elements
$('#overview_page').remove();
BMTestUtils.deleteEnvMessage();
BMTestUtils.cleanupFakeLogin();
// Restore any properties that we might have replaced with mocks
BMTestUtils.CopyAllMethods(BMTestUtils.OverviewBackup, Overview);
BMTestUtils.CopyAllMethods(BMTestUtils.ApiBackup, Api);
BMTestUtils.CopyAllMethods(BMTestUtils.LoginBackup, Login);
// Fail if any other elements were added or removed
BMTestUtils.OverviewPost = BMTestUtils.getAllElements();
assert.deepEqual(
BMTestUtils.OverviewPost, BMTestUtils.OverviewPre,
"After testing, the page should have no unexpected element changes");
}
});
// pre-flight test of whether the Overview module has been loaded
test("test_Overview_is_loaded", function(assert) {
assert.ok(Overview, "The Overview namespace exists");
});
// The purpose of this test is to demonstrate that the flow of
// Overview.showLoggedInPage() is correct for a showXPage function, namely
// that it calls an API getter with a showStatePage function as a
// callback.
//
// Accomplish this by mocking the invoked functions
test("test_Overview.showLoggedInPage", function(assert) {
expect(5);
var cached_getOverview = Overview.getOverview;
var cached_showStatePage = Overview.showPage;
var getOverviewCalled = false;
Overview.showPage = function() {
assert.ok(getOverviewCalled, "Overview.getOverview is called before Overview.showPage");
}
Overview.getOverview = function(callback) {
getOverviewCalled = true;
assert.equal(callback, Overview.showPage,
"Overview.getOverview is called with Overview.showPage as an argument");
callback();
}
Overview.showLoggedInPage();
var item = document.getElementById('overview_page');
assert.equal(item.nodeName, "DIV",
"#overview_page is a div after showLoggedInPage() is called");
Overview.getOverview = cached_getOverview;
Overview.showPage = cached_showStatePage;
});
test("test_Overview.showPreferredOverview", function(assert) {
expect(4); // tests + 2 teardown
Api.getUserPrefsData = function(callback) {
Api.user_prefs = { 'automatically_monitor': false };
callback();
};
Overview.executeMonitor = function() {
assert.ok(!Overview.monitorIsOn, 'Monitor should be off');
assert.ok(false, 'Monitor should not be executed');
};
Overview.getOverview = function() {
assert.ok(!Overview.monitorIsOn, 'Monitor should be off');
assert.ok(true, 'Overview should be displayed');
};
Overview.showPreferredOverview();
});
test("test_Overview.showPreferredOverview_monitor", function(assert) {
expect(4); // tests + 2 teardown
Api.getUserPrefsData = function(callback) {
Api.user_prefs = { 'automatically_monitor': true };
callback();
};
Overview.executeMonitor = function() {
assert.ok(Overview.monitorIsOn, 'Monitor should be on');
assert.ok(true, 'Monitor should be executed');
};
Overview.getOverview = function() {
assert.ok(Overview.monitorIsOn, 'Monitor should be on');
assert.ok(false, 'Overview should not be displayed yet');
};
Overview.showPreferredOverview();
});
test("test_Overview.getOverview", function(assert) {
stop();
Overview.getOverview(function() {
assert.ok(Api.active_games, "active games are parsed from server");
assert.ok(Api.completed_games, "active games are parsed from server");
start();
});
});
test("test_Overview.showLoggedOutPage", function(assert) {
// Undo the fake login data
Login.player = null;
Login.logged_in = false;
Overview.showLoggedOutPage();
assert.equal(Env.message, undefined,
"No Env.message when logged out");
var item = document.getElementById('overview_page');
assert.ok(item.innerHTML.match('Welcome to Button Men'),
"#overview_page contains some welcoming text");
});
test("test_Overview.showPage", function(assert) {
stop();
Overview.getOverview(function() {
Overview.showPage();
var htmlout = Overview.page.html();
assert.ok(htmlout.length > 0,
"The created page should have nonzero contents");
start();
});
});
test("test_Overview.pageAddGameTables", function(assert) {
stop();
Overview.getOverview(function() {
Overview.page = $('<div>');
Overview.pageAddGameTables();
assert.ok(true, "No special testing of pageAddGameTables() as a whole is done");
start();
});
});
// The default overview data contains games awaiting both the player and the opponent
test("test_Overview.pageAddNewgameLink", function(assert) {
stop();
Overview.getOverview(function() {
Overview.page = $('<div>');
Overview.pageAddNewgameLink();
var htmlout = Overview.page.html();
assert.ok(!htmlout.match("Create a new game"),
"Overview page does not contain new game creation message when active games exist");
assert.ok(!htmlout.match("join an open game"),
"Overview page does not contain message about joining open games when active games exist");
assert.ok(htmlout.match("Go to your next pending game"),
"Overview page contains a link to the 'next game' function when a game is awaiting action");
start();
});
});
test("test_Overview.pageAddNewgameLink_noactive", function(assert) {
stop();
Overview.getOverview(function() {
Api.active_games.games.awaitingPlayer = [];
Overview.page = $('<div>');
Overview.pageAddNewgameLink();
var htmlout = Overview.page.html();
assert.ok(!htmlout.match("Create a new game"),
"Overview page does not contain new game creation message when active games exist");
assert.ok(!htmlout.match("join an open game"),
"Overview page does not contain message about joining open games when active games exist");
assert.ok(!htmlout.match("Go to your next pending game"),
"Overview page does not contain a link to the 'next game' function when no game is awaiting action");
start();
});
});
test("test_Overview.pageAddNewgameLink_nogames", function(assert) {
stop();
Overview.getOverview(function() {
Api.active_games.games = {
'awaitingOpponent': [],
'awaitingPlayer': [],
};
Overview.page = $('<div>');
Overview.pageAddNewgameLink();
assert.ok(Overview.page.html().match("Create a new game"),
"Overview page contains new game creation message");
assert.ok(Overview.page.html().match("join an open game"),
"Overview page contains message about joining open games");
start();
});
});
test("test_Overview.pageAddGameTable", function(assert) {
stop();
Overview.getOverview(function() {
Overview.page = $('<div>');
Overview.pageAddGameTable('awaitingPlayer', 'Active games');
var htmlout = Overview.page.html();
assert.ok(htmlout.match('<h2>Active games'), "Section header should be set");
assert.ok(htmlout.match('<table class="gameList activeGames">'), "A table is created");
start();
});
});
test("test_Overview.toggleStaleGame", function(assert) {
// james: currently don't know how to do this testing
})
test("test_Overview.pageAddIntroText", function(assert) {
Overview.page = $('<div>');
Overview.pageAddIntroText();
var htmlout = Overview.page.html();
assert.ok(htmlout.match(
'Button Men is copyright 1999, 2015 James Ernest and Cheapass Games'),
'Page intro text contains the Button Men copyright');
});
test("test_Overview.formDismissGame", function(assert) {
stop();
expect(3);
// Temporarily back up Overview.showLoggedInPage and replace it with
// a mocked version for testing
var showLoggedInPage = Overview.showLoggedInPage;
Overview.showLoggedInPage = function() {
Overview.showLoggedInPage = showLoggedInPage;
assert.equal(Env.message.text, 'Successfully dismissed game',
'Dismiss game should succeed');
start();
};
var link = $('<a>', { 'data-gameId': 5 });
Overview.formDismissGame.call(link, $.Event());
});
test("test_Overview.goToNextNewForumPost", function(assert) {
var initialUrl = "/ui/game.html?game=1";
Env.window.location.href = initialUrl;
Api.forumNavigation = {
'load_status': 'ok',
'nextNewPostId': 3,
'nextNewPostThreadId': 2,
};
Overview.goToNextNewForumPost();
notEqual(Env.window.location.href, initialUrl, "The page has been redirected");
if (Env.window.location.href !== null && Env.window.location.href !== undefined)
{
assert.ok(Env.window.location.href.match(/forum\.html#!threadId=2&postId=3/),
"The page has been redirected to the new post");
}
});
test("test_Overview.executeMonitor", function(assert) {
stop();
expect(3);
Api.user_prefs = {
'monitor_redirects_to_game': false,
'monitor_redirects_to_forum': false,
};
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(true, 'Should go straight to re-displaying the Overview');
start();
};
Overview.completeMonitor = function() {
assert.ok(false, 'Should go straight to re-displaying the Overview');
start();
};
Overview.executeMonitor();
});
test("test_Overview.executeMonitor_withRedirects", function(assert) {
stop();
expect(4);
Api.user_prefs = {
'monitor_redirects_to_game': true,
'monitor_redirects_to_forum': true,
};
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(false, 'Should go retrieve pending game data for redirect');
assert.ok(false, 'Should go retrieve new psot data for redirect');
start();
};
Overview.completeMonitor = function() {
assert.ok(Api.gameNavigation, 'Should go retrieve pending game data for redirect');
assert.ok(Api.forumNavigation, 'Should go retrieve new psot data for redirect');
start();
};
Overview.executeMonitor();
});
test("test_Overview.completeMonitor", function(assert) {
stop();
expect(3);
Api.user_prefs = {
'monitor_redirects_to_game': true,
'monitor_redirects_to_forum': true,
};
Api.gameNavigation = { 'nextGameId': null };
Api.forumNavigation = { 'nextNewPostId': null };
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(true, 'Should go straight to re-displaying the Overview');
start();
};
Login.goToNextPendingGame = function() {
assert.ok(false, 'Should go straight to re-displaying the Overview');
start();
};
Overview.goToNextNewForumPost = function() {
assert.ok(false, 'Should go straight to re-displaying the Overview');
start();
};
Overview.completeMonitor();
});
test("test_Overview.completeMonitor_withPendingGame", function(assert) {
stop();
expect(3);
Api.user_prefs = {
'monitor_redirects_to_game': true,
'monitor_redirects_to_forum': true,
};
Api.gameNavigation = { 'nextGameId': 7 };
Api.forumNavigation = { 'nextNewPostId': null };
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(false, 'Should redirect to pending game');
start();
};
Login.goToNextPendingGame = function() {
assert.ok(true, 'Should redirect to pending game');
start();
};
Overview.goToNextNewForumPost = function() {
assert.ok(false, 'Should redirect to pending game');
start();
};
Overview.completeMonitor();
});
test("test_Overview.completeMonitor_withNewPost", function(assert) {
stop();
expect(3);
Api.user_prefs = {
'monitor_redirects_to_game': true,
'monitor_redirects_to_forum': true,
};
Api.gameNavigation = { 'nextGameId': null };
Api.forumNavigation = { 'nextNewPostId': 3 };
// Replacing functions with mocks, for testing purposes
Overview.getOverview = function() {
assert.ok(false, 'Should redirect to new post');
start();
};
Login.goToNextPendingGame = function() {
assert.ok(false, 'Should redirect to new post');
start();
};
Overview.goToNextNewForumPost = function() {
assert.ok(true, 'Should redirect to new post');
start();
};
Overview.completeMonitor();
});
| Added QUnit stubs for missing tests
| test/src/ui/js/test_Overview.js | Added QUnit stubs for missing tests | <ide><path>est/src/ui/js/test_Overview.js
<ide> });
<ide> });
<ide>
<add>test("test_Overview.pageAddGameTableNew", function(assert) {
<add> stop();
<add> Overview.getOverview(function() {
<add> Overview.page = $('<div>');
<add> Overview.pageAddGameTableNew();
<add> assert.ok(true, "No special testing of pageAddGameTableNew() as a whole is done");
<add> start();
<add> });
<add>});
<add>
<ide> // The default overview data contains games awaiting both the player and the opponent
<ide> test("test_Overview.pageAddNewgameLink", function(assert) {
<ide> stop();
<ide> 'Page intro text contains the Button Men copyright');
<ide> });
<ide>
<add>test("test_Overview.formAcceptGame", function(assert) {
<add> // james: currently not tested
<add>})
<add>
<add>test("test_Overview.formRejectGame", function(assert) {
<add> // james: currently not tested
<add>})
<add>
<ide> test("test_Overview.formDismissGame", function(assert) {
<ide> stop();
<ide> expect(3); |
|
JavaScript | mit | caa9fc8b9fcb4013d8c29d6752100412a5d5d3cf | 0 | elijahmanor/cross-var | #!/usr/bin/env node --harmony
import spawn from "cross-spawn";
import os from "os";
import { exec } from "child_process";
import exit from 'exit';
function normalize( args, isWindows ) {
return args.map( arg => {
Object.keys( process.env )
.sort( ( x, y ) => x.length < y.length ) // sort by descending length to prevent partial replacement
.forEach( key => {
const regex = new RegExp( `\\$${ key }|%${ key }%`, "i" );
arg = arg.replace( regex, process.env[ key ] );
} );
return arg;
} )
}
let args = process.argv.slice( 2 );
if ( args.length === 1 ) {
const [ command ] = normalize( args );
const proc = exec( command, ( error, stdout, stderr ) => {
if ( error ) {
console.error( `exec error: ${ error }` );
return;
}
process.stdout.write( stdout );
process.stderr.write( stderr );
exit(proc.code);
});
} else {
args = normalize( args );
const command = args.shift();
const proc = spawn.sync( command, args, { stdio: "inherit" } );
exit(proc.status);
}
| src/index.js | #!/usr/bin/env node --harmony
import spawn from "cross-spawn";
import os from "os";
import { exec } from "child_process";
import exit from 'exit';
function normalize( args, isWindows ) {
return args.map( arg => {
Object.keys( process.env ).forEach( key => {
const regex = new RegExp( `\\$${ key }|%${ key }%`, "i" );
arg = arg.replace( regex, process.env[ key ] );
} );
return arg;
} )
}
let args = process.argv.slice( 2 );
if ( args.length === 1 ) {
const [ command ] = normalize( args );
const proc = exec( command, ( error, stdout, stderr ) => {
if ( error ) {
console.error( `exec error: ${ error }` );
return;
}
process.stdout.write( stdout );
process.stderr.write( stderr );
exit(proc.code);
});
} else {
args = normalize( args );
const command = args.shift();
const proc = spawn.sync( command, args, { stdio: "inherit" } );
exit(proc.status);
}
| Sort env vars by descending length to prevent partial replacement
Fixes #8 | src/index.js | Sort env vars by descending length to prevent partial replacement | <ide><path>rc/index.js
<ide>
<ide> function normalize( args, isWindows ) {
<ide> return args.map( arg => {
<del> Object.keys( process.env ).forEach( key => {
<del> const regex = new RegExp( `\\$${ key }|%${ key }%`, "i" );
<del> arg = arg.replace( regex, process.env[ key ] );
<del> } );
<add> Object.keys( process.env )
<add> .sort( ( x, y ) => x.length < y.length ) // sort by descending length to prevent partial replacement
<add> .forEach( key => {
<add> const regex = new RegExp( `\\$${ key }|%${ key }%`, "i" );
<add> arg = arg.replace( regex, process.env[ key ] );
<add> } );
<ide> return arg;
<ide> } )
<ide> } |
|
Java | epl-1.0 | 9e65ec2b9cdf2b6901f6395f89e8b6d84bbc1bcd | 0 | Iteration-3/Code,Iteration-3/Code | package model.entity;
import java.util.ArrayList;
import java.util.Collection;
import model.KeyPreferences;
import model.ability.Ability;
import model.ability.summoner.enchantment.Silence;
import model.area.TileCoordinate;
import model.slots.ItemManager;
import utilities.structuredmap.StructuredMap;
import view.EntityView;
import controller.listener.Listener;
public class Summoner extends Avatar {
protected ItemManager itemManger = new ItemManager(this);
private Collection<Ability> abilities= new ArrayList<Ability>();
private Ability Cripple;
private Ability Intimidate;
private Ability Silence;
private Ability HealBoon;
private Ability MovementBoon;
private Ability StrengthBoon;
private Ability FireBolt;
private Ability LightBeam;
private Ability ShadowBlast;
public Summoner(String name, EntityView view, TileCoordinate loc) {
super(name, view, loc);
//TODO(mbregg) abilities should level up in strength with you
//Bane skills
abilities.add(FireBolt);
abilities.add(LightBeam);
abilities.add(ShadowBlast);
//Boon skills
abilities.add(HealBoon);
abilities.add(MovementBoon);
abilities.add(StrengthBoon);
//Enchantment Skills
abilities.add(Cripple);
abilities.add(Intimidate);
abilities.add(new Silence());
}
@Override
public Collection<Listener> getListeners(KeyPreferences preferences){
Collection<Listener> listeners = new ArrayList<Listener>();
return listeners;
}
protected ItemManager createItemManager() {
return new ItemManager(this);
}
@Override
public void attack() {
// TODO Auto-generated method stub
}
@Override
public StructuredMap getStructuredMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public void load(StructuredMap map) {
// TODO Auto-generated method stub
}
@Override
public void update() {
// TODO Auto-generated method stub
}
}
| src/model/entity/Summoner.java | package model.entity;
import java.util.ArrayList;
import java.util.Collection;
import model.KeyPreferences;
import model.ability.Ability;
import model.ability.summoner.bane.Firebolt;
import model.ability.summoner.bane.LightBeam;
import model.ability.summoner.bane.ShadowBlast;
import model.ability.summoner.boon.HealBoon;
import model.ability.summoner.boon.MovementBoon;
import model.ability.summoner.boon.StrengthBoon;
import model.ability.summoner.enchantment.Cripple;
import model.ability.summoner.enchantment.Intimidate;
import model.ability.summoner.enchantment.Silence;
import model.area.TileCoordinate;
import model.slots.ItemManager;
import utilities.structuredmap.StructuredMap;
import view.EntityView;
import controller.listener.Listener;
public class Summoner extends Avatar {
protected ItemManager itemManger = new ItemManager(this);
private Collection<Ability> abilities= new ArrayList<Ability>();
public Summoner(String name, EntityView view, TileCoordinate loc) {
super(name, view, loc);
//TODO(mbregg) abilities should level up in strength with you
//Bane skills
abilities.add(new Firebolt());
abilities.add(new LightBeam());
abilities.add(new ShadowBlast());
//Boone Skills
abilities.add(new HealBoon());
abilities.add(new MovementBoon());
abilities.add(new StrengthBoon());
//Enchantmentskills
abilities.add(new Cripple());
abilities.add(new Intimidate());
abilities.add(new Silence());
}
@Override
public Collection<Listener> getListeners(KeyPreferences preferences){
return null;
}
protected ItemManager createItemManager() {
return new ItemManager(this);
}
@Override
public void attack() {
// TODO Auto-generated method stub
}
@Override
public StructuredMap getStructuredMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public void load(StructuredMap map) {
// TODO Auto-generated method stub
}
@Override
public void update() {
// TODO Auto-generated method stub
}
}
| OOps, fixed the build
| src/model/entity/Summoner.java | OOps, fixed the build | <ide><path>rc/model/entity/Summoner.java
<ide>
<ide> import model.KeyPreferences;
<ide> import model.ability.Ability;
<del>import model.ability.summoner.bane.Firebolt;
<del>import model.ability.summoner.bane.LightBeam;
<del>import model.ability.summoner.bane.ShadowBlast;
<del>import model.ability.summoner.boon.HealBoon;
<del>import model.ability.summoner.boon.MovementBoon;
<del>import model.ability.summoner.boon.StrengthBoon;
<del>import model.ability.summoner.enchantment.Cripple;
<del>import model.ability.summoner.enchantment.Intimidate;
<ide> import model.ability.summoner.enchantment.Silence;
<ide> import model.area.TileCoordinate;
<ide> import model.slots.ItemManager;
<ide>
<ide> public class Summoner extends Avatar {
<ide> protected ItemManager itemManger = new ItemManager(this);
<add>
<ide> private Collection<Ability> abilities= new ArrayList<Ability>();
<add>
<add> private Ability Cripple;
<add> private Ability Intimidate;
<add> private Ability Silence;
<add> private Ability HealBoon;
<add> private Ability MovementBoon;
<add> private Ability StrengthBoon;
<add> private Ability FireBolt;
<add> private Ability LightBeam;
<add> private Ability ShadowBlast;
<ide>
<add>
<add>
<ide> public Summoner(String name, EntityView view, TileCoordinate loc) {
<ide> super(name, view, loc);
<ide> //TODO(mbregg) abilities should level up in strength with you
<ide> //Bane skills
<del> abilities.add(new Firebolt());
<del> abilities.add(new LightBeam());
<del> abilities.add(new ShadowBlast());
<del> //Boone Skills
<del> abilities.add(new HealBoon());
<del> abilities.add(new MovementBoon());
<del> abilities.add(new StrengthBoon());
<del> //Enchantmentskills
<del> abilities.add(new Cripple());
<del> abilities.add(new Intimidate());
<add> abilities.add(FireBolt);
<add> abilities.add(LightBeam);
<add> abilities.add(ShadowBlast);
<add> //Boon skills
<add> abilities.add(HealBoon);
<add> abilities.add(MovementBoon);
<add> abilities.add(StrengthBoon);
<add> //Enchantment Skills
<add> abilities.add(Cripple);
<add> abilities.add(Intimidate);
<ide> abilities.add(new Silence());
<ide> }
<ide>
<ide> @Override
<ide> public Collection<Listener> getListeners(KeyPreferences preferences){
<del> return null;
<add> Collection<Listener> listeners = new ArrayList<Listener>();
<add> return listeners;
<ide>
<ide> }
<ide> |
|
Java | agpl-3.0 | 7f0a1468b6973388306de351f0b830ee4ecf3fed | 0 | o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa | package com.x.message.assemble.communicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject_;
import com.x.base.core.project.config.Message.RestfulConsumer;
import com.x.base.core.project.connection.HttpConnectionResponse;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.message.MessageConnector;
import com.x.base.core.project.queue.AbstractQueue;
import com.x.base.core.project.webservices.WebservicesClient;
import com.x.message.core.entity.Message;
import com.x.message.core.entity.Message_;
public class RestfulConsumeQueue extends AbstractQueue<Message> {
private static final Logger LOGGER = LoggerFactory.getLogger(RestfulConsumeQueue.class);
private static final Pattern pattern = Pattern.compile("\\{\\$(.+?)\\}");
private static final Gson gson = XGsonBuilder.instance();
private static WebservicesClient client = new WebservicesClient();
protected void execute(Message message) throws Exception {
if (null != message) {
update(message);
}
List<String> ids = listOverStay();
if (!ids.isEmpty()) {
LOGGER.info("滞留 restful 消息数量:{}.", ids.size());
for (String id : ids) {
Optional<Message> optional = find(id);
if (optional.isPresent()) {
message = optional.get();
update(message);
}
}
}
}
private Optional<Message> find(String id) {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
return Optional.of(emc.find(id, Message.class));
} catch (Exception e) {
LOGGER.error(e);
}
return Optional.empty();
}
private void update(Message message) {
try {
RestfulConsumer consumer = gson.fromJson(message.getProperties().getConsumerJsonElement(),
RestfulConsumer.class);
String url = url(message, consumer);
HttpConnectionResponse response = client.restful(consumer.getMethod(), url, null, gson.toJson(message),
5000, 5000);
if (null == response) {
throw new ExceptionRestful(message.getTitle(), message.getPerson(), url);
}
success(message.getId());
} catch (Exception e) {
failure(message.getId(), e);
LOGGER.error(e);
}
}
private String url(Message message, RestfulConsumer consumer) {
String url = consumer.getUrl();
JsonElement jsonElement = gson.toJsonTree(message.getBody());
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (null != jsonObject) {
Matcher matcher = pattern.matcher(url);
while (matcher.find()) {
String key = matcher.group(1);
if (jsonObject.has(key)) {
String value = jsonObject.get(key).getAsString();
if (null != value) {
url = StringUtils.replace(url, matcher.group(), value);
}
}
}
}
}
return url;
}
private void success(String id) {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Message message = emc.find(id, Message.class);
if (null != message) {
emc.beginTransaction(Message.class);
message.setConsumed(true);
emc.commit();
}
} catch (Exception e) {
LOGGER.error(e);
}
}
private void failure(String id, Exception exception) {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Message message = emc.find(id, Message.class);
if (null != message) {
emc.beginTransaction(Message.class);
Integer failure = message.getProperties().getFailure();
failure = (null == failure) ? 1 : failure + 1;
message.getProperties().setFailure(failure);
message.getProperties().setError(exception.getMessage());
emc.commit();
}
} catch (Exception e) {
LOGGER.error(e);
}
}
private List<String> listOverStay() {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
EntityManager em = emc.get(Message.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<Message> root = cq.from(Message.class);
Predicate p = cb.equal(root.get(Message_.consumer), MessageConnector.CONSUME_RESTFUL);
p = cb.and(p, cb.notEqual(root.get(Message_.consumed), true));
p = cb.and(p, cb.lessThan(root.get(JpaObject_.updateTime), DateUtils.addMinutes(new Date(), -20)));
cq.select(root.get(Message_.id)).where(p);
return em.createQuery(cq).setMaxResults(20).getResultList();
} catch (Exception e) {
LOGGER.error(e);
}
return new ArrayList<>();
}
}
| o2server/x_message_assemble_communicate/src/main/java/com/x/message/assemble/communicate/RestfulConsumeQueue.java | package com.x.message.assemble.communicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject_;
import com.x.base.core.project.config.Message.RestfulConsumer;
import com.x.base.core.project.connection.HttpConnectionResponse;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.message.MessageConnector;
import com.x.base.core.project.queue.AbstractQueue;
import com.x.base.core.project.webservices.WebservicesClient;
import com.x.message.core.entity.Message;
import com.x.message.core.entity.Message_;
public class RestfulConsumeQueue extends AbstractQueue<Message> {
private static final Logger LOGGER = LoggerFactory.getLogger(RestfulConsumeQueue.class);
private static final Pattern pattern = Pattern.compile("\\{\\$(.+?)\\}");
private static final Gson gson = XGsonBuilder.instance();
private static WebservicesClient client = new WebservicesClient();
protected void execute(Message message) throws Exception {
if (null != message) {
update(message);
}
List<String> ids = listOverStay();
if (!ids.isEmpty()) {
LOGGER.info("滞留 restful 消息数量:{}.", ids.size());
for (String id : ids) {
Optional<Message> optional = find(id);
if (optional.isPresent()) {
message = optional.get();
update(message);
}
}
}
}
private Optional<Message> find(String id) {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
return Optional.of(emc.find(id, Message.class));
} catch (Exception e) {
LOGGER.error(e);
}
return Optional.empty();
}
private void update(Message message) {
try {
RestfulConsumer consumer = gson.fromJson(message.getProperties().getConsumerJsonElement(),
RestfulConsumer.class);
String url = url(message, consumer);
HttpConnectionResponse response = client.restful(consumer.getMethod(), url, null, message.getBody(), 5000,
5000);
if (null == response) {
throw new ExceptionRestful(message.getTitle(), message.getPerson(), url);
}
success(message.getId());
} catch (Exception e) {
failure(message.getId(), e);
LOGGER.error(e);
}
}
private String url(Message message, RestfulConsumer consumer) {
String url = consumer.getUrl();
JsonElement jsonElement = gson.toJsonTree(message.getBody());
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (null != jsonObject) {
Matcher matcher = pattern.matcher(url);
while (matcher.find()) {
String key = matcher.group(1);
if (jsonObject.has(key)) {
String value = jsonObject.get(key).getAsString();
if (null != value) {
url = StringUtils.replace(url, matcher.group(), value);
}
}
}
}
}
return url;
}
private void success(String id) {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Message message = emc.find(id, Message.class);
if (null != message) {
emc.beginTransaction(Message.class);
message.setConsumed(true);
emc.commit();
}
} catch (Exception e) {
LOGGER.error(e);
}
}
private void failure(String id, Exception exception) {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Message message = emc.find(id, Message.class);
if (null != message) {
emc.beginTransaction(Message.class);
Integer failure = message.getProperties().getFailure();
failure = (null == failure) ? 1 : failure + 1;
message.getProperties().setFailure(failure);
message.getProperties().setError(exception.getMessage());
emc.commit();
}
} catch (Exception e) {
LOGGER.error(e);
}
}
private List<String> listOverStay() {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
EntityManager em = emc.get(Message.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<Message> root = cq.from(Message.class);
Predicate p = cb.equal(root.get(Message_.consumer), MessageConnector.CONSUME_RESTFUL);
p = cb.and(p, cb.notEqual(root.get(Message_.consumed), true));
p = cb.and(p, cb.lessThan(root.get(JpaObject_.updateTime), DateUtils.addMinutes(new Date(), -20)));
cq.select(root.get(Message_.id)).where(p);
return em.createQuery(cq).setMaxResults(20).getResultList();
} catch (Exception e) {
LOGGER.error(e);
}
return new ArrayList<>();
}
}
| 修改restful message 消息体.
| o2server/x_message_assemble_communicate/src/main/java/com/x/message/assemble/communicate/RestfulConsumeQueue.java | 修改restful message 消息体. | <ide><path>2server/x_message_assemble_communicate/src/main/java/com/x/message/assemble/communicate/RestfulConsumeQueue.java
<ide> RestfulConsumer consumer = gson.fromJson(message.getProperties().getConsumerJsonElement(),
<ide> RestfulConsumer.class);
<ide> String url = url(message, consumer);
<del> HttpConnectionResponse response = client.restful(consumer.getMethod(), url, null, message.getBody(), 5000,
<del> 5000);
<add> HttpConnectionResponse response = client.restful(consumer.getMethod(), url, null, gson.toJson(message),
<add> 5000, 5000);
<ide> if (null == response) {
<ide> throw new ExceptionRestful(message.getTitle(), message.getPerson(), url);
<ide> } |
|
Java | bsd-3-clause | e560418835481ffa6504c029d56cfa50a35d88d7 | 0 | team-worthwhile/worthwhile,team-worthwhile/worthwhile | package edu.kit.iti.formal.pse.worthwhile.prover;
import org.junit.Assert;
import org.junit.Test;
import edu.kit.iti.formal.pse.worthwhile.common.tests.TestASTProvider;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ASTNode;
import edu.kit.iti.formal.pse.worthwhile.model.ast.AstFactory;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Conjunction;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Implication;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Program;
import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeEqualsHelper;
import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeToStringHelper;
/**
* JUnit TestCases for {@link WPStrategy#transformProgram}.
*
* @author fabian
*
*/
public final class TransformProgramTest {
/**
* Generates an {@link Expression} from a Worthwhile {@link String}.
*
* @param exprString
* some Worthwhile expression code
* @return {@link Expression} AST representing <code>exprString</code>
*/
Expression getExpression(final String exprString) {
Expression e = TestASTProvider.parseFormulaString(exprString);
Assert.assertNotNull(e);
return e;
}
/**
* Generates an {@link Program} from a Worthwhile {@link String}.
*
* @param progString
* some Worthwhile program code
* @return {@link Program} AST representing <code>progString</code>
*/
Program getProgram(final String progString) {
Program p = TestASTProvider.getRootASTNode(progString);
Assert.assertNotNull(p);
return p;
}
/**
* The {@link FormulaGenerator} implementation to test.
*/
private FormulaGenerator transformer = new WPStrategy();
/**
* Asserts equality of an expected and actual {@link ASTNode} result.
*
* Fails the TestCase if <code>expected</code> and <code>was</code> do not equal according to
* {@link ASTNodeEqualator}.
*
* @param expected
* the expected ASTNode
* @param was
* the ASTNode result which must equal <code>expected</code> for the test to pass
*/
private static void assertASTNodeEqual(final ASTNode expected, final ASTNode was) {
if (!AstNodeEqualsHelper.equals(expected, was)) {
Assert.fail("expected: " + AstNodeToStringHelper.toString(expected) + " was: "
+ AstNodeToStringHelper.toString(was));
}
}
/**
* Tests the transformation of {@link Assignment}s.
*/
@Test
public void assignmentRule() {
Program p = this.getProgram("Integer x := 1\n_assert x = 1\n");
Expression result = this.transformer.transformProgram(p);
assertASTNodeEqual(this.getExpression("1 = 1 && true"), result);
p = this.getProgram("Integer x := 1\nx := 0\n_assert x = 1\n");
result = this.transformer.transformProgram(p);
assertASTNodeEqual(this.getExpression("0 = 1 && true"), result);
}
/**
* Tests the transformation of {@link Conditional}s.
*/
@Test
public void conditionalRule() {
Program p = this.getProgram("Integer x := 1\nif x = 1 {\nx := 0\n}\n_assert x = 0\n");
Expression result = this.transformer.transformProgram(p);
// getExpression cannot be used to build expected because `=>' is no valid Worthwhile operator
Conjunction expected = AstFactory.init().createConjunction();
Implication implication = AstFactory.init().createImplication();
implication.setLeft(this.getExpression("1 = 1"));
implication.setRight(this.getExpression("0 = 0 && true"));
expected.setLeft(implication);
implication = AstFactory.init().createImplication();
implication.setLeft(this.getExpression("!(1 = 1)"));
implication.setRight(this.getExpression("true"));
expected.setRight(implication);
assertASTNodeEqual(expected, result);
}
/**
* Test the transformation of {@link Assumption}s.
*/
@Test
public void assumptionRule() {
Program p = this.getProgram("Integer x := 1\n_assume x = 0\n_assert x = 10\n");
Expression result = this.transformer.transformProgram(p);
// getExpression cannot be used to build expected because `=>' is no valid Worthwhile operator
Implication expected = AstFactory.init().createImplication();
expected.setLeft(this.getExpression("1 = 0"));
expected.setRight(this.getExpression("1 = 10 && true"));
assertASTNodeEqual(expected, result);
}
}
| implementierung/src/worthwhile.prover.tests/src/edu/kit/iti/formal/pse/worthwhile/prover/TransformProgramTest.java | package edu.kit.iti.formal.pse.worthwhile.prover;
import org.junit.Assert;
import org.junit.Test;
import edu.kit.iti.formal.pse.worthwhile.common.tests.TestASTProvider;
import edu.kit.iti.formal.pse.worthwhile.model.ast.ASTNode;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Assignment;
import edu.kit.iti.formal.pse.worthwhile.model.ast.AstFactory;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Conditional;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Conjunction;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Implication;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Program;
import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeEqualsHelper;
import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeToStringHelper;
/**
* JUnit TestCases for {@link WPStrategy#transformProgram}.
*
* @author fabian
*
*/
public final class TransformProgramTest {
/**
* Generates an {@link Expression} from a Worthwhile {@link String}.
*
* @param exprString
* some Worthwhile expression code
* @return {@link Expression} AST representing <code>exprString</code>
*/
Expression getExpression(final String exprString) {
Expression e = TestASTProvider.parseFormulaString(exprString);
Assert.assertNotNull(e);
return e;
}
/**
* Generates an {@link Program} from a Worthwhile {@link String}.
*
* @param progString
* some Worthwhile program code
* @return {@link Program} AST representing <code>progString</code>
*/
Program getProgram(final String progString) {
Program p = TestASTProvider.getRootASTNode(progString);
Assert.assertNotNull(p);
return p;
}
/**
* The {@link FormulaGenerator} implementation to test.
*/
private FormulaGenerator transformer = new WPStrategy();
/**
* Asserts equality of an expected and actual {@link ASTNode} result.
*
* Fails the TestCase if <code>expected</code> and <code>was</code> do not equal according to
* {@link ASTNodeEqualator}.
*
* @param expected
* the expected ASTNode
* @param was
* the ASTNode result which must equal <code>expected</code> for the test to pass
*/
private static void assertASTNodeEqual(final ASTNode expected, final ASTNode was) {
if (!AstNodeEqualsHelper.equals(expected, was)) {
Assert.fail("expected: " + AstNodeToStringHelper.toString(expected) + " was: "
+ AstNodeToStringHelper.toString(was));
}
}
/**
* Tests the transformation of {@link Assignment}s.
*/
@Test
public void assignmentRule() {
Program p = this.getProgram("Integer x := 1\n_assert x = 1\n");
Expression result = this.transformer.transformProgram(p);
assertASTNodeEqual(this.getExpression("1 = 1 && true"), result);
p = this.getProgram("Integer x := 1\nx := 0\n_assert x = 1\n");
result = this.transformer.transformProgram(p);
assertASTNodeEqual(this.getExpression("0 = 1 && true"), result);
}
/**
* Tests the transformation of {@link Conditional}s.
*/
@Test
public void conditionalRule() {
Program p = this.getProgram("Integer x := 1\nif x = 1 {\nx := 0\n}\n_assert x = 0\n");
Expression result = this.transformer.transformProgram(p);
// getExpression cannot be used to build expected because `=>' is no valid Worthwhile operator
Conjunction expected = AstFactory.init().createConjunction();
Implication implication = AstFactory.init().createImplication();
implication.setLeft(this.getExpression("1 = 1"));
implication.setRight(this.getExpression("0 = 0 && true"));
expected.setLeft(implication);
implication = AstFactory.init().createImplication();
implication.setLeft(this.getExpression("!(1 = 1)"));
implication.setRight(this.getExpression("true"));
expected.setRight(implication);
assertASTNodeEqual(expected, result);
}
/**
* Test the transformation of {@link Assumption}s.
*/
@Test
public void assumptionRule() {
Program p = this.getProgram("Integer x := 1\n_assume x = 0\n_assert x = 10\n");
Expression result = this.transformer.transformProgram(p);
// getExpression cannot be used to build expected because `=>' is no valid Worthwhile operator
Implication expected = AstFactory.init().createImplication();
expected.setLeft(this.getExpression("1 = 0"));
expected.setRight(this.getExpression("1 = 10 && true"));
assertASTNodeEqual(expected, result);
}
}
| [prover.tests] Remove unused imports from TransformProgramTest
| implementierung/src/worthwhile.prover.tests/src/edu/kit/iti/formal/pse/worthwhile/prover/TransformProgramTest.java | [prover.tests] Remove unused imports from TransformProgramTest | <ide><path>mplementierung/src/worthwhile.prover.tests/src/edu/kit/iti/formal/pse/worthwhile/prover/TransformProgramTest.java
<ide>
<ide> import edu.kit.iti.formal.pse.worthwhile.common.tests.TestASTProvider;
<ide> import edu.kit.iti.formal.pse.worthwhile.model.ast.ASTNode;
<del>import edu.kit.iti.formal.pse.worthwhile.model.ast.Assignment;
<ide> import edu.kit.iti.formal.pse.worthwhile.model.ast.AstFactory;
<del>import edu.kit.iti.formal.pse.worthwhile.model.ast.Conditional;
<ide> import edu.kit.iti.formal.pse.worthwhile.model.ast.Conjunction;
<ide> import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression;
<ide> import edu.kit.iti.formal.pse.worthwhile.model.ast.Implication; |
|
Java | agpl-3.0 | 55792cab5dab6d0d21515ba36126d21ec91c401a | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 3d11b05e-2e60-11e5-9284-b827eb9e62be | hello.java | 3d0c483a-2e60-11e5-9284-b827eb9e62be | 3d11b05e-2e60-11e5-9284-b827eb9e62be | hello.java | 3d11b05e-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>3d0c483a-2e60-11e5-9284-b827eb9e62be
<add>3d11b05e-2e60-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 9ece4a88a9994ba4350a3bfe4570a5797baca6d7 | 0 | spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework | /*
* Copyright 2002-2011 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.expression.spel.support;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* Simple PropertyAccessor that uses reflection to access properties for reading and writing. A property can be accessed
* if it is accessible as a field on the object or through a getter (if being read) or a setter (if being written).
*
* @author Andy Clement
* @author Juergen Hoeller
* @since 3.0
*/
public class ReflectivePropertyAccessor implements PropertyAccessor {
protected final Map<CacheKey, InvokerPair> readerCache = new ConcurrentHashMap<CacheKey, InvokerPair>();
protected final Map<CacheKey, Member> writerCache = new ConcurrentHashMap<CacheKey, Member>();
protected final Map<CacheKey, TypeDescriptor> typeDescriptorCache = new ConcurrentHashMap<CacheKey, TypeDescriptor>();
/**
* @return null which means this is a general purpose accessor
*/
public Class<?>[] getSpecificTargetClasses() {
return null;
}
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
if (target == null) {
return false;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray() && name.equals("length")) {
return true;
}
CacheKey cacheKey = new CacheKey(type, name);
if (this.readerCache.containsKey(cacheKey)) {
return true;
}
Method method = findGetterForProperty(name, type, target instanceof Class);
if (method != null) {
// Treat it like a property
try {
// The readerCache will only contain gettable properties (let's not worry about setters for now)
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, method, null);
TypeDescriptor typeDescriptor = new TypeDescriptor(type, propertyDescriptor);
this.readerCache.put(cacheKey, new InvokerPair(method, typeDescriptor));
this.typeDescriptorCache.put(cacheKey, typeDescriptor);
return true;
}
catch (IntrospectionException ex) {
throw new AccessException("Unable to access property '" + name + "' through getter " + method, ex);
}
}
else {
Field field = findField(name, type, target instanceof Class);
if (field != null) {
TypeDescriptor typeDescriptor = new TypeDescriptor(field);
this.readerCache.put(cacheKey, new InvokerPair(field,typeDescriptor));
this.typeDescriptorCache.put(cacheKey, typeDescriptor);
return true;
}
}
return false;
}
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
if (target == null) {
throw new AccessException("Cannot read property of null target");
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray() && name.equals("length")) {
if (target instanceof Class) {
throw new AccessException("Cannot access length on array class itself");
}
return new TypedValue(Array.getLength(target));
}
CacheKey cacheKey = new CacheKey(type, name);
InvokerPair invoker = this.readerCache.get(cacheKey);
if (invoker == null || invoker.member instanceof Method) {
Method method = (Method) (invoker != null ? invoker.member : null);
if (method == null) {
method = findGetterForProperty(name, type, target instanceof Class);
if (method != null) {
// TODO remove the duplication here between canRead and read
// Treat it like a property
try {
// The readerCache will only contain gettable properties (let's not worry about setters for now)
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, method, null);
TypeDescriptor typeDescriptor = new TypeDescriptor(type, propertyDescriptor);
invoker = new InvokerPair(method, typeDescriptor);
this.readerCache.put(cacheKey, invoker);
}
catch (IntrospectionException ex) {
throw new AccessException(
"Unable to access property '" + name + "' through getter " + method, ex);
}
}
}
if (method != null) {
try {
ReflectionUtils.makeAccessible(method);
Object value = method.invoke(target);
return new TypedValue(value, invoker.typeDescriptor.narrow(value));
}
catch (Exception ex) {
throw new AccessException("Unable to access property '" + name + "' through getter", ex);
}
}
}
if (invoker == null || invoker.member instanceof Field) {
Field field = (Field) (invoker == null ? null : invoker.member);
if (field == null) {
field = findField(name, type, target instanceof Class);
if (field != null) {
invoker = new InvokerPair(field, new TypeDescriptor(field));
this.readerCache.put(cacheKey, invoker);
}
}
if (field != null) {
try {
ReflectionUtils.makeAccessible(field);
Object value = field.get(target);
return new TypedValue(value, invoker.typeDescriptor.narrow(value));
}
catch (Exception ex) {
throw new AccessException("Unable to access field: " + name, ex);
}
}
}
throw new AccessException("Neither getter nor field found for property '" + name + "'");
}
public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
if (target == null) {
return false;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
CacheKey cacheKey = new CacheKey(type, name);
if (this.writerCache.containsKey(cacheKey)) {
return true;
}
Method method = findSetterForProperty(name, type, target instanceof Class);
if (method != null) {
// Treat it like a property
PropertyDescriptor propertyDescriptor = null;
try {
propertyDescriptor = new PropertyDescriptor(name, null, method);
}
catch (IntrospectionException ex) {
throw new AccessException("Unable to access property '" + name + "' through setter "+method, ex);
}
TypeDescriptor typeDescriptor = new TypeDescriptor(type, propertyDescriptor);
this.writerCache.put(cacheKey, method);
this.typeDescriptorCache.put(cacheKey, typeDescriptor);
return true;
}
else {
Field field = findField(name, type, target instanceof Class);
if (field != null) {
this.writerCache.put(cacheKey, field);
this.typeDescriptorCache.put(cacheKey, new TypeDescriptor(field));
return true;
}
}
return false;
}
public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {
if (target == null) {
throw new AccessException("Cannot write property on null target");
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
Object possiblyConvertedNewValue = newValue;
TypeDescriptor typeDescriptor = getTypeDescriptor(context, target, name);
if (typeDescriptor != null) {
try {
possiblyConvertedNewValue = context.getTypeConverter().convertValue(
newValue, TypeDescriptor.forObject(newValue), typeDescriptor);
}
catch (EvaluationException evaluationException) {
throw new AccessException("Type conversion failure",evaluationException);
}
}
CacheKey cacheKey = new CacheKey(type, name);
Member cachedMember = this.writerCache.get(cacheKey);
if (cachedMember == null || cachedMember instanceof Method) {
Method method = (Method) cachedMember;
if (method == null) {
method = findSetterForProperty(name, type, target instanceof Class);
if (method != null) {
cachedMember = method;
this.writerCache.put(cacheKey, cachedMember);
}
}
if (method != null) {
try {
ReflectionUtils.makeAccessible(method);
method.invoke(target, possiblyConvertedNewValue);
return;
}
catch (Exception ex) {
throw new AccessException("Unable to access property '" + name + "' through setter", ex);
}
}
}
if (cachedMember == null || cachedMember instanceof Field) {
Field field = (Field) cachedMember;
if (field == null) {
field = findField(name, type, target instanceof Class);
if (field != null) {
cachedMember = field;
this.writerCache.put(cacheKey, cachedMember);
}
}
if (field != null) {
try {
ReflectionUtils.makeAccessible(field);
field.set(target, possiblyConvertedNewValue);
return;
}
catch (Exception ex) {
throw new AccessException("Unable to access field: " + name, ex);
}
}
}
throw new AccessException("Neither setter nor field found for property '" + name + "'");
}
private TypeDescriptor getTypeDescriptor(EvaluationContext context, Object target, String name) {
if (target == null) {
return null;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray() && name.equals("length")) {
return TypeDescriptor.valueOf(Integer.TYPE);
}
CacheKey cacheKey = new CacheKey(type, name);
TypeDescriptor typeDescriptor = this.typeDescriptorCache.get(cacheKey);
if (typeDescriptor == null) {
// attempt to populate the cache entry
try {
if (canRead(context, target, name)) {
typeDescriptor = this.typeDescriptorCache.get(cacheKey);
}
else if (canWrite(context, target, name)) {
typeDescriptor = this.typeDescriptorCache.get(cacheKey);
}
}
catch (AccessException ex) {
// continue with null type descriptor
}
}
return typeDescriptor;
}
/**
* Find a getter method for the specified property. A getter is defined as a method whose name start with the prefix
* 'get' and the rest of the name is the same as the property name (with the first character uppercased).
*/
protected Method findGetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
Method[] ms = clazz.getMethods();
// Try "get*" method...
String getterName = "get" + StringUtils.capitalize(propertyName);
for (Method method : ms) {
if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 &&
(!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
return method;
}
}
// Try "is*" method...
getterName = "is" + StringUtils.capitalize(propertyName);
for (Method method : ms) {
if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 &&
boolean.class.equals(method.getReturnType()) &&
(!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
return method;
}
}
return null;
}
/**
* Find a setter method for the specified property.
*/
protected Method findSetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
Method[] methods = clazz.getMethods();
String setterName = "set" + StringUtils.capitalize(propertyName);
for (Method method : methods) {
if (method.getName().equals(setterName) && method.getParameterTypes().length == 1 &&
(!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
return method;
}
}
return null;
}
/**
* Find a field of a certain name on a specified class
*/
protected Field findField(String name, Class<?> clazz, boolean mustBeStatic) {
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (field.getName().equals(name) && (!mustBeStatic || Modifier.isStatic(field.getModifiers()))) {
return field;
}
}
return null;
}
/**
* Captures the member (method/field) to call reflectively to access a property value and the type descriptor for the
* value returned by the reflective call.
*/
private static class InvokerPair {
final Member member;
final TypeDescriptor typeDescriptor;
public InvokerPair(Member member, TypeDescriptor typeDescriptor) {
this.member = member;
this.typeDescriptor = typeDescriptor;
}
}
private static class CacheKey {
private final Class clazz;
private final String name;
public CacheKey(Class clazz, String name) {
this.clazz = clazz;
this.name = name;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof CacheKey)) {
return false;
}
CacheKey otherKey = (CacheKey) other;
return (this.clazz.equals(otherKey.clazz) && this.name.equals(otherKey.name));
}
@Override
public int hashCode() {
return this.clazz.hashCode() * 29 + this.name.hashCode();
}
}
/**
* Attempt to create an optimized property accessor tailored for a property of a particular name on
* a particular class. The general ReflectivePropertyAccessor will always work but is not optimal
* due to the need to lookup which reflective member (method/field) to use each time read() is called.
* This method will just return the ReflectivePropertyAccessor instance if it is unable to build
* something more optimal.
*/
public PropertyAccessor createOptimalAccessor(EvaluationContext eContext, Object target, String name) {
// Don't be clever for arrays or null target
if (target == null) {
return this;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray()) {
return this;
}
CacheKey cacheKey = new CacheKey(type, name);
InvokerPair invocationTarget = this.readerCache.get(cacheKey);
if (invocationTarget == null || invocationTarget.member instanceof Method) {
Method method = (Method) (invocationTarget==null?null:invocationTarget.member);
if (method == null) {
method = findGetterForProperty(name, type, target instanceof Class);
if (method != null) {
invocationTarget = new InvokerPair(method,new TypeDescriptor(new MethodParameter(method,-1)));
ReflectionUtils.makeAccessible(method);
this.readerCache.put(cacheKey, invocationTarget);
}
}
if (method != null) {
return new OptimalPropertyAccessor(invocationTarget);
}
}
if (invocationTarget == null || invocationTarget.member instanceof Field) {
Field field = (Field) (invocationTarget==null?null:invocationTarget.member);
if (field == null) {
field = findField(name, type, target instanceof Class);
if (field != null) {
invocationTarget = new InvokerPair(field, new TypeDescriptor(field));
ReflectionUtils.makeAccessible(field);
this.readerCache.put(cacheKey, invocationTarget);
}
}
if (field != null) {
return new OptimalPropertyAccessor(invocationTarget);
}
}
return this;
}
/**
* An optimized form of a PropertyAccessor that will use reflection but only knows how to access a particular property
* on a particular class. This is unlike the general ReflectivePropertyResolver which manages a cache of methods/fields that
* may be invoked to access different properties on different classes. This optimal accessor exists because looking up
* the appropriate reflective object by class/name on each read is not cheap.
*/
static class OptimalPropertyAccessor implements PropertyAccessor {
private final Member member;
private final TypeDescriptor typeDescriptor;
private final boolean needsToBeMadeAccessible;
OptimalPropertyAccessor(InvokerPair target) {
this.member = target.member;
this.typeDescriptor = target.typeDescriptor;
if (this.member instanceof Field) {
Field field = (Field)member;
needsToBeMadeAccessible = (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()))
&& !field.isAccessible();
}
else {
Method method = (Method)member;
needsToBeMadeAccessible = ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible());
}
}
public Class[] getSpecificTargetClasses() {
throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor");
}
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
if (target == null) {
return false;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray()) {
return false;
}
if (member instanceof Method) {
Method method = (Method)member;
String getterName = "get" + StringUtils.capitalize(name);
if (getterName.equals(method.getName())) {
return true;
}
getterName = "is" + StringUtils.capitalize(name);
return getterName.equals(method.getName());
}
else {
Field field = (Field)member;
return field.getName().equals(name);
}
}
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
if (member instanceof Method) {
try {
if (needsToBeMadeAccessible) {
ReflectionUtils.makeAccessible((Method) member);
}
Object value = ((Method) member).invoke(target);
return new TypedValue(value, typeDescriptor.narrow(value));
}
catch (Exception ex) {
throw new AccessException("Unable to access property '" + name + "' through getter", ex);
}
}
if (member instanceof Field) {
try {
if (needsToBeMadeAccessible) {
ReflectionUtils.makeAccessible((Field)member);
}
Object value = ((Field)member).get(target);
return new TypedValue(value, typeDescriptor.narrow(value));
}
catch (Exception ex) {
throw new AccessException("Unable to access field: " + name, ex);
}
}
throw new AccessException("Neither getter nor field found for property '" + name + "'");
}
public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor");
}
public void write(EvaluationContext context, Object target, String name, Object newValue)
throws AccessException {
throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor");
}
}
}
| org.springframework.expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java | /*
* Copyright 2002-2011 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.expression.spel.support;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* Simple PropertyAccessor that uses reflection to access properties for reading and writing. A property can be accessed
* if it is accessible as a field on the object or through a getter (if being read) or a setter (if being written).
*
* @author Andy Clement
* @author Juergen Hoeller
* @since 3.0
*/
public class ReflectivePropertyAccessor implements PropertyAccessor {
protected final Map<CacheKey, InvokerPair> readerCache = new ConcurrentHashMap<CacheKey, InvokerPair>();
protected final Map<CacheKey, Member> writerCache = new ConcurrentHashMap<CacheKey, Member>();
protected final Map<CacheKey, TypeDescriptor> typeDescriptorCache = new ConcurrentHashMap<CacheKey, TypeDescriptor>();
/**
* @return null which means this is a general purpose accessor
*/
public Class<?>[] getSpecificTargetClasses() {
return null;
}
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
if (target == null) {
return false;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray() && name.equals("length")) {
return true;
}
CacheKey cacheKey = new CacheKey(type, name);
if (this.readerCache.containsKey(cacheKey)) {
return true;
}
Method method = findGetterForProperty(name, type, target instanceof Class);
if (method != null) {
// Treat it like a property
try {
// The readerCache will only contain gettable properties (let's not worry about setters for now)
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, method, null);
TypeDescriptor typeDescriptor = new TypeDescriptor(type, propertyDescriptor);
this.readerCache.put(cacheKey, new InvokerPair(method, typeDescriptor));
this.typeDescriptorCache.put(cacheKey, typeDescriptor);
return true;
}
catch (IntrospectionException ex) {
throw new AccessException("Unable to access property '" + name + "' through getter " + method, ex);
}
}
else {
Field field = findField(name, type, target instanceof Class);
if (field != null) {
TypeDescriptor typeDescriptor = new TypeDescriptor(field);
this.readerCache.put(cacheKey, new InvokerPair(field,typeDescriptor));
this.typeDescriptorCache.put(cacheKey, typeDescriptor);
return true;
}
}
return false;
}
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
if (target == null) {
throw new AccessException("Cannot read property of null target");
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray() && name.equals("length")) {
if (target instanceof Class) {
throw new AccessException("Cannot access length on array class itself");
}
return new TypedValue(Array.getLength(target));
}
CacheKey cacheKey = new CacheKey(type, name);
InvokerPair invoker = this.readerCache.get(cacheKey);
if (invoker == null || invoker.member instanceof Method) {
Method method = (Method) (invoker != null ? invoker.member : null);
if (method == null) {
method = findGetterForProperty(name, type, target instanceof Class);
if (method != null) {
// TODO remove the duplication here between canRead and read
// Treat it like a property
try {
// The readerCache will only contain gettable properties (let's not worry about setters for now)
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, method, null);
TypeDescriptor typeDescriptor = new TypeDescriptor(type, propertyDescriptor);
invoker = new InvokerPair(method, typeDescriptor);
this.readerCache.put(cacheKey, invoker);
}
catch (IntrospectionException ex) {
throw new AccessException(
"Unable to access property '" + name + "' through getter " + method, ex);
}
}
}
if (method != null) {
try {
ReflectionUtils.makeAccessible(method);
return new TypedValue(method.invoke(target),invoker.typeDescriptor);
}
catch (Exception ex) {
throw new AccessException("Unable to access property '" + name + "' through getter", ex);
}
}
}
if (invoker == null || invoker.member instanceof Field) {
Field field = (Field) (invoker==null?null:invoker.member);
if (field == null) {
field = findField(name, type, target instanceof Class);
if (field != null) {
invoker = new InvokerPair(field, new TypeDescriptor(field));
this.readerCache.put(cacheKey, invoker);
}
}
if (field != null) {
try {
ReflectionUtils.makeAccessible(field);
return new TypedValue(field.get(target),invoker.typeDescriptor);
}
catch (Exception ex) {
throw new AccessException("Unable to access field: " + name, ex);
}
}
}
throw new AccessException("Neither getter nor field found for property '" + name + "'");
}
public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
if (target == null) {
return false;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
CacheKey cacheKey = new CacheKey(type, name);
if (this.writerCache.containsKey(cacheKey)) {
return true;
}
Method method = findSetterForProperty(name, type, target instanceof Class);
if (method != null) {
// Treat it like a property
PropertyDescriptor propertyDescriptor = null;
try {
propertyDescriptor = new PropertyDescriptor(name,null,method);
}
catch (IntrospectionException ex) {
throw new AccessException("Unable to access property '" + name + "' through setter "+method, ex);
}
TypeDescriptor typeDescriptor = new TypeDescriptor(type, propertyDescriptor);
this.writerCache.put(cacheKey, method);
this.typeDescriptorCache.put(cacheKey, typeDescriptor);
return true;
}
else {
Field field = findField(name, type, target instanceof Class);
if (field != null) {
this.writerCache.put(cacheKey, field);
this.typeDescriptorCache.put(cacheKey, new TypeDescriptor(field));
return true;
}
}
return false;
}
public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {
if (target == null) {
throw new AccessException("Cannot write property on null target");
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
Object possiblyConvertedNewValue = newValue;
TypeDescriptor typeDescriptor = getTypeDescriptor(context, target, name);
if (typeDescriptor != null) {
try {
possiblyConvertedNewValue = context.getTypeConverter().convertValue(
newValue, TypeDescriptor.forObject(newValue), typeDescriptor);
}
catch (EvaluationException evaluationException) {
throw new AccessException("Type conversion failure",evaluationException);
}
}
CacheKey cacheKey = new CacheKey(type, name);
Member cachedMember = this.writerCache.get(cacheKey);
if (cachedMember == null || cachedMember instanceof Method) {
Method method = (Method) cachedMember;
if (method == null) {
method = findSetterForProperty(name, type, target instanceof Class);
if (method != null) {
cachedMember = method;
this.writerCache.put(cacheKey, cachedMember);
}
}
if (method != null) {
try {
ReflectionUtils.makeAccessible(method);
method.invoke(target, possiblyConvertedNewValue);
return;
}
catch (Exception ex) {
throw new AccessException("Unable to access property '" + name + "' through setter", ex);
}
}
}
if (cachedMember == null || cachedMember instanceof Field) {
Field field = (Field) cachedMember;
if (field == null) {
field = findField(name, type, target instanceof Class);
if (field != null) {
cachedMember = field;
this.writerCache.put(cacheKey, cachedMember);
}
}
if (field != null) {
try {
ReflectionUtils.makeAccessible(field);
field.set(target, possiblyConvertedNewValue);
return;
}
catch (Exception ex) {
throw new AccessException("Unable to access field: " + name, ex);
}
}
}
throw new AccessException("Neither setter nor field found for property '" + name + "'");
}
private TypeDescriptor getTypeDescriptor(EvaluationContext context, Object target, String name) {
if (target == null) {
return null;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray() && name.equals("length")) {
return TypeDescriptor.valueOf(Integer.TYPE);
}
CacheKey cacheKey = new CacheKey(type, name);
TypeDescriptor typeDescriptor = this.typeDescriptorCache.get(cacheKey);
if (typeDescriptor == null) {
// attempt to populate the cache entry
try {
if (canRead(context, target, name)) {
typeDescriptor = this.typeDescriptorCache.get(cacheKey);
}
else if (canWrite(context, target, name)) {
typeDescriptor = this.typeDescriptorCache.get(cacheKey);
}
}
catch (AccessException ex) {
// continue with null type descriptor
}
}
return typeDescriptor;
}
/**
* Find a getter method for the specified property. A getter is defined as a method whose name start with the prefix
* 'get' and the rest of the name is the same as the property name (with the first character uppercased).
*/
protected Method findGetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
Method[] ms = clazz.getMethods();
// Try "get*" method...
String getterName = "get" + StringUtils.capitalize(propertyName);
for (Method method : ms) {
if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 &&
(!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
return method;
}
}
// Try "is*" method...
getterName = "is" + StringUtils.capitalize(propertyName);
for (Method method : ms) {
if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 &&
boolean.class.equals(method.getReturnType()) &&
(!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
return method;
}
}
return null;
}
/**
* Find a setter method for the specified property.
*/
protected Method findSetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
Method[] methods = clazz.getMethods();
String setterName = "set" + StringUtils.capitalize(propertyName);
for (Method method : methods) {
if (method.getName().equals(setterName) && method.getParameterTypes().length == 1 &&
(!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
return method;
}
}
return null;
}
/**
* Find a field of a certain name on a specified class
*/
protected Field findField(String name, Class<?> clazz, boolean mustBeStatic) {
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (field.getName().equals(name) && (!mustBeStatic || Modifier.isStatic(field.getModifiers()))) {
return field;
}
}
return null;
}
/**
* Captures the member (method/field) to call reflectively to access a property value and the type descriptor for the
* value returned by the reflective call.
*/
private static class InvokerPair {
final Member member;
final TypeDescriptor typeDescriptor;
public InvokerPair(Member member, TypeDescriptor typeDescriptor) {
this.member = member;
this.typeDescriptor = typeDescriptor;
}
}
private static class CacheKey {
private final Class clazz;
private final String name;
public CacheKey(Class clazz, String name) {
this.clazz = clazz;
this.name = name;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof CacheKey)) {
return false;
}
CacheKey otherKey = (CacheKey) other;
return (this.clazz.equals(otherKey.clazz) && this.name.equals(otherKey.name));
}
@Override
public int hashCode() {
return this.clazz.hashCode() * 29 + this.name.hashCode();
}
}
/**
* Attempt to create an optimized property accessor tailored for a property of a particular name on
* a particular class. The general ReflectivePropertyAccessor will always work but is not optimal
* due to the need to lookup which reflective member (method/field) to use each time read() is called.
* This method will just return the ReflectivePropertyAccessor instance if it is unable to build
* something more optimal.
*/
public PropertyAccessor createOptimalAccessor(EvaluationContext eContext, Object target, String name) {
// Don't be clever for arrays or null target
if (target == null) {
return this;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray()) {
return this;
}
CacheKey cacheKey = new CacheKey(type, name);
InvokerPair invocationTarget = this.readerCache.get(cacheKey);
if (invocationTarget == null || invocationTarget.member instanceof Method) {
Method method = (Method) (invocationTarget==null?null:invocationTarget.member);
if (method == null) {
method = findGetterForProperty(name, type, target instanceof Class);
if (method != null) {
invocationTarget = new InvokerPair(method,new TypeDescriptor(new MethodParameter(method,-1)));
ReflectionUtils.makeAccessible(method);
this.readerCache.put(cacheKey, invocationTarget);
}
}
if (method != null) {
return new OptimalPropertyAccessor(invocationTarget);
}
}
if (invocationTarget == null || invocationTarget.member instanceof Field) {
Field field = (Field) (invocationTarget==null?null:invocationTarget.member);
if (field == null) {
field = findField(name, type, target instanceof Class);
if (field != null) {
invocationTarget = new InvokerPair(field, new TypeDescriptor(field));
ReflectionUtils.makeAccessible(field);
this.readerCache.put(cacheKey, invocationTarget);
}
}
if (field != null) {
return new OptimalPropertyAccessor(invocationTarget);
}
}
return this;
}
/**
* An optimized form of a PropertyAccessor that will use reflection but only knows how to access a particular property
* on a particular class. This is unlike the general ReflectivePropertyResolver which manages a cache of methods/fields that
* may be invoked to access different properties on different classes. This optimal accessor exists because looking up
* the appropriate reflective object by class/name on each read is not cheap.
*/
static class OptimalPropertyAccessor implements PropertyAccessor {
private final Member member;
private final TypeDescriptor typeDescriptor;
private final boolean needsToBeMadeAccessible;
OptimalPropertyAccessor(InvokerPair target) {
this.member = target.member;
this.typeDescriptor = target.typeDescriptor;
if (this.member instanceof Field) {
Field field = (Field)member;
needsToBeMadeAccessible = (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()))
&& !field.isAccessible();
}
else {
Method method = (Method)member;
needsToBeMadeAccessible = ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible());
}
}
public Class[] getSpecificTargetClasses() {
throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor");
}
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
if (target == null) {
return false;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
if (type.isArray()) {
return false;
}
if (member instanceof Method) {
Method method = (Method)member;
String getterName = "get" + StringUtils.capitalize(name);
if (getterName.equals(method.getName())) {
return true;
}
getterName = "is" + StringUtils.capitalize(name);
return getterName.equals(method.getName());
}
else {
Field field = (Field)member;
return field.getName().equals(name);
}
}
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
if (member instanceof Method) {
try {
if (needsToBeMadeAccessible) {
ReflectionUtils.makeAccessible((Method) member);
}
Object value = ((Method) member).invoke(target);
return new TypedValue(value, typeDescriptor.narrow(value));
}
catch (Exception ex) {
throw new AccessException("Unable to access property '" + name + "' through getter", ex);
}
}
if (member instanceof Field) {
try {
if (needsToBeMadeAccessible) {
ReflectionUtils.makeAccessible((Field)member);
}
Object value = ((Field)member).get(target);
return new TypedValue(value, typeDescriptor.narrow(value));
}
catch (Exception ex) {
throw new AccessException("Unable to access field: " + name, ex);
}
}
throw new AccessException("Neither getter nor field found for property '" + name + "'");
}
public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor");
}
public void write(EvaluationContext context, Object target, String name, Object newValue)
throws AccessException {
throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor");
}
}
}
| perform narrowing in reflective property accessor read methods as well
| org.springframework.expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java | perform narrowing in reflective property accessor read methods as well | <ide><path>rg.springframework.expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java
<ide> if (method != null) {
<ide> try {
<ide> ReflectionUtils.makeAccessible(method);
<del> return new TypedValue(method.invoke(target),invoker.typeDescriptor);
<add> Object value = method.invoke(target);
<add> return new TypedValue(value, invoker.typeDescriptor.narrow(value));
<ide> }
<ide> catch (Exception ex) {
<ide> throw new AccessException("Unable to access property '" + name + "' through getter", ex);
<ide> }
<ide>
<ide> if (invoker == null || invoker.member instanceof Field) {
<del> Field field = (Field) (invoker==null?null:invoker.member);
<add> Field field = (Field) (invoker == null ? null : invoker.member);
<ide> if (field == null) {
<ide> field = findField(name, type, target instanceof Class);
<ide> if (field != null) {
<ide> if (field != null) {
<ide> try {
<ide> ReflectionUtils.makeAccessible(field);
<del> return new TypedValue(field.get(target),invoker.typeDescriptor);
<add> Object value = field.get(target);
<add> return new TypedValue(value, invoker.typeDescriptor.narrow(value));
<ide> }
<ide> catch (Exception ex) {
<ide> throw new AccessException("Unable to access field: " + name, ex);
<ide> // Treat it like a property
<ide> PropertyDescriptor propertyDescriptor = null;
<ide> try {
<del> propertyDescriptor = new PropertyDescriptor(name,null,method);
<add> propertyDescriptor = new PropertyDescriptor(name, null, method);
<ide> }
<ide> catch (IntrospectionException ex) {
<ide> throw new AccessException("Unable to access property '" + name + "' through setter "+method, ex); |
|
Java | apache-2.0 | 49552300f8ec5afde7fe5fdaeed9a681986792e0 | 0 | zerem/vax,ohmdrj/vax | package cz.req.ax;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.Id;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author by Ondřej Buriánek, [email protected].
* @since 7.9.15
*/
public class ObjectIdentity {
private static final Logger logger = LoggerFactory.getLogger(ObjectIdentity.class);
static final Map<Class, Method> map = new LinkedHashMap<>();
public static Integer id(Object object) {
//TODO Burianek support Number?
return idInteger(object);
}
public static Integer idInteger(Object object) {
if (object == null) return null;
try {
return (Integer) method(object.getClass()).invoke(object);
} catch (Exception e) {
throw new RuntimeException("Identity exception", e);
}
}
private static Method method(Class clazz) {
Method method = map.get(clazz);
if (method != null) return method;
/*try {
for (PropertyDescriptor descriptor : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
if (descriptor.get )
}
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}*/
PropertyDescriptor descriptor = property(clazz);
//TODO Burianek Id annotation on getter?
if (descriptor == null)
throw new IllegalArgumentException("Missing Id annotation at class " + clazz.getCanonicalName());
method = descriptor.getReadMethod();
map.put(clazz, method);
return method;
}
public static PropertyDescriptor property(Class clazz) {
for (Field field : fields(new LinkedList<>(), clazz)) {
try {
Id annotation = field.getDeclaredAnnotation(Id.class);
if (annotation != null) {
return new PropertyDescriptor(field.getName(), clazz);
}
} catch (Exception e) {
logger.warn("Failed to create PropertyDescriptor for {}: {}", field.getName(), e.getMessage());
}
}
return null;
}
static List<Field> fields(List<Field> fields, Class<?> type) {
fields.addAll(Arrays.asList(type.getDeclaredFields()));
if (type.getSuperclass() != null) {
fields = fields(fields, type.getSuperclass());
}
return fields;
}
}
| src/main/java/cz/req/ax/ObjectIdentity.java | package cz.req.ax;
import javax.persistence.Id;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author by Ondřej Buriánek, [email protected].
* @since 7.9.15
*/
public class ObjectIdentity {
static final Map<Class, Method> map = new LinkedHashMap<>();
public static Integer id(Object object) {
//TODO Burianek support Number?
return idInteger(object);
}
public static Integer idInteger(Object object) {
if (object == null) return null;
try {
return (Integer) method(object.getClass()).invoke(object);
} catch (Exception e) {
throw new RuntimeException("Identity exception", e);
}
}
private static Method method(Class clazz) {
Method method = map.get(clazz);
if (method != null) return method;
/*try {
for (PropertyDescriptor descriptor : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
if (descriptor.get )
}
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}*/
PropertyDescriptor descriptor = property(clazz);
//TODO Burianek Id annotation on getter?
if (descriptor == null)
throw new IllegalArgumentException("Missing Id annotation at class " + clazz.getCanonicalName());
method = descriptor.getReadMethod();
map.put(clazz, method);
return method;
}
public static PropertyDescriptor property(Class clazz) {
PropertyDescriptor descriptor = null;
for (Field field : fields(new LinkedList<>(), clazz)) {
try {
Id annotation = field.getDeclaredAnnotation(Id.class);
if (annotation == null) continue;
descriptor = new PropertyDescriptor(field.getName(), clazz);
} catch (Exception ex) {
//Preskocime
}
}
return descriptor;
}
static List<Field> fields(List<Field> fields, Class<?> type) {
fields.addAll(Arrays.asList(type.getDeclaredFields()));
if (type.getSuperclass() != null) {
fields = fields(fields, type.getSuperclass());
}
return fields;
}
}
| Log exception - ObjectIdentity
| src/main/java/cz/req/ax/ObjectIdentity.java | Log exception - ObjectIdentity | <ide><path>rc/main/java/cz/req/ax/ObjectIdentity.java
<ide> package cz.req.ax;
<ide>
<add>
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<ide>
<ide> import javax.persistence.Id;
<ide> import java.beans.PropertyDescriptor;
<ide> */
<ide> public class ObjectIdentity {
<ide>
<add> private static final Logger logger = LoggerFactory.getLogger(ObjectIdentity.class);
<ide> static final Map<Class, Method> map = new LinkedHashMap<>();
<ide>
<ide> public static Integer id(Object object) {
<ide> }
<ide>
<ide> public static PropertyDescriptor property(Class clazz) {
<del> PropertyDescriptor descriptor = null;
<del>
<ide> for (Field field : fields(new LinkedList<>(), clazz)) {
<ide> try {
<ide> Id annotation = field.getDeclaredAnnotation(Id.class);
<del> if (annotation == null) continue;
<del> descriptor = new PropertyDescriptor(field.getName(), clazz);
<del> } catch (Exception ex) {
<del> //Preskocime
<add> if (annotation != null) {
<add> return new PropertyDescriptor(field.getName(), clazz);
<add> }
<add> } catch (Exception e) {
<add> logger.warn("Failed to create PropertyDescriptor for {}: {}", field.getName(), e.getMessage());
<ide> }
<ide> }
<del> return descriptor;
<add> return null;
<ide> }
<ide>
<ide> static List<Field> fields(List<Field> fields, Class<?> type) { |
|
Java | apache-2.0 | 804320b37b0f6b00f5aa21eb32a97211727202e0 | 0 | d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor | /**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package com.netflix.conductor.dao.es5.index;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.Uninterruptibles;
import com.netflix.conductor.annotations.Trace;
import com.netflix.conductor.common.metadata.events.EventExecution;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskExecLog;
import com.netflix.conductor.common.run.SearchResult;
import com.netflix.conductor.common.run.TaskSummary;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.common.run.WorkflowSummary;
import com.netflix.conductor.core.config.Configuration;
import com.netflix.conductor.core.events.queue.Message;
import com.netflix.conductor.core.execution.ApplicationException;
import com.netflix.conductor.core.execution.ApplicationException.Code;
import com.netflix.conductor.dao.IndexDAO;
import com.netflix.conductor.dao.es5.index.query.parser.Expression;
import com.netflix.conductor.dao.es5.index.query.parser.ParserException;
import com.netflix.conductor.metrics.Monitors;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.ResourceAlreadyExistsException;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.get.GetField;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author Viren
*
*/
@Trace
@Singleton
public class ElasticSearch5DAO implements IndexDAO {
private static Logger log = LoggerFactory.getLogger(ElasticSearch5DAO.class);
private static final String WORKFLOW_DOC_TYPE = "workflow";
private static final String TASK_DOC_TYPE = "task";
private static final String LOG_DOC_TYPE = "task";
private static final String EVENT_DOC_TYPE = "event";
private static final String MSG_DOC_TYPE = "message";
private static final String className = ElasticSearch5DAO.class.getSimpleName();
private String indexName;
private String logIndexName;
private String logIndexPrefix;
private ObjectMapper om;
private Client client;
private static final TimeZone gmt = TimeZone.getTimeZone("GMT");
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMww");
static {
sdf.setTimeZone(gmt);
}
@Inject
public ElasticSearch5DAO(Client client, Configuration config, ObjectMapper om) {
this.om = om;
this.client = client;
this.indexName = config.getProperty("workflow.elasticsearch.index.name", null);
try {
initIndex();
updateIndexName(config);
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> updateIndexName(config), 0, 1, TimeUnit.HOURS);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private void updateIndexName(Configuration config) {
this.logIndexPrefix = config.getProperty("workflow.elasticsearch.tasklog.index.name", "task_log");
this.logIndexName = this.logIndexPrefix + "_" + sdf.format(new Date());
try {
client.admin().indices().prepareGetIndex().addIndices(logIndexName).execute().actionGet();
} catch (IndexNotFoundException infe) {
try {
client.admin().indices().prepareCreate(logIndexName).execute().actionGet();
} catch (ResourceAlreadyExistsException ilee) {
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
/**
* Initializes the index with required templates and mappings.
*/
private void initIndex() throws Exception {
// //0. Add the index template
// GetIndexTemplatesResponse result = client.admin().indices().prepareGetTemplates("wfe_template").execute().actionGet();
// if(result.getIndexTemplates().isEmpty()) {
// log.info("Creating the index template 'wfe_template'");
// InputStream stream = ElasticSearch5DAO.class.getResourceAsStream("/template.json");
// byte[] templateSource = IOUtils.toByteArray(stream);
//
// try {
// client.admin().indices().preparePutTemplate("wfe_template").setSource(templateSource, XContentType.JSON).execute().actionGet();
// }catch(Exception e) {
// log.error(e.getMessage(), e);
// }
// }
//1. Create the required index
try {
client.admin().indices().prepareGetIndex().addIndices(indexName).execute().actionGet();
}catch(IndexNotFoundException infe) {
try {
client.admin().indices().prepareCreate(indexName).execute().actionGet();
}catch(ResourceAlreadyExistsException done) {}
}
// //2. Mapping for the workflow document type
// GetMappingsResponse response = client.admin().indices().prepareGetMappings(indexName).addTypes(WORKFLOW_DOC_TYPE).execute().actionGet();
// if(response.mappings().isEmpty()) {
// log.info("Adding the workflow type mappings");
// InputStream stream = ElasticSearch5DAO.class.getResourceAsStream("/wfe_type.json");
// byte[] bytes = IOUtils.toByteArray(stream);
// String source = new String(bytes);
// try {
// client.admin().indices().preparePutMapping(indexName).setType(WORKFLOW_DOC_TYPE).setSource(source).execute().actionGet();
// }catch(Exception e) {
// log.error(e.getMessage(), e);
// }
// }
}
@Override
public void index(Workflow workflow) {
try {
String id = workflow.getWorkflowId();
WorkflowSummary summary = new WorkflowSummary(workflow);
byte[] doc = om.writeValueAsBytes(summary);
UpdateRequest req = new UpdateRequest(indexName, WORKFLOW_DOC_TYPE, id);
req.doc(doc, XContentType.JSON);
req.upsert(doc, XContentType.JSON);
req.retryOnConflict(5);
updateWithRetry(req);
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
}
}
@Override
public void index(Task task) {
try {
String id = task.getTaskId();
TaskSummary summary = new TaskSummary(task);
byte[] doc = om.writeValueAsBytes(summary);
UpdateRequest req = new UpdateRequest(indexName, TASK_DOC_TYPE, id);
req.doc(doc, XContentType.JSON);
req.upsert(doc, XContentType.JSON);
updateWithRetry(req);
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
}
}
@Override
public void add(List<TaskExecLog> logs) {
if (logs == null || logs.isEmpty()) {
return;
}
int retry = 3;
while(retry > 0) {
try {
BulkRequestBuilder brb = client.prepareBulk();
for(TaskExecLog log : logs) {
IndexRequest request = new IndexRequest(logIndexName, LOG_DOC_TYPE);
request.source(om.writeValueAsBytes(log), XContentType.JSON);
brb.add(request);
}
BulkResponse response = brb.execute().actionGet();
if(!response.hasFailures()) {
break;
}
retry--;
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
retry--;
if(retry > 0) {
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
}
}
}
@Override
public List<TaskExecLog> getTaskLogs(String taskId) {
try {
QueryBuilder qf = QueryBuilders.matchAllQuery();
Expression expression = Expression.fromString("taskId='" + taskId + "'");
qf = expression.getFilterBuilder();
BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(qf);
QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*");
BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
final SearchRequestBuilder srb = client.prepareSearch(logIndexPrefix + "*").setQuery(fq).setTypes(TASK_DOC_TYPE);
SearchResponse response = srb.execute().actionGet();
SearchHit[] hits = response.getHits().getHits();
List<TaskExecLog> logs = new ArrayList<>(hits.length);
for(SearchHit hit : hits) {
String source = hit.getSourceAsString();
TaskExecLog tel = om.readValue(source, TaskExecLog.class);
logs.add(tel);
}
return logs;
}catch(Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
@Override
public void addMessage(String queue, Message msg) {
int retry = 3;
while(retry > 0) {
try {
Map<String, Object> doc = new HashMap<>();
doc.put("messageId", msg.getId());
doc.put("payload", msg.getPayload());
doc.put("queue", queue);
doc.put("created", System.currentTimeMillis());
IndexRequest request = new IndexRequest(logIndexName, MSG_DOC_TYPE);
request.source(doc);
client.index(request).actionGet();
break;
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
retry--;
if(retry > 0) {
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
}
}
}
@Override
public void add(EventExecution ee) {
try {
byte[] doc = om.writeValueAsBytes(ee);
String id = ee.getName() + "." + ee.getEvent() + "." + ee.getMessageId() + "." + ee.getId();
UpdateRequest req = new UpdateRequest(logIndexName, EVENT_DOC_TYPE, id);
req.doc(doc, XContentType.JSON);
req.upsert(doc, XContentType.JSON);
req.retryOnConflict(5);
updateWithRetry(req);
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
}
}
private void updateWithRetry(UpdateRequest request) {
int retry = 3;
while(retry > 0) {
try {
client.update(request).actionGet();
return;
}catch(Exception e) {
Monitors.error(className, "index");
log.error("Indexing failed for {}, {}: {}", request.index(), request.type(), e.getMessage(), e);
retry--;
if(retry > 0) {
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
}
}
}
}
@Override
public SearchResult<String> searchWorkflows(String query, String freeText, int start, int count, List<String> sort) {
try {
return search(query, start, count, sort, freeText);
} catch (ParserException e) {
throw new ApplicationException(Code.BACKEND_ERROR, e.getMessage(), e);
}
}
@Override
public void remove(String workflowId) {
try {
DeleteRequest req = new DeleteRequest(indexName, WORKFLOW_DOC_TYPE, workflowId);
DeleteResponse response = client.delete(req).actionGet();
if (response.getResult() == DocWriteResponse.Result.DELETED) {
log.error("Index removal failed - document not found by id " + workflowId);
}
} catch (Throwable e) {
log.error("Index removal failed failed {}", e.getMessage(), e);
Monitors.error(className, "remove");
}
}
@Override
public void update(String workflowInstanceId, String[] keys, Object[] values) {
if(keys.length != values.length) {
throw new IllegalArgumentException("Number of keys and values should be same.");
}
UpdateRequest request = new UpdateRequest(indexName, WORKFLOW_DOC_TYPE, workflowInstanceId);
Map<String, Object> source = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
Object value= values[i];
log.debug("updating {} with {} and {}", workflowInstanceId, key, value);
source.put(key, value);
}
request.doc(source);
ActionFuture<UpdateResponse> response = client.update(request);
response.actionGet();
}
@Override
public String get(String workflowInstanceId, String fieldToGet) {
Object value = null;
GetRequest request = new GetRequest(indexName, WORKFLOW_DOC_TYPE, workflowInstanceId).storedFields(fieldToGet);
GetResponse response = client.get(request).actionGet();
Map<String, GetField> fields = response.getFields();
if(fields == null) {
return null;
}
GetField field = fields.get(fieldToGet);
if(field != null) value = field.getValue();
if(value != null) {
return value.toString();
}
return null;
}
private SearchResult<String> search(String structuredQuery, int start, int size, List<String> sortOptions, String freeTextQuery) throws ParserException {
QueryBuilder qf = QueryBuilders.matchAllQuery();
if(StringUtils.isNotEmpty(structuredQuery)) {
Expression expression = Expression.fromString(structuredQuery);
qf = expression.getFilterBuilder();
}
BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(qf);
QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(freeTextQuery);
BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
final SearchRequestBuilder srb = client.prepareSearch(indexName).setQuery(fq).setTypes(WORKFLOW_DOC_TYPE).storedFields("_id").setFrom(start).setSize(size);
if(sortOptions != null){
sortOptions.forEach(sortOption -> {
SortOrder order = SortOrder.ASC;
String field = sortOption;
int indx = sortOption.indexOf(':');
if(indx > 0){ //Can't be 0, need the field name at-least
field = sortOption.substring(0, indx);
order = SortOrder.valueOf(sortOption.substring(indx+1));
}
srb.addSort(field, order);
});
}
List<String> result = new LinkedList<String>();
SearchResponse response = srb.get();
response.getHits().forEach(hit -> {
result.add(hit.getId());
});
long count = response.getHits().getTotalHits();
return new SearchResult<String>(count, result);
}
}
| es5-persistence/src/main/java/com/netflix/conductor/dao/es5/index/ElasticSearch5DAO.java | /**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package com.netflix.conductor.dao.es5.index;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.Uninterruptibles;
import com.netflix.conductor.annotations.Trace;
import com.netflix.conductor.common.metadata.events.EventExecution;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskExecLog;
import com.netflix.conductor.common.run.SearchResult;
import com.netflix.conductor.common.run.TaskSummary;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.common.run.WorkflowSummary;
import com.netflix.conductor.core.config.Configuration;
import com.netflix.conductor.core.events.queue.Message;
import com.netflix.conductor.core.execution.ApplicationException;
import com.netflix.conductor.core.execution.ApplicationException.Code;
import com.netflix.conductor.dao.IndexDAO;
import com.netflix.conductor.dao.es5.index.query.parser.Expression;
import com.netflix.conductor.dao.es5.index.query.parser.ParserException;
import com.netflix.conductor.metrics.Monitors;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.ResourceAlreadyExistsException;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.get.GetField;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author Viren
*
*/
@Trace
@Singleton
public class ElasticSearch5DAO implements IndexDAO {
private static Logger log = LoggerFactory.getLogger(ElasticSearch5DAO.class);
private static final String WORKFLOW_DOC_TYPE = "workflow";
private static final String TASK_DOC_TYPE = "task";
private static final String LOG_DOC_TYPE = "task";
private static final String EVENT_DOC_TYPE = "event";
private static final String MSG_DOC_TYPE = "message";
private static final String className = ElasticSearch5DAO.class.getSimpleName();
private String indexName;
private String logIndexName;
private String logIndexPrefix;
private ObjectMapper om;
private Client client;
private static final TimeZone gmt = TimeZone.getTimeZone("GMT");
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMww");
static {
sdf.setTimeZone(gmt);
}
@Inject
public ElasticSearch5DAO(Client client, Configuration config, ObjectMapper om) {
this.om = om;
this.client = client;
this.indexName = config.getProperty("workflow.elasticsearch.index.name", null);
try {
initIndex();
updateIndexName(config);
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> updateIndexName(config), 0, 1, TimeUnit.HOURS);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private void updateIndexName(Configuration config) {
this.logIndexPrefix = config.getProperty("workflow.elasticsearch.tasklog.index.name", "task_log");
this.logIndexName = this.logIndexPrefix + "_" + sdf.format(new Date());
try {
client.admin().indices().prepareGetIndex().addIndices(logIndexName).execute().actionGet();
} catch (IndexNotFoundException infe) {
try {
client.admin().indices().prepareCreate(logIndexName).execute().actionGet();
} catch (ResourceAlreadyExistsException ilee) {
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
/**
* Initializes the index with required templates and mappings.
*/
private void initIndex() throws Exception {
// //0. Add the index template
// GetIndexTemplatesResponse result = client.admin().indices().prepareGetTemplates("wfe_template").execute().actionGet();
// if(result.getIndexTemplates().isEmpty()) {
// log.info("Creating the index template 'wfe_template'");
// InputStream stream = ElasticSearch5DAO.class.getResourceAsStream("/template.json");
// byte[] templateSource = IOUtils.toByteArray(stream);
//
// try {
// client.admin().indices().preparePutTemplate("wfe_template").setSource(templateSource, XContentType.JSON).execute().actionGet();
// }catch(Exception e) {
// log.error(e.getMessage(), e);
// }
// }
//1. Create the required index
try {
client.admin().indices().prepareGetIndex().addIndices(indexName).execute().actionGet();
}catch(IndexNotFoundException infe) {
try {
client.admin().indices().prepareCreate(indexName).execute().actionGet();
}catch(ResourceAlreadyExistsException done) {}
}
// //2. Mapping for the workflow document type
// GetMappingsResponse response = client.admin().indices().prepareGetMappings(indexName).addTypes(WORKFLOW_DOC_TYPE).execute().actionGet();
// if(response.mappings().isEmpty()) {
// log.info("Adding the workflow type mappings");
// InputStream stream = ElasticSearch5DAO.class.getResourceAsStream("/wfe_type.json");
// byte[] bytes = IOUtils.toByteArray(stream);
// String source = new String(bytes);
// try {
// client.admin().indices().preparePutMapping(indexName).setType(WORKFLOW_DOC_TYPE).setSource(source).execute().actionGet();
// }catch(Exception e) {
// log.error(e.getMessage(), e);
// }
// }
}
@Override
public void index(Workflow workflow) {
try {
String id = workflow.getWorkflowId();
WorkflowSummary summary = new WorkflowSummary(workflow);
byte[] doc = om.writeValueAsBytes(summary);
UpdateRequest req = new UpdateRequest(indexName, WORKFLOW_DOC_TYPE, id);
req.doc(doc, XContentType.JSON);
req.upsert(doc, XContentType.JSON);
req.retryOnConflict(5);
updateWithRetry(req);
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
}
}
@Override
public void index(Task task) {
try {
String id = task.getTaskId();
TaskSummary summary = new TaskSummary(task);
byte[] doc = om.writeValueAsBytes(summary);
UpdateRequest req = new UpdateRequest(indexName, TASK_DOC_TYPE, id);
req.doc(doc, XContentType.JSON);
req.upsert(doc, XContentType.JSON);
updateWithRetry(req);
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
}
}
@Override
public void add(List<TaskExecLog> logs) {
if (logs == null || logs.isEmpty()) {
return;
}
int retry = 3;
while(retry > 0) {
try {
BulkRequestBuilder brb = client.prepareBulk();
for(TaskExecLog log : logs) {
IndexRequest request = new IndexRequest(logIndexName, LOG_DOC_TYPE);
request.source(om.writeValueAsBytes(log), XContentType.JSON);
brb.add(request);
}
BulkResponse response = brb.execute().actionGet();
if(!response.hasFailures()) {
break;
}
retry--;
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
retry--;
if(retry > 0) {
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
}
}
}
@Override
public List<TaskExecLog> getTaskLogs(String taskId) {
try {
QueryBuilder qf = QueryBuilders.matchAllQuery();
Expression expression = Expression.fromString("taskId='" + taskId + "'");
qf = expression.getFilterBuilder();
BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(qf);
QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*");
BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
final SearchRequestBuilder srb = client.prepareSearch(indexName).setQuery(fq).setTypes(TASK_DOC_TYPE);
SearchResponse response = srb.execute().actionGet();
SearchHit[] hits = response.getHits().getHits();
List<TaskExecLog> logs = new ArrayList<>(hits.length);
for(SearchHit hit : hits) {
String source = hit.getSourceAsString();
TaskExecLog tel = om.readValue(source, TaskExecLog.class);
logs.add(tel);
}
return logs;
}catch(Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
@Override
public void addMessage(String queue, Message msg) {
int retry = 3;
while(retry > 0) {
try {
Map<String, Object> doc = new HashMap<>();
doc.put("messageId", msg.getId());
doc.put("payload", msg.getPayload());
doc.put("queue", queue);
doc.put("created", System.currentTimeMillis());
IndexRequest request = new IndexRequest(logIndexName, MSG_DOC_TYPE);
request.source(doc);
client.index(request).actionGet();
break;
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
retry--;
if(retry > 0) {
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
}
}
}
@Override
public void add(EventExecution ee) {
try {
byte[] doc = om.writeValueAsBytes(ee);
String id = ee.getName() + "." + ee.getEvent() + "." + ee.getMessageId() + "." + ee.getId();
UpdateRequest req = new UpdateRequest(logIndexName, EVENT_DOC_TYPE, id);
req.doc(doc, XContentType.JSON);
req.upsert(doc, XContentType.JSON);
req.retryOnConflict(5);
updateWithRetry(req);
} catch (Throwable e) {
log.error("Indexing failed {}", e.getMessage(), e);
}
}
private void updateWithRetry(UpdateRequest request) {
int retry = 3;
while(retry > 0) {
try {
client.update(request).actionGet();
return;
}catch(Exception e) {
Monitors.error(className, "index");
log.error("Indexing failed for {}, {}: {}", request.index(), request.type(), e.getMessage(), e);
retry--;
if(retry > 0) {
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
}
}
}
}
@Override
public SearchResult<String> searchWorkflows(String query, String freeText, int start, int count, List<String> sort) {
try {
return search(query, start, count, sort, freeText);
} catch (ParserException e) {
throw new ApplicationException(Code.BACKEND_ERROR, e.getMessage(), e);
}
}
@Override
public void remove(String workflowId) {
try {
DeleteRequest req = new DeleteRequest(indexName, WORKFLOW_DOC_TYPE, workflowId);
DeleteResponse response = client.delete(req).actionGet();
if (response.getResult() == DocWriteResponse.Result.DELETED) {
log.error("Index removal failed - document not found by id " + workflowId);
}
} catch (Throwable e) {
log.error("Index removal failed failed {}", e.getMessage(), e);
Monitors.error(className, "remove");
}
}
@Override
public void update(String workflowInstanceId, String[] keys, Object[] values) {
if(keys.length != values.length) {
throw new IllegalArgumentException("Number of keys and values should be same.");
}
UpdateRequest request = new UpdateRequest(indexName, WORKFLOW_DOC_TYPE, workflowInstanceId);
Map<String, Object> source = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
Object value= values[i];
log.debug("updating {} with {} and {}", workflowInstanceId, key, value);
source.put(key, value);
}
request.doc(source);
ActionFuture<UpdateResponse> response = client.update(request);
response.actionGet();
}
@Override
public String get(String workflowInstanceId, String fieldToGet) {
Object value = null;
GetRequest request = new GetRequest(indexName, WORKFLOW_DOC_TYPE, workflowInstanceId).storedFields(fieldToGet);
GetResponse response = client.get(request).actionGet();
Map<String, GetField> fields = response.getFields();
if(fields == null) {
return null;
}
GetField field = fields.get(fieldToGet);
if(field != null) value = field.getValue();
if(value != null) {
return value.toString();
}
return null;
}
private SearchResult<String> search(String structuredQuery, int start, int size, List<String> sortOptions, String freeTextQuery) throws ParserException {
QueryBuilder qf = QueryBuilders.matchAllQuery();
if(StringUtils.isNotEmpty(structuredQuery)) {
Expression expression = Expression.fromString(structuredQuery);
qf = expression.getFilterBuilder();
}
BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(qf);
QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(freeTextQuery);
BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
final SearchRequestBuilder srb = client.prepareSearch(indexName).setQuery(fq).setTypes(WORKFLOW_DOC_TYPE).storedFields("_id").setFrom(start).setSize(size);
if(sortOptions != null){
sortOptions.forEach(sortOption -> {
SortOrder order = SortOrder.ASC;
String field = sortOption;
int indx = sortOption.indexOf(':');
if(indx > 0){ //Can't be 0, need the field name at-least
field = sortOption.substring(0, indx);
order = SortOrder.valueOf(sortOption.substring(indx+1));
}
srb.addSort(field, order);
});
}
List<String> result = new LinkedList<String>();
SearchResponse response = srb.get();
response.getHits().forEach(hit -> {
result.add(hit.getId());
});
long count = response.getHits().getTotalHits();
return new SearchResult<String>(count, result);
}
}
| Fix for getTaskLogs where the wrong index name was used
| es5-persistence/src/main/java/com/netflix/conductor/dao/es5/index/ElasticSearch5DAO.java | Fix for getTaskLogs where the wrong index name was used | <ide><path>s5-persistence/src/main/java/com/netflix/conductor/dao/es5/index/ElasticSearch5DAO.java
<ide> QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery("*");
<ide> BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
<ide>
<del> final SearchRequestBuilder srb = client.prepareSearch(indexName).setQuery(fq).setTypes(TASK_DOC_TYPE);
<add> final SearchRequestBuilder srb = client.prepareSearch(logIndexPrefix + "*").setQuery(fq).setTypes(TASK_DOC_TYPE);
<ide> SearchResponse response = srb.execute().actionGet();
<ide> SearchHit[] hits = response.getHits().getHits();
<ide> List<TaskExecLog> logs = new ArrayList<>(hits.length); |
|
Java | apache-2.0 | 01f25617b05ac91a5f79373a24048ec131281753 | 0 | mtransitapps/ca-lethbridge-transit-bus-parser | package org.mtransit.parser.ca_lethbridge_transit_bus;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MDirectionType;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// http://opendata.lethbridge.ca/
// http://opendata.lethbridge.ca/datasets/e5ce3aa182114d66926d06ba732fb668
// https://www.lethbridge.ca/OpenDataSets/GTFS_Transit_Data.zip
public class LethbridgeTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-lethbridge-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new LethbridgeTransitBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
MTLog.log("Generating Lethbridge Transit bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this, true);
super.start(args);
MTLog.log("Generating Lethbridge Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public boolean excludeRoute(GRoute gRoute) {
return super.excludeRoute(gRoute);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
private static final String N = "n";
private static final String S = "s";
private static final long RID_STARTS_WITH_N = 140_000L;
private static final long RID_STARTS_WITH_S = 190_000L;
@Override
public long getRouteId(GRoute gRoute) {
if (Utils.isDigitsOnly(gRoute.getRouteShortName())) {
return Long.parseLong(gRoute.getRouteShortName()); // using route short name as route ID
}
Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName());
if (matcher.find()) {
long digits = Long.parseLong(matcher.group());
if (gRoute.getRouteShortName().toLowerCase(Locale.ENGLISH).endsWith(N)) {
return RID_STARTS_WITH_N + digits;
} else if (gRoute.getRouteShortName().toLowerCase(Locale.ENGLISH).endsWith(S)) {
return RID_STARTS_WITH_S + digits;
}
}
MTLog.logFatal("Unexpected route ID for %s!\n", gRoute);
return -1L;
}
private static final String SLASH = " / ";
@SuppressWarnings("DuplicateBranchesInSwitch")
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
if (StringUtils.isEmpty(routeLongName)) {
routeLongName = gRoute.getRouteDesc(); // using route description as route long name
}
if (StringUtils.isEmpty(routeLongName)) {
if (Utils.isDigitsOnly(gRoute.getRouteShortName())) {
int rsn = Integer.parseInt(gRoute.getRouteShortName());
switch (rsn) {
// @formatter:off
case 12: return "University" + SLASH + "Downtown";
case 23: return "Mayor Magrath" + SLASH + "Scenic"; // Counter Clockwise Loop
case 24: return "Mayor Magrath" + SLASH + "Scenic"; // Clockwise
case 31: return "Legacy Rdg" + SLASH + "Uplands";
case 32: return "Indian Battle"+SLASH+ "Columbia Blvd"; // Indian Battle Heights, Varsity Village
case 33: return "Heritage" + SLASH + "West Highlands" ; // Ridgewood, Heritage, West Highlands
case 35: return "Copperwood"; // Copperwood
case 36: return "Sunridge"; // Sunridge, Riverstone, Mtn Hts
case 37: return "Garry Station"; //
// @formatter:on
}
}
if ("20N".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "North Terminal";
} else if ("20S".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "South Enmax";
} else if ("21N".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "Nord-Bridge";
} else if ("21S".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "Henderson Lk" + SLASH + "Industrial";
} else if ("22N".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "North Terminal"; // 22 North
} else if ("22S".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "South Gate"; //
}
MTLog.logFatal("Unexpected route long name for %s!\n", gRoute);
return null;
}
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR_BLUE_LIGHT = "009ADE"; // BLUE LIGHT (from web site CSS)
private static final String AGENCY_COLOR = AGENCY_COLOR_BLUE_LIGHT;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public String getRouteColor(GRoute gRoute) {
if ("20S".equalsIgnoreCase(gRoute.getRouteShortName())) {
if ("80FF00".equalsIgnoreCase(gRoute.getRouteColor())) { // too light
return "81CC2B"; // darker (from PDF schedule)
}
} else if ("32".equalsIgnoreCase(gRoute.getRouteShortName())) {
if ("73CFFF".equalsIgnoreCase(gRoute.getRouteColor())) { // too light
return "76AFE3"; // darker (from PDF schedule)
}
} else if ("36".equalsIgnoreCase(gRoute.getRouteShortName())) {
if ("80FF80".equalsIgnoreCase(gRoute.getRouteColor())) { // too light
return "4DB8A4"; // darker (from PDF schedule)
}
}
return super.getRouteColor(gRoute);
}
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<>();
map2.put(10L, new RouteTripSpec(10L, //
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "City Ctr", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University") //
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13005"), // University Terminal
Stops.getALL_STOPS().get("13007"), // ++ UNIVERSITY DR W & VALLEY RD W
Stops.getALL_STOPS().get("14014") // City Centre Terminal
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("14014"), // City Centre Terminal
Stops.getALL_STOPS().get("13042"), // ++ COLUMBIA BLVD W & lafayette blvd w
Stops.getALL_STOPS().get("13005") // University Terminal
)) //
.compileBothTripSort());
map2.put(20L + RID_STARTS_WITH_N, new RouteTripSpec(20L + RID_STARTS_WITH_N, // 20N
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "North Terminal", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("12216"), // College Terminal
Stops.getALL_STOPS().get("14011"), // City Centre Terminal
Stops.getALL_STOPS().get("11053") // North Terminal
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(20L + RID_STARTS_WITH_S, new RouteTripSpec(20L + RID_STARTS_WITH_S, // 20S
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY, //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "College Terminal") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Collections.emptyList()) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("11053"), // North Terminal
Stops.getALL_STOPS().get("14015"), // City Centre Terminal
Stops.getALL_STOPS().get("12216") // College Terminal
)) //
.compileBothTripSort());
map2.put(21L + RID_STARTS_WITH_N, new RouteTripSpec(21L + RID_STARTS_WITH_N, // 21N
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Westminster", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "City Ctr") //
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("14014"), // City Centre Terminal
Stops.getALL_STOPS().get("11205") // 19 ST N & 7 AVE N #Westminster
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("11205"), // 19 ST N & 7 AVE N #Westminster
Stops.getALL_STOPS().get("14016") // City Centre Terminal
)) //
.compileBothTripSort());
map2.put(21L + RID_STARTS_WITH_S, new RouteTripSpec(21L + RID_STARTS_WITH_S, // 21S
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Henderson Lk" + SLASH + "Industrial", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "City Ctr") //
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("14016"), // == City Center Terminal
Stops.getALL_STOPS().get("14034"), // != 4 Ave & 8 St S
Stops.getALL_STOPS().get("12038"), // == City Hall
Stops.getALL_STOPS().get("12011"), // != LEASIDE AVE S & 2 AVE S
Stops.getALL_STOPS().get("12010"), // == Transfer Point
Stops.getALL_STOPS().get("12330"), // != 1 AVE S & 32 ST S
Stops.getALL_STOPS().get("11267"), // != 39 ST N & 14 AVE N
Stops.getALL_STOPS().get("11271") // 14 AVE N & 39 ST N
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("11271"), // 14 AVE N & 39 ST N
Stops.getALL_STOPS().get("11268"), // != 36 ST N & 14 AVE N
Stops.getALL_STOPS().get("11054"), // != 36 ST S & CROWSNEST HWY
Stops.getALL_STOPS().get("12010"), // == Transfer Point
Stops.getALL_STOPS().get("12009"), // != 28 ST S & 3 AVE S
Stops.getALL_STOPS().get("12034"), // == 6 AVE S & 15 ST S
Stops.getALL_STOPS().get("12035"), // == 6 Ave & 13 St S
Stops.getALL_STOPS().get("14014") // City Center Terminal
)) //
.compileBothTripSort());
map2.put(22L + RID_STARTS_WITH_N, new RouteTripSpec(22L + RID_STARTS_WITH_N, // 22N
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "North Terminal", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("12106"), // College Terminal
Stops.getALL_STOPS().get("14015"), // City Centre Terminal
Stops.getALL_STOPS().get("11210"), // == MEADOWLARK BLVD N & 23 ST N
Stops.getALL_STOPS().get("11275"), // != 26 AVE N & BLUEFOX BLVD N
Stops.getALL_STOPS().get("11035"), // != 26 AVE N & ERMINEDALE BLVD N
Stops.getALL_STOPS().get("11274"), // != 26 AVE N & 23 ST N
Stops.getALL_STOPS().get("11034"), // != UPLANDS BLVD N & BLUEFOX RD N
Stops.getALL_STOPS().get("11052") // == North Terminal
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(22L + RID_STARTS_WITH_S, new RouteTripSpec(22L + RID_STARTS_WITH_S, // 22S
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY, //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "College Terminal") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Collections.emptyList()) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("11052"), // North Terminal
Stops.getALL_STOPS().get("14021"), // City Centre Terminal
Stops.getALL_STOPS().get("12186"), // == SCENIC DR S & TUDOR CRES S
Stops.getALL_STOPS().get("12104"), // != COLLEGE DR & 28 AVE S
Stops.getALL_STOPS().get("12102"), // != Enmax Centre
Stops.getALL_STOPS().get("12130"), // != Lethbridge Soccer Complex
Stops.getALL_STOPS().get("12106") // == College Terminal
)) //
.compileBothTripSort());
map2.put(23L, new RouteTripSpec(23L, //
0, MTrip.HEADSIGN_TYPE_STRING, "CCW", //
1, MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(0, //
Arrays.asList(//
Stops.getALL_STOPS().get("14001"), // City Centre Terminal
Stops.getALL_STOPS().get("14017"), // ++ 5 AVE & 4 ST S
Stops.getALL_STOPS().get("12104"), // ++ COLLEGE DR & 28 AVE S
Stops.getALL_STOPS().get("12106"), // College Terminal
Stops.getALL_STOPS().get("12131"), // ++ 28 AVE S & 28 ST S
Stops.getALL_STOPS().get("12203"), // ++ MAYOR MAGRATH DR S & SOUTH PARKSIDE DR S
Stops.getALL_STOPS().get("11035"), // ++ 26 AVE N & ERMINEDALE BLVD N
Stops.getALL_STOPS().get("11053"), // North Terminal
Stops.getALL_STOPS().get("11112"), // ++ STAFFORD DR N & STAFFORD RD N
Stops.getALL_STOPS().get("14013"), // ++ 4 AVE S & 3 ST S
Stops.getALL_STOPS().get("14001") // City Centre Terminal
)) //
.addTripSort(1, //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(24L, new RouteTripSpec(24L, //
0, MTrip.HEADSIGN_TYPE_STRING, "CW", //
1, MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(0, //
Arrays.asList(//
Stops.getALL_STOPS().get("14000"), // City Centre Terminal
Stops.getALL_STOPS().get("11052"), // North Terminal
Stops.getALL_STOPS().get("12216"), // College Terminal
Stops.getALL_STOPS().get("14000") // City Centre Terminal
)) //
.addTripSort(1, //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(32L, new RouteTripSpec(32L, //
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Indian Battle") //
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13034"), // RED CROW BLVD W & JERRY POTTS BLVD W
Stops.getALL_STOPS().get("13039"), // ++
Stops.getALL_STOPS().get("13068"), // ++
Stops.getALL_STOPS().get("13005") // University Terminal
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13003"), // University Terminal
Stops.getALL_STOPS().get("13029"), // ++
Stops.getALL_STOPS().get("13034") // RED CROW BLVD W & JERRY POTTS BLVD W
)) //
.compileBothTripSort());
map2.put(33L, new RouteTripSpec(33L, //
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Heritage", // "West Highlands", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13002"), // University Terminal
Stops.getALL_STOPS().get("13006"), //
Stops.getALL_STOPS().get("13013"), //
Stops.getALL_STOPS().get("13020") // HERITAGE BLVD & HERITAGE HEIGHTS PLAZA W
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13020"), // HERITAGE BLVD & HERITAGE HEIGHTS PLAZA W
Stops.getALL_STOPS().get("13023"), //
Stops.getALL_STOPS().get("13061"), //
Stops.getALL_STOPS().get("13002") // University Terminal
)) //
.compileBothTripSort());
map2.put(35L, new RouteTripSpec(35L, //
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Crossings") // "Copperwood"
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13311"), // BRITANNIA BLVD W & AQUITANIA BLVD W
Stops.getALL_STOPS().get("13043"), // ++
Stops.getALL_STOPS().get("13004") // University Terminal
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13004"), // University Terminal
Stops.getALL_STOPS().get("13303"), // ++
Stops.getALL_STOPS().get("13311") // BRITANNIA BLVD W & AQUITANIA BLVD W
)) //
.compileBothTripSort());
map2.put(36L, new RouteTripSpec(36L, //
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Sunridge") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13507"), // MT SUNDANCE RD W & MT SUNDIAL CRT W
Stops.getALL_STOPS().get("13517"), // ++
Stops.getALL_STOPS().get("13001") // University Terminal
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13001"), // University Terminal
Stops.getALL_STOPS().get("13503"), // ++
Stops.getALL_STOPS().get("13507") // MT SUNDANCE RD W & MT SUNDIAL CRT W
)) //
.compileBothTripSort());
map2.put(37L, new RouteTripSpec(37L, //
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Garry Sta") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13524"), // Garry Station Prt W & Garry Dr W
Stops.getALL_STOPS().get("13450"), // GARRY DR W & SQUAMISH BLVD W
Stops.getALL_STOPS().get("13000") // University Terminal
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13000"), // University Terminal
Stops.getALL_STOPS().get("13009"), // University Dr W & Edgewood Blvd W
Stops.getALL_STOPS().get("13524") // Garry Station Prt W & Garry Dr W
)) //
.compileBothTripSort());
map2.put(40L, new RouteTripSpec(40L, //
0, MTrip.HEADSIGN_TYPE_STRING, "Fairmont", // CW
1, MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(0, //
Arrays.asList(//
Stops.getALL_STOPS().get("12107"), // College Terminal
Stops.getALL_STOPS().get("12125"), // ++ FAIRMONT BLVD S & FAIRWAY ST S
Stops.getALL_STOPS().get("12107") // College Terminal
)) //
.addTripSort(1, //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(41L, new RouteTripSpec(41L, //
0, MTrip.HEADSIGN_TYPE_STRING, "Blackwolf", // CW
1, MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(0, //
Arrays.asList(//
Stops.getALL_STOPS().get("11051"), // North Terminal
Stops.getALL_STOPS().get("11257"), // ++ LYNX RD N & BLACKWOLF BLVD N
Stops.getALL_STOPS().get("11051") // North Terminal
)) //
.addTripSort(1, //
Collections.emptyList()) //
.compileBothTripSort());
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
String tripHeadsign = gTrip.getTripHeadsign();
mTrip.setHeadsignString(cleanTripHeadsign(tripHeadsign), gTrip.getDirectionId());
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
if (mTrip.getRouteId() == 21L + RID_STARTS_WITH_S) { // 21S
if (Arrays.asList( //
"City Ctr", //
"Henderson Lk", //
"Henderson Lk & Industrial" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Henderson Lk", mTrip.getHeadsignId());
return true;
}
}
MTLog.logFatal("Unexpected trips to merge %s & %s!\n", mTrip, mTripToMerge);
return false;
}
private static final String UNIVERSITY_OF_SHORT = "U of";
private static final Pattern UNIVERSITY_OF = Pattern.compile("((^|\\W){1}(university of)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String UNIVERSITY_OF_REPLACEMENT = "$2" + UNIVERSITY_OF_SHORT + "$4";
private static final Pattern ENDS_WITH_LOOP = Pattern.compile("([\\s]*loop$)", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_ROUTE = Pattern.compile("([\\s]*route$)", Pattern.CASE_INSENSITIVE);
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = ENDS_WITH_LOOP.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_ROUTE.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = UNIVERSITY_OF.matcher(tripHeadsign).replaceAll(UNIVERSITY_OF_REPLACEMENT);
tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
@Override
public String cleanStopName(String gStopName) {
if (Utils.isUppercaseOnly(gStopName, true, true)) {
gStopName = gStopName.toLowerCase(Locale.ENGLISH);
}
gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = CleanUtils.removePoints(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(GStop gStop) {
if (Utils.isDigitsOnly(gStop.getStopCode())) {
return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID
}
Matcher matcher = DIGITS.matcher(gStop.getStopCode());
if (matcher.find()) {
int digits = Integer.parseInt(matcher.group());
if (gStop.getStopCode().startsWith("MESC")) {
return 13050000 + digits;
}
}
MTLog.logFatal("Unexpected stop ID for %s!\n", gStop);
return -1;
}
}
| src/main/java/org/mtransit/parser/ca_lethbridge_transit_bus/LethbridgeTransitBusAgencyTools.java | package org.mtransit.parser.ca_lethbridge_transit_bus;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MDirectionType;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// http://opendata.lethbridge.ca/
// http://opendata.lethbridge.ca/datasets?keyword=GroupTransportation
// http://opendata.lethbridge.ca/datasets?keyword=GroupGTFSTransit
// http://www.lethbridge.ca/OpenDataSets/GTFS_Transit_Data.zip
public class LethbridgeTransitBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-lethbridge-transit-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new LethbridgeTransitBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
MTLog.log("Generating Lethbridge Transit bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this, true);
super.start(args);
MTLog.log("Generating Lethbridge Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public boolean excludeRoute(GRoute gRoute) {
return super.excludeRoute(gRoute);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
private static final String N = "n";
private static final String S = "s";
private static final long RID_STARTS_WITH_N = 140_000L;
private static final long RID_STARTS_WITH_S = 190_000L;
@Override
public long getRouteId(GRoute gRoute) {
if (Utils.isDigitsOnly(gRoute.getRouteShortName())) {
return Long.parseLong(gRoute.getRouteShortName()); // using route short name as route ID
}
Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName());
if (matcher.find()) {
long digits = Long.parseLong(matcher.group());
if (gRoute.getRouteShortName().toLowerCase(Locale.ENGLISH).endsWith(N)) {
return RID_STARTS_WITH_N + digits;
} else if (gRoute.getRouteShortName().toLowerCase(Locale.ENGLISH).endsWith(S)) {
return RID_STARTS_WITH_S + digits;
}
}
MTLog.logFatal("Unexpected route ID for %s!\n", gRoute);
return -1L;
}
private static final String SLASH = " / ";
@SuppressWarnings("DuplicateBranchesInSwitch")
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
if (StringUtils.isEmpty(routeLongName)) {
routeLongName = gRoute.getRouteDesc(); // using route description as route long name
}
if (StringUtils.isEmpty(routeLongName)) {
if (Utils.isDigitsOnly(gRoute.getRouteShortName())) {
int rsn = Integer.parseInt(gRoute.getRouteShortName());
switch (rsn) {
// @formatter:off
case 12: return "University" + SLASH + "Downtown";
case 23: return "Mayor Magrath" + SLASH + "Scenic"; // Counter Clockwise Loop
case 24: return "Mayor Magrath" + SLASH + "Scenic"; // Clockwise
case 31: return "Legacy Rdg" + SLASH + "Uplands";
case 32: return "Indian Battle"+SLASH+ "Columbia Blvd"; // Indian Battle Heights, Varsity Village
case 33: return "Heritage" + SLASH + "West Highlands" ; // Ridgewood, Heritage, West Highlands
case 35: return "Copperwood"; // Copperwood
case 36: return "Sunridge"; // Sunridge, Riverstone, Mtn Hts
case 37: return "Garry Station"; //
// @formatter:on
}
}
if ("20N".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "North Terminal";
} else if ("20S".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "South Enmax";
} else if ("21N".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "Nord-Bridge";
} else if ("21S".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "Henderson Lk" + SLASH + "Industrial";
} else if ("22N".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "North Terminal"; // 22 North
} else if ("22S".equalsIgnoreCase(gRoute.getRouteShortName())) {
return "South Gate"; //
}
MTLog.logFatal("Unexpected route long name for %s!\n", gRoute);
return null;
}
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR_BLUE_LIGHT = "009ADE"; // BLUE LIGHT (from web site CSS)
private static final String AGENCY_COLOR = AGENCY_COLOR_BLUE_LIGHT;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public String getRouteColor(GRoute gRoute) {
if ("20S".equalsIgnoreCase(gRoute.getRouteShortName())) {
if ("80FF00".equalsIgnoreCase(gRoute.getRouteColor())) { // too light
return "81CC2B"; // darker (from PDF schedule)
}
} else if ("32".equalsIgnoreCase(gRoute.getRouteShortName())) {
if ("73CFFF".equalsIgnoreCase(gRoute.getRouteColor())) { // too light
return "76AFE3"; // darker (from PDF schedule)
}
} else if ("36".equalsIgnoreCase(gRoute.getRouteShortName())) {
if ("80FF80".equalsIgnoreCase(gRoute.getRouteColor())) { // too light
return "4DB8A4"; // darker (from PDF schedule)
}
}
return super.getRouteColor(gRoute);
}
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<>();
map2.put(10L, new RouteTripSpec(10L, //
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "City Ctr", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University") //
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13005"), // University Terminal
Stops.getALL_STOPS().get("13007"), // ++ UNIVERSITY DR W & VALLEY RD W
Stops.getALL_STOPS().get("14014") // City Centre Terminal
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("14014"), // City Centre Terminal
Stops.getALL_STOPS().get("13042"), // ++ COLUMBIA BLVD W & lafayette blvd w
Stops.getALL_STOPS().get("13005") // University Terminal
)) //
.compileBothTripSort());
map2.put(20L + RID_STARTS_WITH_N, new RouteTripSpec(20L + RID_STARTS_WITH_N, // 20N
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "North Terminal", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("12216"), // College Terminal
Stops.getALL_STOPS().get("14011"), // City Centre Terminal
Stops.getALL_STOPS().get("11053") // North Terminal
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(20L + RID_STARTS_WITH_S, new RouteTripSpec(20L + RID_STARTS_WITH_S, // 20S
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY, //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "College Terminal") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Collections.emptyList()) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("11053"), // North Terminal
Stops.getALL_STOPS().get("14015"), // City Centre Terminal
Stops.getALL_STOPS().get("12216") // College Terminal
)) //
.compileBothTripSort());
map2.put(21L + RID_STARTS_WITH_N, new RouteTripSpec(21L + RID_STARTS_WITH_N, // 21N
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Westminster", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "City Ctr") //
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("14014"), // City Centre Terminal
Stops.getALL_STOPS().get("11205") // 19 ST N & 7 AVE N #Westminster
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("11205"), // 19 ST N & 7 AVE N #Westminster
Stops.getALL_STOPS().get("14016") // City Centre Terminal
)) //
.compileBothTripSort());
map2.put(21L + RID_STARTS_WITH_S, new RouteTripSpec(21L + RID_STARTS_WITH_S, // 21S
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Henderson Lk" + SLASH + "Industrial", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "City Ctr") //
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("14016"), // == City Center Terminal
Stops.getALL_STOPS().get("14034"), // != 4 Ave & 8 St S
Stops.getALL_STOPS().get("12038"), // == City Hall
Stops.getALL_STOPS().get("12011"), // != LEASIDE AVE S & 2 AVE S
Stops.getALL_STOPS().get("12010"), // == Transfer Point
Stops.getALL_STOPS().get("12330"), // != 1 AVE S & 32 ST S
Stops.getALL_STOPS().get("11267"), // != 39 ST N & 14 AVE N
Stops.getALL_STOPS().get("11271") // 14 AVE N & 39 ST N
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("11271"), // 14 AVE N & 39 ST N
Stops.getALL_STOPS().get("11268"), // != 36 ST N & 14 AVE N
Stops.getALL_STOPS().get("11054"), // != 36 ST S & CROWSNEST HWY
Stops.getALL_STOPS().get("12010"), // == Transfer Point
Stops.getALL_STOPS().get("12009"), // != 28 ST S & 3 AVE S
Stops.getALL_STOPS().get("12034"), // == 6 AVE S & 15 ST S
Stops.getALL_STOPS().get("12035"), // == 6 Ave & 13 St S
Stops.getALL_STOPS().get("14014") // City Center Terminal
)) //
.compileBothTripSort());
map2.put(22L + RID_STARTS_WITH_N, new RouteTripSpec(22L + RID_STARTS_WITH_N, // 22N
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "North Terminal", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("12106"), // College Terminal
Stops.getALL_STOPS().get("14015"), // City Centre Terminal
Stops.getALL_STOPS().get("11210"), // == MEADOWLARK BLVD N & 23 ST N
Stops.getALL_STOPS().get("11275"), // != 26 AVE N & BLUEFOX BLVD N
Stops.getALL_STOPS().get("11035"), // != 26 AVE N & ERMINEDALE BLVD N
Stops.getALL_STOPS().get("11274"), // != 26 AVE N & 23 ST N
Stops.getALL_STOPS().get("11034"), // != UPLANDS BLVD N & BLUEFOX RD N
Stops.getALL_STOPS().get("11052") // == North Terminal
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(22L + RID_STARTS_WITH_S, new RouteTripSpec(22L + RID_STARTS_WITH_S, // 22S
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY, //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "College Terminal") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Collections.emptyList()) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("11052"), // North Terminal
Stops.getALL_STOPS().get("14021"), // City Centre Terminal
Stops.getALL_STOPS().get("12186"), // == SCENIC DR S & TUDOR CRES S
Stops.getALL_STOPS().get("12104"), // != COLLEGE DR & 28 AVE S
Stops.getALL_STOPS().get("12102"), // != Enmax Centre
Stops.getALL_STOPS().get("12130"), // != Lethbridge Soccer Complex
Stops.getALL_STOPS().get("12106") // == College Terminal
)) //
.compileBothTripSort());
map2.put(23L, new RouteTripSpec(23L, //
0, MTrip.HEADSIGN_TYPE_STRING, "CCW", //
1, MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(0, //
Arrays.asList(//
Stops.getALL_STOPS().get("14001"), // City Centre Terminal
Stops.getALL_STOPS().get("14017"), // ++ 5 AVE & 4 ST S
Stops.getALL_STOPS().get("12104"), // ++ COLLEGE DR & 28 AVE S
Stops.getALL_STOPS().get("12106"), // College Terminal
Stops.getALL_STOPS().get("12131"), // ++ 28 AVE S & 28 ST S
Stops.getALL_STOPS().get("12203"), // ++ MAYOR MAGRATH DR S & SOUTH PARKSIDE DR S
Stops.getALL_STOPS().get("11035"), // ++ 26 AVE N & ERMINEDALE BLVD N
Stops.getALL_STOPS().get("11053"), // North Terminal
Stops.getALL_STOPS().get("11112"), // ++ STAFFORD DR N & STAFFORD RD N
Stops.getALL_STOPS().get("14013"), // ++ 4 AVE S & 3 ST S
Stops.getALL_STOPS().get("14001") // City Centre Terminal
)) //
.addTripSort(1, //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(24L, new RouteTripSpec(24L, //
0, MTrip.HEADSIGN_TYPE_STRING, "CW", //
1, MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(0, //
Arrays.asList(//
Stops.getALL_STOPS().get("14000"), // City Centre Terminal
Stops.getALL_STOPS().get("11052"), // North Terminal
Stops.getALL_STOPS().get("12216"), // College Terminal
Stops.getALL_STOPS().get("14000") // City Centre Terminal
)) //
.addTripSort(1, //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(32L, new RouteTripSpec(32L, //
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Indian Battle") //
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13034"), // RED CROW BLVD W & JERRY POTTS BLVD W
Stops.getALL_STOPS().get("13039"), // ++
Stops.getALL_STOPS().get("13068"), // ++
Stops.getALL_STOPS().get("13005") // University Terminal
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13003"), // University Terminal
Stops.getALL_STOPS().get("13029"), // ++
Stops.getALL_STOPS().get("13034") // RED CROW BLVD W & JERRY POTTS BLVD W
)) //
.compileBothTripSort());
map2.put(33L, new RouteTripSpec(33L, //
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Heritage", // "West Highlands", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13002"), // University Terminal
Stops.getALL_STOPS().get("13006"), //
Stops.getALL_STOPS().get("13013"), //
Stops.getALL_STOPS().get("13020") // HERITAGE BLVD & HERITAGE HEIGHTS PLAZA W
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13020"), // HERITAGE BLVD & HERITAGE HEIGHTS PLAZA W
Stops.getALL_STOPS().get("13023"), //
Stops.getALL_STOPS().get("13061"), //
Stops.getALL_STOPS().get("13002") // University Terminal
)) //
.compileBothTripSort());
map2.put(35L, new RouteTripSpec(35L, //
MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University", //
MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Crossings") // "Copperwood"
.addTripSort(MDirectionType.EAST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13311"), // BRITANNIA BLVD W & AQUITANIA BLVD W
Stops.getALL_STOPS().get("13043"), // ++
Stops.getALL_STOPS().get("13004") // University Terminal
)) //
.addTripSort(MDirectionType.WEST.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13004"), // University Terminal
Stops.getALL_STOPS().get("13303"), // ++
Stops.getALL_STOPS().get("13311") // BRITANNIA BLVD W & AQUITANIA BLVD W
)) //
.compileBothTripSort());
map2.put(36L, new RouteTripSpec(36L, //
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Sunridge") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13507"), // MT SUNDANCE RD W & MT SUNDIAL CRT W
Stops.getALL_STOPS().get("13517"), // ++
Stops.getALL_STOPS().get("13001") // University Terminal
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13001"), // University Terminal
Stops.getALL_STOPS().get("13503"), // ++
Stops.getALL_STOPS().get("13507") // MT SUNDANCE RD W & MT SUNDIAL CRT W
)) //
.compileBothTripSort());
map2.put(37L, new RouteTripSpec(37L, //
MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "University", //
MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Garry Sta") //
.addTripSort(MDirectionType.NORTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13524"), // Garry Station Prt W & Garry Dr W
Stops.getALL_STOPS().get("13450"), // GARRY DR W & SQUAMISH BLVD W
Stops.getALL_STOPS().get("13000") // University Terminal
)) //
.addTripSort(MDirectionType.SOUTH.intValue(), //
Arrays.asList(//
Stops.getALL_STOPS().get("13000"), // University Terminal
Stops.getALL_STOPS().get("13009"), // University Dr W & Edgewood Blvd W
Stops.getALL_STOPS().get("13524") // Garry Station Prt W & Garry Dr W
)) //
.compileBothTripSort());
map2.put(40L, new RouteTripSpec(40L, //
0, MTrip.HEADSIGN_TYPE_STRING, "Fairmont", // CW
1, MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(0, //
Arrays.asList(//
Stops.getALL_STOPS().get("12107"), // College Terminal
Stops.getALL_STOPS().get("12125"), // ++ FAIRMONT BLVD S & FAIRWAY ST S
Stops.getALL_STOPS().get("12107") // College Terminal
)) //
.addTripSort(1, //
Collections.emptyList()) //
.compileBothTripSort());
map2.put(41L, new RouteTripSpec(41L, //
0, MTrip.HEADSIGN_TYPE_STRING, "Blackwolf", // CW
1, MTrip.HEADSIGN_TYPE_STRING, StringUtils.EMPTY) //
.addTripSort(0, //
Arrays.asList(//
Stops.getALL_STOPS().get("11051"), // North Terminal
Stops.getALL_STOPS().get("11257"), // ++ LYNX RD N & BLACKWOLF BLVD N
Stops.getALL_STOPS().get("11051") // North Terminal
)) //
.addTripSort(1, //
Collections.emptyList()) //
.compileBothTripSort());
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
String tripHeadsign = gTrip.getTripHeadsign();
mTrip.setHeadsignString(cleanTripHeadsign(tripHeadsign), gTrip.getDirectionId());
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
if (mTrip.getRouteId() == 21L + RID_STARTS_WITH_S) { // 21S
if (Arrays.asList( //
"City Ctr", //
"Henderson Lk", //
"Henderson Lk & Industrial" //
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Henderson Lk", mTrip.getHeadsignId());
return true;
}
}
MTLog.logFatal("Unexpected trips to merge %s & %s!\n", mTrip, mTripToMerge);
return false;
}
private static final String UNIVERSITY_OF_SHORT = "U of";
private static final Pattern UNIVERSITY_OF = Pattern.compile("((^|\\W){1}(university of)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String UNIVERSITY_OF_REPLACEMENT = "$2" + UNIVERSITY_OF_SHORT + "$4";
private static final Pattern ENDS_WITH_LOOP = Pattern.compile("([\\s]*loop$)", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_ROUTE = Pattern.compile("([\\s]*route$)", Pattern.CASE_INSENSITIVE);
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = ENDS_WITH_LOOP.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_ROUTE.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = UNIVERSITY_OF.matcher(tripHeadsign).replaceAll(UNIVERSITY_OF_REPLACEMENT);
tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
@Override
public String cleanStopName(String gStopName) {
if (Utils.isUppercaseOnly(gStopName, true, true)) {
gStopName = gStopName.toLowerCase(Locale.ENGLISH);
}
gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = CleanUtils.removePoints(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(GStop gStop) {
if (Utils.isDigitsOnly(gStop.getStopCode())) {
return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID
}
Matcher matcher = DIGITS.matcher(gStop.getStopCode());
if (matcher.find()) {
int digits = Integer.parseInt(matcher.group());
if (gStop.getStopCode().startsWith("MESC")) {
return 13050000 + digits;
}
}
MTLog.logFatal("Unexpected stop ID for %s!\n", gStop);
return -1;
}
}
| New URLs
| src/main/java/org/mtransit/parser/ca_lethbridge_transit_bus/LethbridgeTransitBusAgencyTools.java | New URLs | <ide><path>rc/main/java/org/mtransit/parser/ca_lethbridge_transit_bus/LethbridgeTransitBusAgencyTools.java
<ide> import java.util.regex.Pattern;
<ide>
<ide> // http://opendata.lethbridge.ca/
<del>// http://opendata.lethbridge.ca/datasets?keyword=GroupTransportation
<del>// http://opendata.lethbridge.ca/datasets?keyword=GroupGTFSTransit
<del>// http://www.lethbridge.ca/OpenDataSets/GTFS_Transit_Data.zip
<add>// http://opendata.lethbridge.ca/datasets/e5ce3aa182114d66926d06ba732fb668
<add>// https://www.lethbridge.ca/OpenDataSets/GTFS_Transit_Data.zip
<ide> public class LethbridgeTransitBusAgencyTools extends DefaultAgencyTools {
<ide>
<ide> public static void main(String[] args) { |
|
Java | agpl-3.0 | a1416e60743b761cbfb5aa38bd13afbc9ce8b022 | 0 | akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow | /*
* Copyright (C) 2019 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package test.java.org.akvo.flow.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import com.fasterxml.jackson.core.type.TypeReference;
import org.akvo.flow.util.FlowJsonObjectReader;
import org.junit.jupiter.api.Test;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto;
import org.waterforpeople.mapping.domain.CaddisflyResource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class FlowJsonObjectReaderTests {
private String QUESTION_DTO_JSON_STRING = "{ \"type\": \"FREE_TEXT\",\n" +
"\"text\": \"How many toilets are present?\",\n" +
"\"dependentFlag\": false,\n" +
"\"questionGroupId\": 12345678,\n" +
"\"surveyId\": 910111213,\n" +
"\"order\": 0 }";
private String COMPLEX_JSON_OBJECT = "{\n" +
" \"tests\": [\n" +
" {\n" +
" \"name\": \"Soil - Electrical Conductivity\",\n" +
" \"subtype\": \"sensor\",\n" +
" \"uuid\": \"80697cd1-acc9-4a15-8358-f32b4257dfaf\",\n" +
" \"deviceId\": \"SoilEC\",\n" +
" \"brand\": \"Caddisfly\",\n" +
" \"image\": \"Caddisfly-Soil-EC\",\n" +
" \"imageScale\": \"centerCrop\",\n" +
" \"ranges\": \"50,12800\",\n" +
" \"responseFormat\": \"$2,$1\",\n" +
" \"instructions\": [],\n" +
" \"results\": [\n" +
" {\n" +
" \"id\": 1,\n" +
" \"name\": \"Soil Electrical Conductivity\",\n" +
" \"unit\": \"μS/cm\"\n" +
" },\n" +
" {\n" +
" \"id\": 2,\n" +
" \"name\": \"Temperature\",\n" +
" \"unit\": \"°Celsius\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"Soil - Moisture\",\n" +
" \"subtype\": \"sensor\",\n" +
" \"uuid\": \"0b4a0aaa-f556-4c11-a539-c4626582cca6\",\n" +
" \"deviceId\": \"Soil Moisture\",\n" +
" \"brand\": \"Caddisfly\",\n" +
" \"image\": \"Caddisfly-Soil-Moisture\",\n" +
" \"imageScale\": \"centerCrop\",\n" +
" \"ranges\": \"0,100\",\n" +
" \"responseFormat\": \"$1\",\n" +
" \"instructions\": [],\n" +
" \"results\": [\n" +
" {\n" +
" \"id\": 1,\n" +
" \"name\": \"Soil Moisture\",\n" +
" \"unit\": \"% VWC\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"]}";
private String DTO_LIST_JSON_OBJECT = "{\n" +
" \"code\": null, \n" +
" \"cursor\": null, \n" +
" \"dtoList\": [\n" +
" {\n" +
" \"ancestorIds\": [\n" +
" 0, \n" +
" 278889175415\n" +
" ], \n" +
" \"code\": \"1.10.36 all questions\", \n" +
" \"createdDateTime\": 1534846914945, \n" +
" \"dataApprovalGroupId\": null, \n" +
" \"defaultLanguageCode\": \"en\", \n" +
" \"description\": \"\", \n" +
" \"keyId\": 2989762914097, \n" +
" \"lastUpdateDateTime\": 1534846926804, \n" +
" \"monitoringGroup\": false, \n" +
" \"name\": \"1.10.36 all questions\", \n" +
" \"newLocaleSurveyId\": null, \n" +
" \"parentId\": 27888911545, \n" +
" \"path\": \"/_1.9.36 and 2.6.0/1.10.36 all questions\", \n" +
" \"privacyLevel\": \"PRIVATE\", \n" +
" \"projectType\": \"PROJECT\", \n" +
" \"published\": false, \n" +
" \"requireDataApproval\": false, \n" +
" \"surveyList\": null\n" +
" }\n" +
" ], \n" +
" \"message\": null, \n" +
" \"offset\": 0, \n" +
" \"resultCount\": 0, \n" +
" \"url\": null\n" +
"}\n";
@Test
void testReadSimpleJsonObject() {
FlowJsonObjectReader reader = new FlowJsonObjectReader();
TypeReference<QuestionDto> typeReference = new TypeReference<QuestionDto>() {};
QuestionDto testQuestionDto = null;
try {
testQuestionDto = reader.readObject(QUESTION_DTO_JSON_STRING, typeReference);
} catch (IOException e) {
//
}
assertEquals(QuestionDto.QuestionType.FREE_TEXT, testQuestionDto.getType());
assertEquals("How many toilets are present?", testQuestionDto.getText());
assertFalse(testQuestionDto.getDependentFlag());
assertEquals(12345678L, testQuestionDto.getQuestionGroupId());
assertEquals(QuestionDto.QuestionType.FREE_TEXT, testQuestionDto.getType());
assertEquals(0, testQuestionDto.getOrder());
}
@Test
void testReadComplexJsonObject() {
FlowJsonObjectReader reader = new FlowJsonObjectReader();
TypeReference<Map<String, List<CaddisflyResource>>> typeReference = new TypeReference<Map<String, List<CaddisflyResource>>>() {};
Map<String, List<CaddisflyResource>> resourcesMap = new HashMap<>();
try {
resourcesMap = reader.readObject(COMPLEX_JSON_OBJECT, typeReference);
} catch (IOException e) {
//
}
List<CaddisflyResource> resourcesList = resourcesMap.get("tests");
assertNotEquals(null, resourcesList);
assertEquals(2, resourcesList.size());
assertEquals(2, resourcesList.get(0).getResults().size());
assertEquals("Soil - Electrical Conductivity", resourcesList.get(0).getName());
assertEquals(1, resourcesList.get(1).getResults().size());
assertEquals("0b4a0aaa-f556-4c11-a539-c4626582cca6", resourcesList.get(1).getUuid());
}
@Test
void testDtoListResponses() {
FlowJsonObjectReader reader = new FlowJsonObjectReader();
TypeReference<SurveyGroupDto> typeReference = new TypeReference<SurveyGroupDto>() {};
List<SurveyGroupDto> surveyList = null;
try {
surveyList = reader.readDtoListObject(DTO_LIST_JSON_OBJECT, typeReference);
} catch (IOException e) {
//
}
assertNotEquals(null, surveyList);
assertEquals(1, surveyList.size());
assertEquals("1.10.36 all questions", surveyList.get(0).getName());
}
}
| GAE/src/test/java/org/akvo/flow/util/FlowJsonObjectReaderTests.java | /*
* Copyright (C) 2019 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package test.java.org.akvo.flow.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import com.fasterxml.jackson.core.type.TypeReference;
import org.akvo.flow.util.FlowJsonObjectReader;
import org.junit.jupiter.api.Test;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto;
import org.waterforpeople.mapping.domain.CaddisflyResource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class FlowJsonObjectReaderTests {
private String QUESTION_DTO_JSON_STRING = "{ \"type\": \"FREE_TEXT\",\n" +
"\"text\": \"How many toilets are present?\",\n" +
"\"dependentFlag\": false,\n" +
"\"questionGroupId\": 12345678,\n" +
"\"surveyId\": 910111213,\n" +
"\"order\": 0 }";
private String COMPLEX_JSON_OBJECT = "{\n" +
" \"tests\": [\n" +
" {\n" +
" \"name\": \"Soil - Electrical Conductivity\",\n" +
" \"subtype\": \"sensor\",\n" +
" \"uuid\": \"80697cd1-acc9-4a15-8358-f32b4257dfaf\",\n" +
" \"deviceId\": \"SoilEC\",\n" +
" \"brand\": \"Caddisfly\",\n" +
" \"image\": \"Caddisfly-Soil-EC\",\n" +
" \"imageScale\": \"centerCrop\",\n" +
" \"ranges\": \"50,12800\",\n" +
" \"responseFormat\": \"$2,$1\",\n" +
" \"instructions\": [],\n" +
" \"results\": [\n" +
" {\n" +
" \"id\": 1,\n" +
" \"name\": \"Soil Electrical Conductivity\",\n" +
" \"unit\": \"μS/cm\"\n" +
" },\n" +
" {\n" +
" \"id\": 2,\n" +
" \"name\": \"Temperature\",\n" +
" \"unit\": \"°Celsius\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"Soil - Moisture\",\n" +
" \"subtype\": \"sensor\",\n" +
" \"uuid\": \"0b4a0aaa-f556-4c11-a539-c4626582cca6\",\n" +
" \"deviceId\": \"Soil Moisture\",\n" +
" \"brand\": \"Caddisfly\",\n" +
" \"image\": \"Caddisfly-Soil-Moisture\",\n" +
" \"imageScale\": \"centerCrop\",\n" +
" \"ranges\": \"0,100\",\n" +
" \"responseFormat\": \"$1\",\n" +
" \"instructions\": [],\n" +
" \"results\": [\n" +
" {\n" +
" \"id\": 1,\n" +
" \"name\": \"Soil Moisture\",\n" +
" \"unit\": \"% VWC\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"]}";
private String DTO_LIST_JSON_OBJECT = "{\n" +
" \"code\": null, \n" +
" \"cursor\": null, \n" +
" \"dtoList\": [\n" +
" {\n" +
" \"ancestorIds\": [\n" +
" 0, \n" +
" 278889175415\n" +
" ], \n" +
" \"code\": \"1.10.36 all questions\", \n" +
" \"createdDateTime\": 1534846914945, \n" +
" \"dataApprovalGroupId\": null, \n" +
" \"defaultLanguageCode\": \"en\", \n" +
" \"description\": \"\", \n" +
" \"keyId\": 2989762914097, \n" +
" \"lastUpdateDateTime\": 1534846926804, \n" +
" \"monitoringGroup\": false, \n" +
" \"name\": \"1.10.36 all questions\", \n" +
" \"newLocaleSurveyId\": null, \n" +
" \"parentId\": 27888911545, \n" +
" \"path\": \"/_1.9.36 and 2.6.0/1.10.36 all questions\", \n" +
" \"privacyLevel\": \"PRIVATE\", \n" +
" \"projectType\": \"PROJECT\", \n" +
" \"published\": false, \n" +
" \"requireDataApproval\": false, \n" +
" \"surveyList\": null\n" +
" }\n" +
" ], \n" +
" \"message\": null, \n" +
" \"offset\": 0, \n" +
" \"resultCount\": 0, \n" +
" \"url\": null\n" +
"}\n";
@Test
void testReadSimpleJsonObject() {
FlowJsonObjectReader reader = new FlowJsonObjectReader();
TypeReference<QuestionDto> typeReference = new TypeReference<QuestionDto>() {};
QuestionDto testQuestionDto = null;
try {
testQuestionDto = reader.readObject(QUESTION_DTO_JSON_STRING, typeReference);
} catch (IOException e) {
//
}
assertEquals(testQuestionDto.getType(), QuestionDto.QuestionType.FREE_TEXT);
assertEquals(testQuestionDto.getText(),"How many toilets are present?");
assertFalse(testQuestionDto.getDependentFlag());
assertEquals(testQuestionDto.getQuestionGroupId(), 12345678L);
assertEquals(testQuestionDto.getType(), QuestionDto.QuestionType.FREE_TEXT);
assertEquals(testQuestionDto.getOrder(), 0);
}
@Test
void testReadComplexJsonObject() {
FlowJsonObjectReader reader = new FlowJsonObjectReader();
TypeReference<Map<String, List<CaddisflyResource>>> typeReference = new TypeReference<Map<String, List<CaddisflyResource>>>() {};
Map<String, List<CaddisflyResource>> resourcesMap = new HashMap<>();
try {
resourcesMap = reader.readObject(COMPLEX_JSON_OBJECT, typeReference);
} catch (IOException e) {
//
}
List<CaddisflyResource> resourcesList = resourcesMap.get("tests");
assertNotEquals(resourcesList, null);
assertEquals(resourcesList.size(), 2);
assertEquals(resourcesList.get(0).getResults().size(), 2);
assertEquals(resourcesList.get(0).getName(), "Soil - Electrical Conductivity");
assertEquals(resourcesList.get(1).getResults().size(), 1);
assertEquals(resourcesList.get(1).getUuid(), "0b4a0aaa-f556-4c11-a539-c4626582cca6");
}
@Test
void testDtoListResponses() {
FlowJsonObjectReader reader = new FlowJsonObjectReader();
TypeReference<SurveyGroupDto> typeReference = new TypeReference<SurveyGroupDto>() {};
List<SurveyGroupDto> surveyList = null;
try {
surveyList = reader.readDtoListObject(DTO_LIST_JSON_OBJECT, typeReference);
} catch (IOException e) {
//
}
assertNotEquals(surveyList, null);
assertEquals(surveyList.size(), 1);
assertEquals(surveyList.get(0).getName(),"1.10.36 all questions");
}
}
| [#2896] Correct parameters for test class assertions
* Review from @valllllll2000
| GAE/src/test/java/org/akvo/flow/util/FlowJsonObjectReaderTests.java | [#2896] Correct parameters for test class assertions * Review from @valllllll2000 | <ide><path>AE/src/test/java/org/akvo/flow/util/FlowJsonObjectReaderTests.java
<ide> } catch (IOException e) {
<ide> //
<ide> }
<del> assertEquals(testQuestionDto.getType(), QuestionDto.QuestionType.FREE_TEXT);
<del> assertEquals(testQuestionDto.getText(),"How many toilets are present?");
<add> assertEquals(QuestionDto.QuestionType.FREE_TEXT, testQuestionDto.getType());
<add> assertEquals("How many toilets are present?", testQuestionDto.getText());
<ide> assertFalse(testQuestionDto.getDependentFlag());
<del> assertEquals(testQuestionDto.getQuestionGroupId(), 12345678L);
<del> assertEquals(testQuestionDto.getType(), QuestionDto.QuestionType.FREE_TEXT);
<del> assertEquals(testQuestionDto.getOrder(), 0);
<add> assertEquals(12345678L, testQuestionDto.getQuestionGroupId());
<add> assertEquals(QuestionDto.QuestionType.FREE_TEXT, testQuestionDto.getType());
<add> assertEquals(0, testQuestionDto.getOrder());
<ide> }
<ide>
<ide> @Test
<ide> }
<ide>
<ide> List<CaddisflyResource> resourcesList = resourcesMap.get("tests");
<del> assertNotEquals(resourcesList, null);
<del> assertEquals(resourcesList.size(), 2);
<del> assertEquals(resourcesList.get(0).getResults().size(), 2);
<del> assertEquals(resourcesList.get(0).getName(), "Soil - Electrical Conductivity");
<del> assertEquals(resourcesList.get(1).getResults().size(), 1);
<del> assertEquals(resourcesList.get(1).getUuid(), "0b4a0aaa-f556-4c11-a539-c4626582cca6");
<add> assertNotEquals(null, resourcesList);
<add> assertEquals(2, resourcesList.size());
<add> assertEquals(2, resourcesList.get(0).getResults().size());
<add> assertEquals("Soil - Electrical Conductivity", resourcesList.get(0).getName());
<add> assertEquals(1, resourcesList.get(1).getResults().size());
<add> assertEquals("0b4a0aaa-f556-4c11-a539-c4626582cca6", resourcesList.get(1).getUuid());
<ide> }
<ide>
<ide> @Test
<ide> //
<ide> }
<ide>
<del> assertNotEquals(surveyList, null);
<del> assertEquals(surveyList.size(), 1);
<del> assertEquals(surveyList.get(0).getName(),"1.10.36 all questions");
<add> assertNotEquals(null, surveyList);
<add> assertEquals(1, surveyList.size());
<add> assertEquals("1.10.36 all questions", surveyList.get(0).getName());
<ide> }
<ide> } |
|
JavaScript | mit | 896f5a97de1d39a7e5591116c27b84d109b0d520 | 0 | maryrosecook/codewithisla | ;(function(exports) {
var Isla, _, codeAnalyzer, nodeDescriber, expressionDescriber, mapper;
if(typeof module !== 'undefined' && module.exports) { // node
Isla = require('../node_modules/isla/src/isla.js').Isla;
_ = require("Underscore");
codeAnalyzer = require('../src/code-analyzer').codeAnalyzer;
nodeDescriber = require('../src/node-describer').nodeDescriber;
expressionDescriber = require('../src/expression-describer')
.expressionDescriber;
mapper = require('../src/mapper').mapper;
} else { // browser
Isla = window.Isla;
_ = window._;
codeAnalyzer = window.codeAnalyzer;
nodeDescriber = window.nodeDescriber;
expressionDescriber = window.expressionDescriber;
mapper = window.mapper;
}
var id = "textHelper";
var TextHelper = function(terminal, consoleIndicator, envStore) {
this.write = function(e) {
if (e.event === "mousemove") {
handleHelp(terminal, e.point, envStore);
} else if (e.event === "mouseout") {
clearHelp();
}
};
var indicate = function(event, data) {
consoleIndicator.write({ event:event, data:data, id:id });
};
var clearHelp = function() {
$('#help').text("");
indicate("clear", {});
};
var handleHelp = function(terminal, point, envStore) {
var text = terminal.getText();
if (isThereHelpForToken(terminal, point, envStore)) {
var index = mapper.getIndex(terminal, text, point);
clearHelp();
indicate("indicate", { thing:"token", index: index });
displayHelp(getTokenHelp(text, index, envStore));
return;
} else if (isOverLine(terminal, point)) {
var lineNumber = mapper.getLineNumber(terminal, text, point);
var line = text.split("\n")[lineNumber];
if (line.length > 0) {
clearHelp();
indicate("indicate", { thing:"line", lineNumber: lineNumber });
displayHelp(getLineHelp(line, envStore));
return;
}
}
clearHelp();
};
};
var isThereHelpForToken = function(terminal, point, envStore) {
var text = terminal.getText();
var index = mapper.getIndex(terminal, text, point);
return index !== undefined &&
codeAnalyzer.getSyntaxTokenIndex(text, index) !== undefined &&
getTokenHelp(text, index, envStore) !== undefined;
};
var isOverLine = function(terminal, point) {
var text = terminal.getText();
return mapper.getLineNumber(terminal, text, point) !== undefined &&
(mapper.getIndex(terminal, text, point) === undefined ||
codeAnalyzer.expressionTokens(text) === undefined);
};
var getTokenHelp = function(text, index, envStore) {
return nodeDescriber.describe(text, index, envStore.latest());
};
var getLineHelp = function(line, envStore) {
var node = codeAnalyzer.expression(line);
return expressionDescriber.describe(node, envStore.latest());
};
var displayHelp = function(help) {
$('#help').text(help.body);
};
exports.TextHelper = TextHelper;
})(typeof exports === 'undefined' ? this : exports)
| src/text-helper.js | ;(function(exports) {
var Isla, _, codeAnalyzer, nodeDescriber, expressionDescriber, mapper;
if(typeof module !== 'undefined' && module.exports) { // node
Isla = require('../node_modules/isla/src/isla.js').Isla;
_ = require("Underscore");
codeAnalyzer = require('../src/code-analyzer').codeAnalyzer;
nodeDescriber = require('../src/node-describer').nodeDescriber;
expressionDescriber = require('../src/expression-describer').expressionDescriber;
mapper = require('../src/mapper').mapper;
} else { // browser
Isla = window.Isla;
_ = window._;
codeAnalyzer = window.codeAnalyzer;
nodeDescriber = window.nodeDescriber;
expressionDescriber = window.expressionDescriber;
mapper = window.mapper;
}
var id = "textHelper";
var TextHelper = function(terminal, consoleIndicator, envStore) {
this.write = function(e) {
if (e.event === "mousemove") {
handleHelp(terminal, e.point, envStore);
} else if (e.event === "mouseout") {
clearHelp();
}
};
var indicate = function(event, data) {
consoleIndicator.write({ event:event, data:data, id:id });
};
var clearHelp = function() {
$('#help').text("");
indicate("clear", { });
};
var handleHelp = function(terminal, point, envStore) {
var text = terminal.getText();
if (isThereHelpForToken(terminal, point, envStore)) {
var index = mapper.getIndex(terminal, text, point);
clearHelp();
indicate("indicate", { thing:"token", index: index });
displayHelp(getTokenHelp(text, index, envStore));
return;
} else if (isOverLine(terminal, point)) {
var lineNumber = mapper.getLineNumber(terminal, text, point);
var line = text.split("\n")[lineNumber];
if (line.length > 0) {
clearHelp();
indicate("indicate", { thing:"line", lineNumber: lineNumber });
displayHelp(getLineHelp(line, envStore));
return;
}
}
clearHelp();
};
};
var isThereHelpForToken = function(terminal, point, envStore) {
var text = terminal.getText();
var index = mapper.getIndex(terminal, text, point);
return index !== undefined &&
codeAnalyzer.getSyntaxTokenIndex(text, index) !== undefined &&
getTokenHelp(text, index, envStore) !== undefined;
};
var isOverLine = function(terminal, point) {
var text = terminal.getText();
return mapper.getLineNumber(terminal, text, point) !== undefined &&
(mapper.getIndex(terminal, text, point) === undefined ||
codeAnalyzer.expressionTokens(text) === undefined);
};
var getTokenHelp = function(text, index, envStore) {
return nodeDescriber.describe(text, index, envStore.latest());
};
var getLineHelp = function(line, envStore) {
var node = codeAnalyzer.expression(line);
return expressionDescriber.describe(node, envStore.latest());
};
var displayHelp = function(help) {
$('#help').text(help.body);
};
exports.TextHelper = TextHelper;
})(typeof exports === 'undefined' ? this : exports)
| Formatting. | src/text-helper.js | Formatting. | <ide><path>rc/text-helper.js
<ide> _ = require("Underscore");
<ide> codeAnalyzer = require('../src/code-analyzer').codeAnalyzer;
<ide> nodeDescriber = require('../src/node-describer').nodeDescriber;
<del> expressionDescriber = require('../src/expression-describer').expressionDescriber;
<add> expressionDescriber = require('../src/expression-describer')
<add> .expressionDescriber;
<ide> mapper = require('../src/mapper').mapper;
<ide> } else { // browser
<ide> Isla = window.Isla;
<ide>
<ide> var clearHelp = function() {
<ide> $('#help').text("");
<del> indicate("clear", { });
<add> indicate("clear", {});
<ide> };
<ide>
<ide> var handleHelp = function(terminal, point, envStore) { |
|
Java | mit | a1f9c42ce278f7271779089e332b57e22ffb2035 | 0 | nbv3/voogasalad_CS308 | import com.syntacticsugar.vooga.authoring.editor.AuthoringEnvironment;
import com.syntacticsugar.vooga.gameplayer.view.implementation.StartingScreenManager;
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
// new AuthoringEnvironment();
new StartingScreenManager(stage);
}
}
| src/Main.java | import com.syntacticsugar.vooga.authoring.editor.AuthoringEnvironment;
import com.syntacticsugar.vooga.gameplayer.view.implementation.StartingScreenManager;
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
new AuthoringEnvironment();
}
}
| Added commented line to test both authoring and gameplayer
| src/Main.java | Added commented line to test both authoring and gameplayer | <ide><path>rc/Main.java
<ide>
<ide> @Override
<ide> public void start(Stage stage) throws Exception {
<del> new AuthoringEnvironment();
<add>// new AuthoringEnvironment();
<add> new StartingScreenManager(stage);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 99d377df9f3b26c2396b9a0c07f5ee06dd3a12b1 | 0 | google/iosched,google/iosched,google/iosched | /*
* Copyright 2017 Google 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.google.samples.apps.iosched.server.schedule.server;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.samples.apps.iosched.rpc.ping.Ping;
import java.io.IOException;
import java.util.Arrays;
public enum PingServiceManager {
INSTANCE;
final String[] SCOPES = {"https://www.googleapis.com/auth/userinfo.email"};
Ping ping;
PingServiceManager() {
this.ping = getSyncService();
}
/**
* Get Sync service.
*
* @return Sync service.
* @throws IOException
*/
private Ping getSyncService() {
HttpTransport httpTransport = new UrlFetchTransport();
JacksonFactory jacksonFactory = new JacksonFactory();
final GoogleCredential credential;
try {
credential = GoogleCredential.getApplicationDefault()
.createScoped(Arrays.asList(SCOPES));
Ping ping = new Ping.Builder(httpTransport, jacksonFactory,
new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
credential.initialize(request);
}
}).setApplicationName("IOSched Backend").build();
return ping;
} catch (IOException e) {
return null;
}
}
}
| server/src/main/java/com/google/samples/apps/iosched/server/schedule/server/PingServiceManager.java | /*
* Copyright 2017 Google 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.google.samples.apps.iosched.server.schedule.server;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.samples.apps.iosched.rpc.ping.Ping;
import java.io.IOException;
import java.util.Arrays;
public enum PingServiceManager {
INSTANCE;
static final String[] SCOPES = {"https://www.googleapis.com/auth/userinfo.email"};
Ping ping;
PingServiceManager() {
this.ping = getSyncService();
}
/**
* Get Sync service.
*
* @return Sync service.
* @throws IOException
*/
private Ping getSyncService() {
HttpTransport httpTransport = new UrlFetchTransport();
JacksonFactory jacksonFactory = new JacksonFactory();
final GoogleCredential credential;
try {
credential = GoogleCredential.getApplicationDefault()
.createScoped(Arrays.asList(SCOPES));
Ping ping = new Ping.Builder(httpTransport, jacksonFactory,
new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
credential.initialize(request);
}
}).setApplicationName("IOSched Backend").build();
return ping;
} catch (IOException e) {
return null;
}
}
}
| Remove static from scopes.
Enums don't allow static variables in their constructors.
Removing statick in the case of a singleton should be fine
since there is only one instance of the object anyway.
Change-Id: If8985831a1c505d6bfde5e3cae1881d0bbdd7e44
| server/src/main/java/com/google/samples/apps/iosched/server/schedule/server/PingServiceManager.java | Remove static from scopes. | <ide><path>erver/src/main/java/com/google/samples/apps/iosched/server/schedule/server/PingServiceManager.java
<ide> public enum PingServiceManager {
<ide> INSTANCE;
<ide>
<del> static final String[] SCOPES = {"https://www.googleapis.com/auth/userinfo.email"};
<add> final String[] SCOPES = {"https://www.googleapis.com/auth/userinfo.email"};
<ide>
<ide> Ping ping;
<ide> |
|
Java | apache-2.0 | 739e248190a9d76856c2b44aae3b758a839bd88d | 0 | Joasis/WeeklyFoodPlanner | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package control;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.IngredientAmount;
import model.Week;
import model.Weekday;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
*
* @author Jonas
*/
public class ServerHandler {
private Socket socket;
private JSONArray jsonRecipies;
public ServerHandler(Socket socket) {
this.socket = socket;
}
public void sendData(Week week) {
// InputStream input = null;
try {
// input = socket.getInputStream();
// Scanner scan = new Scanner(input);
OutputStream ops = socket.getOutputStream();
// PrintWriter pw = new PrintWriter(output, true);
OutputStreamWriter osw = new OutputStreamWriter(ops);
jsonRecipies = new JSONArray();
JSONObject weekObject = new JSONObject();
weekObject.put("week", week.getDate());
for (Weekday wkday : week.getWeekdays()) {
JSONObject recipe = new JSONObject();
recipe.put("name", wkday.getRecipe().getName());
// recipe.put("date", wkday.getDate());
recipe.put("omit", wkday.isOmit());
recipe.put("active", wkday.getRecipe().isActive());
JSONArray ingList = new JSONArray();
for (IngredientAmount ingAm : wkday.getRecipe().getIngredientList()) {
JSONObject ingredient = new JSONObject();
ingredient.put("name", ingAm.getIngredient().getName());
ingredient.put("amount", ingAm.getAmount());
ingredient.put("unit", ingAm.getUnit().getShortname());
ingList.add(ingredient);
}
recipe.put("ingredientList", ingList);
jsonRecipies.add(recipe);
}
weekObject.put("recipies", jsonRecipies);
String output = weekObject.toJSONString();
if (!socket.isClosed()) {
osw.write(output);
// String request = scan.nextLine();
// String response = request + " (" + request.length() + ")";
// pw.println("Du er forbundet");
}
osw.flush();
osw.close();
} catch (IOException ex) {
Logger.getLogger(ServerHandler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
// try {
// input.close();
// } catch (IOException ex) {
// Logger.getLogger(ServerHandler.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
}
| src/control/ServerHandler.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package control;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.IngredientAmount;
import model.Week;
import model.Weekday;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
*
* @author Jonas
*/
public class ServerHandler {
private Socket socket;
private JSONArray json;
public ServerHandler(Socket socket) {
this.socket = socket;
}
public void sendData(Week week) {
// InputStream input = null;
try {
// input = socket.getInputStream();
// Scanner scan = new Scanner(input);
OutputStream ops = socket.getOutputStream();
// PrintWriter pw = new PrintWriter(output, true);
OutputStreamWriter osw = new OutputStreamWriter(ops);
ArrayList<String> list = new ArrayList<>();
json = new JSONArray();
for (Weekday wkday : week.getWeekdays()) {
JSONObject recipe = new JSONObject();
recipe.put("week", week.getDate());
recipe.put("name", wkday.getRecipe().getName());
recipe.put("date", wkday.getDate());
recipe.put("omit", wkday.isOmit());
recipe.put("active", wkday.getRecipe().isActive());
JSONArray ingList = new JSONArray();
for (IngredientAmount ingAm : wkday.getRecipe().getIngredientList()) {
JSONObject ingredient = new JSONObject();
ingredient.put("name", ingAm.getIngredient().getName());
ingredient.put("amount", ingAm.getAmount());
ingredient.put("unit", ingAm.getUnit().getShortname());
ingList.add(ingredient);
}
recipe.put("ingredientList", ingList);
json.add(recipe);
}
String output = json.toJSONString();
if (!socket.isClosed()) {
osw.write(output);
// String request = scan.nextLine();
// String response = request + " (" + request.length() + ")";
// pw.println("Du er forbundet");
}
osw.flush();
osw.close();
} catch (IOException ex) {
Logger.getLogger(ServerHandler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
// try {
// input.close();
// } catch (IOException ex) {
// Logger.getLogger(ServerHandler.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
}
| serverhandler | src/control/ServerHandler.java | serverhandler | <ide><path>rc/control/ServerHandler.java
<ide> public class ServerHandler {
<ide>
<ide> private Socket socket;
<del> private JSONArray json;
<add> private JSONArray jsonRecipies;
<ide>
<ide> public ServerHandler(Socket socket) {
<ide> this.socket = socket;
<ide> OutputStream ops = socket.getOutputStream();
<ide> // PrintWriter pw = new PrintWriter(output, true);
<ide> OutputStreamWriter osw = new OutputStreamWriter(ops);
<del> ArrayList<String> list = new ArrayList<>();
<ide>
<del> json = new JSONArray();
<add> jsonRecipies = new JSONArray();
<add> JSONObject weekObject = new JSONObject();
<add> weekObject.put("week", week.getDate());
<ide> for (Weekday wkday : week.getWeekdays()) {
<ide> JSONObject recipe = new JSONObject();
<del> recipe.put("week", week.getDate());
<ide> recipe.put("name", wkday.getRecipe().getName());
<del> recipe.put("date", wkday.getDate());
<add>// recipe.put("date", wkday.getDate());
<ide> recipe.put("omit", wkday.isOmit());
<ide> recipe.put("active", wkday.getRecipe().isActive());
<ide> JSONArray ingList = new JSONArray();
<ide> ingList.add(ingredient);
<ide> }
<ide> recipe.put("ingredientList", ingList);
<del> json.add(recipe);
<add> jsonRecipies.add(recipe);
<ide> }
<del> String output = json.toJSONString();
<add> weekObject.put("recipies", jsonRecipies);
<add> String output = weekObject.toJSONString();
<ide> if (!socket.isClosed()) {
<ide> osw.write(output);
<ide> // String request = scan.nextLine(); |
|
Java | apache-2.0 | 6ee3019b038dc6b4eb7f601e3871e9e5ffb23270 | 0 | Biocodr/TomP2P,Biocodr/TomP2P | package net.tomp2p.connection;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.util.concurrent.EventExecutor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Stripped-down version of the IdleStateHandler.
*/
public class IdleStateHandlerTomP2P extends ChannelDuplexHandler {
private final long allIdleTimeMillis;
private volatile long lastReadTime;
private volatile long lastWriteTime;
private volatile ScheduledFuture<?> allIdleTimeout;
private volatile int state; // 0 - none, 1 - initialized, 2 - destroyed
/**
* Creates a new instance firing {@link IdleStateEvent}s.
*
* @param allIdleTimeSeconds
* an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE} will be triggered when neither
* read nor write was performed for the specified period of time. Specify {@code 0} to disable.
*/
public IdleStateHandlerTomP2P(int allIdleTimeSeconds) {
this(allIdleTimeSeconds, TimeUnit.SECONDS);
}
/**
* Creates a new instance firing {@link IdleStateEvent}s.
*
* @param allIdleTime
* an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE} will be triggered when neither
* read nor write was performed for the specified period of time. Specify {@code 0} to disable.
* @param unit
* the {@link TimeUnit} of {@code readerIdleTime}, {@code writeIdleTime}, and {@code allIdleTime}
*/
public IdleStateHandlerTomP2P(long allIdleTime, TimeUnit unit) {
if (unit == null) {
throw new NullPointerException("unit");
}
if (allIdleTime <= 0) {
allIdleTimeMillis = 0;
} else {
allIdleTimeMillis = Math.max(unit.toMillis(allIdleTime), 1);
}
}
/**
* Return the allIdleTime that was given when instance this class in milliseconds.
*
*/
public long getAllIdleTimeInMillis() {
return allIdleTimeMillis;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
if (ctx.channel().isActive() && ctx.channel().isRegistered()) {
// channelActvie() event has been fired already, which means this.channelActive() will
// not be invoked. We have to initialize here instead.
initialize(ctx);
} else {
// channelActive() event has not been fired yet. this.channelActive() will be invoked
// and initialization will occur there.
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
destroy();
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// Initialize early if channel is active already.
if (ctx.channel().isActive()) {
initialize(ctx);
}
super.channelRegistered(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// This method will be invoked only if this handler was added
// before channelActive() event is fired. If a user adds this handler
// after the channelActive() event, initialize() will be called by beforeAdd().
initialize(ctx);
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
destroy();
super.channelInactive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
lastReadTime = System.currentTimeMillis();
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
lastWriteTime = System.currentTimeMillis();
}
});
ctx.write(msg, promise);
}
private void initialize(ChannelHandlerContext ctx) {
// Avoid the case where destroy() is called before scheduling timeouts.
// See: https://github.com/netty/netty/issues/143
switch (state) {
case 1:
case 2:
return;
}
state = 1;
lastReadTime = lastWriteTime = System.currentTimeMillis();
if (allIdleTimeMillis > 0) {
allIdleTimeout = ctx.executor().schedule(new AllIdleTimeoutTask(ctx), allIdleTimeMillis,
TimeUnit.MILLISECONDS);
}
}
private void destroy() {
state = 2;
if (allIdleTimeout != null) {
allIdleTimeout.cancel(false);
allIdleTimeout = null;
}
}
private final class AllIdleTimeoutTask implements Runnable {
private final ChannelHandlerContext ctx;
AllIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run() {
if (!ctx.channel().isOpen()) {
return;
}
long currentTime = System.currentTimeMillis();
long lastIoTime = Math.max(lastReadTime, lastWriteTime);
long nextDelay = allIdleTimeMillis - (currentTime - lastIoTime);
if (nextDelay <= 0) {
// Both reader and writer are idle - set a new timeout and
// notify the callback.
allIdleTimeout = ctx.executor().schedule(this, allIdleTimeMillis, TimeUnit.MILLISECONDS);
try {
ctx.fireUserEventTriggered(this);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Either read or write occurred before the timeout - set a new
// timeout with shorter delay.
allIdleTimeout = ctx.executor().schedule(this, nextDelay, TimeUnit.MILLISECONDS);
}
}
}
}
| core/src/main/java/net/tomp2p/connection/IdleStateHandlerTomP2P.java | package net.tomp2p.connection;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.util.concurrent.EventExecutor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Stripped-down version of the IdleStateHandler.
*/
public class IdleStateHandlerTomP2P extends ChannelDuplexHandler {
private final long allIdleTimeMillis;
private volatile long lastReadTime;
private volatile long lastWriteTime;
private volatile ScheduledFuture<?> allIdleTimeout;
private volatile int state; // 0 - none, 1 - initialized, 2 - destroyed
/**
* Creates a new instance firing {@link IdleStateEvent}s.
*
* @param allIdleTimeSeconds
* an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE} will be triggered when neither
* read nor write was performed for the specified period of time. Specify {@code 0} to disable.
*/
public IdleStateHandlerTomP2P(int allIdleTimeSeconds) {
this(allIdleTimeSeconds, TimeUnit.SECONDS);
}
/**
* Creates a new instance firing {@link IdleStateEvent}s.
*
* @param allIdleTime
* an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE} will be triggered when neither
* read nor write was performed for the specified period of time. Specify {@code 0} to disable.
* @param unit
* the {@link TimeUnit} of {@code readerIdleTime}, {@code writeIdleTime}, and {@code allIdleTime}
*/
public IdleStateHandlerTomP2P(long allIdleTime, TimeUnit unit) {
if (unit == null) {
throw new NullPointerException("unit");
}
if (allIdleTime <= 0) {
allIdleTimeMillis = 0;
} else {
allIdleTimeMillis = Math.max(unit.toMillis(allIdleTime), 1);
}
}
/**
* Return the allIdleTime that was given when instance this class in milliseconds.
*
*/
public long getAllIdleTimeInMillis() {
return allIdleTimeMillis;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
if (ctx.channel().isActive() && ctx.channel().isRegistered()) {
// channelActvie() event has been fired already, which means this.channelActive() will
// not be invoked. We have to initialize here instead.
initialize(ctx);
} else {
// channelActive() event has not been fired yet. this.channelActive() will be invoked
// and initialization will occur there.
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
destroy();
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// Initialize early if channel is active already.
if (ctx.channel().isActive()) {
initialize(ctx);
}
super.channelRegistered(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// This method will be invoked only if this handler was added
// before channelActive() event is fired. If a user adds this handler
// after the channelActive() event, initialize() will be called by beforeAdd().
initialize(ctx);
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
destroy();
super.channelInactive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
lastReadTime = System.currentTimeMillis();
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
lastWriteTime = System.currentTimeMillis();
}
});
ctx.write(msg, promise);
}
private void initialize(ChannelHandlerContext ctx) {
// Avoid the case where destroy() is called before scheduling timeouts.
// See: https://github.com/netty/netty/issues/143
switch (state) {
case 1:
case 2:
return;
}
state = 1;
EventExecutor loop = ctx.executor();
lastReadTime = lastWriteTime = System.currentTimeMillis();
if (allIdleTimeMillis > 0) {
allIdleTimeout = loop.schedule(new AllIdleTimeoutTask(ctx), allIdleTimeMillis,
TimeUnit.MILLISECONDS);
}
}
private void destroy() {
state = 2;
if (allIdleTimeout != null) {
allIdleTimeout.cancel(false);
allIdleTimeout = null;
}
}
private final class AllIdleTimeoutTask implements Runnable {
private final ChannelHandlerContext ctx;
AllIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run() {
if (!ctx.channel().isOpen()) {
return;
}
long currentTime = System.currentTimeMillis();
long lastIoTime = Math.max(lastReadTime, lastWriteTime);
long nextDelay = allIdleTimeMillis - (currentTime - lastIoTime);
if (nextDelay <= 0) {
// Both reader and writer are idle - set a new timeout and
// notify the callback.
allIdleTimeout = ctx.executor().schedule(this, allIdleTimeMillis, TimeUnit.MILLISECONDS);
try {
channelIdle(ctx);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Either read or write occurred before the timeout - set a new
// timeout with shorter delay.
allIdleTimeout = ctx.executor().schedule(this, nextDelay, TimeUnit.MILLISECONDS);
}
}
}
private void channelIdle(ChannelHandlerContext ctx) throws Exception {
ctx.fireUserEventTriggered(this);
}
}
| IdleStateHandlerTomP2P: remove unnecessary code
Signed-off-by: Christian Lüthold <[email protected]> | core/src/main/java/net/tomp2p/connection/IdleStateHandlerTomP2P.java | IdleStateHandlerTomP2P: remove unnecessary code | <ide><path>ore/src/main/java/net/tomp2p/connection/IdleStateHandlerTomP2P.java
<ide>
<ide> state = 1;
<ide>
<del> EventExecutor loop = ctx.executor();
<del>
<ide> lastReadTime = lastWriteTime = System.currentTimeMillis();
<ide>
<ide> if (allIdleTimeMillis > 0) {
<del> allIdleTimeout = loop.schedule(new AllIdleTimeoutTask(ctx), allIdleTimeMillis,
<add> allIdleTimeout = ctx.executor().schedule(new AllIdleTimeoutTask(ctx), allIdleTimeMillis,
<ide> TimeUnit.MILLISECONDS);
<ide> }
<ide> }
<ide> // notify the callback.
<ide> allIdleTimeout = ctx.executor().schedule(this, allIdleTimeMillis, TimeUnit.MILLISECONDS);
<ide> try {
<del> channelIdle(ctx);
<add> ctx.fireUserEventTriggered(this);
<ide> } catch (Throwable t) {
<ide> ctx.fireExceptionCaught(t);
<ide> }
<ide> }
<ide> }
<ide> }
<del>
<del> private void channelIdle(ChannelHandlerContext ctx) throws Exception {
<del> ctx.fireUserEventTriggered(this);
<del> }
<ide> } |
|
Java | apache-2.0 | ad66360e064d58c0445a763b9a63768745d3539d | 0 | DigitalPebble/storm-crawler,XciD/storm-crawler,anjackson/storm-crawler,jorgelbg/storm-crawler,anjackson/storm-crawler,foromer4/storm-crawler,DigitalPebble/storm-crawler,jorgelbg/storm-crawler,foromer4/storm-crawler,XciD/storm-crawler | /**
* Licensed to DigitalPebble Ltd under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* DigitalPebble licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpebble.stormcrawler.solr;
import java.io.IOException;
import java.util.Map;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.storm.shade.org.apache.commons.lang.StringUtils;
import com.digitalpebble.stormcrawler.util.ConfUtils;
@SuppressWarnings("serial")
public class SolrConnection {
private SolrClient client;
private UpdateRequest request;
private SolrConnection(SolrClient sc, UpdateRequest r) {
client = sc;
request = r;
}
public SolrClient getClient() {
return client;
}
public UpdateRequest getRequest() {
return request;
}
public static SolrClient getClient(Map stormConf, String boltType) {
String zkHost = ConfUtils.getString(stormConf, "solr." + boltType
+ ".zkhost", null);
String solrUrl = ConfUtils.getString(stormConf, "solr." + boltType
+ ".url", null);
String collection = ConfUtils.getString(stormConf, "solr." + boltType
+ ".collection", null);
int queueSize = ConfUtils.getInt(stormConf, "solr." + boltType
+ ".queueSize", -1);
SolrClient client;
if (StringUtils.isNotBlank(zkHost)) {
client = new CloudSolrClient.Builder().withZkHost(zkHost).build();
if (StringUtils.isNotBlank(collection)) {
((CloudSolrClient) client).setDefaultCollection(collection);
}
} else if (StringUtils.isNotBlank(solrUrl)) {
if (queueSize == -1) {
client = new HttpSolrClient.Builder(solrUrl).build();
} else {
client = new ConcurrentUpdateSolrClient.Builder(solrUrl)
.withQueueSize(queueSize).build();
}
} else {
throw new RuntimeException(
"SolrClient should have zk or solr URL set up");
}
return client;
}
public static UpdateRequest getRequest(Map stormConf, String boltType) {
int commitWithin = ConfUtils.getInt(stormConf, "solr." + boltType
+ ".commit.within", -1);
UpdateRequest request = new UpdateRequest();
if (commitWithin != -1) {
request.setCommitWithin(commitWithin);
}
return request;
}
public static SolrConnection getConnection(Map stormConf, String boltType) {
SolrClient client = getClient(stormConf, boltType);
UpdateRequest request = getRequest(stormConf, boltType);
return new SolrConnection(client, request);
}
public void close() throws IOException, SolrServerException {
if (client != null) {
client.commit();
client.close();
}
}
}
| external/solr/src/main/java/com/digitalpebble/stormcrawler/solr/SolrConnection.java | /**
* Licensed to DigitalPebble Ltd under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* DigitalPebble licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalpebble.stormcrawler.solr;
import java.io.IOException;
import java.util.Map;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.storm.shade.org.apache.commons.lang.StringUtils;
import com.digitalpebble.stormcrawler.util.ConfUtils;
@SuppressWarnings("serial")
public class SolrConnection {
private SolrClient client;
private UpdateRequest request;
private SolrConnection(SolrClient sc, UpdateRequest r) {
client = sc;
request = r;
}
public SolrClient getClient() {
return client;
}
public UpdateRequest getRequest() {
return request;
}
public static SolrClient getClient(Map stormConf, String boltType) {
String zkHost = ConfUtils.getString(stormConf, "solr." + boltType
+ ".zkhost", null);
String solrUrl = ConfUtils.getString(stormConf, "solr." + boltType
+ ".url", null);
String collection = ConfUtils.getString(stormConf, "solr." + boltType
+ ".collection", null);
SolrClient client;
if (StringUtils.isNotBlank(zkHost)) {
client = new CloudSolrClient.Builder().withZkHost(zkHost).build();
if (StringUtils.isNotBlank(collection)) {
((CloudSolrClient) client).setDefaultCollection(collection);
}
} else if (StringUtils.isNotBlank(solrUrl)) {
client = new HttpSolrClient.Builder(solrUrl).build();
} else {
throw new RuntimeException(
"SolrClient should have zk or solr URL set up");
}
return client;
}
public static UpdateRequest getRequest(Map stormConf, String boltType) {
int commitWithin = ConfUtils.getInt(stormConf, "solr." + boltType
+ ".commit.within", -1);
UpdateRequest request = new UpdateRequest();
if (commitWithin != -1) {
request.setCommitWithin(commitWithin);
}
return request;
}
public static SolrConnection getConnection(Map stormConf, String boltType) {
SolrClient client = getClient(stormConf, boltType);
UpdateRequest request = getRequest(stormConf, boltType);
return new SolrConnection(client, request);
}
public void close() throws IOException, SolrServerException {
if (client != null) {
client.commit();
client.close();
}
}
}
| Use ConcurrentUpdateSolrClient; fixes #183
| external/solr/src/main/java/com/digitalpebble/stormcrawler/solr/SolrConnection.java | Use ConcurrentUpdateSolrClient; fixes #183 | <ide><path>xternal/solr/src/main/java/com/digitalpebble/stormcrawler/solr/SolrConnection.java
<ide> import org.apache.solr.client.solrj.SolrClient;
<ide> import org.apache.solr.client.solrj.SolrServerException;
<ide> import org.apache.solr.client.solrj.impl.CloudSolrClient;
<add>import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrClient;
<ide> import org.apache.solr.client.solrj.impl.HttpSolrClient;
<ide> import org.apache.solr.client.solrj.request.UpdateRequest;
<ide> import org.apache.storm.shade.org.apache.commons.lang.StringUtils;
<ide> + ".url", null);
<ide> String collection = ConfUtils.getString(stormConf, "solr." + boltType
<ide> + ".collection", null);
<add> int queueSize = ConfUtils.getInt(stormConf, "solr." + boltType
<add> + ".queueSize", -1);
<ide>
<ide> SolrClient client;
<ide>
<ide> ((CloudSolrClient) client).setDefaultCollection(collection);
<ide> }
<ide> } else if (StringUtils.isNotBlank(solrUrl)) {
<del> client = new HttpSolrClient.Builder(solrUrl).build();
<add> if (queueSize == -1) {
<add> client = new HttpSolrClient.Builder(solrUrl).build();
<add> } else {
<add> client = new ConcurrentUpdateSolrClient.Builder(solrUrl)
<add> .withQueueSize(queueSize).build();
<add> }
<ide> } else {
<ide> throw new RuntimeException(
<ide> "SolrClient should have zk or solr URL set up"); |
|
JavaScript | mit | 7a49d86d3c2ce829806e8ff5b921f602404bbc0f | 0 | QuickGroup/QCObjects,QuickGroup/QCObjects | 'use strict';
Package('cl.quickcorp.components',[
Class('MarkdownComponent',Component,{
name:'markdowncomponent',
url:ComponentURI({
'COMPONENTS_BASE_PATH':Component.basePath,
'COMPONENT_NAME':'README',
'TPLEXTENSION':'md',
'TPL_SOURCE':'default' //here is always default in order to get the right uri
}),
tplsource:'none',
cached:false,
controller:null,
view:null,
templateHandler: 'MarkdownTemplateHandler',
_new_:function (o){
_super_('Component','_new_').call(this,o);
this.tplsource='default';
this.rebuild();
}
})
]);
| src/cl.quickcorp.components.js | 'use strict';
Package('cl.quickcorp.components',[
Class('MarkdownComponent',Component,{
name:'markdowncomponent',
url:'README.md',
tplsource:'none',
cached:false,
controller:null,
view:null,
templateHandler: 'MarkdownTemplateHandler',
_new_:function (o){
_super_('Component','_new_').call(this,o);
this.tplsource='default';
this.rebuild();
}
})
]);
| README url
| src/cl.quickcorp.components.js | README url | <ide><path>rc/cl.quickcorp.components.js
<ide> Package('cl.quickcorp.components',[
<ide> Class('MarkdownComponent',Component,{
<ide> name:'markdowncomponent',
<del> url:'README.md',
<add> url:ComponentURI({
<add> 'COMPONENTS_BASE_PATH':Component.basePath,
<add> 'COMPONENT_NAME':'README',
<add> 'TPLEXTENSION':'md',
<add> 'TPL_SOURCE':'default' //here is always default in order to get the right uri
<add> }),
<ide> tplsource:'none',
<ide> cached:false,
<ide> controller:null, |
|
JavaScript | apache-2.0 | f9de914da821fd3bc3bb0eb52fc9d547a9cc2aac | 0 | rlmv/gitbook-plugin-include |
var path = require('path');
var fs = require('fs');
var Q = require('q');
module.exports = {
book: {}, // we should be able to leave this out, but we get a
// "Cannot read property 'html' of undefined" error
hooks: {
"page:before": function(page) {
// page.raw is the path to the raw file
// page.path is the path to the page in the gitbook
// page.content is a string with the file markdown content
// use multiline flag to grok every line, and global flag to
// find all matches -- finds '' and "" filenames
// -- add initial \s* to eat up whitespace?
var re = /^!INCLUDE\s+(?:\"([^\"]+)\"|'([^']+)')\s*$/gm;
var dir = path.dirname(page.raw);
var files = {};
var promises = [];
// find all !INCLUDE statements.
// read and save files to include using promises
var res;
while ((res = re.exec(page.content)) !== null) {
var filename = res[1] || res[2];
var filepath = path.join(dir, filename);
var promise = Q.nfcall(fs.readFile, filepath)
// closure to save read text by filename
.then(function(filename) {
return function(text) { files[filename] = text; }
}(filename));
promises.push(promise);
}
// once all files are read, replace !INCLUDE statements with
// appropriate file content
return Q.all(promises)
.then(function() {
page.content = page.content.replace(re, function(match, p1, p2) {
var filename = p1 || p2;
console.log("INCLUDING " + filename);
return files[filename].toString().trim();
});
return page;
})
}
}
};
| index.js |
var path = require('path');
var fs = require('fs');
var Q = require('q');
module.exports = {
book: {}, // we should be able to leave this out, but we get a
// "Cannot read property 'html' of undefined" error
hooks: {
"page:before": function(page) {
// page.raw is the path to the raw file
// page.path is the path to the page in the gitbook
// page.content is a string with the file markdown content
// use multiline flag to grok every line, and global flag to
// find all matches -- finds '' and "" filenames
// -- add initial \s* to eat up whitespace?
var re = /^!INCLUDE\s+(?:\"([^\"]+)\"|'([^']+)')\s*$/gm;
var dir = path.dirname(page.raw);
var files = {};
var promises = [];
// find all !INCLUDE statements.
// read and save files to include using promises
var res;
while ((res = re.exec(page.content)) !== null) {
var filename = res[1] || res[2];
var filepath = path.join(dir, filename);
var promise = Q.nfcall(fs.readFile, filepath)
// closure to save read text by filename
.then(function(filename) {
return function(text) { files[filename] = text; }
}(filename));
promises.push(promise);
}
// once all files are read, replace !INCLUDE statements with
// appropriate file content
return Q.all(promises)
.then(function() {
page.content = page.content.replace(re, function(match, p1, p2) {
var filename = p1 || p2;
console.log("INCLUDING " + filename);
return files[filename];
});
return page;
})
}
}
};
| trim whitespace from included files
| index.js | trim whitespace from included files | <ide><path>ndex.js
<ide> page.content = page.content.replace(re, function(match, p1, p2) {
<ide> var filename = p1 || p2;
<ide> console.log("INCLUDING " + filename);
<del> return files[filename];
<add> return files[filename].toString().trim();
<ide> });
<ide> return page;
<ide> }) |
|
JavaScript | apache-2.0 | 378a9136d6f1c55acb985adfee691286ccc9f393 | 0 | grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation | import React from 'react';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import TabBar from './TabBar';
import Tweets from './Tweets';
import Follows from './Follows';
export default ({tweets, follows, stateNavigator}) => (
<ScrollableTabView
prerenderingSiblingsNumber={1}
renderTabBar={() => <TabBar stateNavigator={stateNavigator} />}>
<Tweets tweets={tweets} stateNavigator={stateNavigator} tabLabel="Timeline" />
<Follows follows={follows} stateNavigator={stateNavigator} tabLabel="Notification" />
</ScrollableTabView>
);
| NavigationReactNative/sample/twitter/Home.android.js | import React from 'react';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import TabBar from './TabBar';
import Tweets from './Tweets';
import Follows from './Follows';
export default ({tweets, follows, stateNavigator}) => (
<ScrollableTabView renderTabBar={() => <TabBar stateNavigator={stateNavigator} />}>
<Tweets tweets={tweets} stateNavigator={stateNavigator} tabLabel="Timeline" />
<Follows follows={follows} stateNavigator={stateNavigator} tabLabel="Notification" />
</ScrollableTabView>
);
| Prerendered notifications
| NavigationReactNative/sample/twitter/Home.android.js | Prerendered notifications | <ide><path>avigationReactNative/sample/twitter/Home.android.js
<ide> import Follows from './Follows';
<ide>
<ide> export default ({tweets, follows, stateNavigator}) => (
<del> <ScrollableTabView renderTabBar={() => <TabBar stateNavigator={stateNavigator} />}>
<add> <ScrollableTabView
<add> prerenderingSiblingsNumber={1}
<add> renderTabBar={() => <TabBar stateNavigator={stateNavigator} />}>
<ide> <Tweets tweets={tweets} stateNavigator={stateNavigator} tabLabel="Timeline" />
<ide> <Follows follows={follows} stateNavigator={stateNavigator} tabLabel="Notification" />
<ide> </ScrollableTabView> |
|
JavaScript | mit | a12d9987f98f7808fb87efbcc12dca6a642fbc76 | 0 | pex-gl/pex-context,variablestudio/pex-context | // TODO: get rid of Ramda
const log = require('debug')('context')
// const viz = require('viz.js')
const isBrowser = require('is-browser')
const createGL = require('pex-gl')
const assert = require('assert')
const createTexture = require('./texture')
const createFramebuffer = require('./framebuffer')
const createPass = require('./pass')
const createPipeline = require('./pipeline')
const createProgram = require('./program')
const createBuffer = require('./buffer')
const raf = require('raf')
let ID = 0
function createContext (opts) {
assert(!opts || (typeof opts === 'object'), 'pex-context: createContext requires opts argument to be null or an object')
let gl = null
if (!opts || !opts.gl) gl = createGL(opts)
else if (opts && opts.gl) gl = opts.gl
assert(gl, 'pex-context: createContext failed')
const ext = gl.getExtension('OES_texture_half_float')
if (ext) {
gl.HALF_FLOAT = ext.HALF_FLOAT_OES
}
gl.getExtension('OES_element_index_uint')
const BlendFactor = {
One: gl.ONE,
Zero: gl.ZERO,
SrcAlpha: gl.SRC_ALPHA,
OneMinusSrcAlpha: gl.ONE_MINUS_SRC_ALPHA,
DstAlpha: gl.DST_ALPHA,
OneMinusDstAlpha: gl.ONE_MINUS_DST_ALPHA,
SrcColor: gl.SRC_COLOR,
OneMinusSrcColor: gl.ONE_MINUS_SRC_COLOR,
DstColor: gl.DST_COLOR,
OneMinusDstColor: gl.ONE_MINUS_DST_COLOR
}
const CubemapFace = {
PositiveX: gl.TEXTURE_CUBE_MAP_POSITIVE_X,
NegativeX: gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
PositiveY: gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
NegativeY: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
PositiveZ: gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
NegativeZ: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
}
const DepthFunc = {
Never: gl.NEVER,
Less: gl.LESS,
Equal: gl.EQUAL,
LessEqual: gl.LEQUAL,
Greater: gl.GREATER,
NotEqual: gl.NOTEQUAL,
GreaterEqual: gl.GEQUAL,
Always: gl.ALWAYS
}
const DataType = {
Float32: gl.FLOAT,
Uint8: gl.UNSIGNED_BYTE,
Uint16: gl.UNSIGNED_SHORT,
Uint32: gl.UNSIGNED_INT
}
const Face = {
Front: gl.FRONT,
Back: gl.BACK,
FrontAndBack: gl.FRONT_AND_BACK
}
const Filter = {
Nearest: gl.NEAREST,
Linear: gl.LINEAR,
NearestMipmapNearest: gl.NEAREST_MIPMAP_NEAREST,
NearestMipmapLinear: gl.NEAREST_MIPMAP_LINEAR,
LinearMipmapNearest: gl.LINEAR_MIPMAP_NEAREST,
LinearMipmapLinear: gl.LINEAR_MIPMAP_LINEAR
}
const PixelFormat = {
RGBA8: 'rgba8', // gl.RGBA + gl.UNSIGNED_BYTE
RGBA32F: 'rgba32f', // gl.RGBA + gl.FLOAT
RGBA16F: 'rgba16f', // gl.RGBA + gl.HALF_FLOAT
R32F: 'r32f', // gl.ALPHA + gl.FLOAT
R16F: 'r16f', // gl.ALPHA + gl.HALF_FLOAT
Depth: 'depth' // gl.DEPTH_COMPONENT
}
const Encoding = {
Linear: 1,
Gamma: 2,
SRGB: 3,
RGBM: 4
}
const Primitive = {
Points: gl.POINTS,
Lines: gl.LINES,
LineStrip: gl.LINE_STRIP,
Triangles: gl.TRIANGLES,
TriangleStrip: gl.TRIANGLE_STRIP
}
const Wrap = {
ClampToEdge: gl.CLAMP_TO_EDGE,
Repeat: gl.REPEAT
}
const defaultState = {
pass: {
framebuffer: {
target: gl.FRAMEBUFFER,
handle: null,
width: gl.drawingBufferWidth,
height: gl.drawingBufferHeight
},
clearColor: [0, 0, 0, 1],
clearDepth: 1
},
pipeline: {
program: null,
depthWrite: true,
depthTest: false,
depthFunc: DepthFunc.LessEqual,
blendEnabled: false,
cullFaceEnabled: false,
cullFace: Face.Back,
primitive: Primitive.Triangles
},
viewport: [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight]
}
const capabilities = {
}
// extensions
if (!gl.drawElementsInstanced) {
const ext = gl.getExtension('ANGLE_instanced_arrays')
if (!ext) {
// TODO: this._caps[CAPS_INSTANCED_ARRAYS] = false;
gl.drawElementsInstanced = function () {
throw new Error('gl.drawElementsInstanced not available. ANGLE_instanced_arrays not supported')
}
gl.drawArraysInstanced = function () {
throw new Error('gl.drawArraysInstanced not available. ANGLE_instanced_arrays not supported')
}
gl.vertexAttribDivisor = function () {
throw new Error('gl.vertexAttribDivisor not available. ANGLE_instanced_arrays not supported')
}
capabilities.instancing = false
} else {
// TODO: this._caps[CAPS_INSTANCED_ARRAYS] = true;
gl.drawElementsInstanced = ext.drawElementsInstancedANGLE.bind(ext)
gl.drawArraysInstanced = ext.drawArraysInstancedANGLE.bind(ext)
gl.vertexAttribDivisor = ext.vertexAttribDivisorANGLE.bind(ext)
capabilities.instancing = false
}
} else {
capabilities.instancing = true
}
if (!gl.drawBuffers) {
const ext = gl.getExtension('WEBGL_draw_buffers')
if (!ext) {
gl.drawBuffers = function () {
throw new Error('WEBGL_draw_buffers not supported')
}
} else {
gl.drawBuffers = ext.drawBuffersWEBGL.bind(ext)
}
}
const ctx = {
gl: gl,
BlendFactor: BlendFactor,
CubemapFace: CubemapFace,
DataType: DataType,
DepthFunc: DepthFunc,
Face: Face,
Filter: Filter,
PixelFormat: PixelFormat,
Encoding: Encoding,
Primitive: Primitive,
Wrap: Wrap,
debugMode: false,
capabilities: capabilities,
// debugGraph: '',
debugCommands: [],
resources: [],
stack: [ defaultState ],
defaultState: defaultState,
state: {
pass: {
framebuffer: defaultState.pass.framebuffer
},
activeTextures: [],
activeAttributes: []
},
getGLString: function (glEnum) {
let str = ''
for (let key in gl) {
if ((gl[key] === glEnum)) str = key
}
if (!str) {
str = 'UNDEFINED'
}
return str
},
debug: function (enabled) {
this.debugMode = enabled
// if (enabled) {
// this.debuggraph = ''
// this.debugCommands = []
// if (isBrowser) {
// window.R = R
// window.commands = this.debugCommands
// }
// this.debugGraph = ''
// this.debugGraph += 'digraph frame {\n'
// this.debugGraph += 'size="6,12";\n'
// this.debugGraph += 'rankdir="LR"\n'
// this.debugGraph += 'node [shape=record];\n'
// if (this.debugMode) {
// const res = this.resources.map((res) => {
// return { id: res.id, type: res.id.split('_')[0] }
// })
// const groups = R.groupBy(R.prop('type'), res)
// Object.keys(groups).forEach((g) => {
// this.debugGraph += `subgraph cluster_${g} { \n`
// this.debugGraph += `label = "${g}s" \n`
// groups[g].forEach((res) => {
// this.debugGraph += `${res.id} [style=filled fillcolor = "#DDDDFF"] \n`
// })
// this.debugGraph += `} \n`
// })
// }
// } else {
// if (this.debugGraph) {
// this.debugGraph += 'edge [style=bold, fontname="Arial", weight=100]\n'
// this.debugCommands.forEach((cmd, i, commands) => {
// if (i > 0) {
// const prevCmd = commands[i - 1]
// this.debugGraph += `${prevCmd.name || prevCmd.id} -> ${cmd.name || cmd.id}\n`
// }
// })
// this.debugGraph += '}'
// // log(this.debugGraph)
// // const div = document.createElement('div')
// // div.innerHTML = viz(this.debugGraph)
// // div.style.position = 'absolute'
// // div.style.top = '0'
// // div.style.left = '0'
// // div.style.transformOrigin = '0 0'
// // div.style.transform = 'scale(0.75, 0.75)'
// // document.body.appendChild(div)
// }
// }
},
checkError: function () {
if (this.debugMode) {
var error = gl.getError()
if (error) {
if (isBrowser) log('State', this.state.state)
throw new Error(`GL error ${error} : ${this.getGLString(error)}`)
}
}
},
resource: function (res) {
res.id = res.class + '_' + ID++
this.resources.push(res)
this.checkError()
return res
},
// texture2D({ data: TypedArray, width: Int, height: Int, format: PixelFormat, flipY: Boolean })
texture2D: function (opts) {
log('texture2D', opts)
opts.target = gl.TEXTURE_2D
return this.resource(createTexture(this, opts))
},
// textureCube({ data: [negxData, negyData,...], width: Int, height: Int, format: PixelFormat, flipY: Boolean })
textureCube: function (opts) {
log('textureCube', opts)
opts.target = gl.TEXTURE_CUBE_MAP
return this.resource(createTexture(this, opts))
},
// framebuffer({ color: [ Texture2D, .. ], depth: Texture2D }
// framebuffer({ color: [ { texture: Texture2D, target: Enum, level: int }, .. ], depth: { texture: Texture2D }})
framebuffer: function (opts) {
log('framebuffer', opts)
return this.resource(createFramebuffer(this, opts))
},
// TODO: Should we have named versions or generic 'ctx.buffer' command?
// In regl buffer() is ARRAY_BUFFER (aka VertexBuffer) and elements() is ELEMENT_ARRAY_BUFFER
// Now in WebGL2 we get more types Uniform, TransformFeedback, Copy
// Possible options: {
// data: Array or ArrayBuffer
// type: 'float', 'uint16' etc
// }
vertexBuffer: function (opts) {
log('vertexBuffer', opts)
if (opts.length) {
opts = { data: opts }
}
opts.target = gl.ARRAY_BUFFER
return this.resource(createBuffer(this, opts))
},
indexBuffer: function (opts) {
log('indexBuffer', opts)
if (opts.length) {
opts = { data: opts }
}
opts.target = gl.ELEMENT_ARRAY_BUFFER
return this.resource(createBuffer(this, opts))
},
program: function (opts) {
log('program', opts)
return this.resource(createProgram(this, opts))
},
pipeline: function (opts) {
log('pipeline', opts)
return this.resource(createPipeline(this, opts))
},
pass: function (opts) {
log('pass', opts, opts.color ? opts.color.map((c) => c.texture ? c.texture.info : c.info) : '')
return this.resource(createPass(this, opts))
},
readPixels: function (opts) {
const x = opts.x || 0
const y = opts.y || 0
const width = opts.width
const height = opts.height
// TODO: add support for data out
const format = gl.RGBA
const type = gl.UNSIGNED_BYTE
// const type = this.state.framebuffer ? gl.FLOAT : gl.UNSIGNED_BYTE
// if (!opts.format) {
// throw new Error('ctx.readPixels required valid pixel format')
// }
let pixels = null
// if (type === gl.FLOAT) {
// pixels = new Float32Array(width * height * 4)
// } else {
pixels = new Uint8Array(width * height * 4)
// }
gl.readPixels(x, y, width, height, format, type, pixels)
return pixels
},
// TODO: should data be Array and buffer be TypedArray
// update(texture, { data: TypeArray, [width: Int, height: Int] })
// update(texture, { data: TypedArray })
update: function (resource, opts) {
if (this.debugMode) log('update', { resource: resource, opts: opts })
resource._update(this, resource, opts)
},
// TODO: i don't like this inherit flag
mergeCommands: function (parent, cmd, inherit) {
// copy old state so we don't modify it's internals
const newCmd = Object.assign({}, parent)
if (!inherit) {
// clear values are not merged as they are applied only in the parent command
newCmd.pass = Object.assign({}, parent.pass)
newCmd.pass.clearColor = undefined
newCmd.pass.clearDepth = undefined
}
// overwrite properties from new command
Object.assign(newCmd, cmd)
// set viewport to FBO sizes when rendering to a texture
if (!cmd.viewport && cmd.pass && cmd.pass.opts.color) {
let tex = null
if (cmd.pass.opts.color[0]) tex = cmd.pass.opts.color[0].texture || cmd.pass.opts.color[0]
if (cmd.pass.opts.depth) tex = cmd.pass.opts.depth.texture || cmd.pass.opts.depth
if (tex) {
newCmd.viewport = [0, 0, tex.width, tex.height]
}
}
// merge uniforms
newCmd.uniforms = (parent.uniforms || cmd.uniforms) ? Object.assign({}, parent.uniforms, cmd.uniforms) : null
return newCmd
},
applyPass: function (pass) {
const gl = this.gl
const state = this.state
// if (pass.framebuffer !== state.framebuffer) {
if (state.pass.id !== pass.id) {
if (this.debugMode) log('change framebuffer', state.pass.framebuffer, '->', pass.framebuffer)
state.pass = pass
if (pass.framebuffer._update) {
// rebind pass' color and depth to shared FBO
this.update(pass.framebuffer, pass.opts)
}
gl.bindFramebuffer(pass.framebuffer.target, pass.framebuffer.handle)
if (pass.framebuffer.drawBuffers && pass.framebuffer.drawBuffers.length > 1) {
gl.drawBuffers(pass.framebuffer.drawBuffers)
}
}
let clearBits = 0
if (pass.clearColor !== undefined) {
if (this.debugMode) log('clearing color', pass.clearColor)
clearBits |= gl.COLOR_BUFFER_BIT
// TODO this might be unnecesary but we don't know because we don't store the clearColor in state
gl.clearColor(pass.clearColor[0], pass.clearColor[1], pass.clearColor[2], pass.clearColor[3])
}
if (pass.clearDepth !== undefined) {
if (this.debugMode) log('clearing depth', pass.clearDepth)
clearBits |= gl.DEPTH_BUFFER_BIT
if (!state.depthWrite) {
state.depthWrite = true
gl.depthMask(true)
}
// TODO this might be unnecesary but we don't know because we don't store the clearDepth in state
gl.clearDepth(pass.clearDepth)
}
if (clearBits) {
gl.clear(clearBits)
}
this.checkError()
},
applyPipeline: function (pipeline) {
const gl = this.gl
const state = this.state
if (pipeline.depthWrite !== state.depthWrite) {
state.depthWrite = pipeline.depthWrite
gl.depthMask(state.depthWrite)
}
if (pipeline.depthTest !== state.depthTest) {
state.depthTest = pipeline.depthTest
state.depthTest ? gl.enable(gl.DEPTH_TEST) : gl.disable(gl.DEPTH_TEST)
// TODO: should we flip it only when depth is enabled?
if (pipeline.depthFunc !== state.depthFunc) {
state.depthFunc = pipeline.depthFunc
gl.depthFunc(state.depthFunc)
}
}
if (pipeline.blendEnabled !== state.blendEnabled ||
pipeline.blendSrcRGBFactor !== state.blendSrcRGBFactor ||
pipeline.blendSrcAlphaFactor !== state.blendSrcAlphaFactor ||
pipeline.blendDstRGBFactor !== state.blendDstRGBFactor ||
pipeline.blendDstAlphaFactor !== state.blendDstAlphaFactor) {
state.blendEnabled = pipeline.blendEnabled
state.blendSrcRGBFactor = pipeline.blendSrcRGBFactor
state.blendSrcAlphaFactor = pipeline.blendSrcAlphaFactor
state.blendDstRGBFactor = pipeline.blendDstRGBFactor
state.blendDstAlphaFactor = pipeline.blendDstAlphaFactor
state.blendEnabled ? gl.enable(gl.BLEND) : gl.disable(gl.BLEND)
gl.blendFuncSeparate(
state.blendSrcRGBFactor,
state.blendDstRGBFactor,
state.blendSrcAlphaFactor,
state.blendDstAlphaFactor
)
}
if (pipeline.cullFaceEnabled !== state.cullFaceEnabled || pipeline.cullFace !== state.cullFace) {
state.cullFaceEnabled = pipeline.cullFaceEnabled
state.cullFace = pipeline.cullFace
state.cullFaceEnabled ? gl.enable(gl.CULL_FACE) : gl.disable(gl.CULL_FACE)
if (state.cullFaceEnabled) {
gl.cullFace(state.cullFace)
}
}
// TODO: depthMask: false, depthWrite?
if (pipeline.program !== state.program) {
state.program = pipeline.program
if (state.program) {
gl.useProgram(state.program.handle)
}
}
if (pipeline.vertexLayout) {
state.vertexLayout = pipeline.vertexLayout
}
this.checkError()
},
applyUniforms: function (uniforms, cmd) {
const gl = this.gl
const state = this.state
let numTextures = 0
if (!state.program) {
assert.fail('Trying to draw without an active program')
}
const requiredUniforms = Object.keys(state.program.uniforms)
Object.keys(uniforms).forEach((name) => {
let value = uniforms[name]
// TODO: find a better way to not trying to set unused uniforms that might have been inherited
if (!state.program.uniforms[name] && !state.program.uniforms[name + '[0]']) {
return
}
if (value === null || value === undefined) {
log('invalid command', cmd)
assert.fail(`Can't set uniform "${name}" with a null value`)
}
// FIXME: uniform array hack
if (Array.isArray(value) && !state.program.uniforms[name]) {
if (this.debugMode) log('unknown uniform', name, Object.keys(state.program.uniforms))
value.forEach((val, i) => {
var nameIndex = `${name}[${i}]`
state.program.setUniform(nameIndex, val)
requiredUniforms.splice(requiredUniforms.indexOf(nameIndex), 1)
})
} else if (value.target) { // assuming texture
// FIXME: texture binding hack
const slot = numTextures++
gl.activeTexture(gl.TEXTURE0 + slot)
if (state.activeTextures[slot] !== value) {
gl.bindTexture(value.target, value.handle)
state.activeTextures[slot] = value
}
state.program.setUniform(name, slot)
requiredUniforms.splice(requiredUniforms.indexOf(name), 1)
} else if (!value.length && typeof value === 'object') {
log('invalid command', cmd)
assert.fail(`Can set uniform "${name}" with an Object value`)
} else {
state.program.setUniform(name, value)
requiredUniforms.splice(requiredUniforms.indexOf(name), 1)
}
})
if (requiredUniforms.length > 0) {
log('invalid command', cmd)
assert.fail(`Trying to draw with missing uniforms: ${requiredUniforms.join(', ')}`)
}
this.checkError()
},
drawVertexData: function (cmd) {
const state = this.state
const vertexLayout = state.vertexLayout
if (!state.program) {
assert.fail('Trying to draw without an active program')
}
if (vertexLayout.length !== Object.keys(state.program.attributes).length) {
log('Invalid vertex layout not matching the shader', vertexLayout, state.program.attributes, cmd)
assert.fail('Invalid vertex layout not matching the shader')
}
let instanced = false
// TODO: disable unused vertex array slots
// TODO: disable divisor if attribute not instanced?
for (var i = 0; i < 16; i++) {
state.activeAttributes[i] = null
gl.disableVertexAttribArray(i)
}
// TODO: the same as i support [tex] and { texture: tex } i should support buffers in attributes?
vertexLayout.forEach((layout, i) => {
const name = layout[0]
const location = layout[1]
const size = layout[2]
const attrib = cmd.attributes[i] || cmd.attributes[name]
if (!attrib) {
log('Invalid command', cmd, 'doesn\'t satisfy vertex layout', vertexLayout)
assert.fail(`Command is missing attribute "${name}" at location ${location} with ${attrib}`)
}
let buffer = attrib.buffer
if (!buffer && attrib.class === 'vertexBuffer') {
buffer = attrib
}
if (!buffer || !buffer.target || !buffer.length) {
log('Invalid command', cmd)
assert.fail(`Trying to draw arrays with invalid buffer for attribute : ${name}`)
}
gl.bindBuffer(buffer.target, buffer.handle)
gl.enableVertexAttribArray(location)
state.activeAttributes[location] = buffer
gl.vertexAttribPointer(
location,
size,
attrib.type || buffer.type || gl.FLOAT,
attrib.normalized || false,
attrib.stride || 0,
attrib.offset || 0
)
if (attrib.divisor) {
gl.vertexAttribDivisor(location, attrib.divisor)
instanced = true
} else if (capabilities.instancing) {
gl.vertexAttribDivisor(location, 0)
}
// TODO: how to match index with vertexLayout location?
})
let primitive = cmd.pipeline.primitive
if (cmd.indices) {
let indexBuffer = cmd.indices.buffer
if (!indexBuffer && cmd.indices.class === 'indexBuffer') {
indexBuffer = cmd.indices
}
if (!indexBuffer || !indexBuffer.target) {
log('Invalid command', cmd)
assert.fail(`Trying to draw arrays with invalid buffer for elements`)
}
state.indexBuffer = indexBuffer
gl.bindBuffer(indexBuffer.target, indexBuffer.handle)
var count = cmd.indices.count || indexBuffer.length
var offset = cmd.indices.offset || 0
var type = cmd.indices.type || indexBuffer.type
if (instanced) {
// TODO: check if instancing available
gl.drawElementsInstanced(primitive, count, type, offset, cmd.instances)
} else {
gl.drawElements(primitive, count, type, offset)
}
} else if (cmd.count) {
const first = 0
if (instanced) {
// TODO: check if instancing available
gl.drawElementsInstanced(primitive, first, cmd.count, cmd.instances)
} else {
gl.drawArrays(primitive, first, cmd.count)
}
} else {
assert.fail('Vertex arrays requres elements or count to draw')
}
// if (self.debugMode) {
// var error = gl.getError()
// cmd.error = { code: error, msg: self.getGLString(error) }
// if (error) {
// self.debugCommands.push(cmd)
// throw new Error(`WebGL error ${error} : ${self.getGLString(error)}`)
// }
// log('draw elements', count, error)
// }
this.checkError()
},
frame: function (cb) {
const self = this
raf(function frame () {
if (cb() === false) {
// interrupt render loop
return
}
if (self.defaultState.viewport[2] !== gl.drawingBufferWidth ||
self.defaultState.viewport[3] !== gl.drawingBufferHeight) {
self.defaultState.viewport[2] = gl.drawingBufferWidth
self.defaultState.viewport[3] = gl.drawingBufferHeight
self.defaultState.pass.framebuffer.width = gl.drawingBufferWidth
self.defaultState.pass.framebuffer.height = gl.drawingBufferHeight
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight)
}
raf(frame)
})
},
// TODO: switching to lightweight resources would allow to just clone state
// and use commands as state modifiers?
apply: function (cmd) {
const state = this.state
if (this.debugMode) log('apply', cmd.name || cmd.id, { cmd: cmd, state: JSON.parse(JSON.stringify(state)) })
this.checkError()
if (cmd.pass) this.applyPass(cmd.pass)
if (cmd.pipeline) this.applyPipeline(cmd.pipeline)
if (cmd.uniforms) this.applyUniforms(cmd.uniforms)
if (cmd.viewport) {
if (cmd.viewport !== state.viewport) {
state.viewport = cmd.viewport
gl.viewport(state.viewport[0], state.viewport[1], state.viewport[2], state.viewport[3])
}
}
if (cmd.attributes) {
this.drawVertexData(cmd)
}
},
submit: function (cmd, batches, subCommand) {
if (this.debugMode) {
this.debugCommands.push(cmd)
if (batches && subCommand) log('submit', cmd.name || cmd.id, { depth: this.stack.length, cmd: cmd, batches: batches, subCommand: subCommand, state: this.state, stack: this.stack })
else if (batches) log('submit', cmd.name || cmd.id, { depth: this.stack.length, cmd: cmd, batches: batches, state: this.state, stack: this.stack })
else log('submit', cmd.name || cmd.id, { depth: this.stack.length, cmd: cmd, state: this.state, stack: this.stack })
}
if (batches) {
if (Array.isArray(batches)) {
// TODO: quick hack
batches.forEach((batch) => this.submit(this.mergeCommands(cmd, batch, true), subCommand))
return
} else if (typeof batches === 'object') {
this.submit(this.mergeCommands(cmd, batches, true), subCommand)
return
} else {
subCommand = batches // shift argument
}
}
const parentState = this.stack[this.stack.length - 1]
const cmdState = this.mergeCommands(parentState, cmd, false)
this.apply(cmdState)
if (subCommand) {
if (this.debugMode) {
this.debugGraph += `subgraph cluster_${cmd.name || cmd.id} {\n`
this.debugGraph += `label = "${cmd.name}"\n`
if (cmd.program) {
this.debugGraph += `${cmd.program.id} -> cluster_${cmd.name || cmd.id}\n`
}
if (cmd.framebuffer) {
this.debugGraph += `${cmd.framebuffer.id} -> cluster_${cmd.name || cmd.id}\n`
cmd.framebuffer.color.forEach((attachment) => {
this.debugGraph += `${attachment.texture.id} -> ${cmd.framebuffer.id}\n`
})
if (cmd.framebuffer.depth) {
this.debugGraph += `${cmd.framebuffer.depth.texture.id} -> ${cmd.framebuffer.id}\n`
}
}
}
this.stack.push(cmdState)
subCommand()
this.stack.pop()
if (this.debugMode) {
this.debugGraph += '}\n'
}
} else {
if (this.debugMode) {
let s = `${cmd.name || cmd.id} [style=filled fillcolor = "#DDFFDD" label="`
let cells = [cmd.name || cmd.id]
// this.debugGraph += `cluster_${cmd.name || cmd.id} [style=filled fillcolor = "#DDFFDD"] {\n`
// if (cmd.attributes) {
// cells.push(' ')
// cells.push('vertex arrays')
// Object.keys(cmd.attributes).forEach((attribName, index) => {
// const attrib = cmd.attributes[attribName]
// cells.push(`<a${index}>${attribName}`)
// this.debugGraph += `${attrib.buffer.id} -> ${cmd.name || cmd.id}:a${index}\n`
// })
// }
// if (cmd.indices) {
// cells.push(' ')
// cells.push(`<e>elements`)
// this.debugGraph += `${cmd.elements.buffer.id} -> ${cmd.name || cmd.id}:e\n`
// }
// if (cmd.program) {
// this.debugGraph += `${cmd.program.id} -> ${cmd.name || cmd.id}\n`
// }
// if (cmd.framebuffer) {
// this.debugGraph += `${cmd.framebuffer.id} -> ${cmd.name || cmd.id}\n`
// cmd.framebuffer.color.forEach((tex) => {
// console.log('tex', tex)
// })
// }
if (cmd.uniforms) {
cells.push(' ')
cells.push('uniforms')
Object.keys(cmd.uniforms).forEach((uniformName, index) => {
cells.push(`<u${index}>${uniformName}`)
const value = cmd.uniforms[uniformName]
if (value === null || value === undefined) {
log('Invalid command', cmd)
assert.fail(`Trying to draw with uniform "${uniformName}" = null`)
}
if (value.id) {
this.debugGraph += `${value.id} -> ${cmd.name || cmd.id}:u${index}\n`
}
})
}
s += cells.join('|')
s += '"]'
this.debugGraph += `${s}\n`
}
}
this.checkError()
}
}
ctx.apply(defaultState)
return ctx
}
module.exports = createContext
| index.js | // TODO: get rid of Ramda
const log = require('debug')('context')
// const viz = require('viz.js')
const isBrowser = require('is-browser')
const createGL = require('pex-gl')
const assert = require('assert')
const createTexture = require('./texture')
const createFramebuffer = require('./framebuffer')
const createPass = require('./pass')
const createPipeline = require('./pipeline')
const createProgram = require('./program')
const createBuffer = require('./buffer')
const raf = require('raf')
let ID = 0
function createContext (opts) {
assert(!opts || (typeof opts === 'object'), 'pex-context: createContext requires opts argument to be null or an object')
let gl = null
if (!opts || !opts.gl) gl = createGL(opts)
else if (opts && opts.gl) gl = opts.gl
assert(gl, 'pex-context: createContext failed')
const ext = gl.getExtension('OES_texture_half_float')
if (ext) {
gl.HALF_FLOAT = ext.HALF_FLOAT_OES
}
gl.getExtension('OES_element_index_uint')
const BlendFactor = {
One: gl.ONE,
Zero: gl.ZERO,
SrcAlpha: gl.SRC_ALPHA,
OneMinusSrcAlpha: gl.ONE_MINUS_SRC_ALPHA,
DstAlpha: gl.DST_ALPHA,
OneMinusDstAlpha: gl.ONE_MINUS_DST_ALPHA,
SrcColor: gl.SRC_COLOR,
OneMinusSrcColor: gl.ONE_MINUS_SRC_COLOR,
DstColor: gl.DST_COLOR,
OneMinusDstColor: gl.ONE_MINUS_DST_COLOR
}
const CubemapFace = {
PositiveX: gl.TEXTURE_CUBE_MAP_POSITIVE_X,
NegativeX: gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
PositiveY: gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
NegativeY: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
PositiveZ: gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
NegativeZ: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
}
const DepthFunc = {
Never: gl.NEVER,
Less: gl.LESS,
Equal: gl.EQUAL,
LessEqual: gl.LEQUAL,
Greater: gl.GREATER,
NotEqual: gl.NOTEQUAL,
GreaterEqual: gl.GEQUAL,
Always: gl.ALWAYS
}
const DataType = {
Float32: gl.FLOAT,
Uint8: gl.UNSIGNED_BYTE,
Uint16: gl.UNSIGNED_SHORT,
Uint32: gl.UNSIGNED_INT
}
const Face = {
Front: gl.FRONT,
Back: gl.BACK,
FrontAndBack: gl.FRONT_AND_BACK
}
const Filter = {
Nearest: gl.NEAREST,
Linear: gl.LINEAR,
NearestMipmapNearest: gl.NEAREST_MIPMAP_NEAREST,
NearestMipmapLinear: gl.NEAREST_MIPMAP_LINEAR,
LinearMipmapNearest: gl.LINEAR_MIPMAP_NEAREST,
LinearMipmapLinear: gl.LINEAR_MIPMAP_LINEAR
}
const PixelFormat = {
RGBA8: 'rgba8', // gl.RGBA + gl.UNSIGNED_BYTE
RGBA32F: 'rgba32f', // gl.RGBA + gl.FLOAT
RGBA16F: 'rgba16f', // gl.RGBA + gl.HALF_FLOAT
R32F: 'r32f', // gl.ALPHA + gl.FLOAT
R16F: 'r16f', // gl.ALPHA + gl.HALF_FLOAT
Depth: 'depth' // gl.DEPTH_COMPONENT
}
const Encoding = {
Linear: 1,
Gamma: 2,
SRGB: 3,
RGBM: 4
}
const Primitive = {
Points: gl.POINTS,
Lines: gl.LINES,
LineStrip: gl.LINE_STRIP,
Triangles: gl.TRIANGLES,
TriangleStrip: gl.TRIANGLE_STRIP
}
const Wrap = {
ClampToEdge: gl.CLAMP_TO_EDGE,
Repeat: gl.REPEAT
}
const defaultState = {
pass: {
framebuffer: {
target: gl.FRAMEBUFFER,
handle: null,
width: gl.drawingBufferWidth,
height: gl.drawingBufferHeight
},
clearColor: [0, 0, 0, 1],
clearDepth: 1
},
pipeline: {
program: null,
depthWrite: true,
depthTest: false,
depthFunc: DepthFunc.LessEqual,
blendEnabled: false,
cullFaceEnabled: false,
cullFace: Face.Back,
primitive: Primitive.Triangles
},
viewport: [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight]
}
const capabilities = {
}
// extensions
if (!gl.drawElementsInstanced) {
const ext = gl.getExtension('ANGLE_instanced_arrays')
if (!ext) {
// TODO: this._caps[CAPS_INSTANCED_ARRAYS] = false;
gl.drawElementsInstanced = function () {
throw new Error('gl.drawElementsInstanced not available. ANGLE_instanced_arrays not supported')
}
gl.drawArraysInstanced = function () {
throw new Error('gl.drawArraysInstanced not available. ANGLE_instanced_arrays not supported')
}
gl.vertexAttribDivisor = function () {
throw new Error('gl.vertexAttribDivisor not available. ANGLE_instanced_arrays not supported')
}
capabilities.instancing = false
} else {
// TODO: this._caps[CAPS_INSTANCED_ARRAYS] = true;
gl.drawElementsInstanced = ext.drawElementsInstancedANGLE.bind(ext)
gl.drawArraysInstanced = ext.drawArraysInstancedANGLE.bind(ext)
gl.vertexAttribDivisor = ext.vertexAttribDivisorANGLE.bind(ext)
capabilities.instancing = false
}
} else {
capabilities.instancing = true
}
if (!gl.drawBuffers) {
const ext = gl.getExtension('WEBGL_draw_buffers')
if (!ext) {
gl.drawBuffers = function () {
throw new Error('WEBGL_draw_buffers not supported')
}
} else {
gl.drawBuffers = ext.drawBuffersWEBGL.bind(ext)
}
}
const ctx = {
gl: gl,
BlendFactor: BlendFactor,
CubemapFace: CubemapFace,
DataType: DataType,
DepthFunc: DepthFunc,
Face: Face,
Filter: Filter,
PixelFormat: PixelFormat,
Encoding: Encoding,
Primitive: Primitive,
Wrap: Wrap,
debugMode: false,
capabilities: capabilities,
// debugGraph: '',
debugCommands: [],
resources: [],
stack: [ defaultState ],
defaultState: defaultState,
state: {
pass: {
framebuffer: defaultState.pass.framebuffer
},
activeTextures: [],
activeAttributes: []
},
getGLString: function (glEnum) {
let str = ''
for (let key in gl) {
if ((gl[key] === glEnum)) str = key
}
if (!str) {
str = 'UNDEFINED'
}
return str
},
debug: function (enabled) {
this.debugMode = enabled
// if (enabled) {
// this.debuggraph = ''
// this.debugCommands = []
// if (isBrowser) {
// window.R = R
// window.commands = this.debugCommands
// }
// this.debugGraph = ''
// this.debugGraph += 'digraph frame {\n'
// this.debugGraph += 'size="6,12";\n'
// this.debugGraph += 'rankdir="LR"\n'
// this.debugGraph += 'node [shape=record];\n'
// if (this.debugMode) {
// const res = this.resources.map((res) => {
// return { id: res.id, type: res.id.split('_')[0] }
// })
// const groups = R.groupBy(R.prop('type'), res)
// Object.keys(groups).forEach((g) => {
// this.debugGraph += `subgraph cluster_${g} { \n`
// this.debugGraph += `label = "${g}s" \n`
// groups[g].forEach((res) => {
// this.debugGraph += `${res.id} [style=filled fillcolor = "#DDDDFF"] \n`
// })
// this.debugGraph += `} \n`
// })
// }
// } else {
// if (this.debugGraph) {
// this.debugGraph += 'edge [style=bold, fontname="Arial", weight=100]\n'
// this.debugCommands.forEach((cmd, i, commands) => {
// if (i > 0) {
// const prevCmd = commands[i - 1]
// this.debugGraph += `${prevCmd.name || prevCmd.id} -> ${cmd.name || cmd.id}\n`
// }
// })
// this.debugGraph += '}'
// // log(this.debugGraph)
// // const div = document.createElement('div')
// // div.innerHTML = viz(this.debugGraph)
// // div.style.position = 'absolute'
// // div.style.top = '0'
// // div.style.left = '0'
// // div.style.transformOrigin = '0 0'
// // div.style.transform = 'scale(0.75, 0.75)'
// // document.body.appendChild(div)
// }
// }
},
checkError: function () {
if (this.debugMode) {
var error = gl.getError()
if (error) {
if (isBrowser) log('State', this.state.state)
throw new Error(`GL error ${error} : ${this.getGLString(error)}`)
}
}
},
resource: function (res) {
res.id = res.class + '_' + ID++
this.resources.push(res)
this.checkError()
return res
},
// texture2D({ data: TypedArray, width: Int, height: Int, format: PixelFormat, flipY: Boolean })
texture2D: function (opts) {
log('texture2D', opts)
opts.target = gl.TEXTURE_2D
return this.resource(createTexture(this, opts))
},
// textureCube({ data: [negxData, negyData,...], width: Int, height: Int, format: PixelFormat, flipY: Boolean })
textureCube: function (opts) {
log('textureCube', opts)
opts.target = gl.TEXTURE_CUBE_MAP
return this.resource(createTexture(this, opts))
},
// framebuffer({ color: [ Texture2D, .. ], depth: Texture2D }
// framebuffer({ color: [ { texture: Texture2D, target: Enum, level: int }, .. ], depth: { texture: Texture2D }})
framebuffer: function (opts) {
log('framebuffer', opts)
return this.resource(createFramebuffer(this, opts))
},
// TODO: Should we have named versions or generic 'ctx.buffer' command?
// In regl buffer() is ARRAY_BUFFER (aka VertexBuffer) and elements() is ELEMENT_ARRAY_BUFFER
// Now in WebGL2 we get more types Uniform, TransformFeedback, Copy
// Possible options: {
// data: Array or ArrayBuffer
// type: 'float', 'uint16' etc
// }
vertexBuffer: function (opts) {
log('vertexBuffer', opts)
if (opts.length) {
opts = { data: opts }
}
opts.target = gl.ARRAY_BUFFER
return this.resource(createBuffer(this, opts))
},
indexBuffer: function (opts) {
log('indexBuffer', opts)
if (opts.length) {
opts = { data: opts }
}
opts.target = gl.ELEMENT_ARRAY_BUFFER
return this.resource(createBuffer(this, opts))
},
program: function (opts) {
log('program', opts)
return this.resource(createProgram(this, opts))
},
pipeline: function (opts) {
log('pipeline', opts)
return this.resource(createPipeline(this, opts))
},
pass: function (opts) {
log('pass', opts, opts.color ? opts.color.map((c) => c.texture ? c.texture.info : c.info) : '')
return this.resource(createPass(this, opts))
},
readPixels: function (opts) {
const x = opts.x || 0
const y = opts.y || 0
const width = opts.width
const height = opts.height
// TODO: add support for data out
const format = gl.RGBA
const type = gl.UNSIGNED_BYTE
// const type = this.state.framebuffer ? gl.FLOAT : gl.UNSIGNED_BYTE
// if (!opts.format) {
// throw new Error('ctx.readPixels required valid pixel format')
// }
let pixels = null
// if (type === gl.FLOAT) {
// pixels = new Float32Array(width * height * 4)
// } else {
pixels = new Uint8Array(width * height * 4)
// }
gl.readPixels(x, y, width, height, format, type, pixels)
return pixels
},
// TODO: should data be Array and buffer be TypedArray
// update(texture, { data: TypeArray, [width: Int, height: Int] })
// update(texture, { data: TypedArray })
update: function (resource, opts) {
if (this.debugMode) log('update', { resource: resource, opts: opts })
resource._update(this, resource, opts)
},
// TODO: i don't like this inherit flag
mergeCommands: function (parent, cmd, inherit) {
// copy old state so we don't modify it's internals
const newCmd = Object.assign({}, parent)
if (!inherit) {
// clear values are not merged as they are applied only in the parent command
newCmd.pass = Object.assign({}, parent.pass)
newCmd.pass.clearColor = undefined
newCmd.pass.clearDepth = undefined
}
// overwrite properties from new command
Object.assign(newCmd, cmd)
// set viewport to FBO sizes when rendering to a texture
if (!cmd.viewport && cmd.pass && cmd.pass.opts.color) {
let tex = null
if (cmd.pass.opts.color[0]) tex = cmd.pass.opts.color[0].texture || cmd.pass.opts.color[0]
if (cmd.pass.opts.depth) tex = cmd.pass.opts.depth.texture || cmd.pass.opts.depth
if (tex) {
newCmd.viewport = [0, 0, tex.width, tex.height]
}
}
// merge uniforms
newCmd.uniforms = (parent.uniforms || cmd.uniforms) ? Object.assign({}, parent.uniforms, cmd.uniforms) : null
return newCmd
},
applyPass: function (pass) {
const gl = this.gl
const state = this.state
// if (pass.framebuffer !== state.framebuffer) {
if (state.pass.id !== pass.id) {
if (this.debugMode) log('change framebuffer', state.pass.framebuffer, '->', pass.framebuffer)
state.pass = pass
if (pass.framebuffer._update) {
// rebind pass' color and depth to shared FBO
this.update(pass.framebuffer, pass.opts)
}
gl.bindFramebuffer(pass.framebuffer.target, pass.framebuffer.handle)
if (pass.framebuffer.drawBuffers && pass.framebuffer.drawBuffers.length > 1) {
gl.drawBuffers(pass.framebuffer.drawBuffers)
}
}
let clearBits = 0
if (pass.clearColor !== undefined) {
if (this.debugMode) log('clearing color', pass.clearColor)
clearBits |= gl.COLOR_BUFFER_BIT
// TODO this might be unnecesary but we don't know because we don't store the clearColor in state
gl.clearColor(pass.clearColor[0], pass.clearColor[1], pass.clearColor[2], pass.clearColor[3])
}
if (pass.clearDepth !== undefined) {
if (this.debugMode) log('clearing depth', pass.clearDepth)
clearBits |= gl.DEPTH_BUFFER_BIT
if (!state.depthWrite) {
state.depthWrite = true
gl.depthMask(true)
}
// TODO this might be unnecesary but we don't know because we don't store the clearDepth in state
gl.clearDepth(pass.clearDepth)
}
if (clearBits) {
gl.clear(clearBits)
}
this.checkError()
},
applyPipeline: function (pipeline) {
const gl = this.gl
const state = this.state
if (pipeline.depthWrite !== state.depthWrite) {
state.depthWrite = pipeline.depthWrite
gl.depthMask(state.depthWrite)
}
if (pipeline.depthTest !== state.depthTest) {
state.depthTest = pipeline.depthTest
state.depthTest ? gl.enable(gl.DEPTH_TEST) : gl.disable(gl.DEPTH_TEST)
// TODO: should we flip it only when depth is enabled?
if (pipeline.depthFunc !== state.depthFunc) {
state.depthFunc = pipeline.depthFunc
gl.depthFunc(state.depthFunc)
}
}
if (pipeline.blendEnabled !== state.blendEnabled ||
pipeline.blendSrcRGBFactor !== state.blendSrcRGBFactor ||
pipeline.blendSrcAlphaFactor !== state.blendSrcAlphaFactor ||
pipeline.blendDstRGBFactor !== state.blendDstRGBFactor ||
pipeline.blendDstAlphaFactor !== state.blendDstAlphaFactor) {
state.blendEnabled = pipeline.blendEnabled
state.blendSrcRGBFactor = pipeline.blendSrcRGBFactor
state.blendSrcAlphaFactor = pipeline.blendSrcAlphaFactor
state.blendDstRGBFactor = pipeline.blendDstRGBFactor
state.blendDstAlphaFactor = pipeline.blendDstAlphaFactor
state.blendEnabled ? gl.enable(gl.BLEND) : gl.disable(gl.BLEND)
gl.blendFuncSeparate(
state.blendSrcRGBFactor,
state.blendDstRGBFactor,
state.blendSrcAlphaFactor,
state.blendDstAlphaFactor
)
}
if (pipeline.cullFaceEnabled !== state.cullFaceEnabled || pipeline.cullFace !== state.cullFace) {
state.cullFaceEnabled = pipeline.cullFaceEnabled
state.cullFace = pipeline.cullFace
state.cullFaceEnabled ? gl.enable(gl.CULL_FACE) : gl.disable(gl.CULL_FACE)
if (state.cullFaceEnabled) {
gl.cullFace(state.cullFace)
}
}
// TODO: depthMask: false, depthWrite?
if (pipeline.program !== state.program) {
state.program = pipeline.program
if (state.program) {
gl.useProgram(state.program.handle)
}
}
if (pipeline.vertexLayout) {
state.vertexLayout = pipeline.vertexLayout
}
this.checkError()
},
applyUniforms: function (uniforms, cmd) {
const gl = this.gl
const state = this.state
let numTextures = 0
if (!state.program) {
assert.fail('Trying to draw without an active program')
}
const requiredUniforms = Object.keys(state.program.uniforms)
Object.keys(uniforms).forEach((name) => {
let value = uniforms[name]
// TODO: find a better way to not trying to set unused uniforms that might have been inherited
if (!state.program.uniforms[name] && !state.program.uniforms[name + '[0]']) {
return
}
if (value === null || value === undefined) {
log('invalid command', cmd)
assert.fail(`Can't set uniform "${name}" with a null value`)
}
// FIXME: uniform array hack
if (Array.isArray(value) && !state.program.uniforms[name]) {
if (this.debugMode) log('unknown uniform', name, Object.keys(state.program.uniforms))
value.forEach((val, i) => {
var nameIndex = `${name}[${i}]`
state.program.setUniform(nameIndex, val)
requiredUniforms.splice(requiredUniforms.indexOf(nameIndex), 1)
})
} else if (value.target) { // assuming texture
// FIXME: texture binding hack
const slot = numTextures++
gl.activeTexture(gl.TEXTURE0 + slot)
if (state.activeTextures[slot] !== value) {
gl.bindTexture(value.target, value.handle)
state.activeTextures[slot] = value
}
state.program.setUniform(name, slot)
requiredUniforms.splice(requiredUniforms.indexOf(name), 1)
} else if (!value.length && typeof value === 'object') {
log('invalid command', cmd)
assert.fail(`Can set uniform "${name}" with an Object value`)
} else {
state.program.setUniform(name, value)
requiredUniforms.splice(requiredUniforms.indexOf(name), 1)
}
})
if (requiredUniforms.length > 0) {
log('invalid command', cmd)
assert.fail(`Trying to draw with missing uniforms: ${requiredUniforms.join(', ')}`)
}
this.checkError()
},
drawVertexData: function (cmd) {
const state = this.state
const vertexLayout = state.vertexLayout
if (!state.program) {
assert.fail('Trying to draw without an active program')
}
if (vertexLayout.length !== Object.keys(state.program.attributes).length) {
log('Invalid vertex layout not matching the shader', vertexLayout, state.program.attributes, cmd)
assert.fail('Invalid vertex layout not matching the shader')
}
let instanced = false
// TODO: disable unused vertex array slots
// TODO: disable divisor if attribute not instanced?
for (var i = 0; i < 16; i++) {
state.activeAttributes[i] = null
gl.disableVertexAttribArray(i)
}
// TODO: the same as i support [tex] and { texture: tex } i should support buffers in attributes?
vertexLayout.forEach((layout, i) => {
const name = layout[0]
const location = layout[1]
const size = layout[2]
const attrib = cmd.attributes[i] || cmd.attributes[name]
if (!attrib) {
log('Invalid command', cmd, 'doesn\'t satisfy vertex layout', vertexLayout)
assert.fail(`Command is missing attribute "${name}" at location ${location} with ${attrib}`)
}
let buffer = attrib.buffer
if (!buffer && attrib.class === 'vertexBuffer') {
buffer = attrib
}
if (!buffer || !buffer.target || !buffer.length) {
log('Invalid command', cmd)
assert.fail(`Trying to draw arrays with invalid buffer for attribute : ${name}`)
}
gl.bindBuffer(buffer.target, buffer.handle)
gl.enableVertexAttribArray(location)
state.activeAttributes[location] = buffer
// logSometimes('drawVertexData', name, location, attrib.buffer._length)
gl.vertexAttribPointer(
location,
size,
buffer.type || gl.FLOAT,
attrib.normalized || false,
attrib.stride || 0,
attrib.offset || 0
)
if (attrib.divisor) {
gl.vertexAttribDivisor(location, attrib.divisor)
instanced = true
} else if (capabilities.instancing) {
gl.vertexAttribDivisor(location, 0)
}
// TODO: how to match index with vertexLayout location?
})
let primitive = cmd.pipeline.primitive
if (cmd.indices) {
let indexBuffer = cmd.indices.buffer
if (!indexBuffer && cmd.indices.class === 'indexBuffer') {
indexBuffer = cmd.indices
}
if (!indexBuffer || !indexBuffer.target) {
log('Invalid command', cmd)
assert.fail(`Trying to draw arrays with invalid buffer for elements`)
}
state.indexBuffer = indexBuffer
gl.bindBuffer(indexBuffer.target, indexBuffer.handle)
var count = indexBuffer.length
// TODO: support for unint32 type
// TODO: support for offset
if (instanced) {
// TODO: check if instancing available
gl.drawElementsInstanced(primitive, count, indexBuffer.type, 0, cmd.instances)
} else {
gl.drawElements(primitive, count, indexBuffer.type, 0)
}
} else if (cmd.count) {
if (instanced) {
// TODO: check if instancing available
gl.drawElementsInstanced(primitive, 0, cmd.count, cmd.instances)
} else {
gl.drawArrays(primitive, 0, cmd.count)
}
} else {
assert.fail('Vertex arrays requres elements or count to draw')
}
// if (self.debugMode) {
// var error = gl.getError()
// cmd.error = { code: error, msg: self.getGLString(error) }
// if (error) {
// self.debugCommands.push(cmd)
// throw new Error(`WebGL error ${error} : ${self.getGLString(error)}`)
// }
// log('draw elements', count, error)
// }
this.checkError()
},
frame: function (cb) {
const self = this
raf(function frame () {
if (cb() === false) {
// interrupt render loop
return
}
if (self.defaultState.viewport[2] !== gl.drawingBufferWidth ||
self.defaultState.viewport[3] !== gl.drawingBufferHeight) {
self.defaultState.viewport[2] = gl.drawingBufferWidth
self.defaultState.viewport[3] = gl.drawingBufferHeight
self.defaultState.pass.framebuffer.width = gl.drawingBufferWidth
self.defaultState.pass.framebuffer.height = gl.drawingBufferHeight
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight)
}
raf(frame)
})
},
// TODO: switching to lightweight resources would allow to just clone state
// and use commands as state modifiers?
apply: function (cmd) {
const state = this.state
if (this.debugMode) log('apply', cmd.name || cmd.id, { cmd: cmd, state: JSON.parse(JSON.stringify(state)) })
this.checkError()
if (cmd.pass) this.applyPass(cmd.pass)
if (cmd.pipeline) this.applyPipeline(cmd.pipeline)
if (cmd.uniforms) this.applyUniforms(cmd.uniforms)
if (cmd.viewport) {
if (cmd.viewport !== state.viewport) {
state.viewport = cmd.viewport
gl.viewport(state.viewport[0], state.viewport[1], state.viewport[2], state.viewport[3])
}
}
if (cmd.attributes) {
this.drawVertexData(cmd)
}
},
submit: function (cmd, batches, subCommand) {
if (this.debugMode) {
this.debugCommands.push(cmd)
if (batches && subCommand) log('submit', cmd.name || cmd.id, { depth: this.stack.length, cmd: cmd, batches: batches, subCommand: subCommand, state: this.state, stack: this.stack })
else if (batches) log('submit', cmd.name || cmd.id, { depth: this.stack.length, cmd: cmd, batches: batches, state: this.state, stack: this.stack })
else log('submit', cmd.name || cmd.id, { depth: this.stack.length, cmd: cmd, state: this.state, stack: this.stack })
}
if (batches) {
if (Array.isArray(batches)) {
// TODO: quick hack
batches.forEach((batch) => this.submit(this.mergeCommands(cmd, batch, true), subCommand))
return
} else if (typeof batches === 'object') {
this.submit(this.mergeCommands(cmd, batches, true), subCommand)
return
} else {
subCommand = batches // shift argument
}
}
const parentState = this.stack[this.stack.length - 1]
const cmdState = this.mergeCommands(parentState, cmd, false)
this.apply(cmdState)
if (subCommand) {
if (this.debugMode) {
this.debugGraph += `subgraph cluster_${cmd.name || cmd.id} {\n`
this.debugGraph += `label = "${cmd.name}"\n`
if (cmd.program) {
this.debugGraph += `${cmd.program.id} -> cluster_${cmd.name || cmd.id}\n`
}
if (cmd.framebuffer) {
this.debugGraph += `${cmd.framebuffer.id} -> cluster_${cmd.name || cmd.id}\n`
cmd.framebuffer.color.forEach((attachment) => {
this.debugGraph += `${attachment.texture.id} -> ${cmd.framebuffer.id}\n`
})
if (cmd.framebuffer.depth) {
this.debugGraph += `${cmd.framebuffer.depth.texture.id} -> ${cmd.framebuffer.id}\n`
}
}
}
this.stack.push(cmdState)
subCommand()
this.stack.pop()
if (this.debugMode) {
this.debugGraph += '}\n'
}
} else {
if (this.debugMode) {
let s = `${cmd.name || cmd.id} [style=filled fillcolor = "#DDFFDD" label="`
let cells = [cmd.name || cmd.id]
// this.debugGraph += `cluster_${cmd.name || cmd.id} [style=filled fillcolor = "#DDFFDD"] {\n`
// if (cmd.attributes) {
// cells.push(' ')
// cells.push('vertex arrays')
// Object.keys(cmd.attributes).forEach((attribName, index) => {
// const attrib = cmd.attributes[attribName]
// cells.push(`<a${index}>${attribName}`)
// this.debugGraph += `${attrib.buffer.id} -> ${cmd.name || cmd.id}:a${index}\n`
// })
// }
// if (cmd.indices) {
// cells.push(' ')
// cells.push(`<e>elements`)
// this.debugGraph += `${cmd.elements.buffer.id} -> ${cmd.name || cmd.id}:e\n`
// }
// if (cmd.program) {
// this.debugGraph += `${cmd.program.id} -> ${cmd.name || cmd.id}\n`
// }
// if (cmd.framebuffer) {
// this.debugGraph += `${cmd.framebuffer.id} -> ${cmd.name || cmd.id}\n`
// cmd.framebuffer.color.forEach((tex) => {
// console.log('tex', tex)
// })
// }
if (cmd.uniforms) {
cells.push(' ')
cells.push('uniforms')
Object.keys(cmd.uniforms).forEach((uniformName, index) => {
cells.push(`<u${index}>${uniformName}`)
const value = cmd.uniforms[uniformName]
if (value === null || value === undefined) {
log('Invalid command', cmd)
assert.fail(`Trying to draw with uniform "${uniformName}" = null`)
}
if (value.id) {
this.debugGraph += `${value.id} -> ${cmd.name || cmd.id}:u${index}\n`
}
})
}
s += cells.join('|')
s += '"]'
this.debugGraph += `${s}\n`
}
}
this.checkError()
}
}
ctx.apply(defaultState)
return ctx
}
module.exports = createContext
| Add support buffer offsets | index.js | Add support buffer offsets | <ide><path>ndex.js
<ide> gl.bindBuffer(buffer.target, buffer.handle)
<ide> gl.enableVertexAttribArray(location)
<ide> state.activeAttributes[location] = buffer
<del> // logSometimes('drawVertexData', name, location, attrib.buffer._length)
<ide> gl.vertexAttribPointer(
<ide> location,
<ide> size,
<del> buffer.type || gl.FLOAT,
<add> attrib.type || buffer.type || gl.FLOAT,
<ide> attrib.normalized || false,
<ide> attrib.stride || 0,
<ide> attrib.offset || 0
<ide> }
<ide> state.indexBuffer = indexBuffer
<ide> gl.bindBuffer(indexBuffer.target, indexBuffer.handle)
<del> var count = indexBuffer.length
<del> // TODO: support for unint32 type
<del> // TODO: support for offset
<add> var count = cmd.indices.count || indexBuffer.length
<add> var offset = cmd.indices.offset || 0
<add> var type = cmd.indices.type || indexBuffer.type
<ide> if (instanced) {
<ide> // TODO: check if instancing available
<del> gl.drawElementsInstanced(primitive, count, indexBuffer.type, 0, cmd.instances)
<add> gl.drawElementsInstanced(primitive, count, type, offset, cmd.instances)
<ide> } else {
<del> gl.drawElements(primitive, count, indexBuffer.type, 0)
<add> gl.drawElements(primitive, count, type, offset)
<ide> }
<ide> } else if (cmd.count) {
<add> const first = 0
<ide> if (instanced) {
<ide> // TODO: check if instancing available
<del> gl.drawElementsInstanced(primitive, 0, cmd.count, cmd.instances)
<add> gl.drawElementsInstanced(primitive, first, cmd.count, cmd.instances)
<ide> } else {
<del> gl.drawArrays(primitive, 0, cmd.count)
<add> gl.drawArrays(primitive, first, cmd.count)
<ide> }
<ide> } else {
<ide> assert.fail('Vertex arrays requres elements or count to draw') |
|
Java | lgpl-2.1 | 603803f70bc6fcaa6648b225acb0aebb9f907b05 | 0 | JordanReiter/railo,getrailo/railo,modius/railo,modius/railo,JordanReiter/railo,getrailo/railo,getrailo/railo | package railo.runtime.functions.international;
import java.io.UnsupportedEncodingException;
import railo.runtime.PageContext;
import railo.runtime.exp.FunctionException;
import railo.runtime.exp.PageException;
import railo.runtime.ext.function.Function;
import railo.runtime.op.Caster;
/**
* Implements the CFML Function setlocale
*/
public final class SetEncoding implements Function {
public static String call(PageContext pc , String scope, String charset) throws PageException {
scope=scope.trim().toLowerCase();
try {
if(scope.equals("url"))(pc.urlScope()).setEncoding(pc.getApplicationContext(),charset);
else if(scope.equals("form"))(pc.formScope()).setEncoding(pc.getApplicationContext(),charset);
else throw new FunctionException(pc,"setEncoding",1,"scope","scope must have the one of the following values [url,form] not ["+scope+"]");
} catch (UnsupportedEncodingException e) {
throw Caster.toPageException(e);
}
return "";
}
} | railo-java/railo-core/src/railo/runtime/functions/international/SetEncoding.java | package railo.runtime.functions.international;
import java.io.UnsupportedEncodingException;
import railo.runtime.PageContext;
import railo.runtime.exp.FunctionException;
import railo.runtime.exp.PageException;
import railo.runtime.ext.function.Function;
import railo.runtime.op.Caster;
/**
* Implements the CFML Function setlocale
*/
public final class SetEncoding implements Function {
public static String call(PageContext pc , String scope, String charset) throws PageException {
scope=scope.trim().toLowerCase();
try {
if(scope.equals("url"))(pc.urlScope()).setEncoding(pc.getApplicationContext(),charset);
else if(scope.equals("form"))(pc.formScope()).setEncoding(pc.getApplicationContext(),charset);
else throw new FunctionException(pc,"setEncoding",1,"scope","scope must have the one of the following values [url,from] not ["+scope+"]");
} catch (UnsupportedEncodingException e) {
throw Caster.toPageException(e);
}
return "";
}
} | solved ticket https://issues.jboss.org/browse/RAILO-2542
| railo-java/railo-core/src/railo/runtime/functions/international/SetEncoding.java | solved ticket https://issues.jboss.org/browse/RAILO-2542 | <ide><path>ailo-java/railo-core/src/railo/runtime/functions/international/SetEncoding.java
<ide> try {
<ide> if(scope.equals("url"))(pc.urlScope()).setEncoding(pc.getApplicationContext(),charset);
<ide> else if(scope.equals("form"))(pc.formScope()).setEncoding(pc.getApplicationContext(),charset);
<del> else throw new FunctionException(pc,"setEncoding",1,"scope","scope must have the one of the following values [url,from] not ["+scope+"]");
<add> else throw new FunctionException(pc,"setEncoding",1,"scope","scope must have the one of the following values [url,form] not ["+scope+"]");
<ide>
<ide> } catch (UnsupportedEncodingException e) {
<ide> throw Caster.toPageException(e); |
|
Java | apache-2.0 | 0167f1cfc51c969c734ffbdb9fc30f2c93370206 | 0 | king1033/BookReader,lishoulin/BookReader,lishoulin/BookReader,JustWayward/BookReader,JustWayward/BookReader,lishoulin/BookReader,king1033/BookReader,king1033/BookReader,JustWayward/BookReader | package com.justwayward.reader.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.justwayward.reader.R;
import com.justwayward.reader.base.BaseActivity;
import com.justwayward.reader.bean.SearchDetail;
import com.justwayward.reader.common.OnRvItemClickListener;
import com.justwayward.reader.component.AppComponent;
import com.justwayward.reader.component.DaggerSearchActivityComponent;
import com.justwayward.reader.ui.adapter.AutoCompleteAdapter;
import com.justwayward.reader.ui.adapter.SearchResultAdapter;
import com.justwayward.reader.ui.contract.SearchContract;
import com.justwayward.reader.ui.presenter.SearchPresenter;
import com.justwayward.reader.view.SupportDividerItemDecoration;
import com.justwayward.reader.view.TagColor;
import com.justwayward.reader.view.TagGroup;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.Bind;
/**
* Created by Administrator on 2016/8/6.
*/
public class SearchActivity extends BaseActivity implements SearchContract.View, OnRvItemClickListener<SearchDetail.SearchBooks> {
public static final String INTENT_QUERY = "query";
public static void startActivity(Context context, String query) {
context.startActivity(new Intent(context, SearchActivity.class)
.putExtra(INTENT_QUERY, query));
}
@Bind(R.id.tvChangeWords)
TextView mTvChangeWords;
@Bind(R.id.tag_group)
TagGroup mTagGroup;
@Bind(R.id.rootLayout)
LinearLayout mRootLayout;
@Bind(R.id.recyclerview)
RecyclerView mRecyclerView;
@Bind(R.id.layoutHotWord)
RelativeLayout mLayoutHotWord;
@Inject
SearchPresenter mPresenter;
private List<String> tagList = new ArrayList<>();
private int times = 0;
private SearchResultAdapter mAdapter;
private List<SearchDetail.SearchBooks> mList = new ArrayList<>();
private AutoCompleteAdapter mAutoAdapter;
private List<String> mAutoList = new ArrayList<>();
private String key;
private MenuItem searchMenuItem;
private SearchView searchView;
private ListPopupWindow mListPopupWindow;
@Override
public int getLayoutId() {
return R.layout.activity_search;
}
@Override
protected void setupActivityComponent(AppComponent appComponent) {
DaggerSearchActivityComponent.builder()
.appComponent(appComponent)
.build()
.inject(this);
}
@Override
public void initToolBar() {
mCommonToolbar.setTitle("");
mCommonToolbar.setNavigationIcon(R.drawable.ab_back);
}
@Override
public void initDatas() {
}
@Override
public void configViews() {
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new SupportDividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
mAdapter = new SearchResultAdapter(mContext, mList, this);
mRecyclerView.setAdapter(mAdapter);
mAutoAdapter = new AutoCompleteAdapter(this, mAutoList);
mListPopupWindow = new ListPopupWindow(this);
mListPopupWindow.setAdapter(mAutoAdapter);
mListPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
mListPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
mListPopupWindow.setAnchorView(mCommonToolbar);
mListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListPopupWindow.dismiss();
TextView tv = (TextView) view.findViewById(R.id.tvAutoCompleteItem);
String str = tv.getText().toString();
search(str);
}
});
mTagGroup.setOnTagClickListener(new TagGroup.OnTagClickListener() {
@Override
public void onTagClick(String tag) {
search(tag);
}
});
mTvChangeWords.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showHotWord();
}
});
mPresenter.attachView(this);
mPresenter.getHotWordList();
key = getIntent().getStringExtra(INTENT_QUERY);
}
@Override
public synchronized void showHotWordList(List<String> list) {
tagList.clear();
tagList.addAll(list);
times = 0;
showHotWord();
}
/**
* 每次显示8个
*/
private void showHotWord() {
int start, end;
if (times < tagList.size() && times + 8 <= tagList.size()) {
start = times;
end = times + 8;
} else if (times < tagList.size() - 1 && times + 8 > tagList.size()) {
start = times;
end = tagList.size() - 1;
} else {
start = 0;
end = tagList.size() > 8 ? 8 : tagList.size();
}
times = end;
if (end - start > 0) {
List<String> batch = tagList.subList(start, end);
List<TagColor> colors = TagColor.getRandomColors(batch.size());
mTagGroup.setTags(colors, (String[]) batch.toArray(new String[batch.size()]));
}
}
@Override
public void showAutoCompleteList(List<String> list) {
mAutoList.clear();
mAutoList.addAll(list);
if (!mListPopupWindow.isShowing()) {
mListPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
mListPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
mListPopupWindow.show();
}
mAutoAdapter.notifyDataSetChanged();
}
@Override
public void showSearchResultList(List<SearchDetail.SearchBooks> list) {
mList.clear();
mList.addAll(list);
mAdapter.notifyDataSetChanged();
initSearchResult();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
searchMenuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
key = query;
mPresenter.getSearchResultList(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
if (mListPopupWindow.isShowing())
mListPopupWindow.dismiss();
initTagGroup();
} else {
mPresenter.getAutoCompleteList(newText);
}
return false;
}
});
search(key);
MenuItemCompat.setOnActionExpandListener(searchMenuItem,
new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
initTagGroup();
return true;
}
});
return true;
}
private void search(String key) {
if (!TextUtils.isEmpty(key)) {
MenuItemCompat.expandActionView(searchMenuItem);
searchView.setQuery(key, true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
//initSearchResult();
return true;
}
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void initSearchResult() {
mTagGroup.setVisibility(View.GONE);
mLayoutHotWord.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
if (mListPopupWindow.isShowing())
mListPopupWindow.dismiss();
}
private void initTagGroup() {
mTagGroup.setVisibility(View.VISIBLE);
mLayoutHotWord.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
if (mListPopupWindow.isShowing())
mListPopupWindow.dismiss();
}
@Override
public void onItemClick(View view, int position, SearchDetail.SearchBooks data) {
startActivity(new Intent(SearchActivity.this, BookDetailActivity.class).putExtra
("bookId", data._id));
}
}
| app/src/main/java/com/justwayward/reader/ui/activity/SearchActivity.java | package com.justwayward.reader.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.justwayward.reader.R;
import com.justwayward.reader.base.BaseActivity;
import com.justwayward.reader.bean.SearchDetail;
import com.justwayward.reader.common.OnRvItemClickListener;
import com.justwayward.reader.component.AppComponent;
import com.justwayward.reader.component.DaggerSearchActivityComponent;
import com.justwayward.reader.ui.adapter.AutoCompleteAdapter;
import com.justwayward.reader.ui.adapter.SearchResultAdapter;
import com.justwayward.reader.ui.contract.SearchContract;
import com.justwayward.reader.ui.presenter.SearchPresenter;
import com.justwayward.reader.view.SupportDividerItemDecoration;
import com.justwayward.reader.view.TagColor;
import com.justwayward.reader.view.TagGroup;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.Bind;
/**
* Created by Administrator on 2016/8/6.
*/
public class SearchActivity extends BaseActivity implements SearchContract.View, OnRvItemClickListener<SearchDetail.SearchBooks> {
public static final String INTENT_QUERY = "query";
public static void startActivity(Context context, String query) {
context.startActivity(new Intent(context, SearchActivity.class)
.putExtra(INTENT_QUERY, query));
}
@Bind(R.id.tvChangeWords)
TextView mTvChangeWords;
@Bind(R.id.tag_group)
TagGroup mTagGroup;
@Bind(R.id.rootLayout)
LinearLayout mRootLayout;
@Bind(R.id.recyclerview)
RecyclerView mRecyclerView;
@Bind(R.id.layoutHotWord)
RelativeLayout mLayoutHotWord;
@Inject
SearchPresenter mPresenter;
private List<String> tagList = new ArrayList<>();
private int times = 0;
private SearchResultAdapter mAdapter;
private List<SearchDetail.SearchBooks> mList = new ArrayList<>();
private AutoCompleteAdapter mAutoAdapter;
private List<String> mAutoList = new ArrayList<>();
private String key;
private SearchView searchView;
private ListPopupWindow mListPopupWindow;
@Override
public int getLayoutId() {
return R.layout.activity_search;
}
@Override
protected void setupActivityComponent(AppComponent appComponent) {
DaggerSearchActivityComponent.builder()
.appComponent(appComponent)
.build()
.inject(this);
}
@Override
public void initToolBar() {
mCommonToolbar.setTitle("");
mCommonToolbar.setNavigationIcon(R.drawable.ab_back);
}
@Override
public void initDatas() {
}
@Override
public void configViews() {
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new SupportDividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
mAdapter = new SearchResultAdapter(mContext, mList, this);
mRecyclerView.setAdapter(mAdapter);
mAutoAdapter = new AutoCompleteAdapter(this, mAutoList);
mListPopupWindow = new ListPopupWindow(this);
mListPopupWindow.setAdapter(mAutoAdapter);
mListPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
mListPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
mListPopupWindow.setAnchorView(mCommonToolbar);
mListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListPopupWindow.dismiss();
TextView tv = (TextView) view.findViewById(R.id.tvAutoCompleteItem);
String str = tv.getText().toString();
searchView.setQuery(str, true);
}
});
mTagGroup.setOnTagClickListener(new TagGroup.OnTagClickListener() {
@Override
public void onTagClick(String tag) {
searchView.onActionViewExpanded();
searchView.setQuery(tag, true);
}
});
mTvChangeWords.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showHotWord();
}
});
mPresenter.attachView(this);
mPresenter.getHotWordList();
key = getIntent().getStringExtra(INTENT_QUERY);
}
@Override
public synchronized void showHotWordList(List<String> list) {
tagList.clear();
tagList.addAll(list);
times = 0;
showHotWord();
}
/**
* 每次显示8个
*/
private void showHotWord() {
int start, end;
if (times < tagList.size() && times + 8 <= tagList.size()) {
start = times;
end = times + 8;
} else if (times < tagList.size() - 1 && times + 8 > tagList.size()) {
start = times;
end = tagList.size() - 1;
} else {
start = 0;
end = tagList.size() > 8 ? 8 : tagList.size();
}
times = end;
if (end - start > 0) {
List<String> batch = tagList.subList(start, end);
List<TagColor> colors = TagColor.getRandomColors(batch.size());
mTagGroup.setTags(colors, (String[]) batch.toArray(new String[batch.size()]));
}
}
@Override
public void showAutoCompleteList(List<String> list) {
mAutoList.clear();
mAutoList.addAll(list);
if (!mListPopupWindow.isShowing()) {
mListPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
mListPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
mListPopupWindow.show();
}
mAutoAdapter.notifyDataSetChanged();
}
@Override
public void showSearchResultList(List<SearchDetail.SearchBooks> list) {
mList.clear();
mList.addAll(list);
mAdapter.notifyDataSetChanged();
initSearchResult();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
key = query;
mPresenter.getSearchResultList(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
if (mListPopupWindow.isShowing())
mListPopupWindow.dismiss();
initTagGroup();
} else {
mPresenter.getAutoCompleteList(newText);
}
return false;
}
});
if (!TextUtils.isEmpty(key)) {
MenuItemCompat.expandActionView(menuItem);
searchView.setQuery(key, true);
}
MenuItemCompat.setOnActionExpandListener(menuItem,
new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
initTagGroup();
return true;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
//initSearchResult();
return true;
}
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void initSearchResult() {
mTagGroup.setVisibility(View.GONE);
mLayoutHotWord.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
if (mListPopupWindow.isShowing())
mListPopupWindow.dismiss();
}
private void initTagGroup() {
mTagGroup.setVisibility(View.VISIBLE);
mLayoutHotWord.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
if (mListPopupWindow.isShowing())
mListPopupWindow.dismiss();
}
@Override
public void onItemClick(View view, int position, SearchDetail.SearchBooks data) {
startActivity(new Intent(SearchActivity.this, BookDetailActivity.class).putExtra
("bookId", data._id));
}
}
| 优化书籍搜索
| app/src/main/java/com/justwayward/reader/ui/activity/SearchActivity.java | 优化书籍搜索 | <ide><path>pp/src/main/java/com/justwayward/reader/ui/activity/SearchActivity.java
<ide> private List<String> mAutoList = new ArrayList<>();
<ide>
<ide> private String key;
<add> private MenuItem searchMenuItem;
<ide> private SearchView searchView;
<ide>
<ide> private ListPopupWindow mListPopupWindow;
<ide> mListPopupWindow.dismiss();
<ide> TextView tv = (TextView) view.findViewById(R.id.tvAutoCompleteItem);
<ide> String str = tv.getText().toString();
<del> searchView.setQuery(str, true);
<add> search(str);
<ide> }
<ide> });
<ide>
<ide> mTagGroup.setOnTagClickListener(new TagGroup.OnTagClickListener() {
<ide> @Override
<ide> public void onTagClick(String tag) {
<del> searchView.onActionViewExpanded();
<del> searchView.setQuery(tag, true);
<add> search(tag);
<ide> }
<ide> });
<ide>
<ide> MenuInflater inflater = getMenuInflater();
<ide> inflater.inflate(R.menu.menu_search, menu);
<ide>
<del> MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
<del> searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
<add> searchMenuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
<add> searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
<ide> searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
<ide>
<ide> @Override
<ide> return false;
<ide> }
<ide> });
<del> if (!TextUtils.isEmpty(key)) {
<del> MenuItemCompat.expandActionView(menuItem);
<del> searchView.setQuery(key, true);
<del> }
<del> MenuItemCompat.setOnActionExpandListener(menuItem,
<add> search(key);
<add> MenuItemCompat.setOnActionExpandListener(searchMenuItem,
<ide> new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
<ide> @Override
<ide> public boolean onMenuItemActionExpand(MenuItem item) {
<ide> return true;
<ide> }
<ide>
<add> private void search(String key) {
<add> if (!TextUtils.isEmpty(key)) {
<add> MenuItemCompat.expandActionView(searchMenuItem);
<add> searchView.setQuery(key, true);
<add> }
<add> }
<add>
<ide> @Override
<ide> public boolean onOptionsItemSelected(MenuItem item) {
<ide> int id = item.getItemId(); |
|
Java | apache-2.0 | bb59098d31af64b5fe6790c3ce041e8dd81d17c9 | 0 | michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-3 | package ai.h2o.automl;
import hex.FrameSplitter;
import hex.Model;
import hex.genmodel.utils.DistributionFamily;
import hex.tree.gbm.GBM;
import hex.tree.gbm.GBMModel;
import org.junit.*;
import water.H2O;
import water.TestUtil;
import water.fvec.Frame;
import water.fvec.TestFrameBuilder;
import water.fvec.Vec;
import water.rapids.Rapids;
import water.rapids.Val;
import water.rapids.ast.prims.mungers.AstGroup;
import water.util.FrameUtils;
import water.util.IcedHashMap;
import water.util.TwoDimTable;
import java.util.Map;
import static org.junit.Assert.*;
import static water.util.FrameUtils.generateNumKeys;
public class TargetEncodingTest extends TestUtil {
@BeforeClass public static void setup() {
stall_till_cloudsize(1);
}
private Frame fr = null;
@Before
public void beforeEach() {
System.out.println("Before each setup");
}
/*@Ignore
@Test public void TitanicDemoWithTargetEncodingTest() {
Frame fr=null;
try {
fr = parse_test_file("./smalldata/gbm_test/titanic.csv");
fr = FrameUtils.categoricalEncoder(fr, new String[]{},
Model.Parameters.CategoricalEncodingScheme.LabelEncoder, null, -1);
// Splitting phase
double[] ratios = ard(0.7f, 0.1f, 0.1f);
Frame[] splits = null;
long numberOfRows = fr.numRows();
FrameSplitter fs = new FrameSplitter(fr, ratios, generateNumKeys(fr._key, ratios.length+1), null);
H2O.submitTask(fs).join();
splits = fs.getResult();
Frame train = splits[0];
Frame valid = splits[1];
Frame te_holdout = splits[2];
Frame test = splits[3];
long l = train.numRows();
double v = Math.floor(numberOfRows * 0.7);
assert l == v;
assert splits.length == 4;
String[] colNames = train.names();
//myX <- setdiff(colnames(train), c("survived", "name", "ticket", "boat", "body"))
// Building default GBM
GBMModel gbm = null;
Frame fr2 = null;
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = train._key;
parms._response_column = "survived";
parms._ntrees = 2;
parms._max_depth = 3;
parms._distribution = DistributionFamily.AUTO;
parms._keep_cross_validation_predictions=true;
GBM job = new GBM(parms);
gbm = job.trainModel().get();
Assert.assertTrue(job.isStopped());
fr2 = gbm.score(fr);
} finally {
if(fr != null) fr.remove();
}
}
*/
@Test(expected = IllegalStateException.class)
public void targetEncoderPrepareEncodingFrameValidationDataIsNotNullTest() {
TargetEncoder tec = new TargetEncoder();
String[] teColumns = {"0"};
tec.prepareEncodingMap(null, teColumns, "2", null);
}
@Test(expected = IllegalStateException.class)
public void targetEncoderPrepareEncodingFrameValidationTEColumnsIsNotEmptyTest() {
TargetEncoder tec = new TargetEncoder();
String[] teColumns = {};
tec.prepareEncodingMap(null, teColumns, "2", null);
}
@Test
public void targetEncoderPrepareEncodingFrameValidationTest() {
//TODO test other validation checks
}
@Test
public void targetEncoderFilterOutNAsTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withVecTypes(Vec.T_NUM, Vec.T_NUM, Vec.T_STR)
.withDataForCol(0, ard(1, 1))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar(null, "6"))
.build();
TargetEncoder tec = new TargetEncoder();
Frame result = tec.filterOutNAsFromTargetColumn(fr, 2);
assertEquals(1L, result.numRows());
}
@Test
public void allTEColumnsAreCategoricalTest() {
TestFrameBuilder baseBuilder = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withDataForCol(0, ar("1", "0"))
.withDataForCol(2, ar("1", "6"));
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0, 1};
fr = baseBuilder
.withDataForCol(1, ar(0, 1))
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT)
.build();
try {
tec.prepareEncodingMap(fr, teColumns, 2, null);
fail();
} catch (IllegalStateException ex) {
assertEquals("Argument 'columnsToEncode' should contain only names of categorical columns", ex.getMessage());
}
fr = baseBuilder
.withDataForCol(1, ar("a", "b"))
.withVecTypes(Vec.T_CAT, Vec.T_CAT, Vec.T_CAT)
.build();
try {
tec.prepareEncodingMap(fr, teColumns, 2, null);
} catch (IllegalStateException ex) {
fail(String.format("All columns were categorical but something else went wrong: %s", ex.getMessage()));
}
}
@Test
public void prepareEncodingMapForKFoldCaseTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b"))
.withDataForCol(1, ard(1, 1, 4, 7))
.withDataForCol(2, ar("2", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame colAEncoding = targetEncodingMap.get("ColA");
TwoDimTable twoDimTable = colAEncoding.toTwoDimTable();
System.out.println(twoDimTable.toString());
assertVecEquals(vec(0, 2, 1), colAEncoding.vec(2), 1e-5);
assertVecEquals(vec(1, 2, 1), colAEncoding.vec(3), 1e-5);
}
@Test
public void prepareEncodingMapWithoutFoldColumnCaseTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar("a", "b", "b", "b"))
.withDataForCol(1, ard(1, 1, 4, 7))
.withDataForCol(2, ar("2", "6", "6", "6"))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2);
Frame colAEncoding = targetEncodingMap.get("ColA");
TwoDimTable twoDimTable = colAEncoding.toTwoDimTable();
System.out.println(twoDimTable.toString());
assertVecEquals(vec(0, 3), colAEncoding.vec(1), 1e-5);
assertVecEquals(vec(1, 3), colAEncoding.vec(2), 1e-5);
}
@Test
public void prepareEncodingMapForKFoldCaseWithSomeOfTheTEValuesRepresentedOnlyInOneFold_Test() {
//TODO like in te_encoding_possible_bug_demo.R test
}
// ------------------------ KFold holdout type -------------------------------------------------------------------//
@Test
public void targetEncoderKFoldHoldoutApplyingTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.KFold, 3, false, 0, 1234.0);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
Vec vec = resultWithEncoding.vec(4);
assertVecEquals(vec(1,0,1,1,1), vec, 1e-5);
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithoutFoldColumnTest() {
//TODO fold_column = null case
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithNoiseTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
//If we do not pass noise_level as parameter then it will be calculated according to the type of target column. For categorical target column it defaults to 1e-2
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.KFold, 3, false);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
assertVecEquals(vec(1,0,1,1,1), resultWithEncoding.vec(4), 1e-2); // TODO if it's ok that encoding contains negative values?
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithCustomNoiseTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.KFold, 3, false, 0.02, 1234.0);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
assertVecEquals(vec(1,0,1,1,1), resultWithEncoding.vec(4), 2e-2); // TODO we do not check here actually that we have noise more then default 0.01. We need to check that sometimes we get 0.01 < delta < 0.02
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithCustomNoiseForNumericColumnTest() {
//TODO
}
@Test
public void calculateSingleNumberResultTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA")
.withVecTypes(Vec.T_NUM)
.withDataForCol(0, ard(1, 2, 3))
.build();
String tree = "(sum (cols testFrame [0.0] ))";
Val val = Rapids.exec(tree);
assertEquals(val.getNum(), 6.0, 1e-5);
}
@Test
public void calculateGlobalMeanTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_NUM, Vec.T_NUM)
.withDataForCol(0, ard(1, 2, 3))
.withDataForCol(1, ard(3, 4, 5))
.build();
TargetEncoder tec = new TargetEncoder();
double result = tec.calculateGlobalMean(fr, 0, 1);
assertEquals(result, 0.5, 1e-5);
}
@Test
public void calculateAndAppendBlendedTEEncodingTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_NUM, Vec.T_NUM)
.withDataForCol(0, ard(1, 2, 3))
.withDataForCol(1, ard(3, 4, 5))
.build();
TargetEncoder tec = new TargetEncoder();
Frame result = tec.calculateAndAppendBlendedTEEncoding(fr, 0, 1, "targetEncoded" );
TwoDimTable twoDimTable = result.toTwoDimTable();
System.out.println(twoDimTable.toString());
// k <- 20
// f <- 10
// global_mean <- sum(x_map$numerator)/sum(x_map$denominator)
// lambda <- 1/(1 + exp((-1)* (te_frame$denominator - k)/f))
// te_frame$target_encode <- ((1 - lambda) * global_mean) + (lambda * te_frame$numerator/te_frame$denominator)
double globalMean = (1.0 + 2.0 + 3.0) / (3 + 4 + 5);
double lambda1 = 1.0 /( 1 + Math.exp( (20.0 - 3) / 10));
double te1 = (1 - lambda1) * globalMean + ( lambda1 * 1 / 3);
double lambda2 = 1.0 /( 1 + Math.exp( (20.0 - 4) / 10));
double te2 = (1.0 - lambda2) * globalMean + ( lambda2 * 2 / 4);
double lambda3 = 1.0 /( 1 + Math.exp( (20.0 - 5) / 10));
double te3 = (1.0 - lambda3) * globalMean + ( lambda3 * 3 / 5);
assertEquals(te1, result.vec(2).at(0), 1e-5);
assertEquals(te2, result.vec(2).at(1), 1e-5);
assertEquals(te3, result.vec(2).at(2), 1e-5);
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithBlendedAvgTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.KFold, 3, true, 0.0, 1234.0);
printOutFrameAsTable(resultWithEncoding);
Vec encodedVec = resultWithEncoding.vec(4);
// TODO I'm not sure if the values are correct but we at least can fix them and avoid regression while changing code further.
assertEquals(0.855, encodedVec.at(0), 1e-3);
assertEquals(0.724, encodedVec.at(1), 1e-3);
assertEquals( 0.855, encodedVec.at(2), 1e-3);
assertEquals( 0.856, encodedVec.at(4), 1e-3);
}
// ------------------------ LeaveOneOut holdout type -------------------------------------------------------------//
@Test
public void targetEncoderLOOHoldoutDivisionByZeroTest() {
//TODO Check division by zero when we subtract current row's value and then use results to calculate numerator/denominator
}
@Test
public void targetEncoderLOOHoldoutSubtractCurrentRowTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "numerator", "denominator", "target")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar("a", "b", "b", "b", "a", "b"))
.withDataForCol(1, ard(1, 1, 4, 7, 4, 2))
.withDataForCol(2, ard(1, 1, 4, 7, 4, 6))
.withDataForCol(3, ar("2", "6", "6", "6", "6", null))
.build();
TargetEncoder tec = new TargetEncoder();
printOutFrameAsTable(fr);
Frame res = tec.subtractTargetValueForLOO(fr, 1, 2, 3);
printOutFrameAsTable(res);
// We check here that for `target column = NA` we do not subtract anything and for other cases we subtract current row's target value
Vec vecNotSubtracted = vec(1, 0, 3, 6, 3, 2);
assertVecEquals(vecNotSubtracted, res.vec(1), 1e-5);
Vec vecSubtracted = vec(0, 0, 3, 6, 3, 6);
assertVecEquals(vecSubtracted, res.vec(2), 1e-5);
}
@Test
public void vecESPCTest() {
Vec vecOfALengthTwo = vec(1, 0);
long [] espcForLengthTwo = {0, 2};
assertArrayEquals(espcForLengthTwo, Vec.ESPC.espc(vecOfALengthTwo));
Vec vecOfALengthThree = vec(1, 0, 3);
long [] espcForVecOfALengthThree = {0, 3};
assertArrayEquals(espcForVecOfALengthThree, Vec.ESPC.espc(vecOfALengthThree));
}
@Test
public void targetEncoderLOOHoldoutApplyingTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.LeaveOneOut,false, 0, 1234.0);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
assertVecEquals(vec(1,0,1,1,1), resultWithEncoding.vec(3), 1e-5);
}
@Test
public void targetEncoderLOOHoldoutApplyingWithFoldColumnTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.LeaveOneOut, 3,false, 0, 1234.0);
assertVecEquals(vec(1,0,1,1,1), resultWithEncoding.vec(4), 1e-5);
}
// ------------------------ None holdout type --------------------------------------------------------------------//
@Test
public void targetEncoderNoneHoldoutApplyingTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.None, 3,false, 0, 1234.0);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
Vec vec = resultWithEncoding.vec(4);
assertEquals(0.5, vec.at(0), 1e-5);
assertEquals(0.5, vec.at(1), 1e-5);
assertEquals(1, vec.at(2), 1e-5);
assertEquals(1, vec.at(3), 1e-5);
assertEquals(1, vec.at(4), 1e-5);
}
// ------------------------ Multiple columns for target encoding -------------------------------------------------//
@Test
public void targetEncoderNoneHoldoutMultipleTEColumnsTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_CAT, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ar("d", "e", "d", "e", "e"))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0, 1};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame firstColumnEncoding = targetEncodingMap.get("ColA");
printOutFrameAsTable(firstColumnEncoding);
Frame secondColumnEncoding = targetEncodingMap.get("ColB");
printOutFrameAsTable(secondColumnEncoding);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.None, 3,false, 0, 1234.0);
// TODO We need vec(..) for doubles to make it easier.
// For the first encoded column
assertEquals(0.5, resultWithEncoding.vec(4).at(0), 1e-5);
assertEquals(1, resultWithEncoding.vec(4).at(1), 1e-5);
assertEquals(0.5, resultWithEncoding.vec(4).at(2), 1e-5);
assertEquals(1, resultWithEncoding.vec(4).at(3), 1e-5);
assertEquals(1, resultWithEncoding.vec(4).at(4), 1e-5);
// For the second encoded column
assertEquals(0.5, resultWithEncoding.vec(5).at(0), 1e-5);
assertEquals(0.5, resultWithEncoding.vec(5).at(1), 1e-5);
assertEquals(1, resultWithEncoding.vec(5).at(2), 1e-5);
assertEquals(1, resultWithEncoding.vec(5).at(3), 1e-5);
assertEquals(1, resultWithEncoding.vec(5).at(4), 1e-5);
}
@Test
public void AddNoiseLevelTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA")
.withVecTypes(Vec.T_NUM)
.withDataForCol(0, ard(1, 2, 3))
.build();
double noiseLevel = 1e-2;
TargetEncoder tec = new TargetEncoder();
fr = tec.addNoise(fr, "ColA", noiseLevel, 1234.0);
assertVecEquals(vec(1, 2, 3), fr.vec(0), 1e-2);
}
@Test
public void getColumnIndexByNameTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar("2", "6"))
.withDataForCol(3, ar(1, 2))
.build();
TargetEncoder tec = new TargetEncoder();
assertEquals(2, tec.getColumnIndexByName(fr, "ColC"));
assertEquals(3, tec.getColumnIndexByName(fr, "fold_column"));
}
@Test
public void getColumnNamesByIndexesTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar("2", "6"))
.build();
TargetEncoder tec = new TargetEncoder();
int[] columns = ari(0,2);
String [] columnNames = tec.getColumnNamesBy(fr, columns);
assertEquals("ColA", columnNames[0]);
assertEquals("ColC", columnNames[1]);
}
@Test
public void renameColumnTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar("2", "6"))
.withDataForCol(3, ar(1, 2))
.build();
TargetEncoder tec = new TargetEncoder();
// Case1: Renaming by index
String indexOfColumnToRename = "0";
String newName = "NewColA";
Frame renamedFrame = tec.renameColumn(fr, Integer.parseInt(indexOfColumnToRename), newName);
TwoDimTable twoDimTable = renamedFrame.toTwoDimTable();
assertEquals( twoDimTable.getColHeaders()[Integer.parseInt(indexOfColumnToRename)], newName);
// Case2: Renaming by name
String newName2 = "NewColA-2";
renamedFrame = tec.renameColumn(fr, "NewColA", newName2);
TwoDimTable table = renamedFrame.toTwoDimTable();
assertEquals( table.getColHeaders()[Integer.parseInt(indexOfColumnToRename)], newName2);
}
@Test
public void ensureTargetColumnIsNumericOrBinaryCategoricalTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "ColD")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_STR, Vec.T_CAT)
.withDataForCol(0, ar("a", "b", "c"))
.withDataForCol(1, ard(1, 2, 3))
.withDataForCol(2, ar("2", "6", "6"))
.withDataForCol(3, ar("2", "6", "6"))
.build();
TargetEncoder tec = new TargetEncoder();
try {
tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 0);
fail();
} catch (Exception ex) {
assertEquals( "`target` must be a binary vector", ex.getMessage());
}
try {
tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 2);
fail();
} catch (Exception ex) {
assertEquals( "`target` must be a numeric or binary vector", ex.getMessage());
}
// Check that numerical column is ok
tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 1);
// Check that binary categorical is ok (transformation is checked in another test)
tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 3);
}
@Test
public void transformBinaryTargetColumnTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar("2", "6"))
.withDataForCol(3, ar(1, 2))
.build();
TargetEncoder tec = new TargetEncoder();
TwoDimTable twoDimTable = fr.toTwoDimTable();
System.out.println(twoDimTable.toString());
Frame res = tec.transformBinaryTargetColumn(fr, 2);
TwoDimTable twoDimTable2 = res.toTwoDimTable();
System.out.println(twoDimTable2.toString());
Vec transformedVector = res.vec(2);
assertTrue(transformedVector.isNumeric());
assertEquals(0, transformedVector.at(0), 1e-5);
assertEquals(1, transformedVector.at(1), 1e-5);
}
@Test
public void targetEncoderGetOutOfFoldDataTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_NUM, Vec.T_NUM)
.withDataForCol(0, ard(5, 6, 7, 9))
.withDataForCol(1, ard(1, 2, 3, 1))
.build();
TargetEncoder tec = new TargetEncoder();
Frame outOfFoldData = tec.getOutOfFoldData(fr, "1", 1);
TwoDimTable twoDimTable = outOfFoldData.toTwoDimTable();
assertEquals(outOfFoldData.numRows(), 2);
assertEquals(6L, twoDimTable.get(5, 0));
assertEquals(7L, twoDimTable.get(6, 0));
Frame outOfFoldData2 = tec.getOutOfFoldData(fr, "1", 2);
TwoDimTable twoDimTable2 = outOfFoldData2.toTwoDimTable();
assertEquals(5L, twoDimTable2.get(5, 0));
assertEquals(7L, twoDimTable2.get(6, 0));
assertEquals(9L, twoDimTable2.get(7, 0));
}
@After
public void afterEach() {
System.out.println("After each setup");
Vec.ESPC.clear();
// TODO in checkLeakedKeys method from TestUntil we are purging store anyway. So maybe we should add default cleanup? or we need to inform developer about specific leakages?
H2O.STORE.clear();
}
// TODO remove.
private void printOutFrameAsTable(Frame fr) {
TwoDimTable twoDimTable = fr.toTwoDimTable();
System.out.println(twoDimTable.toString());
}
}
| h2o-automl/src/test/java/ai/h2o/automl/TargetEncodingTest.java | package ai.h2o.automl;
import hex.FrameSplitter;
import hex.Model;
import hex.genmodel.utils.DistributionFamily;
import hex.tree.gbm.GBM;
import hex.tree.gbm.GBMModel;
import org.junit.*;
import water.H2O;
import water.TestUtil;
import water.fvec.Frame;
import water.fvec.TestFrameBuilder;
import water.fvec.Vec;
import water.rapids.Rapids;
import water.rapids.Val;
import water.rapids.ast.prims.mungers.AstGroup;
import water.util.FrameUtils;
import water.util.IcedHashMap;
import water.util.TwoDimTable;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static water.util.FrameUtils.generateNumKeys;
public class TargetEncodingTest extends TestUtil {
@BeforeClass public static void setup() {
stall_till_cloudsize(1);
}
private Frame fr = null;
@Before
public void beforeEach() {
System.out.println("Before each setup");
}
/*@Ignore
@Test public void TitanicDemoWithTargetEncodingTest() {
Frame fr=null;
try {
fr = parse_test_file("./smalldata/gbm_test/titanic.csv");
fr = FrameUtils.categoricalEncoder(fr, new String[]{},
Model.Parameters.CategoricalEncodingScheme.LabelEncoder, null, -1);
// Splitting phase
double[] ratios = ard(0.7f, 0.1f, 0.1f);
Frame[] splits = null;
long numberOfRows = fr.numRows();
FrameSplitter fs = new FrameSplitter(fr, ratios, generateNumKeys(fr._key, ratios.length+1), null);
H2O.submitTask(fs).join();
splits = fs.getResult();
Frame train = splits[0];
Frame valid = splits[1];
Frame te_holdout = splits[2];
Frame test = splits[3];
long l = train.numRows();
double v = Math.floor(numberOfRows * 0.7);
assert l == v;
assert splits.length == 4;
String[] colNames = train.names();
//myX <- setdiff(colnames(train), c("survived", "name", "ticket", "boat", "body"))
// Building default GBM
GBMModel gbm = null;
Frame fr2 = null;
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = train._key;
parms._response_column = "survived";
parms._ntrees = 2;
parms._max_depth = 3;
parms._distribution = DistributionFamily.AUTO;
parms._keep_cross_validation_predictions=true;
GBM job = new GBM(parms);
gbm = job.trainModel().get();
Assert.assertTrue(job.isStopped());
fr2 = gbm.score(fr);
} finally {
if(fr != null) fr.remove();
}
}
*/
@Test(expected = IllegalStateException.class)
public void targetEncoderPrepareEncodingFrameValidationDataIsNotNullTest() {
TargetEncoder tec = new TargetEncoder();
String[] teColumns = {"0"};
tec.prepareEncodingMap(null, teColumns, "2", null);
}
@Test(expected = IllegalStateException.class)
public void targetEncoderPrepareEncodingFrameValidationTEColumnsIsNotEmptyTest() {
TargetEncoder tec = new TargetEncoder();
String[] teColumns = {};
tec.prepareEncodingMap(null, teColumns, "2", null);
}
@Test
public void targetEncoderPrepareEncodingFrameValidationTest() {
//TODO test other validation checks
}
@Ignore
@Test public void groupByWithAstGroupTest() {
Frame fr=null;
try {
fr = parse_test_file("./smalldata/gbm_test/titanic.csv");
int[] gbCols = {1};
IcedHashMap<AstGroup.G, String> gss = AstGroup.doGroups(fr, gbCols, AstGroup.aggNRows());
IcedHashMap<AstGroup.G, String> g = gss;
}
finally {
if(fr != null) fr.remove();
}
}
@Test
public void targetEncoderFilterOutNAsTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withVecTypes(Vec.T_NUM, Vec.T_NUM, Vec.T_STR)
.withDataForCol(0, ard(1, 1))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar(null, "6"))
.build();
TargetEncoder tec = new TargetEncoder();
Frame result = tec.filterOutNAsFromTargetColumn(fr, 2);
assertEquals(1L, result.numRows());
}
@Test
public void allTEColumnsAreCategoricalTest() {
TestFrameBuilder baseBuilder = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withDataForCol(0, ar("1", "0"))
.withDataForCol(2, ar("1", "6"));
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0, 1};
fr = baseBuilder
.withDataForCol(1, ar(0, 1))
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT)
.build();
try {
tec.prepareEncodingMap(fr, teColumns, 2, null);
fail();
} catch (IllegalStateException ex) {
assertEquals("Argument 'columnsToEncode' should contain only names of categorical columns", ex.getMessage());
}
fr = baseBuilder
.withDataForCol(1, ar("a", "b"))
.withVecTypes(Vec.T_CAT, Vec.T_CAT, Vec.T_CAT)
.build();
try {
tec.prepareEncodingMap(fr, teColumns, 2, null);
} catch (IllegalStateException ex) {
fail(String.format("All columns were categorical but something else went wrong: %s", ex.getMessage()));
}
}
@Test
public void prepareEncodingMapForKFoldCaseTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b"))
.withDataForCol(1, ard(1, 1, 4, 7))
.withDataForCol(2, ar("2", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame colAEncoding = targetEncodingMap.get("ColA");
TwoDimTable twoDimTable = colAEncoding.toTwoDimTable();
System.out.println(twoDimTable.toString());
assertVecEquals(vec(0, 2, 1), colAEncoding.vec(2), 1e-5);
assertVecEquals(vec(1, 2, 1), colAEncoding.vec(3), 1e-5);
}
@Test
public void prepareEncodingMapWithoutFoldColumnCaseTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar("a", "b", "b", "b"))
.withDataForCol(1, ard(1, 1, 4, 7))
.withDataForCol(2, ar("2", "6", "6", "6"))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2);
Frame colAEncoding = targetEncodingMap.get("ColA");
TwoDimTable twoDimTable = colAEncoding.toTwoDimTable();
System.out.println(twoDimTable.toString());
assertVecEquals(vec(0, 3), colAEncoding.vec(1), 1e-5);
assertVecEquals(vec(1, 3), colAEncoding.vec(2), 1e-5);
}
@Test
public void prepareEncodingMapForKFoldCaseWithSomeOfTheTEValuesRepresentedOnlyInOneFold_Test() {
//TODO like in te_encoding_possible_bug_demo.R test
}
// ------------------------ KFold holdout type -------------------------------------------------------------------//
@Test
public void targetEncoderKFoldHoldoutApplyingTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.KFold, 3, false, 0, 1234.0);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
Vec vec = resultWithEncoding.vec(4);
assertVecEquals(vec(1,0,1,1,1), vec, 1e-5);
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithoutFoldColumnTest() {
//TODO fold_column = null case
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithNoiseTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
//If we do not pass noise_level as parameter then it will be calculated according to the type of target column. For categorical target column it defaults to 1e-2
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.KFold, 3, false);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
assertVecEquals(vec(1,0,1,1,1), resultWithEncoding.vec(4), 1e-2); // TODO if it's ok that encoding contains negative values?
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithCustomNoiseTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.KFold, 3, false, 0.02, 1234.0);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
assertVecEquals(vec(1,0,1,1,1), resultWithEncoding.vec(4), 2e-2); // TODO we do not check here actually that we have noise more then default 0.01. We need to check that sometimes we get 0.01 < delta < 0.02
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithCustomNoiseForNumericColumnTest() {
//TODO
}
@Test
public void calculateSingleNumberResultTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA")
.withVecTypes(Vec.T_NUM)
.withDataForCol(0, ard(1, 2, 3))
.build();
String tree = "(sum (cols testFrame [0.0] ))";
Val val = Rapids.exec(tree);
assertEquals(val.getNum(), 6.0, 1e-5);
}
@Test
public void calculateGlobalMeanTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_NUM, Vec.T_NUM)
.withDataForCol(0, ard(1, 2, 3))
.withDataForCol(1, ard(3, 4, 5))
.build();
TargetEncoder tec = new TargetEncoder();
double result = tec.calculateGlobalMean(fr, 0, 1);
assertEquals(result, 0.5, 1e-5);
}
@Test
public void calculateAndAppendBlendedTEEncodingTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_NUM, Vec.T_NUM)
.withDataForCol(0, ard(1, 2, 3))
.withDataForCol(1, ard(3, 4, 5))
.build();
TargetEncoder tec = new TargetEncoder();
Frame result = tec.calculateAndAppendBlendedTEEncoding(fr, 0, 1, "targetEncoded" );
TwoDimTable twoDimTable = result.toTwoDimTable();
System.out.println(twoDimTable.toString());
// k <- 20
// f <- 10
// global_mean <- sum(x_map$numerator)/sum(x_map$denominator)
// lambda <- 1/(1 + exp((-1)* (te_frame$denominator - k)/f))
// te_frame$target_encode <- ((1 - lambda) * global_mean) + (lambda * te_frame$numerator/te_frame$denominator)
double globalMean = (1.0 + 2.0 + 3.0) / (3 + 4 + 5);
double lambda1 = 1.0 /( 1 + Math.exp( (20.0 - 3) / 10));
double te1 = (1 - lambda1) * globalMean + ( lambda1 * 1 / 3);
double lambda2 = 1.0 /( 1 + Math.exp( (20.0 - 4) / 10));
double te2 = (1.0 - lambda2) * globalMean + ( lambda2 * 2 / 4);
double lambda3 = 1.0 /( 1 + Math.exp( (20.0 - 5) / 10));
double te3 = (1.0 - lambda3) * globalMean + ( lambda3 * 3 / 5);
assertEquals(te1, result.vec(2).at(0), 1e-5);
assertEquals(te2, result.vec(2).at(1), 1e-5);
assertEquals(te3, result.vec(2).at(2), 1e-5);
}
@Test
public void targetEncoderKFoldHoldoutApplyingWithBlendedAvgTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.KFold, 3, true, 0.0, 1234.0);
printOutFrameAsTable(resultWithEncoding);
Vec encodedVec = resultWithEncoding.vec(4);
// TODO I'm not sure if the values are correct but we at least can fix them and avoid regression while changing code further.
assertEquals(0.855, encodedVec.at(0), 1e-3);
assertEquals(0.724, encodedVec.at(1), 1e-3);
assertEquals( 0.855, encodedVec.at(2), 1e-3);
assertEquals( 0.856, encodedVec.at(4), 1e-3);
}
// ------------------------ LeaveOneOut holdout type -------------------------------------------------------------//
@Test
public void targetEncoderLOOHoldoutDivisionByZeroTest() {
//TODO Check division by zero when we subtract current row's value and then use results to calculate numerator/denominator
}
@Ignore
@Test
public void targetEncoderLOOHoldoutSubtractCurrentRowTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "numerator", "denominator", "target")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar("a", "b", "b", "b", "a", "b"))
.withDataForCol(1, ard(1, 1, 4, 7, 4, 2))
.withDataForCol(2, ard(1, 1, 4, 7, 4, 6))
.withDataForCol(3, ar("2", "6", "6", "6", "6", null))
.build();
TargetEncoder tec = new TargetEncoder();
printOutFrameAsTable(fr);
Frame res = tec.subtractTargetValueForLOO(fr, 1, 2, 3);
printOutFrameAsTable(res);
// We check here that for `target column = NA` we do not subtract anything and for other cases we subtract current row's target value
assertVecEquals(vec(1,0,3,6,3,2), res.vec(1), 1e-5);
assertVecEquals(vec(0,0,3,6,3,6), res.vec(2), 1e-5);
}
// This test is causing AssertionError in Vec.rowLayout method.
@Ignore
@Test
public void targetEncoderLOOHoldoutApplyingTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.LeaveOneOut,false, 0, 1234.0);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
assertVecEquals(vec(1,0,1,1,1), resultWithEncoding.vec(3), 1e-5);
}
@Test
public void targetEncoderLOOHoldoutApplyingWithFoldColumnTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.LeaveOneOut, 3,false, 0, 1234.0);
assertVecEquals(vec(1,0,1,1,1), resultWithEncoding.vec(4), 1e-5);
}
// ------------------------ None holdout type --------------------------------------------------------------------//
@Test
public void targetEncoderNoneHoldoutApplyingTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ard(1, 1, 4, 7, 4))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.None, 3,false, 0, 1234.0);
TwoDimTable resultTable = resultWithEncoding.toTwoDimTable();
System.out.println("Result table" + resultTable.toString());
Vec vec = resultWithEncoding.vec(4);
assertEquals(0.5, vec.at(0), 1e-5);
assertEquals(0.5, vec.at(1), 1e-5);
assertEquals(1, vec.at(2), 1e-5);
assertEquals(1, vec.at(3), 1e-5);
assertEquals(1, vec.at(4), 1e-5);
}
// ------------------------ Multiple columns for target encoding -------------------------------------------------//
@Test
public void targetEncoderNoneHoldoutMultipleTEColumnsTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_CAT, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "b", "b", "a"))
.withDataForCol(1, ar("d", "e", "d", "e", "e"))
.withDataForCol(2, ar("2", "6", "6", "6", "6"))
.withDataForCol(3, ar(1, 2, 2, 3, 2))
.build();
TargetEncoder tec = new TargetEncoder();
int[] teColumns = {0, 1};
Map<String, Frame> targetEncodingMap = tec.prepareEncodingMap(fr, teColumns, 2, 3);
Frame firstColumnEncoding = targetEncodingMap.get("ColA");
printOutFrameAsTable(firstColumnEncoding);
Frame secondColumnEncoding = targetEncodingMap.get("ColB");
printOutFrameAsTable(secondColumnEncoding);
Frame resultWithEncoding = tec.applyTargetEncoding(fr, teColumns, 2, targetEncodingMap, TargetEncoder.HoldoutType.None, 3,false, 0, 1234.0);
// TODO We need vec(..) for doubles to make it easier.
// For the first encoded column
assertEquals(0.5, resultWithEncoding.vec(4).at(0), 1e-5);
assertEquals(1, resultWithEncoding.vec(4).at(1), 1e-5);
assertEquals(0.5, resultWithEncoding.vec(4).at(2), 1e-5);
assertEquals(1, resultWithEncoding.vec(4).at(3), 1e-5);
assertEquals(1, resultWithEncoding.vec(4).at(4), 1e-5);
// For the second encoded column
assertEquals(0.5, resultWithEncoding.vec(5).at(0), 1e-5);
assertEquals(0.5, resultWithEncoding.vec(5).at(1), 1e-5);
assertEquals(1, resultWithEncoding.vec(5).at(2), 1e-5);
assertEquals(1, resultWithEncoding.vec(5).at(3), 1e-5);
assertEquals(1, resultWithEncoding.vec(5).at(4), 1e-5);
}
@Test
public void AddNoiseLevelTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA")
.withVecTypes(Vec.T_NUM)
.withDataForCol(0, ard(1, 2, 3))
.build();
double noiseLevel = 1e-2;
TargetEncoder tec = new TargetEncoder();
fr = tec.addNoise(fr, "ColA", noiseLevel, 1234.0);
assertVecEquals(vec(1, 2, 3), fr.vec(0), 1e-2);
}
@Test
public void getColumnIndexByNameTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar("2", "6"))
.withDataForCol(3, ar(1, 2))
.build();
TargetEncoder tec = new TargetEncoder();
assertEquals(2, tec.getColumnIndexByName(fr, "ColC"));
assertEquals(3, tec.getColumnIndexByName(fr, "fold_column"));
}
@Test
public void getColumnNamesByIndexesTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar("2", "6"))
.build();
TargetEncoder tec = new TargetEncoder();
int[] columns = ari(0,2);
String [] columnNames = tec.getColumnNamesBy(fr, columns);
assertEquals("ColA", columnNames[0]);
assertEquals("ColC", columnNames[1]);
}
@Test
public void renameColumnTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar("2", "6"))
.withDataForCol(3, ar(1, 2))
.build();
TargetEncoder tec = new TargetEncoder();
// Case1: Renaming by index
String indexOfColumnToRename = "0";
String newName = "NewColA";
Frame renamedFrame = tec.renameColumn(fr, Integer.parseInt(indexOfColumnToRename), newName);
TwoDimTable twoDimTable = renamedFrame.toTwoDimTable();
assertEquals( twoDimTable.getColHeaders()[Integer.parseInt(indexOfColumnToRename)], newName);
// Case2: Renaming by name
String newName2 = "NewColA-2";
renamedFrame = tec.renameColumn(fr, "NewColA", newName2);
TwoDimTable table = renamedFrame.toTwoDimTable();
assertEquals( table.getColHeaders()[Integer.parseInt(indexOfColumnToRename)], newName2);
}
@Test
public void ensureTargetColumnIsNumericOrBinaryCategoricalTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "ColD")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_STR, Vec.T_CAT)
.withDataForCol(0, ar("a", "b", "c"))
.withDataForCol(1, ard(1, 2, 3))
.withDataForCol(2, ar("2", "6", "6"))
.withDataForCol(3, ar("2", "6", "6"))
.build();
TargetEncoder tec = new TargetEncoder();
try {
tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 0);
fail();
} catch (Exception ex) {
assertEquals( "`target` must be a binary vector", ex.getMessage());
}
try {
tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 2);
fail();
} catch (Exception ex) {
assertEquals( "`target` must be a numeric or binary vector", ex.getMessage());
}
// Check that numerical column is ok
tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 1);
// Check that binary categorical is ok (transformation is checked in another test)
tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 3);
}
@Ignore
@Test
public void transformBinaryTargetColumnTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB", "ColC", "fold_column")
.withVecTypes(Vec.T_CAT, Vec.T_NUM, Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.withDataForCol(2, ar("2", "6"))
.withDataForCol(3, ar(1, 2))
.build();
TargetEncoder tec = new TargetEncoder();
TwoDimTable twoDimTable = fr.toTwoDimTable();
System.out.println(twoDimTable.toString());
Frame res = tec.transformBinaryTargetColumn(fr, 2);
TwoDimTable twoDimTable2 = res.toTwoDimTable();
System.out.println(twoDimTable2.toString());
Vec transformedVector = res.vec(2);
assertTrue(transformedVector.isNumeric());
// assertVecEquals(vec(0, 1), transformedVector, 1e-5); //TODO this row is causing an error with layout as well.
}
@Test
public void targetEncoderGetOutOfFoldDataTest() {
fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_NUM, Vec.T_NUM)
.withDataForCol(0, ard(5, 6, 7, 9))
.withDataForCol(1, ard(1, 2, 3, 1))
.build();
TargetEncoder tec = new TargetEncoder();
Frame outOfFoldData = tec.getOutOfFoldData(fr, "1", 1);
TwoDimTable twoDimTable = outOfFoldData.toTwoDimTable();
assertEquals(outOfFoldData.numRows(), 2);
assertEquals(6L, twoDimTable.get(5, 0));
assertEquals(7L, twoDimTable.get(6, 0));
Frame outOfFoldData2 = tec.getOutOfFoldData(fr, "1", 2);
TwoDimTable twoDimTable2 = outOfFoldData2.toTwoDimTable();
assertEquals(5L, twoDimTable2.get(5, 0));
assertEquals(7L, twoDimTable2.get(6, 0));
assertEquals(9L, twoDimTable2.get(7, 0));
}
@After
public void afterEach() {
System.out.println("After each setup");
// TODO in checkLeakedKeys method from TestUntil we are purging store anyway. So maybe we should add default cleanup? or we need to inform developer about specific leakages?
H2O.STORE.clear();
}
// TODO remove.
private void printOutFrameAsTable(Frame fr) {
TwoDimTable twoDimTable = fr.toTwoDimTable();
System.out.println(twoDimTable.toString());
}
}
| PUBDEV-5378: Fixed issue with AssertionError from rowLayout method while running multiple tests. There is a state in Vec.ESPC that we need to clean after each test. All tests are green.
| h2o-automl/src/test/java/ai/h2o/automl/TargetEncodingTest.java | PUBDEV-5378: Fixed issue with AssertionError from rowLayout method while running multiple tests. There is a state in Vec.ESPC that we need to clean after each test. All tests are green. | <ide><path>2o-automl/src/test/java/ai/h2o/automl/TargetEncodingTest.java
<ide>
<ide> import java.util.Map;
<ide>
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertTrue;
<del>import static org.junit.Assert.fail;
<add>import static org.junit.Assert.*;
<ide> import static water.util.FrameUtils.generateNumKeys;
<ide>
<ide> public class TargetEncodingTest extends TestUtil {
<ide>
<ide> }
<ide>
<del> @Ignore
<del> @Test public void groupByWithAstGroupTest() {
<del> Frame fr=null;
<del> try {
<del> fr = parse_test_file("./smalldata/gbm_test/titanic.csv");
<del> int[] gbCols = {1};
<del> IcedHashMap<AstGroup.G, String> gss = AstGroup.doGroups(fr, gbCols, AstGroup.aggNRows());
<del> IcedHashMap<AstGroup.G, String> g = gss;
<del> }
<del> finally {
<del> if(fr != null) fr.remove();
<del> }
<del> }
<del>
<ide> @Test
<ide> public void targetEncoderFilterOutNAsTest() {
<ide>
<ide> //TODO Check division by zero when we subtract current row's value and then use results to calculate numerator/denominator
<ide> }
<ide>
<del> @Ignore
<ide> @Test
<ide> public void targetEncoderLOOHoldoutSubtractCurrentRowTest() {
<ide> fr = new TestFrameBuilder()
<ide>
<ide> Frame res = tec.subtractTargetValueForLOO(fr, 1, 2, 3);
<ide> printOutFrameAsTable(res);
<add>
<ide> // We check here that for `target column = NA` we do not subtract anything and for other cases we subtract current row's target value
<del> assertVecEquals(vec(1,0,3,6,3,2), res.vec(1), 1e-5);
<del> assertVecEquals(vec(0,0,3,6,3,6), res.vec(2), 1e-5);
<del> }
<del>
<del> // This test is causing AssertionError in Vec.rowLayout method.
<del> @Ignore
<add> Vec vecNotSubtracted = vec(1, 0, 3, 6, 3, 2);
<add> assertVecEquals(vecNotSubtracted, res.vec(1), 1e-5);
<add> Vec vecSubtracted = vec(0, 0, 3, 6, 3, 6);
<add> assertVecEquals(vecSubtracted, res.vec(2), 1e-5);
<add> }
<add>
<add> @Test
<add> public void vecESPCTest() {
<add> Vec vecOfALengthTwo = vec(1, 0);
<add> long [] espcForLengthTwo = {0, 2};
<add> assertArrayEquals(espcForLengthTwo, Vec.ESPC.espc(vecOfALengthTwo));
<add> Vec vecOfALengthThree = vec(1, 0, 3);
<add> long [] espcForVecOfALengthThree = {0, 3};
<add> assertArrayEquals(espcForVecOfALengthThree, Vec.ESPC.espc(vecOfALengthThree));
<add> }
<add>
<ide> @Test
<ide> public void targetEncoderLOOHoldoutApplyingTest() {
<ide> fr = new TestFrameBuilder()
<ide> tec.ensureTargetColumnIsNumericOrBinaryCategorical(fr, 3);
<ide> }
<ide>
<del> @Ignore
<ide> @Test
<ide> public void transformBinaryTargetColumnTest() {
<ide> fr = new TestFrameBuilder()
<ide>
<ide> Vec transformedVector = res.vec(2);
<ide> assertTrue(transformedVector.isNumeric());
<del>// assertVecEquals(vec(0, 1), transformedVector, 1e-5); //TODO this row is causing an error with layout as well.
<add> assertEquals(0, transformedVector.at(0), 1e-5);
<add> assertEquals(1, transformedVector.at(1), 1e-5);
<ide> }
<ide>
<ide> @Test
<ide> @After
<ide> public void afterEach() {
<ide> System.out.println("After each setup");
<add> Vec.ESPC.clear();
<ide> // TODO in checkLeakedKeys method from TestUntil we are purging store anyway. So maybe we should add default cleanup? or we need to inform developer about specific leakages?
<ide> H2O.STORE.clear();
<ide> } |
|
Java | apache-2.0 | 653b5cf119f4fbc140b5ddf122889f5f0a7aa681 | 0 | meisteg/PickTheWinner,meisteg/PickTheWinner,meisteg/PickTheWinner | /*
* Copyright (C) 2012 Gregory S. Meiste <http://gregmeiste.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meiste.greg.ptw;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
public class EditPreferences extends SherlockPreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String KEY_ACCOUNT_EMAIL = "account.email";
public static final String KEY_ACCOUNT_COOKIE = "account.cookie";
public static final String KEY_REMIND_QUESTIONS = "remind.questions";
public static final String KEY_REMIND_RACE = "remind.race";
public static final String KEY_REMIND_VIBRATE = "remind.vibrate";
public static final String KEY_REMIND_LED = "remind.led";
public static final String KEY_REMIND_RINGTONE = "remind.ringtone";
private static final String KEY_ACCOUNT_SCREEN = "account_screen";
private static final String KEY_REMINDER_SETTINGS = "reminder_settings_category";
private Preference mVibrate;
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mVibrate = findPreference(KEY_REMIND_VIBRATE);
boolean methodAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (methodAvailable && (vibrator == null || !vibrator.hasVibrator())) {
Util.log("Remove vibrator option since vibrator not present");
PreferenceCategory pc = (PreferenceCategory)findPreference(KEY_REMINDER_SETTINGS);
pc.removePreference(mVibrate);
}
}
@SuppressWarnings("deprecation")
@Override
protected void onResume() {
super.onResume();
Util.log("EditPreferences.onResume");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
reminderCheck(prefs);
Preference account = findPreference(KEY_ACCOUNT_SCREEN);
account.setSummary(prefs.getString(KEY_ACCOUNT_EMAIL, getString(R.string.account_needed)));
}
@Override
protected void onPause() {
super.onPause();
Util.log("EditPreferences.onPause");
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals(KEY_REMIND_QUESTIONS)) {
if (prefs.getBoolean(key, true)) {
QuestionAlarm.set(this);
}
reminderCheck(prefs);
} else if (key.equals(KEY_REMIND_RACE)) {
if (prefs.getBoolean(key, true)) {
RaceAlarm.set(this);
}
reminderCheck(prefs);
}
}
@SuppressWarnings("deprecation")
private void reminderCheck(SharedPreferences prefs) {
if (prefs.getBoolean(KEY_REMIND_QUESTIONS, true) ||
prefs.getBoolean(KEY_REMIND_RACE, true)) {
findPreference(KEY_REMIND_LED).setEnabled(true);
findPreference(KEY_REMIND_RINGTONE).setEnabled(true);
if (mVibrate != null)
mVibrate.setEnabled(true);
} else {
findPreference(KEY_REMIND_LED).setEnabled(false);
findPreference(KEY_REMIND_RINGTONE).setEnabled(false);
if (mVibrate != null)
mVibrate.setEnabled(false);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent homeIntent = new Intent(this, MainActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(homeIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| app/src/com/meiste/greg/ptw/EditPreferences.java | /*
* Copyright (C) 2012 Gregory S. Meiste <http://gregmeiste.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meiste.greg.ptw;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
public class EditPreferences extends SherlockPreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String KEY_ACCOUNT_EMAIL = "account.email";
public static final String KEY_ACCOUNT_COOKIE = "account.cookie";
public static final String KEY_REMIND_QUESTIONS = "remind.questions";
public static final String KEY_REMIND_RACE = "remind.race";
public static final String KEY_REMIND_VIBRATE = "remind.vibrate";
public static final String KEY_REMIND_LED = "remind.led";
public static final String KEY_REMIND_RINGTONE = "remind.ringtone";
private static final String KEY_ACCOUNT_SCREEN = "account_screen";
private static final String KEY_REMINDER_SETTINGS = "reminder_settings_category";
private Preference mVibrate;
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mVibrate = findPreference(KEY_REMIND_VIBRATE);
boolean methodAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (methodAvailable && (vibrator == null || !vibrator.hasVibrator())) {
Util.log("Remove vibrator option since vibrator not present");
PreferenceCategory pc = (PreferenceCategory)findPreference(KEY_REMINDER_SETTINGS);
pc.removePreference(mVibrate);
}
}
@SuppressWarnings("deprecation")
@Override
protected void onResume() {
super.onResume();
Util.log("EditPreferences.onResume");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
reminderCheck(prefs);
Preference account = findPreference(KEY_ACCOUNT_SCREEN);
account.setSummary(prefs.getString(KEY_ACCOUNT_EMAIL, getString(R.string.account_needed)));
}
@Override
protected void onPause() {
super.onPause();
Util.log("EditPreferences.onPause");
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (!key.equals(KEY_REMIND_RINGTONE))
Util.log(key + "=" + prefs.getBoolean(key, true));
if (key.equals(KEY_REMIND_QUESTIONS)) {
if (prefs.getBoolean(key, true)) {
QuestionAlarm.set(this);
}
reminderCheck(prefs);
} else if (key.equals(KEY_REMIND_RACE)) {
if (prefs.getBoolean(key, true)) {
RaceAlarm.set(this);
}
reminderCheck(prefs);
}
}
@SuppressWarnings("deprecation")
private void reminderCheck(SharedPreferences prefs) {
if (prefs.getBoolean(KEY_REMIND_QUESTIONS, true) ||
prefs.getBoolean(KEY_REMIND_RACE, true)) {
findPreference(KEY_REMIND_LED).setEnabled(true);
findPreference(KEY_REMIND_RINGTONE).setEnabled(true);
if (mVibrate != null)
mVibrate.setEnabled(true);
} else {
findPreference(KEY_REMIND_LED).setEnabled(false);
findPreference(KEY_REMIND_RINGTONE).setEnabled(false);
if (mVibrate != null)
mVibrate.setEnabled(false);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent homeIntent = new Intent(this, MainActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(homeIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| Remove debug log print when preference changed
User could cause an exception by initiating account connect and
pressing back arrow before connection completes. The connection
will still complete successfully and update the preferences,
resulting in onSharedPreferenceChanged() being called (since
that activity is now active). The account preferences are not
booleans, which resulted in the exception.
Signed-off-by: Greg Meiste <[email protected]>
| app/src/com/meiste/greg/ptw/EditPreferences.java | Remove debug log print when preference changed | <ide><path>pp/src/com/meiste/greg/ptw/EditPreferences.java
<ide>
<ide> @Override
<ide> public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
<del> if (!key.equals(KEY_REMIND_RINGTONE))
<del> Util.log(key + "=" + prefs.getBoolean(key, true));
<del>
<ide> if (key.equals(KEY_REMIND_QUESTIONS)) {
<ide> if (prefs.getBoolean(key, true)) {
<ide> QuestionAlarm.set(this); |
|
JavaScript | bsd-3-clause | 7c5c517114fd248a08d24a219f6a4b48fd93e43e | 0 | glensc/toggl-button,topdown/toggl-button,eatskolnikov/toggl-button,andreimoldo/toggl-button,glensc/toggl-button,bitbull-team/toggl-button,glensc/toggl-button,eatskolnikov/toggl-button,andreimoldo/toggl-button,topdown/toggl-button,bitbull-team/toggl-button | /*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
togglbutton.render('.task:not(.toggl)', {observe: true}, function (elem) {
var link,
projectElem = $('#client_name b'),
taskElem = $('.task h1');
if (!taskElem) {
return;
}
taskElem = taskElem.childNodes[2].textContent.trim();
link = togglbutton.createTimerLink({
className: 'worksection',
description: taskElem,
projectName: projectElem && projectElem.textContent.trim()
});
link.classList.add('norm');
$('#tmenu2', elem).appendChild(link);
});
| src/scripts/content/worksection.js | /*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
togglbutton.render('.task:not(.toggl)', {observe: true}, function (elem) {
var link,
projectElem = $('#client_name b'),
taskElem = $('.task h1').childNodes[2].textContent.trim();
link = togglbutton.createTimerLink({
className: 'worksection',
description: taskElem,
projectName: projectElem && projectElem.textContent.trim()
});
link.classList.add('norm');
$('#tmenu2', elem).appendChild(link);
});
| Improved Worksection selectors
| src/scripts/content/worksection.js | Improved Worksection selectors | <ide><path>rc/scripts/content/worksection.js
<ide> togglbutton.render('.task:not(.toggl)', {observe: true}, function (elem) {
<ide> var link,
<ide> projectElem = $('#client_name b'),
<del> taskElem = $('.task h1').childNodes[2].textContent.trim();
<add> taskElem = $('.task h1');
<add>
<add> if (!taskElem) {
<add> return;
<add> }
<add>
<add> taskElem = taskElem.childNodes[2].textContent.trim();
<ide>
<ide> link = togglbutton.createTimerLink({
<ide> className: 'worksection', |
|
Java | apache-2.0 | 7d8a68be454f255b004007542dea0d869c4b6da1 | 0 | CandleCandle/camel,tlehoux/camel,pkletsko/camel,gnodet/camel,tdiesler/camel,veithen/camel,mcollovati/camel,isururanawaka/camel,jpav/camel,yury-vashchyla/camel,neoramon/camel,joakibj/camel,manuelh9r/camel,davidkarlsen/camel,nboukhed/camel,noelo/camel,mzapletal/camel,oalles/camel,mike-kukla/camel,johnpoth/camel,arnaud-deprez/camel,maschmid/camel,bgaudaen/camel,yogamaha/camel,adessaigne/camel,jpav/camel,curso007/camel,dvankleef/camel,ekprayas/camel,haku/camel,gilfernandes/camel,jkorab/camel,mike-kukla/camel,lasombra/camel,isavin/camel,atoulme/camel,lburgazzoli/apache-camel,partis/camel,jlpedrosa/camel,anton-k11/camel,dvankleef/camel,jonmcewen/camel,chirino/camel,FingolfinTEK/camel,tadayosi/camel,sirlatrom/camel,pax95/camel,dvankleef/camel,nikhilvibhav/camel,borcsokj/camel,akhettar/camel,YoshikiHigo/camel,jarst/camel,tkopczynski/camel,brreitme/camel,nboukhed/camel,neoramon/camel,pkletsko/camel,brreitme/camel,tkopczynski/camel,lasombra/camel,bgaudaen/camel,dmvolod/camel,drsquidop/camel,CandleCandle/camel,snadakuduru/camel,Thopap/camel,pplatek/camel,Thopap/camel,satishgummadelli/camel,coderczp/camel,isururanawaka/camel,curso007/camel,nboukhed/camel,allancth/camel,Fabryprog/camel,nicolaferraro/camel,pmoerenhout/camel,eformat/camel,pmoerenhout/camel,gautric/camel,rmarting/camel,FingolfinTEK/camel,yuruki/camel,zregvart/camel,mzapletal/camel,MohammedHammam/camel,noelo/camel,jmandawg/camel,sabre1041/camel,rmarting/camel,bfitzpat/camel,driseley/camel,arnaud-deprez/camel,anton-k11/camel,mike-kukla/camel,sirlatrom/camel,yury-vashchyla/camel,onders86/camel,jkorab/camel,jlpedrosa/camel,akhettar/camel,allancth/camel,DariusX/camel,jamesnetherton/camel,eformat/camel,chirino/camel,FingolfinTEK/camel,drsquidop/camel,prashant2402/camel,haku/camel,jpav/camel,erwelch/camel,sverkera/camel,stravag/camel,FingolfinTEK/camel,objectiser/camel,ullgren/camel,erwelch/camel,tdiesler/camel,YoshikiHigo/camel,pax95/camel,sabre1041/camel,ge0ffrey/camel,tlehoux/camel,qst-jdc-labs/camel,onders86/camel,chanakaudaya/camel,dmvolod/camel,objectiser/camel,trohovsky/camel,mohanaraosv/camel,yury-vashchyla/camel,bhaveshdt/camel,ekprayas/camel,mike-kukla/camel,bfitzpat/camel,bhaveshdt/camel,NickCis/camel,nikvaessen/camel,alvinkwekel/camel,duro1/camel,tadayosi/camel,erwelch/camel,atoulme/camel,edigrid/camel,jollygeorge/camel,mike-kukla/camel,tarilabs/camel,lburgazzoli/camel,sirlatrom/camel,jmandawg/camel,lburgazzoli/camel,davidwilliams1978/camel,neoramon/camel,MrCoder/camel,manuelh9r/camel,gilfernandes/camel,atoulme/camel,jamesnetherton/camel,davidwilliams1978/camel,acartapanis/camel,FingolfinTEK/camel,cunningt/camel,arnaud-deprez/camel,zregvart/camel,cunningt/camel,gilfernandes/camel,haku/camel,oalles/camel,Thopap/camel,chirino/camel,ge0ffrey/camel,jmandawg/camel,isururanawaka/camel,ge0ffrey/camel,ssharma/camel,yury-vashchyla/camel,eformat/camel,johnpoth/camel,apache/camel,sverkera/camel,isavin/camel,apache/camel,coderczp/camel,erwelch/camel,scranton/camel,sirlatrom/camel,bgaudaen/camel,mzapletal/camel,mzapletal/camel,joakibj/camel,jarst/camel,davidwilliams1978/camel,gilfernandes/camel,YMartsynkevych/camel,kevinearls/camel,snadakuduru/camel,jmandawg/camel,sabre1041/camel,edigrid/camel,maschmid/camel,sverkera/camel,lburgazzoli/camel,onders86/camel,coderczp/camel,qst-jdc-labs/camel,nikvaessen/camel,woj-i/camel,gilfernandes/camel,nicolaferraro/camel,bgaudaen/camel,rmarting/camel,w4tson/camel,tkopczynski/camel,noelo/camel,tlehoux/camel,gyc567/camel,akhettar/camel,pplatek/camel,iweiss/camel,MrCoder/camel,rparree/camel,cunningt/camel,gautric/camel,Fabryprog/camel,lowwool/camel,kevinearls/camel,davidwilliams1978/camel,jollygeorge/camel,snurmine/camel,w4tson/camel,FingolfinTEK/camel,davidkarlsen/camel,prashant2402/camel,pax95/camel,tdiesler/camel,acartapanis/camel,lasombra/camel,satishgummadelli/camel,joakibj/camel,coderczp/camel,pplatek/camel,isururanawaka/camel,drsquidop/camel,brreitme/camel,zregvart/camel,anoordover/camel,coderczp/camel,trohovsky/camel,YMartsynkevych/camel,punkhorn/camel-upstream,onders86/camel,nikhilvibhav/camel,chirino/camel,drsquidop/camel,nboukhed/camel,cunningt/camel,jpav/camel,pkletsko/camel,isavin/camel,bhaveshdt/camel,YoshikiHigo/camel,adessaigne/camel,askannon/camel,haku/camel,jamesnetherton/camel,jpav/camel,satishgummadelli/camel,w4tson/camel,anton-k11/camel,partis/camel,iweiss/camel,allancth/camel,nboukhed/camel,oalles/camel,onders86/camel,ekprayas/camel,pplatek/camel,mohanaraosv/camel,w4tson/camel,haku/camel,jollygeorge/camel,dmvolod/camel,tlehoux/camel,woj-i/camel,sabre1041/camel,stravag/camel,DariusX/camel,chanakaudaya/camel,davidwilliams1978/camel,oalles/camel,mohanaraosv/camel,mzapletal/camel,RohanHart/camel,driseley/camel,neoramon/camel,anoordover/camel,pmoerenhout/camel,nikvaessen/camel,gnodet/camel,dvankleef/camel,YMartsynkevych/camel,bhaveshdt/camel,woj-i/camel,kevinearls/camel,rparree/camel,ge0ffrey/camel,jamesnetherton/camel,prashant2402/camel,ullgren/camel,dkhanolkar/camel,ekprayas/camel,yury-vashchyla/camel,isururanawaka/camel,mgyongyosi/camel,yogamaha/camel,woj-i/camel,christophd/camel,lasombra/camel,iweiss/camel,nikvaessen/camel,hqstevenson/camel,NickCis/camel,pkletsko/camel,bfitzpat/camel,dvankleef/camel,hqstevenson/camel,rparree/camel,dvankleef/camel,CodeSmell/camel,sebi-hgdata/camel,dkhanolkar/camel,partis/camel,rmarting/camel,jollygeorge/camel,MohammedHammam/camel,sirlatrom/camel,jarst/camel,tdiesler/camel,neoramon/camel,sebi-hgdata/camel,maschmid/camel,scranton/camel,rparree/camel,anoordover/camel,maschmid/camel,stravag/camel,sirlatrom/camel,noelo/camel,partis/camel,alvinkwekel/camel,gautric/camel,pmoerenhout/camel,royopa/camel,woj-i/camel,acartapanis/camel,Thopap/camel,tarilabs/camel,scranton/camel,jollygeorge/camel,ge0ffrey/camel,royopa/camel,rmarting/camel,tadayosi/camel,w4tson/camel,borcsokj/camel,kevinearls/camel,driseley/camel,jollygeorge/camel,qst-jdc-labs/camel,trohovsky/camel,trohovsky/camel,askannon/camel,gyc567/camel,lburgazzoli/apache-camel,tarilabs/camel,tarilabs/camel,scranton/camel,isavin/camel,DariusX/camel,veithen/camel,zregvart/camel,veithen/camel,sebi-hgdata/camel,johnpoth/camel,kevinearls/camel,yuruki/camel,prashant2402/camel,prashant2402/camel,manuelh9r/camel,akhettar/camel,snadakuduru/camel,duro1/camel,hqstevenson/camel,allancth/camel,tlehoux/camel,erwelch/camel,brreitme/camel,gyc567/camel,YMartsynkevych/camel,YoshikiHigo/camel,mohanaraosv/camel,apache/camel,scranton/camel,jarst/camel,yuruki/camel,lasombra/camel,ssharma/camel,acartapanis/camel,JYBESSON/camel,johnpoth/camel,jmandawg/camel,isavin/camel,onders86/camel,dkhanolkar/camel,iweiss/camel,driseley/camel,acartapanis/camel,pplatek/camel,satishgummadelli/camel,ekprayas/camel,tdiesler/camel,RohanHart/camel,rparree/camel,lburgazzoli/apache-camel,MohammedHammam/camel,eformat/camel,borcsokj/camel,anoordover/camel,nikvaessen/camel,curso007/camel,RohanHart/camel,sabre1041/camel,CandleCandle/camel,coderczp/camel,rparree/camel,mgyongyosi/camel,scranton/camel,noelo/camel,stravag/camel,trohovsky/camel,chanakaudaya/camel,gnodet/camel,sabre1041/camel,NickCis/camel,bhaveshdt/camel,joakibj/camel,pax95/camel,dkhanolkar/camel,cunningt/camel,tkopczynski/camel,tkopczynski/camel,yogamaha/camel,CandleCandle/camel,gautric/camel,YoshikiHigo/camel,punkhorn/camel-upstream,jkorab/camel,kevinearls/camel,tadayosi/camel,duro1/camel,jkorab/camel,lowwool/camel,stravag/camel,royopa/camel,jlpedrosa/camel,JYBESSON/camel,MrCoder/camel,neoramon/camel,atoulme/camel,partis/camel,adessaigne/camel,tarilabs/camel,gnodet/camel,RohanHart/camel,stravag/camel,chirino/camel,duro1/camel,ssharma/camel,driseley/camel,jarst/camel,joakibj/camel,snadakuduru/camel,nicolaferraro/camel,jlpedrosa/camel,borcsokj/camel,jonmcewen/camel,akhettar/camel,bfitzpat/camel,edigrid/camel,pplatek/camel,objectiser/camel,arnaud-deprez/camel,yuruki/camel,mgyongyosi/camel,gyc567/camel,joakibj/camel,sverkera/camel,qst-jdc-labs/camel,gautric/camel,atoulme/camel,Fabryprog/camel,lburgazzoli/apache-camel,mgyongyosi/camel,christophd/camel,mcollovati/camel,punkhorn/camel-upstream,CandleCandle/camel,lowwool/camel,prashant2402/camel,christophd/camel,bgaudaen/camel,jamesnetherton/camel,RohanHart/camel,curso007/camel,woj-i/camel,ullgren/camel,ge0ffrey/camel,DariusX/camel,pax95/camel,qst-jdc-labs/camel,tadayosi/camel,jpav/camel,jamesnetherton/camel,dmvolod/camel,davidwilliams1978/camel,snurmine/camel,yogamaha/camel,hqstevenson/camel,askannon/camel,snurmine/camel,YMartsynkevych/camel,brreitme/camel,snurmine/camel,tlehoux/camel,Thopap/camel,iweiss/camel,lburgazzoli/apache-camel,yogamaha/camel,davidkarlsen/camel,royopa/camel,mgyongyosi/camel,dkhanolkar/camel,maschmid/camel,tkopczynski/camel,jonmcewen/camel,nikhilvibhav/camel,JYBESSON/camel,NickCis/camel,lowwool/camel,mohanaraosv/camel,duro1/camel,punkhorn/camel-upstream,anoordover/camel,chanakaudaya/camel,jonmcewen/camel,jkorab/camel,maschmid/camel,veithen/camel,bfitzpat/camel,drsquidop/camel,chanakaudaya/camel,dmvolod/camel,satishgummadelli/camel,nboukhed/camel,anoordover/camel,akhettar/camel,salikjan/camel,ssharma/camel,bhaveshdt/camel,cunningt/camel,MohammedHammam/camel,RohanHart/camel,anton-k11/camel,trohovsky/camel,JYBESSON/camel,sebi-hgdata/camel,pmoerenhout/camel,CodeSmell/camel,nicolaferraro/camel,manuelh9r/camel,gnodet/camel,gyc567/camel,arnaud-deprez/camel,erwelch/camel,nikhilvibhav/camel,borcsokj/camel,alvinkwekel/camel,satishgummadelli/camel,snadakuduru/camel,ullgren/camel,askannon/camel,arnaud-deprez/camel,anton-k11/camel,mgyongyosi/camel,chanakaudaya/camel,sverkera/camel,adessaigne/camel,chirino/camel,lasombra/camel,CodeSmell/camel,YoshikiHigo/camel,anton-k11/camel,lburgazzoli/camel,hqstevenson/camel,salikjan/camel,gyc567/camel,royopa/camel,mike-kukla/camel,edigrid/camel,christophd/camel,ssharma/camel,gautric/camel,sebi-hgdata/camel,allancth/camel,apache/camel,jarst/camel,lowwool/camel,CodeSmell/camel,mcollovati/camel,curso007/camel,haku/camel,NickCis/camel,yuruki/camel,objectiser/camel,jlpedrosa/camel,adessaigne/camel,apache/camel,allancth/camel,mcollovati/camel,yury-vashchyla/camel,iweiss/camel,eformat/camel,tdiesler/camel,edigrid/camel,borcsokj/camel,dmvolod/camel,duro1/camel,isururanawaka/camel,JYBESSON/camel,pplatek/camel,oalles/camel,NickCis/camel,edigrid/camel,veithen/camel,partis/camel,CandleCandle/camel,lburgazzoli/camel,mzapletal/camel,pkletsko/camel,MrCoder/camel,adessaigne/camel,pkletsko/camel,MrCoder/camel,hqstevenson/camel,alvinkwekel/camel,tarilabs/camel,curso007/camel,royopa/camel,mohanaraosv/camel,driseley/camel,Fabryprog/camel,ekprayas/camel,ssharma/camel,atoulme/camel,JYBESSON/camel,rmarting/camel,oalles/camel,brreitme/camel,yuruki/camel,apache/camel,lburgazzoli/camel,davidkarlsen/camel,tadayosi/camel,christophd/camel,snurmine/camel,nikvaessen/camel,dkhanolkar/camel,drsquidop/camel,acartapanis/camel,askannon/camel,noelo/camel,jkorab/camel,johnpoth/camel,isavin/camel,qst-jdc-labs/camel,sebi-hgdata/camel,YMartsynkevych/camel,sverkera/camel,bgaudaen/camel,askannon/camel,christophd/camel,gilfernandes/camel,MrCoder/camel,manuelh9r/camel,jonmcewen/camel,yogamaha/camel,johnpoth/camel,jmandawg/camel,veithen/camel,snadakuduru/camel,jonmcewen/camel,lburgazzoli/apache-camel,MohammedHammam/camel,lowwool/camel,manuelh9r/camel,w4tson/camel,eformat/camel,pmoerenhout/camel,MohammedHammam/camel,jlpedrosa/camel,Thopap/camel,pax95/camel,snurmine/camel,bfitzpat/camel | /**
* 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.camel.component.mongodb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.impl.DefaultMessage;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@UriEndpoint(scheme = "mongodb", title = "MongoDB", syntax = "mongodb:connectionBean", consumerClass = MongoDbTailableCursorConsumer.class, label = "database,nosql")
public class MongoDbEndpoint extends DefaultEndpoint {
private static final Logger LOG = LoggerFactory.getLogger(MongoDbEndpoint.class);
private Mongo mongoConnection;
@UriPath @Metadata(required = "true")
private String connectionBean;
@UriParam
private String database;
@UriParam
private String collection;
@UriParam
private String collectionIndex;
@UriParam
private MongoDbOperation operation;
@UriParam(defaultValue = "true")
private boolean createCollection = true;
@UriParam
private WriteConcern writeConcern;
private WriteConcern writeConcernRef;
@UriParam
private ReadPreference readPreference;
@UriParam
private boolean dynamicity;
@UriParam
private boolean writeResultAsHeader;
// tailable cursor consumer by default
private MongoDbConsumerType consumerType;
@UriParam(defaultValue = "1000")
private long cursorRegenerationDelay = 1000L;
@UriParam
private String tailTrackIncreasingField;
// persitent tail tracking
@UriParam
private boolean persistentTailTracking;
@UriParam
private String persistentId;
@UriParam
private String tailTrackDb;
@UriParam
private String tailTrackCollection;
@UriParam
private String tailTrackField;
private MongoDbTailTrackingConfig tailTrackingConfig;
@UriParam
private MongoDbOutputType outputType;
private DBCollection dbCollection;
private DB db;
// ======= Constructors ===============================================
public MongoDbEndpoint() {
}
public MongoDbEndpoint(String uri, MongoDbComponent component) {
super(uri, component);
}
@SuppressWarnings("deprecation")
public MongoDbEndpoint(String endpointUri) {
super(endpointUri);
}
// ======= Implementation methods =====================================
public Producer createProducer() throws Exception {
validateOptions('P');
initializeConnection();
return new MongoDbProducer(this);
}
public Consumer createConsumer(Processor processor) throws Exception {
validateOptions('C');
// we never create the collection
createCollection = false;
initializeConnection();
// select right consumer type
if (consumerType == null) {
consumerType = MongoDbConsumerType.tailable;
}
Consumer consumer;
if (consumerType == MongoDbConsumerType.tailable) {
consumer = new MongoDbTailableCursorConsumer(this, processor);
} else {
throw new CamelMongoDbException("Consumer type not supported: " + consumerType);
}
configureConsumer(consumer);
return consumer;
}
/**
* Check if outputType is compatible with operation. DbCursor and DBObjectList applies to findAll. DBObject applies to others.
*/
private void validateOutputType() {
if (!ObjectHelper.isEmpty(outputType)) {
if (MongoDbOutputType.DBObjectList.equals(outputType) && !(MongoDbOperation.findAll.equals(operation))) {
throw new IllegalArgumentException("outputType DBObjectList is only compatible with operation findAll");
}
if (MongoDbOutputType.DBCursor.equals(outputType) && !(MongoDbOperation.findAll.equals(operation))) {
throw new IllegalArgumentException("outputType DBCursor is only compatible with operation findAll");
}
if (MongoDbOutputType.DBObject.equals(outputType) && (MongoDbOperation.findAll.equals(operation))) {
throw new IllegalArgumentException("outputType DBObject is not compatible with operation findAll");
}
}
}
private void validateOptions(char role) throws IllegalArgumentException {
// make our best effort to validate, options with defaults are checked against their defaults, which is not always a guarantee that
// they haven't been explicitly set, but it is enough
if (role == 'P') {
if (!ObjectHelper.isEmpty(consumerType) || persistentTailTracking || !ObjectHelper.isEmpty(tailTrackDb)
|| !ObjectHelper.isEmpty(tailTrackCollection) || !ObjectHelper.isEmpty(tailTrackField) || cursorRegenerationDelay != 1000L) {
throw new IllegalArgumentException("consumerType, tailTracking, cursorRegenerationDelay options cannot appear on a producer endpoint");
}
} else if (role == 'C') {
if (!ObjectHelper.isEmpty(operation) || !ObjectHelper.isEmpty(writeConcern) || writeConcernRef != null
|| dynamicity || outputType != null) {
throw new IllegalArgumentException("operation, writeConcern, writeConcernRef, dynamicity, outputType "
+ "options cannot appear on a consumer endpoint");
}
if (consumerType == MongoDbConsumerType.tailable) {
if (tailTrackIncreasingField == null) {
throw new IllegalArgumentException("tailTrackIncreasingField option must be set for tailable cursor MongoDB consumer endpoint");
}
if (persistentTailTracking && (ObjectHelper.isEmpty(persistentId))) {
throw new IllegalArgumentException("persistentId is compulsory for persistent tail tracking");
}
}
} else {
throw new IllegalArgumentException("Unknown endpoint role");
}
}
public boolean isSingleton() {
return true;
}
/**
* Initialises the MongoDB connection using the Mongo object provided to the endpoint
*
* @throws CamelMongoDbException
*/
public void initializeConnection() throws CamelMongoDbException {
LOG.info("Initialising MongoDb endpoint: {}", this.toString());
if (database == null || (collection == null && !(MongoDbOperation.getDbStats.equals(operation) || MongoDbOperation.command.equals(operation)))) {
throw new CamelMongoDbException("Missing required endpoint configuration: database and/or collection");
}
db = mongoConnection.getDB(database);
if (db == null) {
throw new CamelMongoDbException("Could not initialise MongoDbComponent. Database " + database + " does not exist.");
}
if (collection != null) {
if (!createCollection && !db.collectionExists(collection)) {
throw new CamelMongoDbException("Could not initialise MongoDbComponent. Collection " + collection + " and createCollection is false.");
}
dbCollection = db.getCollection(collection);
LOG.debug("MongoDb component initialised and endpoint bound to MongoDB collection with the following parameters. Address list: {}, Db: {}, Collection: {}",
new Object[]{mongoConnection.getAllAddress().toString(), db.getName(), dbCollection.getName()});
try {
if (ObjectHelper.isNotEmpty(collectionIndex)) {
ensureIndex(dbCollection, createIndex());
}
} catch (Exception e) {
throw new CamelMongoDbException("Error creating index", e);
}
}
}
/**
* Add Index
*
* @param collection
*/
public void ensureIndex(DBCollection collection, List<DBObject> dynamicIndex) {
if (dynamicIndex != null && !dynamicIndex.isEmpty()) {
for (DBObject index : dynamicIndex) {
LOG.debug("create BDObject Index {}", index);
collection.createIndex(index);
}
}
}
/**
* Create technical list index
*
* @return technical list index
*/
@SuppressWarnings("unchecked")
public List<DBObject> createIndex() throws Exception {
List<DBObject> indexList = new ArrayList<DBObject>();
if (ObjectHelper.isNotEmpty(collectionIndex)) {
HashMap<String, String> indexMap = new ObjectMapper().readValue(collectionIndex, HashMap.class);
for (Map.Entry<String, String> set : indexMap.entrySet()) {
DBObject index = new BasicDBObject();
// MongoDB 2.4 upwards is restrictive about the type of the 'single field index' being
// in use below (set.getValue())) as only an integer value type is accepted, otherwise
// server will throw an exception, see more details:
// http://docs.mongodb.org/manual/release-notes/2.4/#improved-validation-of-index-types
index.put(set.getKey(), set.getValue());
indexList.add(index);
}
}
return indexList;
}
/**
* Applies validation logic specific to this endpoint type. If everything succeeds, continues initialization
*/
@Override
protected void doStart() throws Exception {
if (writeConcern != null && writeConcernRef != null) {
String msg = "Cannot set both writeConcern and writeConcernRef at the same time. Respective values: " + writeConcern
+ ", " + writeConcernRef + ". Aborting initialization.";
throw new IllegalArgumentException(msg);
}
setWriteReadOptionsOnConnection();
super.doStart();
}
public Exchange createMongoDbExchange(DBObject dbObj) {
Exchange exchange = super.createExchange();
Message message = exchange.getIn();
message.setHeader(MongoDbConstants.DATABASE, database);
message.setHeader(MongoDbConstants.COLLECTION, collection);
message.setHeader(MongoDbConstants.FROM_TAILABLE, true);
message.setBody(dbObj);
return exchange;
}
private void setWriteReadOptionsOnConnection() {
// Set the WriteConcern
if (writeConcern != null) {
mongoConnection.setWriteConcern(writeConcern);
} else if (writeConcernRef != null) {
mongoConnection.setWriteConcern(writeConcernRef);
}
// Set the ReadPreference
if (readPreference != null) {
mongoConnection.setReadPreference(readPreference);
}
}
// ======= Getters and setters ===============================================
public String getConnectionBean() {
return connectionBean;
}
/**
* Name of {@link com.mongodb.Mongo} to use.
*/
public void setConnectionBean(String connectionBean) {
this.connectionBean = connectionBean;
}
/**
* Sets the name of the MongoDB collection to bind to this endpoint
*
* @param collection collection name
*/
public void setCollection(String collection) {
this.collection = collection;
}
public String getCollection() {
return collection;
}
/**
* Sets the collection index (JSON FORMAT : { "field1" : order1, "field2" : order2})
*/
public void setCollectionIndex(String collectionIndex) {
this.collectionIndex = collectionIndex;
}
public String getCollectionIndex() {
return collectionIndex;
}
/**
* Sets the operation this endpoint will execute against MongoDB. For possible values, see {@link MongoDbOperation}.
*
* @param operation name of the operation as per catalogued values
* @throws CamelMongoDbException
*/
public void setOperation(String operation) throws CamelMongoDbException {
try {
this.operation = MongoDbOperation.valueOf(operation);
} catch (IllegalArgumentException e) {
throw new CamelMongoDbException("Operation not supported", e);
}
}
public MongoDbOperation getOperation() {
return operation;
}
/**
* Sets the name of the MongoDB database to target
*
* @param database name of the MongoDB database
*/
public void setDatabase(String database) {
this.database = database;
}
public String getDatabase() {
return database;
}
/**
* Create collection during initialisation if it doesn't exist. Default is true.
*
* @param createCollection true or false
*/
public void setCreateCollection(boolean createCollection) {
this.createCollection = createCollection;
}
public boolean isCreateCollection() {
return createCollection;
}
public DB getDb() {
return db;
}
public DBCollection getDbCollection() {
return dbCollection;
}
/**
* Sets the Mongo instance that represents the backing connection
*
* @param mongoConnection the connection to the database
*/
public void setMongoConnection(Mongo mongoConnection) {
this.mongoConnection = mongoConnection;
}
public Mongo getMongoConnection() {
return mongoConnection;
}
/**
* Set the {@link WriteConcern} for write operations on MongoDB using the standard ones.
* Resolved from the fields of the WriteConcern class by calling the {@link WriteConcern#valueOf(String)} method.
*
* @param writeConcern the standard name of the WriteConcern
* @see <a href="http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html#valueOf(java.lang.String)">possible options</a>
*/
public void setWriteConcern(String writeConcern) {
this.writeConcern = WriteConcern.valueOf(writeConcern);
}
public WriteConcern getWriteConcern() {
return writeConcern;
}
/**
* Set the {@link WriteConcern} for write operations on MongoDB, passing in the bean ref to a custom WriteConcern which exists in the Registry.
* You can also use standard WriteConcerns by passing in their key. See the {@link #setWriteConcern(String) setWriteConcern} method.
*
* @param writeConcernRef the name of the bean in the registry that represents the WriteConcern to use
*/
public void setWriteConcernRef(String writeConcernRef) {
WriteConcern wc = this.getCamelContext().getRegistry().lookupByNameAndType(writeConcernRef, WriteConcern.class);
if (wc == null) {
String msg = "Camel MongoDB component could not find the WriteConcern in the Registry. Verify that the "
+ "provided bean name (" + writeConcernRef + ") is correct. Aborting initialization.";
throw new IllegalArgumentException(msg);
}
this.writeConcernRef = wc;
}
public WriteConcern getWriteConcernRef() {
return writeConcernRef;
}
/**
* Sets a MongoDB {@link ReadPreference} on the Mongo connection. Read preferences set directly on the connection will be
* overridden by this setting.
* <p/>
* The {@link com.mongodb.ReadPreference#valueOf(String)} utility method is used to resolve the passed {@code readPreference}
* value. Some examples for the possible values are {@code nearest}, {@code primary} or {@code secondary} etc.
*
* @param readPreference the name of the read preference to set
*/
public void setReadPreference(String readPreference) {
this.readPreference = ReadPreference.valueOf(readPreference);
}
public ReadPreference getReadPreference() {
return readPreference;
}
/**
* Sets whether this endpoint will attempt to dynamically resolve the target database and collection from the incoming Exchange properties.
* Can be used to override at runtime the database and collection specified on the otherwise static endpoint URI.
* It is disabled by default to boost performance. Enabling it will take a minimal performance hit.
*
* @see MongoDbConstants#DATABASE
* @see MongoDbConstants#COLLECTION
* @param dynamicity true or false indicated whether target database and collection should be calculated dynamically based on Exchange properties.
*/
public void setDynamicity(boolean dynamicity) {
this.dynamicity = dynamicity;
}
public boolean isDynamicity() {
return dynamicity;
}
/**
* Reserved for future use, when more consumer types are supported.
*
* @param consumerType key of the consumer type
* @throws CamelMongoDbException
*/
public void setConsumerType(String consumerType) throws CamelMongoDbException {
try {
this.consumerType = MongoDbConsumerType.valueOf(consumerType);
} catch (IllegalArgumentException e) {
throw new CamelMongoDbException("Consumer type not supported", e);
}
}
public MongoDbConsumerType getConsumerType() {
return consumerType;
}
public String getTailTrackDb() {
return tailTrackDb;
}
/**
* Indicates what database the tail tracking mechanism will persist to. If not specified, the current database will
* be picked by default. Dynamicity will not be taken into account even if enabled, i.e. the tail tracking database
* will not vary past endpoint initialisation.
*
* @param tailTrackDb database name
*/
public void setTailTrackDb(String tailTrackDb) {
this.tailTrackDb = tailTrackDb;
}
public String getTailTrackCollection() {
return tailTrackCollection;
}
/**
* Collection where tail tracking information will be persisted. If not specified, {@link MongoDbTailTrackingConfig#DEFAULT_COLLECTION}
* will be used by default.
*
* @param tailTrackCollection collection name
*/
public void setTailTrackCollection(String tailTrackCollection) {
this.tailTrackCollection = tailTrackCollection;
}
public String getTailTrackField() {
return tailTrackField;
}
/**
* Field where the last tracked value will be placed. If not specified, {@link MongoDbTailTrackingConfig#DEFAULT_FIELD}
* will be used by default.
*
* @param tailTrackField field name
*/
public void setTailTrackField(String tailTrackField) {
this.tailTrackField = tailTrackField;
}
/**
* Enable persistent tail tracking, which is a mechanism to keep track of the last consumed message across system restarts.
* The next time the system is up, the endpoint will recover the cursor from the point where it last stopped slurping records.
*
* @param persistentTailTracking true or false
*/
public void setPersistentTailTracking(boolean persistentTailTracking) {
this.persistentTailTracking = persistentTailTracking;
}
public boolean isPersistentTailTracking() {
return persistentTailTracking;
}
/**
* Correlation field in the incoming record which is of increasing nature and will be used to position the tailing cursor every
* time it is generated.
* The cursor will be (re)created with a query of type: tailTrackIncreasingField > lastValue (possibly recovered from persistent
* tail tracking).
* Can be of type Integer, Date, String, etc.
* NOTE: No support for dot notation at the current time, so the field should be at the top level of the document.
*
* @param tailTrackIncreasingField
*/
public void setTailTrackIncreasingField(String tailTrackIncreasingField) {
this.tailTrackIncreasingField = tailTrackIncreasingField;
}
public String getTailTrackIncreasingField() {
return tailTrackIncreasingField;
}
public MongoDbTailTrackingConfig getTailTrackingConfig() {
if (tailTrackingConfig == null) {
tailTrackingConfig = new MongoDbTailTrackingConfig(persistentTailTracking, tailTrackIncreasingField, tailTrackDb == null ? database : tailTrackDb, tailTrackCollection,
tailTrackField, getPersistentId());
}
return tailTrackingConfig;
}
/**
* MongoDB tailable cursors will block until new data arrives. If no new data is inserted, after some time the cursor will be automatically
* freed and closed by the MongoDB server. The client is expected to regenerate the cursor if needed. This value specifies the time to wait
* before attempting to fetch a new cursor, and if the attempt fails, how long before the next attempt is made. Default value is 1000ms.
*
* @param cursorRegenerationDelay delay specified in milliseconds
*/
public void setCursorRegenerationDelay(long cursorRegenerationDelay) {
this.cursorRegenerationDelay = cursorRegenerationDelay;
}
public long getCursorRegenerationDelay() {
return cursorRegenerationDelay;
}
/**
* One tail tracking collection can host many trackers for several tailable consumers.
* To keep them separate, each tracker should have its own unique persistentId.
*
* @param persistentId the value of the persistent ID to use for this tailable consumer
*/
public void setPersistentId(String persistentId) {
this.persistentId = persistentId;
}
public String getPersistentId() {
return persistentId;
}
public boolean isWriteResultAsHeader() {
return writeResultAsHeader;
}
/**
* In write operations, it determines whether instead of returning {@link WriteResult} as the body of the OUT
* message, we transfer the IN message to the OUT and attach the WriteResult as a header.
*
* @param writeResultAsHeader flag to indicate if this option is enabled
*/
public void setWriteResultAsHeader(boolean writeResultAsHeader) {
this.writeResultAsHeader = writeResultAsHeader;
}
public MongoDbOutputType getOutputType() {
return outputType;
}
/**
* Convert the output of the producer to the selected type : "DBObjectList", "DBObject" or "DBCursor".
* DBObjectList or DBObject applies to findAll.
* DBCursor applies to all other operations.
* @param outputType
*/
public void setOutputType(MongoDbOutputType outputType) {
this.outputType = outputType;
}
}
| components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java | /**
* 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.camel.component.mongodb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.impl.DefaultMessage;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@UriEndpoint(scheme = "mongodb", title = "MongoDB", syntax = "mongodb:connectionBean", consumerClass = MongoDbTailableCursorConsumer.class, label = "database,nosql")
public class MongoDbEndpoint extends DefaultEndpoint {
private static final Logger LOG = LoggerFactory.getLogger(MongoDbEndpoint.class);
private Mongo mongoConnection;
@UriPath @Metadata(required = "true")
private String connectionBean;
@UriParam
private String database;
@UriParam
private String collection;
@UriParam
private String collectionIndex;
@UriParam
private MongoDbOperation operation;
@UriParam(defaultValue = "true")
private boolean createCollection = true;
@UriParam
private WriteConcern writeConcern;
private WriteConcern writeConcernRef;
@UriParam
private ReadPreference readPreference;
@UriParam
private boolean dynamicity;
@UriParam
private boolean writeResultAsHeader;
// tailable cursor consumer by default
private MongoDbConsumerType consumerType;
@UriParam(defaultValue = "1000")
private long cursorRegenerationDelay = 1000L;
@UriParam
private String tailTrackIncreasingField;
// persitent tail tracking
@UriParam
private boolean persistentTailTracking;
@UriParam
private String persistentId;
@UriParam
private String tailTrackDb;
@UriParam
private String tailTrackCollection;
@UriParam
private String tailTrackField;
private MongoDbTailTrackingConfig tailTrackingConfig;
@UriParam
private MongoDbOutputType outputType;
private DBCollection dbCollection;
private DB db;
// ======= Constructors ===============================================
public MongoDbEndpoint() {
}
public MongoDbEndpoint(String uri, MongoDbComponent component) {
super(uri, component);
}
@SuppressWarnings("deprecation")
public MongoDbEndpoint(String endpointUri) {
super(endpointUri);
}
// ======= Implementation methods =====================================
public Producer createProducer() throws Exception {
validateOptions('P');
initializeConnection();
return new MongoDbProducer(this);
}
public Consumer createConsumer(Processor processor) throws Exception {
validateOptions('C');
// we never create the collection
createCollection = false;
initializeConnection();
// select right consumer type
if (consumerType == null) {
consumerType = MongoDbConsumerType.tailable;
}
Consumer consumer;
if (consumerType == MongoDbConsumerType.tailable) {
consumer = new MongoDbTailableCursorConsumer(this, processor);
} else {
throw new CamelMongoDbException("Consumer type not supported: " + consumerType);
}
configureConsumer(consumer);
return consumer;
}
/**
* Check if outputType is compatible with operation. DbCursor and DBObjectList applies to findAll. DBObject applies to others.
*/
private void validateOutputType() {
if (!ObjectHelper.isEmpty(outputType)) {
if (MongoDbOutputType.DBObjectList.equals(outputType) && !(MongoDbOperation.findAll.equals(operation))) {
throw new IllegalArgumentException("outputType DBObjectList is only compatible with operation findAll");
}
if (MongoDbOutputType.DBCursor.equals(outputType) && !(MongoDbOperation.findAll.equals(operation))) {
throw new IllegalArgumentException("outputType DBCursor is only compatible with operation findAll");
}
if (MongoDbOutputType.DBObject.equals(outputType) && (MongoDbOperation.findAll.equals(operation))) {
throw new IllegalArgumentException("outputType DBObject is not compatible with operation findAll");
}
}
}
private void validateOptions(char role) throws IllegalArgumentException {
// make our best effort to validate, options with defaults are checked against their defaults, which is not always a guarantee that
// they haven't been explicitly set, but it is enough
if (role == 'P') {
if (!ObjectHelper.isEmpty(consumerType) || persistentTailTracking || !ObjectHelper.isEmpty(tailTrackDb)
|| !ObjectHelper.isEmpty(tailTrackCollection) || !ObjectHelper.isEmpty(tailTrackField) || cursorRegenerationDelay != 1000L) {
throw new IllegalArgumentException("consumerType, tailTracking, cursorRegenerationDelay options cannot appear on a producer endpoint");
}
} else if (role == 'C') {
if (!ObjectHelper.isEmpty(operation) || !ObjectHelper.isEmpty(writeConcern) || writeConcernRef != null
|| dynamicity || outputType != null) {
throw new IllegalArgumentException("operation, writeConcern, writeConcernRef, dynamicity, outputType "
+ "options cannot appear on a consumer endpoint");
}
if (consumerType == MongoDbConsumerType.tailable) {
if (tailTrackIncreasingField == null) {
throw new IllegalArgumentException("tailTrackIncreasingField option must be set for tailable cursor MongoDB consumer endpoint");
}
if (persistentTailTracking && (ObjectHelper.isEmpty(persistentId))) {
throw new IllegalArgumentException("persistentId is compulsory for persistent tail tracking");
}
}
} else {
throw new IllegalArgumentException("Unknown endpoint role");
}
}
public boolean isSingleton() {
return true;
}
/**
* Initialises the MongoDB connection using the Mongo object provided to the endpoint
*
* @throws CamelMongoDbException
*/
public void initializeConnection() throws CamelMongoDbException {
LOG.info("Initialising MongoDb endpoint: {}", this.toString());
if (database == null || (collection == null && !(MongoDbOperation.getDbStats.equals(operation) || MongoDbOperation.command.equals(operation)))) {
throw new CamelMongoDbException("Missing required endpoint configuration: database and/or collection");
}
db = mongoConnection.getDB(database);
if (db == null) {
throw new CamelMongoDbException("Could not initialise MongoDbComponent. Database " + database + " does not exist.");
}
if (collection != null) {
if (!createCollection && !db.collectionExists(collection)) {
throw new CamelMongoDbException("Could not initialise MongoDbComponent. Collection " + collection + " and createCollection is false.");
}
dbCollection = db.getCollection(collection);
LOG.debug("MongoDb component initialised and endpoint bound to MongoDB collection with the following parameters. Address list: {}, Db: {}, Collection: {}",
new Object[]{mongoConnection.getAllAddress().toString(), db.getName(), dbCollection.getName()});
try {
if (ObjectHelper.isNotEmpty(collectionIndex)) {
ensureIndex(dbCollection, createIndex());
}
} catch (Exception e) {
throw new CamelMongoDbException("Error creating index", e);
}
}
}
/**
* Add Index
*
* @param collection
*/
public void ensureIndex(DBCollection collection, List<DBObject> dynamicIndex) {
if (dynamicIndex != null && !dynamicIndex.isEmpty()) {
for (DBObject index : dynamicIndex) {
LOG.debug("create BDObject Index {}", index);
collection.createIndex(index);
}
}
}
/**
* Create technical list index
*
* @return technical list index
*/
@SuppressWarnings("unchecked")
public List<DBObject> createIndex() throws Exception {
List<DBObject> indexList = new ArrayList<DBObject>();
if (ObjectHelper.isNotEmpty(collectionIndex)) {
HashMap<String, String> indexMap = new ObjectMapper().readValue(collectionIndex, HashMap.class);
for (Map.Entry<String, String> set : indexMap.entrySet()) {
DBObject index = new BasicDBObject();
// MongoDB 2.4 upwards is restrictive about the type of the 'single field index' being
// in use below (set.getValue())) as only an integer value type is accepted, otherwise
// server will throw an exception, see more details:
// http://docs.mongodb.org/manual/release-notes/2.4/#improved-validation-of-index-types
index.put(set.getKey(), set.getValue());
indexList.add(index);
}
}
return indexList;
}
/**
* Applies validation logic specific to this endpoint type. If everything succeeds, continues initialization
*/
@Override
protected void doStart() throws Exception {
if (writeConcern != null && writeConcernRef != null) {
String msg = "Cannot set both writeConcern and writeConcernRef at the same time. Respective values: " + writeConcern
+ ", " + writeConcernRef + ". Aborting initialization.";
throw new IllegalArgumentException(msg);
}
setWriteReadOptionsOnConnection();
super.doStart();
}
public Exchange createMongoDbExchange(DBObject dbObj) {
Exchange exchange = super.createExchange();
Message message = new DefaultMessage();
message.setHeader(MongoDbConstants.DATABASE, database);
message.setHeader(MongoDbConstants.COLLECTION, collection);
message.setHeader(MongoDbConstants.FROM_TAILABLE, true);
message.setBody(dbObj);
exchange.setIn(message);
return exchange;
}
private void setWriteReadOptionsOnConnection() {
// Set the WriteConcern
if (writeConcern != null) {
mongoConnection.setWriteConcern(writeConcern);
} else if (writeConcernRef != null) {
mongoConnection.setWriteConcern(writeConcernRef);
}
// Set the ReadPreference
if (readPreference != null) {
mongoConnection.setReadPreference(readPreference);
}
}
// ======= Getters and setters ===============================================
public String getConnectionBean() {
return connectionBean;
}
/**
* Name of {@link com.mongodb.Mongo} to use.
*/
public void setConnectionBean(String connectionBean) {
this.connectionBean = connectionBean;
}
/**
* Sets the name of the MongoDB collection to bind to this endpoint
*
* @param collection collection name
*/
public void setCollection(String collection) {
this.collection = collection;
}
public String getCollection() {
return collection;
}
/**
* Sets the collection index (JSON FORMAT : { "field1" : order1, "field2" : order2})
*/
public void setCollectionIndex(String collectionIndex) {
this.collectionIndex = collectionIndex;
}
public String getCollectionIndex() {
return collectionIndex;
}
/**
* Sets the operation this endpoint will execute against MongoDB. For possible values, see {@link MongoDbOperation}.
*
* @param operation name of the operation as per catalogued values
* @throws CamelMongoDbException
*/
public void setOperation(String operation) throws CamelMongoDbException {
try {
this.operation = MongoDbOperation.valueOf(operation);
} catch (IllegalArgumentException e) {
throw new CamelMongoDbException("Operation not supported", e);
}
}
public MongoDbOperation getOperation() {
return operation;
}
/**
* Sets the name of the MongoDB database to target
*
* @param database name of the MongoDB database
*/
public void setDatabase(String database) {
this.database = database;
}
public String getDatabase() {
return database;
}
/**
* Create collection during initialisation if it doesn't exist. Default is true.
*
* @param createCollection true or false
*/
public void setCreateCollection(boolean createCollection) {
this.createCollection = createCollection;
}
public boolean isCreateCollection() {
return createCollection;
}
public DB getDb() {
return db;
}
public DBCollection getDbCollection() {
return dbCollection;
}
/**
* Sets the Mongo instance that represents the backing connection
*
* @param mongoConnection the connection to the database
*/
public void setMongoConnection(Mongo mongoConnection) {
this.mongoConnection = mongoConnection;
}
public Mongo getMongoConnection() {
return mongoConnection;
}
/**
* Set the {@link WriteConcern} for write operations on MongoDB using the standard ones.
* Resolved from the fields of the WriteConcern class by calling the {@link WriteConcern#valueOf(String)} method.
*
* @param writeConcern the standard name of the WriteConcern
* @see <a href="http://api.mongodb.org/java/current/com/mongodb/WriteConcern.html#valueOf(java.lang.String)">possible options</a>
*/
public void setWriteConcern(String writeConcern) {
this.writeConcern = WriteConcern.valueOf(writeConcern);
}
public WriteConcern getWriteConcern() {
return writeConcern;
}
/**
* Set the {@link WriteConcern} for write operations on MongoDB, passing in the bean ref to a custom WriteConcern which exists in the Registry.
* You can also use standard WriteConcerns by passing in their key. See the {@link #setWriteConcern(String) setWriteConcern} method.
*
* @param writeConcernRef the name of the bean in the registry that represents the WriteConcern to use
*/
public void setWriteConcernRef(String writeConcernRef) {
WriteConcern wc = this.getCamelContext().getRegistry().lookupByNameAndType(writeConcernRef, WriteConcern.class);
if (wc == null) {
String msg = "Camel MongoDB component could not find the WriteConcern in the Registry. Verify that the "
+ "provided bean name (" + writeConcernRef + ") is correct. Aborting initialization.";
throw new IllegalArgumentException(msg);
}
this.writeConcernRef = wc;
}
public WriteConcern getWriteConcernRef() {
return writeConcernRef;
}
/**
* Sets a MongoDB {@link ReadPreference} on the Mongo connection. Read preferences set directly on the connection will be
* overridden by this setting.
* <p/>
* The {@link com.mongodb.ReadPreference#valueOf(String)} utility method is used to resolve the passed {@code readPreference}
* value. Some examples for the possible values are {@code nearest}, {@code primary} or {@code secondary} etc.
*
* @param readPreference the name of the read preference to set
*/
public void setReadPreference(String readPreference) {
this.readPreference = ReadPreference.valueOf(readPreference);
}
public ReadPreference getReadPreference() {
return readPreference;
}
/**
* Sets whether this endpoint will attempt to dynamically resolve the target database and collection from the incoming Exchange properties.
* Can be used to override at runtime the database and collection specified on the otherwise static endpoint URI.
* It is disabled by default to boost performance. Enabling it will take a minimal performance hit.
*
* @see MongoDbConstants#DATABASE
* @see MongoDbConstants#COLLECTION
* @param dynamicity true or false indicated whether target database and collection should be calculated dynamically based on Exchange properties.
*/
public void setDynamicity(boolean dynamicity) {
this.dynamicity = dynamicity;
}
public boolean isDynamicity() {
return dynamicity;
}
/**
* Reserved for future use, when more consumer types are supported.
*
* @param consumerType key of the consumer type
* @throws CamelMongoDbException
*/
public void setConsumerType(String consumerType) throws CamelMongoDbException {
try {
this.consumerType = MongoDbConsumerType.valueOf(consumerType);
} catch (IllegalArgumentException e) {
throw new CamelMongoDbException("Consumer type not supported", e);
}
}
public MongoDbConsumerType getConsumerType() {
return consumerType;
}
public String getTailTrackDb() {
return tailTrackDb;
}
/**
* Indicates what database the tail tracking mechanism will persist to. If not specified, the current database will
* be picked by default. Dynamicity will not be taken into account even if enabled, i.e. the tail tracking database
* will not vary past endpoint initialisation.
*
* @param tailTrackDb database name
*/
public void setTailTrackDb(String tailTrackDb) {
this.tailTrackDb = tailTrackDb;
}
public String getTailTrackCollection() {
return tailTrackCollection;
}
/**
* Collection where tail tracking information will be persisted. If not specified, {@link MongoDbTailTrackingConfig#DEFAULT_COLLECTION}
* will be used by default.
*
* @param tailTrackCollection collection name
*/
public void setTailTrackCollection(String tailTrackCollection) {
this.tailTrackCollection = tailTrackCollection;
}
public String getTailTrackField() {
return tailTrackField;
}
/**
* Field where the last tracked value will be placed. If not specified, {@link MongoDbTailTrackingConfig#DEFAULT_FIELD}
* will be used by default.
*
* @param tailTrackField field name
*/
public void setTailTrackField(String tailTrackField) {
this.tailTrackField = tailTrackField;
}
/**
* Enable persistent tail tracking, which is a mechanism to keep track of the last consumed message across system restarts.
* The next time the system is up, the endpoint will recover the cursor from the point where it last stopped slurping records.
*
* @param persistentTailTracking true or false
*/
public void setPersistentTailTracking(boolean persistentTailTracking) {
this.persistentTailTracking = persistentTailTracking;
}
public boolean isPersistentTailTracking() {
return persistentTailTracking;
}
/**
* Correlation field in the incoming record which is of increasing nature and will be used to position the tailing cursor every
* time it is generated.
* The cursor will be (re)created with a query of type: tailTrackIncreasingField > lastValue (possibly recovered from persistent
* tail tracking).
* Can be of type Integer, Date, String, etc.
* NOTE: No support for dot notation at the current time, so the field should be at the top level of the document.
*
* @param tailTrackIncreasingField
*/
public void setTailTrackIncreasingField(String tailTrackIncreasingField) {
this.tailTrackIncreasingField = tailTrackIncreasingField;
}
public String getTailTrackIncreasingField() {
return tailTrackIncreasingField;
}
public MongoDbTailTrackingConfig getTailTrackingConfig() {
if (tailTrackingConfig == null) {
tailTrackingConfig = new MongoDbTailTrackingConfig(persistentTailTracking, tailTrackIncreasingField, tailTrackDb == null ? database : tailTrackDb, tailTrackCollection,
tailTrackField, getPersistentId());
}
return tailTrackingConfig;
}
/**
* MongoDB tailable cursors will block until new data arrives. If no new data is inserted, after some time the cursor will be automatically
* freed and closed by the MongoDB server. The client is expected to regenerate the cursor if needed. This value specifies the time to wait
* before attempting to fetch a new cursor, and if the attempt fails, how long before the next attempt is made. Default value is 1000ms.
*
* @param cursorRegenerationDelay delay specified in milliseconds
*/
public void setCursorRegenerationDelay(long cursorRegenerationDelay) {
this.cursorRegenerationDelay = cursorRegenerationDelay;
}
public long getCursorRegenerationDelay() {
return cursorRegenerationDelay;
}
/**
* One tail tracking collection can host many trackers for several tailable consumers.
* To keep them separate, each tracker should have its own unique persistentId.
*
* @param persistentId the value of the persistent ID to use for this tailable consumer
*/
public void setPersistentId(String persistentId) {
this.persistentId = persistentId;
}
public String getPersistentId() {
return persistentId;
}
public boolean isWriteResultAsHeader() {
return writeResultAsHeader;
}
/**
* In write operations, it determines whether instead of returning {@link WriteResult} as the body of the OUT
* message, we transfer the IN message to the OUT and attach the WriteResult as a header.
*
* @param writeResultAsHeader flag to indicate if this option is enabled
*/
public void setWriteResultAsHeader(boolean writeResultAsHeader) {
this.writeResultAsHeader = writeResultAsHeader;
}
public MongoDbOutputType getOutputType() {
return outputType;
}
/**
* Convert the output of the producer to the selected type : "DBObjectList", "DBObject" or "DBCursor".
* DBObjectList or DBObject applies to findAll.
* DBCursor applies to all other operations.
* @param outputType
*/
public void setOutputType(MongoDbOutputType outputType) {
this.outputType = outputType;
}
}
| Fixes #591. Polished
| components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java | Fixes #591. Polished | <ide><path>omponents/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
<ide>
<ide> public Exchange createMongoDbExchange(DBObject dbObj) {
<ide> Exchange exchange = super.createExchange();
<del> Message message = new DefaultMessage();
<add> Message message = exchange.getIn();
<ide> message.setHeader(MongoDbConstants.DATABASE, database);
<ide> message.setHeader(MongoDbConstants.COLLECTION, collection);
<ide> message.setHeader(MongoDbConstants.FROM_TAILABLE, true);
<ide> message.setBody(dbObj);
<del> exchange.setIn(message);
<ide> return exchange;
<ide> }
<ide> |
|
Java | apache-2.0 | 256edab86b77b3e88215bca7940cfb96f5233399 | 0 | aspectran/aspectran,aspectran/aspectran | /*
* Copyright (c) 2008-2019 The Aspectran 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.aspectran.web.support.view;
import com.aspectran.core.activity.Activity;
import com.aspectran.core.activity.process.result.ProcessResult;
import com.aspectran.core.activity.response.dispatch.DispatchResponse;
import com.aspectran.core.activity.response.dispatch.ViewDispatcher;
import com.aspectran.core.activity.response.dispatch.ViewDispatcherException;
import com.aspectran.core.adapter.RequestAdapter;
import com.aspectran.core.adapter.ResponseAdapter;
import com.aspectran.core.context.rule.DispatchRule;
import com.aspectran.core.util.ToStringBuilder;
import com.aspectran.core.util.logging.Log;
import com.aspectran.core.util.logging.LogFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
/**
* JSP or other web resource integration.
* Sends the model produced by Aspectran's internal activity
* to the JSP to render the final view page.
*
* <p>Created: 2019. 02. 18</p>
*/
public class JspTemplateViewDispatcher implements ViewDispatcher {
private static final Log log = LogFactory.getLog(JspTemplateViewDispatcher.class);
private static final String DEFAULT_CONTENT_TYPE = "text/html;charset=ISO-8859-1";
private String contentType;
private String template;
private String includePageKey;
@Override
public String getContentType() {
return (contentType != null ? contentType : "text/html");
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public void setTemplate(String template) {
this.template = template;
}
public void setIncludePageKey(String includePageKey) {
this.includePageKey = includePageKey;
}
@Override
public void dispatch(Activity activity, DispatchRule dispatchRule)
throws ViewDispatcherException {
try {
if (template == null) {
throw new IllegalArgumentException("No specified template page");
}
if (includePageKey == null) {
throw new IllegalArgumentException("No attribute name to specify the include page name");
}
String dispatchName = dispatchRule.getName(activity);
if (dispatchName == null) {
throw new IllegalArgumentException("No specified dispatch name");
}
RequestAdapter requestAdapter = activity.getRequestAdapter();
ResponseAdapter responseAdapter = activity.getResponseAdapter();
requestAdapter.setAttribute(includePageKey, dispatchName);
String contentType = dispatchRule.getContentType();
if (contentType != null) {
responseAdapter.setContentType(contentType);
} else {
responseAdapter.setContentType(DEFAULT_CONTENT_TYPE);
}
String encoding = dispatchRule.getEncoding();
if (encoding != null) {
responseAdapter.setEncoding(encoding);
} else {
encoding = activity.getTranslet().getResponseEncoding();
if (encoding != null) {
responseAdapter.setEncoding(encoding);
}
}
ProcessResult processResult = activity.getProcessResult();
DispatchResponse.fetchAttributes(requestAdapter, processResult);
HttpServletRequest request = requestAdapter.getAdaptee();
HttpServletResponse response = responseAdapter.getAdaptee();
if (log.isDebugEnabled()) {
log.debug("Dispatching to JSP Template [" + template + "] with page [" + dispatchName + "]");
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher(template);
requestDispatcher.forward(request, response);
if (response.getStatus() == 404) {
throw new FileNotFoundException("Failed to find resource '" + template + "'");
}
} catch (Exception e) {
throw new ViewDispatcherException("Failed to dispatch to JSP " +
dispatchRule.toString(this, template), e);
}
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public String toString() {
ToStringBuilder tsb = new ToStringBuilder();
tsb.append("name", super.toString());
tsb.append("defaultContentType", contentType);
tsb.append("template", template);
tsb.append("includePageKey", includePageKey);
return tsb.toString();
}
}
| web/src/main/java/com/aspectran/web/support/view/JspTemplateViewDispatcher.java | /*
* Copyright (c) 2008-2019 The Aspectran 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.aspectran.web.support.view;
import com.aspectran.core.activity.Activity;
import com.aspectran.core.activity.process.result.ProcessResult;
import com.aspectran.core.activity.response.dispatch.DispatchResponse;
import com.aspectran.core.activity.response.dispatch.ViewDispatcher;
import com.aspectran.core.activity.response.dispatch.ViewDispatcherException;
import com.aspectran.core.adapter.RequestAdapter;
import com.aspectran.core.adapter.ResponseAdapter;
import com.aspectran.core.context.rule.DispatchRule;
import com.aspectran.core.util.ToStringBuilder;
import com.aspectran.core.util.logging.Log;
import com.aspectran.core.util.logging.LogFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
/**
* JSP or other web resource integration.
* Sends the model produced by Aspectran's internal activity
* to the JSP to render the final view page.
*
* <p>Created: 2008. 03. 22 PM 5:51:58</p>
*/
public class JspTemplateViewDispatcher implements ViewDispatcher {
private static final Log log = LogFactory.getLog(JspTemplateViewDispatcher.class);
private static final String DEFAULT_CONTENT_TYPE = "text/html;charset=ISO-8859-1";
private String contentType;
private String template;
private String includePageKey;
@Override
public String getContentType() {
return (contentType != null ? contentType : "text/html");
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public void setTemplate(String template) {
this.template = template;
}
public void setIncludePageKey(String includePageKey) {
this.includePageKey = includePageKey;
}
@Override
public void dispatch(Activity activity, DispatchRule dispatchRule)
throws ViewDispatcherException {
try {
if (template == null) {
throw new IllegalArgumentException("No specified template page");
}
if (includePageKey == null) {
throw new IllegalArgumentException("No attribute name to specify the include page name");
}
String dispatchName = dispatchRule.getName(activity);
if (dispatchName == null) {
throw new IllegalArgumentException("No specified dispatch name");
}
RequestAdapter requestAdapter = activity.getRequestAdapter();
ResponseAdapter responseAdapter = activity.getResponseAdapter();
requestAdapter.setAttribute(includePageKey, dispatchName);
String contentType = dispatchRule.getContentType();
if (contentType != null) {
responseAdapter.setContentType(contentType);
} else {
responseAdapter.setContentType(DEFAULT_CONTENT_TYPE);
}
String encoding = dispatchRule.getEncoding();
if (encoding != null) {
responseAdapter.setEncoding(encoding);
} else {
encoding = activity.getTranslet().getResponseEncoding();
if (encoding != null) {
responseAdapter.setEncoding(encoding);
}
}
ProcessResult processResult = activity.getProcessResult();
DispatchResponse.fetchAttributes(requestAdapter, processResult);
HttpServletRequest request = requestAdapter.getAdaptee();
HttpServletResponse response = responseAdapter.getAdaptee();
if (log.isDebugEnabled()) {
log.debug("Dispatching to JSP Template [" + template + "] with page [" + dispatchName + "]");
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher(template);
requestDispatcher.forward(request, response);
if (response.getStatus() == 404) {
throw new FileNotFoundException("Failed to find resource '" + template + "'");
}
} catch (Exception e) {
throw new ViewDispatcherException("Failed to dispatch to JSP " +
dispatchRule.toString(this, template), e);
}
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public String toString() {
ToStringBuilder tsb = new ToStringBuilder();
tsb.append("name", super.toString());
tsb.append("defaultContentType", contentType);
tsb.append("template", template);
tsb.append("pageKey", includePageKey);
return tsb.toString();
}
}
| Polishing
| web/src/main/java/com/aspectran/web/support/view/JspTemplateViewDispatcher.java | Polishing | <ide><path>eb/src/main/java/com/aspectran/web/support/view/JspTemplateViewDispatcher.java
<ide> * Sends the model produced by Aspectran's internal activity
<ide> * to the JSP to render the final view page.
<ide> *
<del> * <p>Created: 2008. 03. 22 PM 5:51:58</p>
<add> * <p>Created: 2019. 02. 18</p>
<ide> */
<ide> public class JspTemplateViewDispatcher implements ViewDispatcher {
<ide>
<ide> tsb.append("name", super.toString());
<ide> tsb.append("defaultContentType", contentType);
<ide> tsb.append("template", template);
<del> tsb.append("pageKey", includePageKey);
<add> tsb.append("includePageKey", includePageKey);
<ide> return tsb.toString();
<ide> }
<ide> |
|
JavaScript | mpl-2.0 | 80cff1c7eb3aaa133da430d61a4d3ac7e84f8707 | 0 | Croydon/vertical-tabs-reloaded,Croydon/vertical-tabs-reloaded | /*
* Functionality for grouping tabs.
*
* Groups are implemented as a special kind of tab (see binding in
* group.xml). There are a few advantages and disadvantages to this:
*
* - Groups can be regular children of tabbrowser.tabContainer
* (cf. https://bugzilla.mozilla.org/show_bug.cgi?id=475142).
*
* - The nsISessionStore service takes care of restoring groups and
* their properties.
*
* - But we have to make sure that groups don't behave like tabs at
* all.
*/
const EXPORTED_SYMBOLS = ["VTGroups"];
Components.utils.import("resource://verticaltabs/tabdatastore.js");
const TAB_DROP_TYPE = "application/x-moz-tabbrowser-tab";
function VTGroups(tabs) {
this.tabs = tabs;
tabs.VTGroups = this;
// Restore group and in-group status
tabs.addEventListener('SSTabRestoring', this, true);
// Updating UI
tabs.addEventListener('TabSelect', this, false);
// For clicks on the twisty
tabs.addEventListener('click', this, true);
// For synchronizing group behaviour and tab positioning
tabs.addEventListener('dragover', this, false);
tabs.addEventListener('dragenter', this, false);
tabs.addEventListener('dragleave', this, false);
tabs.addEventListener('dragend', this, false);
tabs.addEventListener('drop', this, false);
tabs.addEventListener('TabMove', this, false);
tabs.addEventListener('TabClose', this, false);
}
VTGroups.prototype = {
kId: 'verticaltabs-id',
kGroup: 'verticaltabs-group',
kInGroup: 'verticaltabs-ingroup',
kLabel: 'verticaltabs-grouplabel',
kCollapsed: 'verticaltabs-collapsed',
kDropTarget: 'verticaltabs-droptarget',
kDropInGroup: 'verticaltabs-dropingroup',
kDropToNewGroup: 'verticaltabs-droptonewgroup',
kIgnoreMove: 'verticaltabs-ignoremove',
/*** Public API ***/
/*
* Create a new group tab. If given as an argument, the label is
* applied to the group. Otherwise the label will be made
* editable.
*/
addGroup: function(aLabel) {
let group = this.tabs.tabbrowser.addTab();
VTTabDataStore.setTabValue(group, this.kGroup, "true");
let window = this.tabs.ownerDocument.defaultView;
function makeLabelEditable() {
// XBL bindings aren't applied synchronously.
if (typeof group.editLabel !== "function") {
window.setTimeout(makeLabelEditable, 10);
return;
}
group.editLabel();
}
if (aLabel) {
VTTabDataStore.setTabValue(group, this.kLabel, aLabel);
group.groupLabel = aLabel;
} else {
makeLabelEditable();
}
return group;
},
/*
* Return the child tabs of a given group. The return value is a
* JavaScript Array (not just a NodeList) and is "owned" by the
* caller (e.g. it may be modified).
*/
getChildren: function(aGroup) {
let groupId = this.tabs.VTTabIDs.id(aGroup);
let children = this.tabs.getElementsByAttribute(this.kInGroup, groupId);
// Return a copy
return Array.prototype.slice.call(children);
},
_updateCount: function(aGroup) {
let count = this.getChildren(aGroup).length;
function update() {
if (!aGroup.mCounter) {
let window = aGroup.ownerDocument.defaultView;
window.setTimeout(update, 10);
return;
}
aGroup.mCounter.firstChild.nodeValue = "" + count;
}
update();
},
/*
* Add a tab to a group. This won't physically move the tab
* anywhere, just create the logical connection.
*/
addChild: function(aGroup, aTab) {
// Only groups can have children
if (!this.isGroup(aGroup)) {
return;
}
// We don't allow nested groups
if (this.isGroup(aTab)) {
return;
}
// Assign a group to the tab. If the tab was in another group
// before, this will simply overwrite the old value.
let groupId = this.tabs.VTTabIDs.id(aGroup);
VTTabDataStore.setTabValue(aTab, this.kInGroup, groupId);
this._updateCount(aGroup);
// Apply the group's collapsed state to the tab
let collapsed = (VTTabDataStore.getTabValue(aGroup, this.kCollapsed)
== "true");
this._tabCollapseExpand(aTab, collapsed);
},
addChildren: function(aGroup, aTabs) {
for each (let tab in aTabs) {
this.addChild(aGroup, tab);
}
},
/*
* Remove a tab from its group.
*/
removeChild: function(aTab) {
let groupId = VTTabDataStore.getTabValue(aTab, this.kInGroup);
if (!groupId) {
return;
}
VTTabDataStore.deleteTabValue(aTab, this.kInGroup);
this._updateCount(aGroup);
},
removeChildren: function(aTabs) {
for each (let tab in aTabs) {
this.removeChild(tab);
}
},
/*
* Creates a tab from the active selection.
*/
createGroupFromMultiSelect: function() {
let group = this.addGroup();
let children = this.tabs.VTMultiSelect.getSelected();
for each (let tab in children) {
// Moving the tabs to the right position is enough, the
// TabMove handler knows the right thing to do.
this.tabs.tabbrowser.moveTabTo(tab, group._tPos+1);
}
this.tabs.VTMultiSelect.clear();
},
/*
* Return true if a given tab is a group tab.
*/
isGroup: function(aTab) {
return (VTTabDataStore.getTabValue(aTab, this.kGroup) == "true");
},
/*
* Toggle collapsed/expanded state of a group tab.
*/
collapseExpand: function(aGroup) {
if (!this.isGroup(aGroup)) {
return;
}
let collapsed = (VTTabDataStore.getTabValue(aGroup, this.kCollapsed)
== "true");
for each (let tab in this.getChildren(aGroup)) {
this._tabCollapseExpand(tab, !collapsed);
if (!collapsed && tab.selected) {
this.tabs.tabbrowser.selectedTab = aGroup;
}
}
VTTabDataStore.setTabValue(aGroup, this.kCollapsed, !collapsed);
},
/*** Event handlers ***/
handleEvent: function(aEvent) {
switch (aEvent.type) {
case "SSTabRestoring":
this.onTabRestoring(aEvent.originalTarget);
return;
case "TabSelect":
this.onTabSelect(aEvent);
return;
case "TabMove":
this.onTabMove(aEvent);
return;
case "TabClose":
this.onTabClose(aEvent);
return;
case "click":
this.onClick(aEvent);
return;
case "dragover":
this.onDragOver(aEvent);
return;
case "dragenter":
this.onDragEnter(aEvent);
return;
case "dragleave":
this.onDragLeave(aEvent);
return;
case "dragend":
this._clearDropTargets();
return;
case "drop":
this.onDrop(aEvent);
return;
}
},
onTabRestoring: function(aTab) {
// Restore tab attributes from session data (this isn't done
// automatically). kId is restored by VTTabIDs.
for each (let attr in [this.kGroup,
this.kInGroup,
this.kLabel,
this.kCollapsed]) {
let value = VTTabDataStore.getTabValue(aTab, attr);
if (value) {
aTab.setAttribute(attr, value);
}
}
// Restore collapsed state if we belong to a group.
let groupId = VTTabDataStore.getTabValue(aTab, this.kInGroup);
if (!groupId) {
return;
}
let self = this;
let window = this.tabs.ownerDocument.defaultView;
function restoreCollapsedState() {
// The group tab we belong to may not have been restored yet.
let group = self.tabs.VTTabIDs.get(groupId);
if (group === undefined) {
window.setTimeout(restoreCollapsedState, 10);
return;
}
self._updateCount(group);
let collapsed = (VTTabDataStore.getTabValue(group, self.kCollapsed)
== "true");
self._tabCollapseExpand(aTab, collapsed);
}
restoreCollapsedState();
},
_tabCollapseExpand: function(aTab, collapsed) {
if (collapsed) {
aTab.classList.add(this.kCollapsed);
} else {
aTab.classList.remove(this.kCollapsed);
}
},
onTabSelect: function(aEvent) {
let tab = aEvent.target;
let document = tab.ownerDocument;
let urlbar = document.getElementById("urlbar");
let isGroup = this.isGroup(tab);
if (isGroup) {
//TODO l10n
urlbar.placeholder = "Group: " + tab.groupLabel;
} else {
urlbar.placeholder = urlbar.getAttribute("bookmarkhistoryplaceholder");
// Selecting a tab that's in a collapsed group will expand
// the group.
if (tab.classList.contains(this.kCollapsed)) {
let groupId = VTTabDataStore.getTabValue(tab, this.kInGroup);
if (groupId) {
let group = this.tabs.VTTabIDs.get(groupId);
this.collapseExpand(group);
}
}
}
urlbar.disabled = isGroup;
//XXX this doesn't quite work:
let buttons = ["reload-button", "home-button", "urlbar", "searchbar"];
for (let i=0; i < buttons.length; i++) {
let element = document.getElementById(buttons[i]);
element.disabled = isGroup;
}
},
onClick: function(aEvent) {
let tab = aEvent.target;
if (tab.localName != "tab") {
return;
}
if (aEvent.originalTarget !== tab.mTwisty) {
return;
}
this.collapseExpand(tab);
},
/*
* Remove style from all potential drop targets (usually there
* should only be one...).
*/
_clearDropTargets: function() {
let groups = this.tabs.getElementsByClassName(this.kDropTarget);
// Make a copy of the array before modifying its contents.
groups = Array.prototype.slice.call(groups);
for (let i=0; i < groups.length; i++) {
groups[i].classList.remove(this.kDropTarget);
}
},
onDragOver: function(aEvent) {
if (aEvent.target.localName != "tab") {
return;
}
// Potentially remove drop target style
//XXX is this inefficient?
this._clearDropTargets();
// Directly dropping on a group or the tab icon:
// Disable drop indicator, mark tab as drop target.
if (this.isGroup(aEvent.target)
|| (aEvent.originalTarget.classList
&& aEvent.originalTarget.classList.contains("tab-icon-image"))) {
aEvent.target.classList.add(this.kDropTarget);
this.tabs._tabDropIndicator.collapsed = true;
return;
}
// Find out if the tab's new position would add it to a group.
// If so, mark the group as drop target and indent drop indicator.
let dropindex = this.tabs._getDropIndex(aEvent);
let tab = this.tabs.childNodes[dropindex];
let groupId = VTTabDataStore.getTabValue(tab, this.kInGroup);
if (!groupId) {
this.tabs._tabDropIndicator.classList.remove(this.kDropInGroup);
return;
}
// Add drop style to the group and the indicator
let group = this.tabs.VTTabIDs.get(groupId);
group.classList.add(this.kDropTarget);
this.tabs._tabDropIndicator.classList.add(this.kDropInGroup);
},
onDragEnter: function(aEvent) {
if (aEvent.target.localName != "tab") {
return;
}
// Dragging a tab over a tab's icon changes the icon to the
// "create group" icon.
if (aEvent.originalTarget.classList
&& aEvent.originalTarget.classList.contains("tab-icon-image")) {
aEvent.originalTarget.classList.add(this.kDropToNewGroup);
}
},
onDragLeave: function(aEvent) {
if (aEvent.target.localName != "tab") {
return;
}
// Change the tab's icon back from the "create group" to
// whatever it was before.
if (aEvent.originalTarget.classList
&& aEvent.originalTarget.classList.contains("tab-icon-image")) {
aEvent.originalTarget.classList.remove(this.kDropToNewGroup);
}
},
onDrop: function(aEvent) {
this._clearDropTargets();
let tab = aEvent.target;
let dt = aEvent.dataTransfer;
let draggedTab = dt.mozGetDataAt(TAB_DROP_TYPE, 0);
if (!this.tabs._isAllowedForDataTransfer(draggedTab)) {
return;
}
// Dropping a tab on another tab's icon will create a new
// group with those two tabs in it.
if (aEvent.originalTarget.classList
&& aEvent.originalTarget.classList.contains("tab-icon-image")) {
let group = this.addGroup();
this.tabs.tabbrowser.moveTabTo(tab, group._tPos+1);
this.tabs.tabbrowser.moveTabTo(draggedTab, group._tPos+1);
return;
}
// Dropping on a group will append to that group's children.
if (this.isGroup(tab)) {
if (this.isGroup(draggedTab)) {
// If it's a group we're dropping, merge groups.
this.addChildren(tab, this.getChildren(draggedTab));
this.tabs.tabbrowser.removeTab(draggedTab);
return;
}
// Dropping onto a collapsed group should select the group.
if (VTTabDataStore.getTabValue(tab, this.kCollapsed) == "true") {
this.tabs.tabbrowser.selectedTab = tab;
}
this.addChild(tab, draggedTab);
}
},
onTabMove: function(aEvent) {
let tab = aEvent.target;
if (tab.getAttribute(this.kIgnoreMove) == "true") {
tab.removeAttribute(this.kIgnoreMove);
return;
}
if (this.isGroup(tab)) {
let newGroup = this._findGroupFromContext(tab);
// Move group's children.
let children = this.getChildren(tab);
let offset = 0;
if (children.length && children[0]._tPos > tab._tPos) {
offset = 1;
}
for (let i = 0; i < children.length; i++) {
children[i].setAttribute(this.kIgnoreMove, "true");
this.tabs.tabbrowser.moveTabTo(children[i],
tab._tPos + i + offset);
}
// If we're being dragged into another group, merge groups.
if (newGroup) {
this.addChildren(newGroup, children);
this.tabs.tabbrowser.removeTab(tab);
}
return;
}
let group = this._findGroupFromContext(tab);
if (!group) {
this.removeChild(tab);
} else {
this.addChild(group, tab);
}
},
/*
* Determine whether a tab move should result in the tab being
* added to a group (or removed from one).
*/
_findGroupFromContext: function(tab) {
let group;
let nextPos = tab._tPos + 1;
if (nextPos < this.tabs.childNodes.length) {
// If the next tab down the line is in a group, then the
// tab is added to that group.
let next = this.tabs.childNodes[nextPos];
let groupId = VTTabDataStore.getTabValue(next, this.kInGroup);
group = this.tabs.VTTabIDs.get(groupId);
} else {
// We're moved to the last position, so let's look at the
// previous tab. Is it a group or in a group?
nextPos = tab._tPos - 1;
let prev = this.tabs.childNodes[nextPos];
if (this.isGroup(prev)) {
group = prev;
} else {
let groupId = VTTabDataStore.getTabValue(prev, this.kInGroup);
group = this.tabs.VTTabIDs.get(groupId);
}
}
return group;
},
onTabClose: function(aEvent) {
let group = aEvent.target;
if (!this.isGroup(group)) {
return;
}
// If a collapsed group is removed, close its children as
// well. Otherwise just remove their group pointer.
let collapsed = (VTTabDataStore.getTabValue(group, this.kCollapsed)
== "true");
let children = this.getChildren(group);
if (!collapsed) {
this.removeChildren(children);
return;
}
let window = group.ownerDocument.defaultView;
let tabbrowser = this.tabs.tabbrowser;
// Remove children async to avoid confusing tabbrowser.removeTab()
window.setTimeout(function() {
for each (let tab in children) {
tabbrowser.removeTab(tab);
}
}, 10);
}
};
| modules/groups.js | /*
* Functionality for grouping tabs.
*
* Groups are implemented as a special kind of tab (see binding in
* group.xml). There are a few advantages and disadvantages to this:
*
* - Groups can be regular children of tabbrowser.tabContainer
* (cf. https://bugzilla.mozilla.org/show_bug.cgi?id=475142).
*
* - The nsISessionStore service takes care of restoring groups and
* their properties.
*
* - But we have to make sure that groups don't behave like tabs at
* all.
*/
const EXPORTED_SYMBOLS = ["VTGroups"];
Components.utils.import("resource://verticaltabs/tabdatastore.js");
const TAB_DROP_TYPE = "application/x-moz-tabbrowser-tab";
function VTGroups(tabs) {
this.tabs = tabs;
tabs.VTGroups = this;
// Restore group and in-group status
tabs.addEventListener('SSTabRestoring', this, true);
// Updating UI
tabs.addEventListener('TabSelect', this, false);
// For clicks on the twisty
tabs.addEventListener('click', this, true);
// For synchronizing group behaviour and tab positioning
tabs.addEventListener('dragover', this, false);
tabs.addEventListener('dragenter', this, false);
tabs.addEventListener('dragleave', this, false);
tabs.addEventListener('dragend', this, false);
tabs.addEventListener('drop', this, false);
tabs.addEventListener('TabMove', this, false);
tabs.addEventListener('TabClose', this, false);
}
VTGroups.prototype = {
kId: 'verticaltabs-id',
kGroup: 'verticaltabs-group',
kInGroup: 'verticaltabs-ingroup',
kLabel: 'verticaltabs-grouplabel',
kCollapsed: 'verticaltabs-collapsed',
kDropTarget: 'verticaltabs-droptarget',
kDropInGroup: 'verticaltabs-dropingroup',
kDropToNewGroup: 'verticaltabs-droptonewgroup',
kIgnoreMove: 'verticaltabs-ignoremove',
/*** Public API ***/
/*
* Create a new group tab. If given as an argument, the label is
* applied to the group. Otherwise the label will be made
* editable.
*/
addGroup: function(aLabel) {
let group = this.tabs.tabbrowser.addTab();
VTTabDataStore.setTabValue(group, this.kGroup, "true");
let window = this.tabs.ownerDocument.defaultView;
function makeLabelEditable() {
// XBL bindings aren't applied synchronously.
if (typeof group.editLabel !== "function") {
window.setTimeout(makeLabelEditable, 10);
return;
}
group.editLabel();
}
if (aLabel) {
VTTabDataStore.setTabValue(group, this.kLabel, aLabel);
group.groupLabel = aLabel;
} else {
makeLabelEditable();
}
return group;
},
/*
* Return the child tabs of a given group. The return value is a
* JavaScript Array (not just a NodeList) and is "owned" by the
* caller (e.g. it may be modified).
*/
getChildren: function(aGroup) {
let groupId = this.tabs.VTTabIDs.id(aGroup);
let children = this.tabs.getElementsByAttribute(this.kInGroup, groupId);
// Return a copy
return Array.prototype.slice.call(children);
},
_updateCount: function(aGroup) {
let count = this.getChildren(aGroup).length;
function update() {
if (!aGroup.mCounter) {
let window = aGroup.ownerDocument.defaultView;
window.setTimeout(update, 10);
return;
}
aGroup.mCounter.firstChild.nodeValue = "" + count;
}
update();
},
/*
* Add a tab to a group. This won't physically move the tab
* anywhere, just create the logical connection.
*/
addChild: function(aGroup, aTab) {
// Only groups can have children
if (!this.isGroup(aGroup)) {
return;
}
// We don't allow nested groups
if (this.isGroup(aTab)) {
return;
}
// Assign a group to the tab. If the tab was in another group
// before, this will simply overwrite the old value.
let groupId = this.tabs.VTTabIDs.id(aGroup);
VTTabDataStore.setTabValue(aTab, this.kInGroup, groupId);
this._updateCount(aGroup);
// Apply the group's collapsed state to the tab
let collapsed = (VTTabDataStore.getTabValue(aGroup, this.kCollapsed)
== "true");
this._tabCollapseExpand(aTab, collapsed);
},
addChildren: function(aGroup, aTabs) {
for each (let tab in aTabs) {
this.addChild(aGroup, tab);
}
},
/*
* Remove a tab from its group.
*/
removeChild: function(aTab) {
let groupId = VTTabDataStore.getTabValue(aTab, this.kInGroup);
if (!groupId) {
return;
}
VTTabDataStore.deleteTabValue(aTab, this.kInGroup);
this._updateCount(aGroup);
},
removeChildren: function(aTabs) {
for each (let tab in aTabs) {
this.removeChild(tab);
}
},
/*
* Creates a tab from the active selection.
*/
createGroupFromMultiSelect: function() {
let group = this.addGroup();
let children = this.tabs.VTMultiSelect.getSelected();
for each (let tab in children) {
// Moving the tabs to the right position is enough, the
// TabMove handler knows the right thing to do.
this.tabs.tabbrowser.moveTabTo(tab, group._tPos+1);
}
this.tabs.VTMultiSelect.clear();
},
/*
* Return true if a given tab is a group tab.
*/
isGroup: function(aTab) {
return (VTTabDataStore.getTabValue(aTab, this.kGroup) == "true");
},
/*
* Toggle collapsed/expanded state of a group tab.
*/
collapseExpand: function(aGroup) {
if (!this.isGroup(aGroup)) {
return;
}
let collapsed = (VTTabDataStore.getTabValue(aGroup, this.kCollapsed)
== "true");
for each (let tab in this.getChildren(aGroup)) {
this._tabCollapseExpand(tab, !collapsed);
if (!collapsed && tab.selected) {
this.tabs.tabbrowser.selectedTab = aGroup;
}
}
VTTabDataStore.setTabValue(aGroup, this.kCollapsed, !collapsed);
},
/*** Event handlers ***/
handleEvent: function(aEvent) {
switch (aEvent.type) {
case "SSTabRestoring":
this.onTabRestoring(aEvent.originalTarget);
return;
case "TabSelect":
this.onTabSelect(aEvent);
return;
case "TabMove":
this.onTabMove(aEvent);
return;
case "TabClose":
this.onTabClose(aEvent);
return;
case "click":
this.onClick(aEvent);
return;
case "dragover":
this.onDragOver(aEvent);
return;
case "dragenter":
this.onDragEnter(aEvent);
return;
case "dragleave":
this.onDragLeave(aEvent);
return;
case "dragend":
this._clearDropTargets();
return;
case "drop":
this.onDrop(aEvent);
return;
}
},
onTabRestoring: function(aTab) {
// Restore tab attributes from session data (this isn't done
// automatically). kId is restored by VTTabIDs.
for each (let attr in [this.kGroup,
this.kInGroup,
this.kLabel,
this.kCollapsed]) {
let value = VTTabDataStore.getTabValue(aTab, attr);
if (value) {
aTab.setAttribute(attr, value);
}
}
// Restore collapsed state if we belong to a group.
let groupId = VTTabDataStore.getTabValue(aTab, this.kInGroup);
if (!groupId) {
return;
}
let self = this;
let window = this.tabs.ownerDocument.defaultView;
function restoreCollapsedState() {
// The group tab we belong to may not have been restored yet.
let group = self.tabs.VTTabIDs.get(groupId);
if (group === undefined) {
window.setTimeout(restoreCollapsedState, 10);
return;
}
self._updateCount(group);
let collapsed = (VTTabDataStore.getTabValue(group, self.kCollapsed)
== "true");
self._tabCollapseExpand(aTab, collapsed);
}
restoreCollapsedState();
},
_tabCollapseExpand: function(aTab, collapsed) {
if (collapsed) {
aTab.classList.add(this.kCollapsed);
} else {
aTab.classList.remove(this.kCollapsed);
}
},
onTabSelect: function(aEvent) {
let tab = aEvent.target;
let document = tab.ownerDocument;
let urlbar = document.getElementById("urlbar");
let isGroup = this.isGroup(tab);
if (isGroup) {
//TODO l10n
urlbar.placeholder = "Group: " + tab.groupLabel;
} else {
urlbar.placeholder = urlbar.getAttribute("bookmarkhistoryplaceholder");
// Selecting a tab that's in a collapsed group will expand
// the group.
if (tab.classList.contains(this.kCollapsed)) {
let groupId = VTTabDataStore.getTabValue(tab, this.kInGroup);
if (groupId) {
let group = this.tabs.VTTabIDs.get(groupId);
this.collapseExpand(group);
}
}
}
urlbar.disabled = isGroup;
//XXX this doesn't quite work:
let buttons = ["reload-button", "home-button", "urlbar", "searchbar"];
for (let i=0; i < buttons.length; i++) {
let element = document.getElementById(buttons[i]);
element.disabled = isGroup;
}
},
onClick: function(aEvent) {
let tab = aEvent.target;
if (tab.localName != "tab") {
return;
}
if (aEvent.originalTarget !== tab.mTwisty) {
return;
}
this.collapseExpand(tab);
},
/*
* Remove style from all potential drop targets (usually there
* should only be one...).
*/
_clearDropTargets: function() {
let groups = this.tabs.getElementsByClassName(this.kDropTarget);
// Make a copy of the array before modifying its contents.
groups = Array.prototype.slice.call(groups);
for (let i=0; i < groups.length; i++) {
groups[i].classList.remove(this.kDropTarget);
}
},
onDragOver: function(aEvent) {
if (aEvent.target.localName != "tab") {
return;
}
// Potentially remove drop target style
//XXX is this inefficient?
this._clearDropTargets();
// Directly dropping on a group or the tab icon:
// Disable drop indicator, mark tab as drop target.
if (this.isGroup(aEvent.target)
|| (aEvent.originalTarget.classList
&& aEvent.originalTarget.classList.contains("tab-icon-image"))) {
aEvent.target.classList.add(this.kDropTarget);
this.tabs._tabDropIndicator.collapsed = true;
return;
}
// Find out if the tab's new position would add it to a group.
// If so, mark the group as drop target and indent drop indicator.
let dropindex = this.tabs._getDropIndex(aEvent);
let tab = this.tabs.childNodes[dropindex];
let groupId = VTTabDataStore.getTabValue(tab, this.kInGroup);
if (!groupId) {
this.tabs._tabDropIndicator.classList.remove(this.kDropInGroup);
return;
}
// Add drop style to the group and the indicator
let group = this.tabs.VTTabIDs.get(groupId);
group.classList.add(this.kDropTarget);
this.tabs._tabDropIndicator.classList.add(this.kDropInGroup);
},
onDragEnter: function(aEvent) {
if (aEvent.target.localName != "tab") {
return;
}
// Dragging a tab over a tab's icon changes the icon to the
// "create group" icon.
if (aEvent.originalTarget.classList
&& aEvent.originalTarget.classList.contains("tab-icon-image")) {
aEvent.originalTarget.classList.add(this.kDropToNewGroup);
}
},
onDragLeave: function(aEvent) {
if (aEvent.target.localName != "tab") {
return;
}
// Change the tab's icon back from the "create group" to
// whatever it was before.
if (aEvent.originalTarget.classList
&& aEvent.originalTarget.classList.contains("tab-icon-image")) {
aEvent.originalTarget.classList.remove(this.kDropToNewGroup);
}
},
onDrop: function(aEvent) {
this._clearDropTargets();
let tab = aEvent.target;
let dt = aEvent.dataTransfer;
let draggedTab = dt.mozGetDataAt(TAB_DROP_TYPE, 0);
if (!this.tabs._isAllowedForDataTransfer(draggedTab)) {
return;
}
// Dropping a tab on another tab's icon will create a new
// group with those two tabs in it.
if (aEvent.originalTarget.classList
&& aEvent.originalTarget.classList.contains("tab-icon-image")) {
let group = this.addGroup();
this.tabs.tabbrowser.moveTabTo(tab, group._tPos+1);
this.tabs.tabbrowser.moveTabTo(draggedTab, group._tPos+1);
return;
}
// Dropping on a group will append to that group's children.
if (this.isGroup(tab)) {
if (this.isGroup(draggedTab)) {
// If it's a group we're dropping, merge groups.
this.addChildren(tab, this.getChildren(draggedTab));
this.tabs.tabbrowser.removeTab(draggedTab);
} else {
this.addChild(tab, draggedTab);
}
}
},
onTabMove: function(aEvent) {
let tab = aEvent.target;
if (tab.getAttribute(this.kIgnoreMove) == "true") {
tab.removeAttribute(this.kIgnoreMove);
return;
}
if (this.isGroup(tab)) {
let newGroup = this._findGroupFromContext(tab);
// Move group's children.
let children = this.getChildren(tab);
let offset = 0;
if (children.length && children[0]._tPos > tab._tPos) {
offset = 1;
}
for (let i = 0; i < children.length; i++) {
children[i].setAttribute(this.kIgnoreMove, "true");
this.tabs.tabbrowser.moveTabTo(children[i],
tab._tPos + i + offset);
}
// If we're being dragged into another group, merge groups.
if (newGroup) {
this.addChildren(newGroup, children);
this.tabs.tabbrowser.removeTab(tab);
}
return;
}
let group = this._findGroupFromContext(tab);
if (!group) {
this.removeChild(tab);
} else {
this.addChild(group, tab);
}
},
/*
* Determine whether a tab move should result in the tab being
* added to a group (or removed from one).
*/
_findGroupFromContext: function(tab) {
let group;
let nextPos = tab._tPos + 1;
if (nextPos < this.tabs.childNodes.length) {
// If the next tab down the line is in a group, then the
// tab is added to that group.
let next = this.tabs.childNodes[nextPos];
let groupId = VTTabDataStore.getTabValue(next, this.kInGroup);
group = this.tabs.VTTabIDs.get(groupId);
} else {
// We're moved to the last position, so let's look at the
// previous tab. Is it a group or in a group?
nextPos = tab._tPos - 1;
let prev = this.tabs.childNodes[nextPos];
if (this.isGroup(prev)) {
group = prev;
} else {
let groupId = VTTabDataStore.getTabValue(prev, this.kInGroup);
group = this.tabs.VTTabIDs.get(groupId);
}
}
return group;
},
onTabClose: function(aEvent) {
let group = aEvent.target;
if (!this.isGroup(group)) {
return;
}
// If a collapsed group is removed, close its children as
// well. Otherwise just remove their group pointer.
let collapsed = (VTTabDataStore.getTabValue(group, this.kCollapsed)
== "true");
let children = this.getChildren(group);
if (!collapsed) {
this.removeChildren(children);
return;
}
let window = group.ownerDocument.defaultView;
let tabbrowser = this.tabs.tabbrowser;
// Remove children async to avoid confusing tabbrowser.removeTab()
window.setTimeout(function() {
for each (let tab in children) {
tabbrowser.removeTab(tab);
}
}, 10);
}
};
| Dropping onto a collapsed group should select the group.
| modules/groups.js | Dropping onto a collapsed group should select the group. | <ide><path>odules/groups.js
<ide> // If it's a group we're dropping, merge groups.
<ide> this.addChildren(tab, this.getChildren(draggedTab));
<ide> this.tabs.tabbrowser.removeTab(draggedTab);
<del> } else {
<del> this.addChild(tab, draggedTab);
<del> }
<add> return;
<add> }
<add> // Dropping onto a collapsed group should select the group.
<add> if (VTTabDataStore.getTabValue(tab, this.kCollapsed) == "true") {
<add> this.tabs.tabbrowser.selectedTab = tab;
<add> }
<add> this.addChild(tab, draggedTab);
<ide> }
<ide> },
<ide> |
|
Java | bsd-2-clause | 965d093cc144d1047bcb870bf3d60bb551413a2c | 0 | biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej | //
// LegacyPlugin.java
//
/*
ImageJ software for multidimensional image processing and analysis.
Copyright (c) 2010, ImageJDev.org.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of the ImageJDev.org developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package imagej.legacy.plugin;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import imagej.ImageJ;
import imagej.data.Dataset;
import imagej.display.DisplayManager;
import imagej.legacy.DatasetHarmonizer;
import imagej.legacy.LegacyImageMap;
import imagej.legacy.LegacyManager;
import imagej.object.ObjectManager;
import imagej.plugin.ImageJPlugin;
import imagej.plugin.Parameter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.imglib2.img.Axes;
import net.imglib2.img.Img;
import net.imglib2.img.basictypeaccess.PlanarAccess;
import net.imglib2.type.numeric.RealType;
/**
* Executes an IJ1 plugin.
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class LegacyPlugin implements ImageJPlugin {
@Parameter
private String className;
@Parameter
private String arg;
@Parameter(output=true)
private List<Dataset> outputs;
/** Used to provide one list of datasets per calling thread. */
private static ThreadLocal<Set<ImagePlus>> outputImps =
new ThreadLocal<Set<ImagePlus>>()
{
@Override
protected synchronized Set<ImagePlus> initialValue() {
return new HashSet<ImagePlus>();
}
};
// -- public interface --
@Override
public void run() {
/*
dirty flag for a ds - special one for harmonizer
image map can track dirty harm and listen events
*/
final Dataset activeDS = ImageJ.get(DisplayManager.class).getActiveDataset();
final LegacyImageMap map = ImageJ.get(LegacyManager.class).getImageMap();
final DatasetHarmonizer harmonizer = new DatasetHarmonizer(map.getTranslator());
final Set<ImagePlus> outputSet = LegacyPlugin.getOutputs();
outputSet.clear();
prePluginHarmonization(map, harmonizer);
WindowManager.setTempCurrentImage(map.findImagePlus(activeDS));
IJ.runPlugIn(className, arg);
outputs = postPluginHarmonization(map, harmonizer);
outputSet.clear();
}
/**
* Gets a list for storing output parameter values.
* This method is thread-safe, because it uses a separate map per thread.
*/
public static Set<ImagePlus> getOutputs() {
return outputImps.get();
}
// -- helpers --
private void prePluginHarmonization(LegacyImageMap map,
DatasetHarmonizer harmonizer)
{
// TODO - have LegacyImageMap track dataset events and keep a dirty bit.
// then only harmonize those datasets that have changed.
ObjectManager objMgr = ImageJ.get(ObjectManager.class);
for (Dataset ds : objMgr.getObjects(Dataset.class)) {
// TODO : when we allow nonplanar images and other primitive types
// to go over to IJ1 world this will need updating
if (isIJ1Compatible(ds)) {
ImagePlus imp = map.findImagePlus(ds);
if (imp == null)
map.registerDataset(ds);
else
harmonizer.updateLegacyImage(ds, imp);
}
}
}
private List<Dataset> postPluginHarmonization(LegacyImageMap map,
DatasetHarmonizer harmonizer)
{
// the IJ1 plugin may not have any outputs but just changes current
// ImagePlus make sure we catch any changes via harmonization
ImagePlus currImp = IJ.getImage();
Dataset ds = map.findDataset(currImp);
if (ds != null)
harmonizer.updateDataset(ds, currImp);
// also harmonize any outputs
List<Dataset> datasets = new ArrayList<Dataset>();
for (ImagePlus imp : getOutputs()) {
ds = map.findDataset(imp);
if (ds == null)
ds = map.registerLegacyImage(imp);
else {
if (imp == currImp) {
// we harmonized this earlier
}
else
harmonizer.updateDataset(ds, imp);
}
datasets.add(ds);
}
return datasets;
}
private boolean isIJ1Compatible(Dataset ds) {
// for now only allow Datasets that can be represented in a planar
// fashion made up of unsigned bytes, unsigned shorts, and float32s
final Img<? extends RealType<?>> img = ds.getImgPlus().getImg();
if (img instanceof PlanarAccess) {
int bitsPerPixel = ds.getType().getBitsPerPixel();
boolean signed = ds.isSigned();
boolean integer = ds.isInteger();
boolean color = ds.isRGBMerged();
long channels = (ds.getAxisIndex(Axes.CHANNEL) == -1) ? 1 :
ds.getImgPlus().dimension(ds.getAxisIndex(Axes.CHANNEL));
if (signed && !integer && bitsPerPixel == 32) return true;
if (!signed && integer && bitsPerPixel == 8) return true;
if (!signed && integer && bitsPerPixel == 16) return true;
if (color && integer && bitsPerPixel == 8 && channels == 3) return true;
}
return false;
}
}
| core/legacy/src/main/java/imagej/legacy/plugin/LegacyPlugin.java | //
// LegacyPlugin.java
//
/*
ImageJ software for multidimensional image processing and analysis.
Copyright (c) 2010, ImageJDev.org.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of the ImageJDev.org developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package imagej.legacy.plugin;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import imagej.ImageJ;
import imagej.data.Dataset;
import imagej.display.DisplayManager;
import imagej.legacy.DatasetHarmonizer;
import imagej.legacy.LegacyImageMap;
import imagej.legacy.LegacyManager;
import imagej.object.ObjectManager;
import imagej.plugin.ImageJPlugin;
import imagej.plugin.Parameter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.imglib2.img.Axes;
import net.imglib2.img.Img;
import net.imglib2.img.basictypeaccess.PlanarAccess;
import net.imglib2.type.numeric.RealType;
/**
* Executes an IJ1 plugin.
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class LegacyPlugin implements ImageJPlugin {
@Parameter
private String className;
@Parameter
private String arg;
@Parameter(output=true)
private List<Dataset> outputs;
/** Used to provide one list of datasets per calling thread. */
private static ThreadLocal<Set<ImagePlus>> outputImps =
new ThreadLocal<Set<ImagePlus>>()
{
@Override
protected synchronized Set<ImagePlus> initialValue() {
return new HashSet<ImagePlus>();
}
};
// -- public interface --
@Override
public void run() {
/*
dirty flag for a ds - special one for harmonizer
image map can track dirty harm and listen events
*/
final Dataset activeDS = ImageJ.get(DisplayManager.class).getActiveDataset();
final LegacyImageMap map = ImageJ.get(LegacyManager.class).getImageMap();
final DatasetHarmonizer harmonizer = new DatasetHarmonizer(map.getTranslator());
final Set<ImagePlus> outputSet = LegacyPlugin.getOutputs();
outputSet.clear();
harmonizeInputImagePluses(map, harmonizer);
WindowManager.setTempCurrentImage(map.findImagePlus(activeDS));
IJ.runPlugIn(className, arg);
harmonizeCurrentImagePlus(map, harmonizer);
outputs = harmonizeOutputImagePluses(map, harmonizer);
outputSet.clear();
}
/**
* Gets a list for storing output parameter values.
* This method is thread-safe, because it uses a separate map per thread.
*/
public static Set<ImagePlus> getOutputs() {
return outputImps.get();
}
// -- helpers --
private void harmonizeInputImagePluses(LegacyImageMap map,
DatasetHarmonizer harmonizer)
{
// TODO - have LegacyImageMap track dataset events and keep a dirty bit.
// then only harmonize those datasets that have changed.
ObjectManager objMgr = ImageJ.get(ObjectManager.class);
for (Dataset ds : objMgr.getObjects(Dataset.class)) {
// TODO : when we allow nonplanar images and other primitive types
// to go over to IJ1 world this will need updating
if (isIJ1Compatible(ds)) {
ImagePlus imp = map.findImagePlus(ds);
if (imp == null)
map.registerDataset(ds);
else
harmonizer.updateLegacyImage(ds, imp);
}
}
}
private void harmonizeCurrentImagePlus(LegacyImageMap map,
DatasetHarmonizer harmonizer)
{
// the IJ1 plugin may not have any outputs but just changes current
// ImagePlus make sure we catch any changes via harmonization
ImagePlus currImp = IJ.getImage();
Dataset ds = map.findDataset(currImp);
if (ds != null)
harmonizer.updateDataset(ds, currImp);
}
private List<Dataset> harmonizeOutputImagePluses(LegacyImageMap map,
DatasetHarmonizer harmonizer)
{
List<Dataset> datasets = new ArrayList<Dataset>();
// also harmonize all outputs
for (ImagePlus imp : getOutputs()) {
Dataset ds = map.findDataset(imp);
if (ds == null)
ds = map.registerLegacyImage(imp);
else {
if (imp == IJ.getImage()) {
// we harmonized this earlier
}
else
harmonizer.updateDataset(ds, imp);
}
datasets.add(ds);
}
return datasets;
}
private boolean isIJ1Compatible(Dataset ds) {
// for now only allow Datasets that can be represented in a planar
// fashion made up of unsigned bytes, unsigned shorts, and float32s
final Img<? extends RealType<?>> img = ds.getImgPlus().getImg();
if (img instanceof PlanarAccess) {
int bitsPerPixel = ds.getType().getBitsPerPixel();
boolean signed = ds.isSigned();
boolean integer = ds.isInteger();
boolean color = ds.isRGBMerged();
long channels = (ds.getAxisIndex(Axes.CHANNEL) == -1) ? 1 :
ds.getImgPlus().dimension(ds.getAxisIndex(Axes.CHANNEL));
if (signed && !integer && bitsPerPixel == 32) return true;
if (!signed && integer && bitsPerPixel == 8) return true;
if (!signed && integer && bitsPerPixel == 16) return true;
if (color && integer && bitsPerPixel == 8 && channels == 3) return true;
}
return false;
}
}
| improve design of harmonization calls
This used to be revision r2945.
| core/legacy/src/main/java/imagej/legacy/plugin/LegacyPlugin.java | improve design of harmonization calls | <ide><path>ore/legacy/src/main/java/imagej/legacy/plugin/LegacyPlugin.java
<ide> final DatasetHarmonizer harmonizer = new DatasetHarmonizer(map.getTranslator());
<ide> final Set<ImagePlus> outputSet = LegacyPlugin.getOutputs();
<ide> outputSet.clear();
<del> harmonizeInputImagePluses(map, harmonizer);
<add> prePluginHarmonization(map, harmonizer);
<ide> WindowManager.setTempCurrentImage(map.findImagePlus(activeDS));
<ide> IJ.runPlugIn(className, arg);
<del> harmonizeCurrentImagePlus(map, harmonizer);
<del> outputs = harmonizeOutputImagePluses(map, harmonizer);
<add> outputs = postPluginHarmonization(map, harmonizer);
<ide> outputSet.clear();
<ide> }
<ide>
<ide>
<ide> // -- helpers --
<ide>
<del> private void harmonizeInputImagePluses(LegacyImageMap map,
<add> private void prePluginHarmonization(LegacyImageMap map,
<ide> DatasetHarmonizer harmonizer)
<ide> {
<ide> // TODO - have LegacyImageMap track dataset events and keep a dirty bit.
<ide> }
<ide> }
<ide>
<del> private void harmonizeCurrentImagePlus(LegacyImageMap map,
<add> private List<Dataset> postPluginHarmonization(LegacyImageMap map,
<ide> DatasetHarmonizer harmonizer)
<ide> {
<ide> // the IJ1 plugin may not have any outputs but just changes current
<ide> Dataset ds = map.findDataset(currImp);
<ide> if (ds != null)
<ide> harmonizer.updateDataset(ds, currImp);
<del> }
<del>
<del> private List<Dataset> harmonizeOutputImagePluses(LegacyImageMap map,
<del> DatasetHarmonizer harmonizer)
<del> {
<add>
<add> // also harmonize any outputs
<add>
<ide> List<Dataset> datasets = new ArrayList<Dataset>();
<ide>
<del> // also harmonize all outputs
<ide> for (ImagePlus imp : getOutputs()) {
<del> Dataset ds = map.findDataset(imp);
<add> ds = map.findDataset(imp);
<ide> if (ds == null)
<ide> ds = map.registerLegacyImage(imp);
<ide> else {
<del> if (imp == IJ.getImage()) {
<add> if (imp == currImp) {
<ide> // we harmonized this earlier
<ide> }
<ide> else |
|
JavaScript | mit | 32bfc8dd5b8df648749236a3d79e70240b2dca4b | 0 | dailymotion/vast-client-js | import { isCompanionAd } from './companion_ad';
import { isCreativeLinear } from './creative/creative_linear';
import { EventEmitter } from './util/event_emitter';
import { isNonLinearAd } from './non_linear_ad';
import { util } from './util/util';
/**
* The default skip delay used in case a custom one is not provided
* @constant
* @type {Number}
*/
const DEFAULT_SKIP_DELAY = -1;
/**
* This class provides methods to track an ad execution.
*
* @export
* @class VASTTracker
* @extends EventEmitter
*/
export class VASTTracker extends EventEmitter {
/**
* Creates an instance of VASTTracker.
*
* @param {VASTClient} client - An instance of VASTClient that can be updated by the tracker. [optional]
* @param {Ad} ad - The ad to track.
* @param {Creative} creative - The creative to track.
* @param {Object} [variation=null] - An optional variation of the creative.
* @constructor
*/
constructor(client, ad, creative, variation = null) {
super();
this.ad = ad;
this.creative = creative;
this.variation = variation;
this.muted = false;
this.impressed = false;
this.skippable = false;
this.trackingEvents = {};
// We need to save the already triggered quartiles, in order to not trigger them again
this._alreadyTriggeredQuartiles = {};
// Tracker listeners should be notified with some events
// no matter if there is a tracking URL or not
this.emitAlwaysEvents = [
'creativeView',
'start',
'firstQuartile',
'midpoint',
'thirdQuartile',
'complete',
'resume',
'pause',
'rewind',
'skip',
'closeLinear',
'close'
];
// Duplicate the creative's trackingEvents property so we can alter it
for (const eventName in this.creative.trackingEvents) {
const events = this.creative.trackingEvents[eventName];
this.trackingEvents[eventName] = events.slice(0);
}
// Nonlinear and companion creatives provide some tracking information at a variation level
// While linear creatives provided that at a creative level. That's why we need to
// differentiate how we retrieve some tracking information.
if (isCreativeLinear(this.creative)) {
this._initLinearTracking();
} else {
this._initVariationTracking();
}
// If the tracker is associated with a client we add a listener to the start event
// to update the lastSuccessfulAd property.
if (client) {
this.on('start', () => {
client.lastSuccessfulAd = Date.now();
});
}
}
/**
* Init the custom tracking options for linear creatives.
*
* @return {void}
*/
_initLinearTracking() {
this.linear = true;
this.skipDelay = this.creative.skipDelay;
this.setDuration(this.creative.duration);
this.clickThroughURLTemplate = this.creative.videoClickThroughURLTemplate;
this.clickTrackingURLTemplates = this.creative.videoClickTrackingURLTemplates;
}
/**
* Init the custom tracking options for nonlinear and companion creatives.
* These options are provided in the variation Object.
*
* @return {void}
*/
_initVariationTracking() {
this.linear = false;
this.skipDelay = DEFAULT_SKIP_DELAY;
// If no variation has been provided there's nothing else to set
if (!this.variation) {
return;
}
// Duplicate the variation's trackingEvents property so we can alter it
for (const eventName in this.variation.trackingEvents) {
const events = this.variation.trackingEvents[eventName];
// If for the given eventName we already had some trackingEvents provided by the creative
// we want to keep both the creative trackingEvents and the variation ones
if (this.trackingEvents[eventName]) {
this.trackingEvents[eventName] = this.trackingEvents[eventName].concat(
events.slice(0)
);
} else {
this.trackingEvents[eventName] = events.slice(0);
}
}
if (isNonLinearAd(this.variation)) {
this.clickThroughURLTemplate = this.variation.nonlinearClickThroughURLTemplate;
this.clickTrackingURLTemplates = this.variation.nonlinearClickTrackingURLTemplates;
this.setDuration(this.variation.minSuggestedDuration);
} else if (isCompanionAd(this.variation)) {
this.clickThroughURLTemplate = this.variation.companionClickThroughURLTemplate;
this.clickTrackingURLTemplates = this.variation.companionClickTrackingURLTemplates;
}
}
/**
* Sets the duration of the ad and updates the quartiles based on that.
*
* @param {Number} duration - The duration of the ad.
*/
setDuration(duration) {
this.assetDuration = duration;
// beware of key names, theses are also used as event names
this.quartiles = {
firstQuartile: Math.round(25 * this.assetDuration) / 100,
midpoint: Math.round(50 * this.assetDuration) / 100,
thirdQuartile: Math.round(75 * this.assetDuration) / 100
};
}
/**
* Sets the duration of the ad and updates the quartiles based on that.
* This is required for tracking time related events.
*
* @param {Number} progress - Current playback time in seconds.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#start
* @emits VASTTracker#skip-countdown
* @emits VASTTracker#progress-[0-100]%
* @emits VASTTracker#progress-[currentTime]
* @emits VASTTracker#rewind
* @emits VASTTracker#firstQuartile
* @emits VASTTracker#midpoint
* @emits VASTTracker#thirdQuartile
*/
setProgress(progress, macros = {}) {
const skipDelay = this.skipDelay || DEFAULT_SKIP_DELAY;
if (skipDelay !== -1 && !this.skippable) {
if (skipDelay > progress) {
this.emit('skip-countdown', skipDelay - progress);
} else {
this.skippable = true;
this.emit('skip-countdown', 0);
}
}
if (this.assetDuration > 0) {
const events = [];
if (progress > 0) {
const percent = Math.round((progress / this.assetDuration) * 100);
events.push('start');
events.push(`progress-${percent}%`);
events.push(`progress-${Math.round(progress)}`);
for (const quartile in this.quartiles) {
if (
this.isQuartileReached(quartile, this.quartiles[quartile], progress)
) {
events.push(quartile);
this._alreadyTriggeredQuartiles[quartile] = true;
}
}
}
events.forEach(eventName => {
this.track(eventName, { macros, once: true });
});
if (progress < this.progress) {
this.track('rewind', { macros });
}
}
this.progress = progress;
}
/**
* Checks if a quartile has been reached without have being triggered already.
*
* @param {String} quartile - Quartile name
* @param {Number} time - Time offset, when this quartile is reached in seconds.
* @param {Number} progress - Current progress of the ads in seconds.
*
* @return {Boolean}
*/
isQuartileReached(quartile, time, progress) {
let quartileReached = false;
// if quartile time already reached and never triggered
if (time <= progress && !this._alreadyTriggeredQuartiles[quartile]) {
quartileReached = true;
}
return quartileReached;
}
/**
* Updates the mute state and calls the mute/unmute tracking URLs.
*
* @param {Boolean} muted - Indicates if the video is muted or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#mute
* @emits VASTTracker#unmute
*/
setMuted(muted, macros = {}) {
if (this.muted !== muted) {
this.track(muted ? 'mute' : 'unmute', { macros });
}
this.muted = muted;
}
/**
* Update the pause state and call the resume/pause tracking URLs.
*
* @param {Boolean} paused - Indicates if the video is paused or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#pause
* @emits VASTTracker#resume
*/
setPaused(paused, macros = {}) {
if (this.paused !== paused) {
this.track(paused ? 'pause' : 'resume', { macros });
}
this.paused = paused;
}
/**
* Updates the fullscreen state and calls the fullscreen tracking URLs.
*
* @param {Boolean} fullscreen - Indicates if the video is in fulscreen mode or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#fullscreen
* @emits VASTTracker#exitFullscreen
*/
setFullscreen(fullscreen, macros = {}) {
if (this.fullscreen !== fullscreen) {
this.track(fullscreen ? 'fullscreen' : 'exitFullscreen', { macros });
}
this.fullscreen = fullscreen;
}
/**
* Updates the expand state and calls the expand/collapse tracking URLs.
*
* @param {Boolean} expanded - Indicates if the video is expanded or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#expand
* @emits VASTTracker#playerExpand
* @emits VASTTracker#collapse
* @emits VASTTracker#playerCollapse
*/
setExpand(expanded, macros = {}) {
if (this.expanded !== expanded) {
this.track(expanded ? 'expand' : 'collapse', { macros });
this.track(expanded ? 'playerExpand' : 'playerCollapse', { macros });
}
this.expanded = expanded;
}
/**
* Must be called if you want to overwrite the <Linear> Skipoffset value.
* This will init the skip countdown duration. Then, every time setProgress() is called,
* it will decrease the countdown and emit a skip-countdown event with the remaining time.
* Do not call this method if you want to keep the original Skipoffset value.
*
* @param {Number} duration - The time in seconds until the skip button is displayed.
*/
setSkipDelay(duration) {
if (typeof duration === 'number') {
this.skipDelay = duration;
}
}
/**
* Tracks an impression (can be called only once).
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#creativeView
*/
trackImpression(macros = {}) {
if (!this.impressed) {
this.impressed = true;
this.trackURLs(this.ad.impressionURLTemplates);
this.track('creativeView', { macros });
}
}
/**
* Send a request to the URI provided by the VAST <Error> element.
* If an [ERRORCODE] macro is included, it will be substitute with errorCode.
*
* @param {String} errorCode - Replaces [ERRORCODE] macro. [ERRORCODE] values are listed in the VAST specification.
* @param {Boolean} [isCustomCode=false] - Flag to allow custom values on error code.
*/
errorWithCode(errorCode, isCustomCode = false) {
this.trackURLs(
this.ad.errorURLTemplates,
{ ERRORCODE: errorCode },
{ isCustomCode }
);
}
/**
* Must be called when the user watched the linear creative until its end.
* Calls the complete tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#complete
*/
complete(macros = {}) {
this.track('complete', { macros });
}
/**
* Must be called if the ad was not and will not be played
* This is a terminal event; no other tracking events should be sent when this is used.
* Calls the notUsed tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#notUsed
*/
notUsed(macros = {}) {
this.track('notUsed', { macros });
this.trackingEvents = [];
}
/**
* An optional metric that can capture all other user interactions
* under one metric such as hover-overs, or custom clicks. It should NOT replace
* clickthrough events or other existing events like mute, unmute, pause, etc.
* Calls the otherAdInteraction tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#otherAdInteraction
*/
otherAdInteraction(macros = {}) {
this.track('otherAdInteraction', { macros });
}
/**
* Must be called if the user clicked or otherwise activated a control used to
* pause streaming content,* which either expands the ad within the player’s
* viewable area or “takes-over” the streaming content area by launching
* additional portion of the ad.
* Calls the acceptInvitation tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#acceptInvitation
*/
acceptInvitation(macros = {}) {
this.track('acceptInvitation', { macros });
}
/**
* Must be called if user activated a control to expand the creative.
* Calls the adExpand tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#adExpand
*/
adExpand(macros = {}) {
this.track('adExpand', { macros });
}
/**
* Must be called when the user activated a control to reduce the creative to its original dimensions.
* Calls the adCollapse tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#adCollapse
*/
adCollapse(macros = {}) {
this.track('adCollapse', { macros });
}
/**
* Must be called if the user clicked or otherwise activated a control used to minimize the ad.
* Calls the minimize tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#minimize
*/
minimize(macros = {}) {
this.track('minimize', { macros });
}
/**
* Must be called if the player did not or was not able to execute the provided
* verification code.The [REASON] macro must be filled with reason code
* Calls the verificationNotExecuted tracking URL of associated verification vendor.
*
* @param {String} vendor - An identifier for the verification vendor. The recommended format is [domain]-[useCase], to avoid name collisions. For example, "company.com-omid".
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#verificationNotExecuted
*/
verificationNotExecuted(vendor, macros = {}) {
if (
!this.ad ||
!this.ad.adVerifications ||
!this.ad.adVerifications.length
) {
throw new Error('No adVerifications provided');
}
if (!vendor) {
throw new Error(
'No vendor provided, unable to find associated verificationNotExecuted'
);
}
const vendorVerification = this.ad.adVerifications.find(
verifications => verifications.vendor === vendor
);
if (!vendorVerification) {
throw new Error(
`No associated verification element found for vendor: ${vendor}`
);
}
const vendorTracking = vendorVerification.trackingEvents;
if (vendorTracking && vendorTracking.verificationNotExecuted) {
const verifsNotExecuted = vendorTracking.verificationNotExecuted;
this.trackURLs(verifsNotExecuted, macros);
this.emit('verificationNotExecuted', {
trackingURLTemplates: verifsNotExecuted
});
}
}
/**
* The time that the initial ad is displayed. This time is based on
* the time between the impression and either the completed length of display based
* on the agreement between transactional parties or a close, minimize, or accept
* invitation event.
* The time will be passed using [ADPLAYHEAD] and [MEDIAPLAYHEAD] macros for VAST 4.1
* Calls the overlayViewDuration tracking URLs.
*
* @param {String} duration - The time that the initial ad is displayed.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#overlayViewDuration
*/
overlayViewDuration(duration, macros = {}) {
macros['CONTENTPLAYHEAD'] = duration;
macros['MEDIAPLAYHEAD'] = macros['ADPLAYHEAD'] = macros['CONTENTPLAYHEAD'];
this.track('overlayViewDuration', { macros });
}
/**
* Must be called when the player or the window is closed during the ad.
* Calls the `closeLinear` (in VAST 3.0 and 4.1) and `close` tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#closeLinear
* @emits VASTTracker#close
*/
close(macros = {}) {
this.track(this.linear ? 'closeLinear' : 'close', { macros });
}
/**
* Must be called when the skip button is clicked. Calls the skip tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#skip
*/
skip(macros = {}) {
this.track('skip', { macros });
}
/**
* Must be called then loaded and buffered the creative’s media and assets either fully
* or to the extent that it is ready to play the media
* Calls the loaded tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#loaded
*/
load(macros = {}) {
this.track('loaded', { macros });
}
/**
* Must be called when the user clicks on the creative.
* It calls the tracking URLs and emits a 'clickthrough' event with the resolved
* clickthrough URL when done.
*
* @param {String} [fallbackClickThroughURL=null] - an optional clickThroughURL template that could be used as a fallback
* @emits VASTTracker#clickthrough
*/
click(fallbackClickThroughURL = null, macros = {}) {
if (
this.clickTrackingURLTemplates &&
this.clickTrackingURLTemplates.length
) {
this.trackURLs(this.clickTrackingURLTemplates, macros);
}
// Use the provided fallbackClickThroughURL as a fallback
const clickThroughURLTemplate =
this.clickThroughURLTemplate || fallbackClickThroughURL;
if (clickThroughURLTemplate) {
if (this.linear) {
macros['CONTENTPLAYHEAD'] = this.progressFormatted();
macros['MEDIAPLAYHEAD'] = macros['ADPLAYHEAD'] =
macros['CONTENTPLAYHEAD'];
}
const clickThroughURL = util.resolveURLTemplates(
[clickThroughURLTemplate],
macros
)[0];
this.emit('clickthrough', clickThroughURL);
}
}
/**
* Calls the tracking URLs for the given eventName and emits the event.
*
* @param {String} eventName - The name of the event.
* @param {Object} [macros={}] - An optional Object of parameters(vast macros) to be used in the tracking calls.
* @param {Boolean} [once=false] - Boolean to define if the event has to be tracked only once.
*
*/
track(eventName, { macros = {}, once = false } = {}) {
// closeLinear event was introduced in VAST 3.0
// Fallback to vast 2.0 close event if necessary
if (
eventName === 'closeLinear' &&
!this.trackingEvents[eventName] &&
this.trackingEvents['close']
) {
eventName = 'close';
}
const trackingURLTemplates = this.trackingEvents[eventName];
const isAlwaysEmitEvent = this.emitAlwaysEvents.indexOf(eventName) > -1;
if (trackingURLTemplates) {
this.emit(eventName, { trackingURLTemplates });
this.trackURLs(trackingURLTemplates, macros);
} else if (isAlwaysEmitEvent) {
this.emit(eventName, null);
}
if (once) {
delete this.trackingEvents[eventName];
if (isAlwaysEmitEvent) {
this.emitAlwaysEvents.splice(
this.emitAlwaysEvents.indexOf(eventName),
1
);
}
}
}
/**
* Calls the tracking urls templates with the given macros .
*
* @param {Array} URLTemplates - An array of tracking url templates.
* @param {Object} [macros ={}] - An optional Object of parameters to be used in the tracking calls.
* @param {Object} [options={}] - An optional Object of options to be used in the tracking calls.
*/
trackURLs(URLTemplates, macros = {}, options = {}) {
if (this.linear) {
if (
this.creative &&
this.creative.mediaFiles &&
this.creative.mediaFiles[0] &&
this.creative.mediaFiles[0].fileURL
) {
macros['ASSETURI'] = this.creative.mediaFiles[0].fileURL;
}
if (!macros['CONTENTPLAYHEAD'] && this.progress) {
//CONTENTPLAYHEAD @deprecated in VAST 4.1 replaced by ADPLAYHEAD & CONTENTPLAYHEAD
macros['CONTENTPLAYHEAD'] = this.progressFormatted();
macros['MEDIAPLAYHEAD'] = macros['ADPLAYHEAD'] =
macros['CONTENTPLAYHEAD'];
}
}
if (
this.creative &&
this.creative.universalAdId &&
this.creative.universalAdId.idRegistry &&
this.creative.universalAdId.value
) {
macros['UNIVERSALADID'] = `${this.creative.universalAdId.idRegistry} ${
this.creative.universalAdId.value
}`;
}
if (this.ad) {
if (this.ad.sequence) {
macros['PODSEQUENCE'] = this.ad.sequence;
}
if (this.ad.adType) {
macros['ADTYPE'] = this.ad.adType;
}
if (this.ad.adServingId) {
macros['ADSERVINGID'] = this.ad.adServingId;
}
if (this.ad.categories && this.ad.categories.length) {
macros['ADCATEGORIES'] = this.ad.categories
.map(categorie => categorie.value)
.join(',');
}
if (this.ad.blockedAdCategories && this.ad.blockedAdCategories.length) {
macros['BLOCKEDADCATEGORIES'] = this.ad.blockedAdCategories;
}
}
util.track(URLTemplates, macros, options);
}
/**
* Formats time progress in a readable string.
*
* @return {String}
*/
progressFormatted() {
const seconds = parseInt(this.progress);
let h = seconds / (60 * 60);
if (h.length < 2) {
h = `0${h}`;
}
let m = (seconds / 60) % 60;
if (m.length < 2) {
m = `0${m}`;
}
let s = seconds % 60;
if (s.length < 2) {
s = `0${m}`;
}
const ms = parseInt((this.progress - seconds) * 100);
return `${h}:${m}:${s}.${ms}`;
}
}
| src/vast_tracker.js | import { isCompanionAd } from './companion_ad';
import { isCreativeLinear } from './creative/creative_linear';
import { EventEmitter } from './util/event_emitter';
import { isNonLinearAd } from './non_linear_ad';
import { util } from './util/util';
/**
* The default skip delay used in case a custom one is not provided
* @constant
* @type {Number}
*/
const DEFAULT_SKIP_DELAY = -1;
/**
* This class provides methods to track an ad execution.
*
* @export
* @class VASTTracker
* @extends EventEmitter
*/
export class VASTTracker extends EventEmitter {
/**
* Creates an instance of VASTTracker.
*
* @param {VASTClient} client - An instance of VASTClient that can be updated by the tracker. [optional]
* @param {Ad} ad - The ad to track.
* @param {Creative} creative - The creative to track.
* @param {Object} [variation=null] - An optional variation of the creative.
* @constructor
*/
constructor(client, ad, creative, variation = null) {
super();
this.ad = ad;
this.creative = creative;
this.variation = variation;
this.muted = false;
this.impressed = false;
this.skippable = false;
this.trackingEvents = {};
// We need to save the already triggered quartiles, in order to not trigger them again
this._alreadyTriggeredQuartiles = {};
// Tracker listeners should be notified with some events
// no matter if there is a tracking URL or not
this.emitAlwaysEvents = [
'creativeView',
'start',
'firstQuartile',
'midpoint',
'thirdQuartile',
'complete',
'resume',
'pause',
'rewind',
'skip',
'closeLinear',
'close'
];
// Duplicate the creative's trackingEvents property so we can alter it
for (const eventName in this.creative.trackingEvents) {
const events = this.creative.trackingEvents[eventName];
this.trackingEvents[eventName] = events.slice(0);
}
// Nonlinear and companion creatives provide some tracking information at a variation level
// While linear creatives provided that at a creative level. That's why we need to
// differentiate how we retrieve some tracking information.
if (isCreativeLinear(this.creative)) {
this._initLinearTracking();
} else {
this._initVariationTracking();
}
// If the tracker is associated with a client we add a listener to the start event
// to update the lastSuccessfulAd property.
if (client) {
this.on('start', () => {
client.lastSuccessfulAd = Date.now();
});
}
}
/**
* Init the custom tracking options for linear creatives.
*
* @return {void}
*/
_initLinearTracking() {
this.linear = true;
this.skipDelay = this.creative.skipDelay;
this.setDuration(this.creative.duration);
this.clickThroughURLTemplate = this.creative.videoClickThroughURLTemplate;
this.clickTrackingURLTemplates = this.creative.videoClickTrackingURLTemplates;
}
/**
* Init the custom tracking options for nonlinear and companion creatives.
* These options are provided in the variation Object.
*
* @return {void}
*/
_initVariationTracking() {
this.linear = false;
this.skipDelay = DEFAULT_SKIP_DELAY;
// If no variation has been provided there's nothing else to set
if (!this.variation) {
return;
}
// Duplicate the variation's trackingEvents property so we can alter it
for (const eventName in this.variation.trackingEvents) {
const events = this.variation.trackingEvents[eventName];
// If for the given eventName we already had some trackingEvents provided by the creative
// we want to keep both the creative trackingEvents and the variation ones
if (this.trackingEvents[eventName]) {
this.trackingEvents[eventName] = this.trackingEvents[eventName].concat(
events.slice(0)
);
} else {
this.trackingEvents[eventName] = events.slice(0);
}
}
if (isNonLinearAd(this.variation)) {
this.clickThroughURLTemplate = this.variation.nonlinearClickThroughURLTemplate;
this.clickTrackingURLTemplates = this.variation.nonlinearClickTrackingURLTemplates;
this.setDuration(this.variation.minSuggestedDuration);
} else if (isCompanionAd(this.variation)) {
this.clickThroughURLTemplate = this.variation.companionClickThroughURLTemplate;
this.clickTrackingURLTemplates = this.variation.companionClickTrackingURLTemplates;
}
}
/**
* Sets the duration of the ad and updates the quartiles based on that.
*
* @param {Number} duration - The duration of the ad.
*/
setDuration(duration) {
this.assetDuration = duration;
// beware of key names, theses are also used as event names
this.quartiles = {
firstQuartile: Math.round(25 * this.assetDuration) / 100,
midpoint: Math.round(50 * this.assetDuration) / 100,
thirdQuartile: Math.round(75 * this.assetDuration) / 100
};
}
/**
* Sets the duration of the ad and updates the quartiles based on that.
* This is required for tracking time related events.
*
* @param {Number} progress - Current playback time in seconds.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#start
* @emits VASTTracker#skip-countdown
* @emits VASTTracker#progress-[0-100]%
* @emits VASTTracker#progress-[currentTime]
* @emits VASTTracker#rewind
* @emits VASTTracker#firstQuartile
* @emits VASTTracker#midpoint
* @emits VASTTracker#thirdQuartile
*/
setProgress(progress, macros = {}) {
const skipDelay = this.skipDelay || DEFAULT_SKIP_DELAY;
if (skipDelay !== -1 && !this.skippable) {
if (skipDelay > progress) {
this.emit('skip-countdown', skipDelay - progress);
} else {
this.skippable = true;
this.emit('skip-countdown', 0);
}
}
if (this.assetDuration > 0) {
const events = [];
if (progress > 0) {
const percent = Math.round((progress / this.assetDuration) * 100);
events.push('start');
events.push(`progress-${percent}%`);
events.push(`progress-${Math.round(progress)}`);
for (const quartile in this.quartiles) {
if (
this.isQuartileReached(quartile, this.quartiles[quartile], progress)
) {
events.push(quartile);
this._alreadyTriggeredQuartiles[quartile] = true;
}
}
}
events.forEach(eventName => {
this.track(eventName, { macros, once: true });
});
if (progress < this.progress) {
this.track('rewind', { macros });
}
}
this.progress = progress;
}
/**
* Checks if a quartile has been reached without have being triggered already.
*
* @param {String} quartile - Quartile name
* @param {Number} time - Time offset, when this quartile is reached in seconds.
* @param {Number} progress - Current progress of the ads in seconds.
*
* @return {Boolean}
*/
isQuartileReached(quartile, time, progress) {
let quartileReached = false;
// if quartile time already reached and never triggered
if (time <= progress && !this._alreadyTriggeredQuartiles[quartile]) {
quartileReached = true;
}
return quartileReached;
}
/**
* Updates the mute state and calls the mute/unmute tracking URLs.
*
* @param {Boolean} muted - Indicates if the video is muted or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#mute
* @emits VASTTracker#unmute
*/
setMuted(muted, macros = {}) {
if (this.muted !== muted) {
this.track(muted ? 'mute' : 'unmute', { macros });
}
this.muted = muted;
}
/**
* Update the pause state and call the resume/pause tracking URLs.
*
* @param {Boolean} paused - Indicates if the video is paused or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#pause
* @emits VASTTracker#resume
*/
setPaused(paused, macros = {}) {
if (this.paused !== paused) {
this.track(paused ? 'pause' : 'resume', { macros });
}
this.paused = paused;
}
/**
* Updates the fullscreen state and calls the fullscreen tracking URLs.
*
* @param {Boolean} fullscreen - Indicates if the video is in fulscreen mode or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#fullscreen
* @emits VASTTracker#exitFullscreen
*/
setFullscreen(fullscreen, macros = {}) {
if (this.fullscreen !== fullscreen) {
this.track(fullscreen ? 'fullscreen' : 'exitFullscreen', { macros });
}
this.fullscreen = fullscreen;
}
/**
* Updates the expand state and calls the expand/collapse tracking URLs.
*
* @param {Boolean} expanded - Indicates if the video is expanded or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#expand
* @emits VASTTracker#playerExpand
* @emits VASTTracker#collapse
* @emits VASTTracker#playerCollapse
*/
setExpand(expanded, macros = {}) {
if (this.expanded !== expanded) {
this.track(expanded ? 'expand' : 'collapse', { macros });
this.track(expanded ? 'playerExpand' : 'playerCollapse', { macros });
}
this.expanded = expanded;
}
/**
* Must be called if you want to overwrite the <Linear> Skipoffset value.
* This will init the skip countdown duration. Then, every time setProgress() is called,
* it will decrease the countdown and emit a skip-countdown event with the remaining time.
* Do not call this method if you want to keep the original Skipoffset value.
*
* @param {Number} duration - The time in seconds until the skip button is displayed.
*/
setSkipDelay(duration) {
if (typeof duration === 'number') {
this.skipDelay = duration;
}
}
/**
* Tracks an impression (can be called only once).
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#creativeView
*/
trackImpression(macros = {}) {
if (!this.impressed) {
this.impressed = true;
this.trackURLs(this.ad.impressionURLTemplates);
this.track('creativeView', { macros });
}
}
/**
* Send a request to the URI provided by the VAST <Error> element.
* If an [ERRORCODE] macro is included, it will be substitute with errorCode.
*
* @param {String} errorCode - Replaces [ERRORCODE] macro. [ERRORCODE] values are listed in the VAST specification.
* @param {Boolean} [isCustomCode=false] - Flag to allow custom values on error code.
*/
errorWithCode(errorCode, isCustomCode = false) {
this.trackURLs(
this.ad.errorURLTemplates,
{ ERRORCODE: errorCode },
{ isCustomCode }
);
}
/**
* Must be called when the user watched the linear creative until its end.
* Calls the complete tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#complete
*/
complete(macros = {}) {
this.track('complete', { macros });
}
/**
* Must be called if the ad was not and will not be played
* This is a terminal event; no other tracking events should be sent when this is used.
* Calls the notUsed tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#notUsed
*/
notUsed(macros = {}) {
this.track('notUsed', { macros });
this.trackingEvents = [];
}
/**
* An optional metric that can capture all other user interactions
* under one metric such as hover-overs, or custom clicks. It should NOT replace
* clickthrough events or other existing events like mute, unmute, pause, etc.
* Calls the otherAdInteraction tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#otherAdInteraction
*/
otherAdInteraction(macros = {}) {
this.track('otherAdInteraction', { macros });
}
/**
* Must be called if the user clicked or otherwise activated a control used to
* pause streaming content,* which either expands the ad within the player’s
* viewable area or “takes-over” the streaming content area by launching
* additional portion of the ad.
* Calls the acceptInvitation tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#acceptInvitation
*/
acceptInvitation(macros = {}) {
this.track('acceptInvitation', { macros });
}
/**
* Must be called if user activated a control to expand the creative.
* Calls the adExpand tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#adExpand
*/
adExpand(macros = {}) {
this.track('adExpand', { macros });
}
/**
* Must be called when the user activated a control to reduce the creative to its original dimensions.
* Calls the adCollapse tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#adCollapse
*/
adCollapse(macros = {}) {
this.track('adCollapse', { macros });
}
/**
* Must be called if the user clicked or otherwise activated a control used to minimize the ad.
* Calls the minimize tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#minimize
*/
minimize(macros = {}) {
this.track('minimize', { macros });
}
/**
* Must be called if the player did not or was not able to execute the provided
* verification code.The [REASON] macro must be filled with reason code
* Calls the verificationNotExecuted tracking URL of associated verification vendor.
*
* @param {String} vendor - An identifier for the verification vendor. The recommended format is [domain]-[useCase], to avoid name collisions. For example, "company.com-omid".
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#verificationNotExecuted
*/
verificationNotExecuted(vendor, macros = {}) {
if (
!this.ad ||
!this.ad.adVerifications ||
!this.ad.adVerifications.length
) {
throw new Error('No adVerifications provided');
}
if (!vendor) {
throw new Error(
'No vendor provided, unable to find associated verificationNotExecuted'
);
}
const vendorVerification = this.ad.adVerifications.find(
verifications => verifications.vendor === vendor
);
if (!vendorVerification) {
throw new Error(
`No associated verification element found for vendor: ${vendor}`
);
}
const vendorTracking = vendorVerification.trackingEvents;
if (vendorTracking && vendorTracking.verificationNotExecuted) {
const verifsNotExecuted = vendorTracking.verificationNotExecuted;
this.trackURLs(verifsNotExecuted, macros);
this.emit('verificationNotExecuted', {
trackingURLTemplates: verifsNotExecuted
});
}
}
/**
* The time that the initial ad is displayed. This time is based on
* the time between the impression and either the completed length of display based
* on the agreement between transactional parties or a close, minimize, or accept
* invitation event.
* The time will be passed using [ADPLAYHEAD] and [MEDIAPLAYHEAD] macros for VAST 4.1
* Calls the overlayViewDuration tracking URLs.
*
* @param {String} duration - The time that the initial ad is displayed.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#overlayViewDuration
*/
overlayViewDuration(duration, macros = {}) {
macros['CONTENTPLAYHEAD'] = duration;
macros['MEDIAPLAYHEAD'] = macros['ADPLAYHEAD'] = macros['CONTENTPLAYHEAD'];
this.track('overlayViewDuration', { macros });
}
/**
* Must be called when the player or the window is closed during the ad.
* Calls the `closeLinear` (in VAST 3.0 and 4.1) and `close` tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#closeLinear
* @emits VASTTracker#close
*/
close(macros = {}) {
this.track(this.linear ? 'closeLinear' : 'close', { macros });
}
/**
* Must be called when the skip button is clicked. Calls the skip tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#skip
*/
skip(macros = {}) {
this.track('skip', { macros });
}
/**
* Must be called then loaded and buffered the creative’s media and assets either fully
* or to the extent that it is ready to play the media
* Calls the loaded tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#loaded
*/
load(macros = {}) {
this.track('loaded', { macros });
}
/**
* Must be called when the user clicks on the creative.
* It calls the tracking URLs and emits a 'clickthrough' event with the resolved
* clickthrough URL when done.
*
* @param {String} [fallbackClickThroughURL=null] - an optional clickThroughURL template that could be used as a fallback
* @emits VASTTracker#clickthrough
*/
click(fallbackClickThroughURL = null, macros = {}) {
if (
this.clickTrackingURLTemplates &&
this.clickTrackingURLTemplates.length
) {
this.trackURLs(this.clickTrackingURLTemplates, macros);
}
// Use the provided fallbackClickThroughURL as a fallback
const clickThroughURLTemplate =
this.clickThroughURLTemplate || fallbackClickThroughURL;
if (clickThroughURLTemplate) {
if (this.linear) {
macros['CONTENTPLAYHEAD'] = this.progressFormatted();
macros['MEDIAPLAYHEAD'] = macros['ADPLAYHEAD'] =
macros['CONTENTPLAYHEAD'];
}
const clickThroughURL = util.resolveURLTemplates(
[clickThroughURLTemplate],
macros
)[0];
this.emit('clickthrough', clickThroughURL);
}
}
/**
* Calls the tracking URLs for the given eventName and emits the event.
*
* @param {String} eventName - The name of the event.
* @param {Object} [macros={}] - An optional Object of parameters(vast macros) to be used in the tracking calls.
* @param {Boolean} [once=false] - Boolean to define if the event has to be tracked only once.
*
*/
track(eventName, { macros = {}, once = false } = {}) {
// closeLinear event was introduced in VAST 3.0
// Fallback to vast 2.0 close event if necessary
if (
eventName === 'closeLinear' &&
!this.trackingEvents[eventName] &&
this.trackingEvents['close']
) {
eventName = 'close';
}
const trackingURLTemplates = this.trackingEvents[eventName];
const isAlwaysEmitEvent = this.emitAlwaysEvents.indexOf(eventName) > -1;
if (trackingURLTemplates) {
this.emit(eventName, { trackingURLTemplates });
this.trackURLs(trackingURLTemplates, macros);
} else if (isAlwaysEmitEvent) {
this.emit(eventName, null);
}
if (once) {
delete this.trackingEvents[eventName];
if (isAlwaysEmitEvent) {
this.emitAlwaysEvents.splice(
this.emitAlwaysEvents.indexOf(eventName),
1
);
}
}
}
/**
* Calls the tracking urls templates with the given macros .
*
* @param {Array} URLTemplates - An array of tracking url templates.
* @param {Object} [macros ={}] - An optional Object of parameters to be used in the tracking calls.
* @param {Object} [options={}] - An optional Object of options to be used in the tracking calls.
*/
trackURLs(URLTemplates, macros = {}, options = {}) {
if (this.linear) {
if (
this.creative &&
this.creative.mediaFiles &&
this.creative.mediaFiles[0] &&
this.creative.mediaFiles[0].fileURL
) {
macros['ASSETURI'] = this.creative.mediaFiles[0].fileURL;
}
if (!macros['CONTENTPLAYHEAD'] && this.progress) {
//CONTENTPLAYHEAD @deprecated in VAST 4.1 replaced by ADPLAYHEAD & CONTENTPLAYHEAD
macros['CONTENTPLAYHEAD'] = this.progressFormatted();
macros['MEDIAPLAYHEAD'] = macros['ADPLAYHEAD'] =
macros['CONTENTPLAYHEAD'];
}
}
if (
this.creative &&
this.creative.universalAdId &&
this.creative.universalAdId.idRegistry &&
this.creative.universalAdId.value
) {
macros['UNIVERSALADID'] = `${this.creative.universalAdId.idRegistry} ${
this.creative.universalAdId.value
}`;
}
if (this.ad) {
if (this.ad.sequence) {
macros['PODSEQUENCE'] = this.ad.sequence;
}
if (this.ad.adType) {
macros['ADTYPE'] = this.ad.adType;
}
if (this.ad.adServingId) {
macros['ADSERVINGID'] = this.ad.adServingId;
}
if (this.ad.categories && this.ad.categories.length) {
macros['ADCATEGORIES'] = this.ad.categories
.map(categorie => categorie.value)
.join(',');
}
}
util.track(URLTemplates, macros, options);
}
/**
* Formats time progress in a readable string.
*
* @return {String}
*/
progressFormatted() {
const seconds = parseInt(this.progress);
let h = seconds / (60 * 60);
if (h.length < 2) {
h = `0${h}`;
}
let m = (seconds / 60) % 60;
if (m.length < 2) {
m = `0${m}`;
}
let s = seconds % 60;
if (s.length < 2) {
s = `0${m}`;
}
const ms = parseInt((this.progress - seconds) * 100);
return `${h}:${m}:${s}.${ms}`;
}
}
| [tracker] Replace blockedAdCategories macros when value known
| src/vast_tracker.js | [tracker] Replace blockedAdCategories macros when value known | <ide><path>rc/vast_tracker.js
<ide> .map(categorie => categorie.value)
<ide> .join(',');
<ide> }
<add> if (this.ad.blockedAdCategories && this.ad.blockedAdCategories.length) {
<add> macros['BLOCKEDADCATEGORIES'] = this.ad.blockedAdCategories;
<add> }
<ide> }
<ide>
<ide> util.track(URLTemplates, macros, options); |
|
JavaScript | apache-2.0 | 6e6646c8d1699b44518e35278f77e2942a8f6fa9 | 0 | codeaudit/dig,NextCenturyCorporation/dig,codeaudit/dig,NextCenturyCorporation/dig,codeaudit/dig,codeaudit/dig,NextCenturyCorporation/dig,NextCenturyCorporation/dig,NextCenturyCorporation/dig,codeaudit/dig | 'use strict';
var path = require('path');
var _ = require('lodash');
var pjson = require('../../../package.json');
function requiredProcessEnv(name) {
if(!process.env[name]) {
throw new Error('You must set the ' + name + ' environment variable');
}
return process.env[name];
}
// All configurations will extend these options
// ============================================
var all = {
env: process.env.NODE_ENV,
// Root path of server
root: path.normalize(__dirname + '/../../..'),
// Server port
port: process.env.PORT || 9000,
// Should we populate the DB with sample data?
seedDB: false,
// Secret for session, you will want to change this and make it an environment variable
secrets: {
session: 'dig-secret'
},
// List of user roles
userRoles: ['guest', 'user', 'admin'],
// MongoDB connection options
mongo: {
options: {
db: {
safe: true
}
}
},
appVersion: pjson.version,
euiServerUrl: process.env.EUI_SERVER_URL || 'http://localhost',
euiServerPort: process.env.EUI_SERVER_PORT || 9200,
euiSearchIndex: process.env.EUI_SEARCH_INDEX || 'dig',
imageSimUrl: process.env.IMAGE_SIM_URL || 'http://localhost',
imageSimPort: process.env.IMAGE_SIM_PORT || 3001,
blurImages: ((!!process.env.BLUR_IMAGES && process.env.BLUR_IMAGES === 'false') ? false : (process.env.BLUR_IMAGES ? process.env.BLUR_IMAGES : 'blur')),
blurPercentage: process.env.BLUR_PERCENT || 2.5,
pixelatePercentage: process.env.PIXELATE_PERCENT || 5,
euiConfigs: {
'dig-latest': {
facets: {
euiFilters: [{
title: 'Phone',
type: 'eui-filter',
field: 'phonenumber',
terms: 'phone'
}],
simFilter: {
title: 'Image',
type: 'simFilter',
field: 'hasFeatureCollection.similar_images_feature.featureValue'
},
aggFilters: [{
title: 'City/Region',
type: 'eui-aggregation',
field: 'city_agg',
terms: 'hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality',
termsType: 'string',
count: 30
},{
title: 'Ethnicity',
type: 'eui-aggregation',
field: 'etn_agg',
terms: 'person_ethnicity',
termsType: 'string',
count: 20
},{
title: 'Hair Color',
type: 'eui-aggregation',
field: 'hc_agg',
terms: 'person_haircolor',
termsType: 'string',
count: 10
},{
title: 'Age',
type: 'eui-aggregation',
field: 'age_agg',
terms: 'person_age',
termsType: 'number',
count: 10
},{
title: 'Provider',
type: 'eui-aggregation',
field: 'provider_agg',
terms: 'provider_name',
termsType: 'string',
count: 10
}],
dateFilters: [{
title: 'Date',
aggName: 'date_agg',
field: 'dateCreated'
}]
},
highlight: {
fields: [
'hasBodyPart.text',
'hasTitlePart.text'
]
},
sort: {
field: 'dateCreated',
defaultOption: {
order: 'rank', title: 'Best Match'
},
options: [
{
order: 'rank',
title: 'Best Match'
},{
order: 'desc',
title: 'Newest First'
},{
order: 'asc',
title: 'Oldest First'
}
]
},
lastUpdateQuery: {
field: 'dateCreated'
},
listFields: {
title: [{
title: 'Title',
type: 'title',
field: 'doc.highlight["hasTitlePart.text"][0] || doc._source.hasTitlePart.text',
section: 'title'
}],
short: [{
title: 'Date',
field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'",
classes: 'date'
},{
title: 'Location',
field: 'doc._source.hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality || doc._source.hasFeatureCollection.place_postalAddress_feature[0].place_postalAddress',
classes: 'location'
},{
title: 'Phone',
field: 'doc._source.hasFeatureCollection.phonenumber_feature.phonenumber || doc._source.hasFeatureCollection.phonenumber_feature[0].phonenumber',
classes: 'phone'
},{
title: 'Name',
field: 'doc._source.hasFeatureCollection.person_name_feature.person_name || doc._source.hasFeatureCollection.person_name_feature[0].person_name',
classes: 'name'
},{
title: 'Age',
field: 'doc._source.hasFeatureCollection.person_age_feature.person_age || doc._source.hasFeatureCollection.person_age_feature[0].person_age',
classes: 'age'
}],
full: {
"1": {
classes: 'listing-details',
fields: [{
title: 'Name(s)',
field: 'doc._source.hasFeatureCollection.person_name_feature.person_name',
featureArray: 'doc._source.hasFeatureCollection.person_name_feature',
featureValue: 'person_name'
},{
title: 'City',
field: 'doc._source.hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality',
featureArray: 'doc._source.hasFeatureCollection.place_postalAddress_feature',
featureValue: 'place_postalAddress'
},{
title: 'Phone Number',
field: 'doc._source.hasFeatureCollection.phonenumber_feature.phonenumber',
featureArray: 'doc._source.hasFeatureCollection.phonenumber_feature',
featureValue: 'phonenumber'
},{
title: 'Email',
field: 'doc._source.hasFeatureCollection.emailaddress_feature.emailaddress',
featureArray: 'doc._source.hasFeatureCollection.emailaddress_feature',
featureValue: 'emailaddress'
},{
title: 'Web Site',
field: 'doc._source.hasFeatureCollection.website_feature.website',
featureArray: 'doc._source.hasFeatureCollection.website_feature',
featureValue: 'website'
},{
title: 'Provider',
field: 'doc._source.hasFeatureCollection.provider_name_feature.provider_name',
featureArray: 'doc._source.hasFeatureCollection.provider_name_feature',
featureValue: 'provider_name'
},{
title: 'Created',
field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'"
}]
},
"2": {
classes: 'person-details',
fields: [{
title: 'Age',
field: 'doc._source.hasFeatureCollection.person_age_feature.person_age',
featureArray: 'doc._source.hasFeatureCollection.person_age_feature',
featureValue: 'person_age'
},{
title: 'Ethnicity',
field: 'doc._source.hasFeatureCollection.person_ethnicity_feature.person_ethnicity',
featureArray: 'doc._source.hasFeatureCollection.person_ethnicity_feature',
featureValue: 'person_ethnicity'
},{
title: 'Hair Color',
field: 'doc._source.hasFeatureCollection.person_haircolor_feature.person_haircolor',
featureArray: 'doc._source.hasFeatureCollection.person_haircolor_feature',
featureValue: 'person_haircolor'
},{
title: 'Height',
field: 'doc._source.hasFeatureCollection.person_height_feature.person_height',
featureArray: 'doc._source.hasFeatureCollection.person_height_feature',
featureValue: 'person_height'
},{
title: 'Weight',
field: "doc['_source']['hasFeatureCollection']['person_weight_feature ']['person_weight']",
featureArray: "doc['_source']['hasFeatureCollection']['person_weight_feature ']",
featureValue: 'person_weight'
}]
}
}
},
debugFields: {
fields: ['doc._id']
},
detailFields: {
"1": {
classes: 'listing-details',
fields: [{
title: 'Created',
field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'"
},{
title: 'City',
field: 'doc._source.hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality',
featureArray: 'doc._source.hasFeatureCollection.place_postalAddress_feature',
featureValue: 'place_postalAddress'
},{
title: 'Phone Number',
field: 'doc._source.hasFeatureCollection.phonenumber_feature.phonenumber',
featureArray: 'doc._source.hasFeatureCollection.phonenumber_feature',
featureValue: 'phonenumber'
},{
title: 'Email',
field: 'doc._source.hasFeatureCollection.emailaddress_feature.emailaddress',
featureArray: 'doc._source.hasFeatureCollection.emailaddress_feature',
featureValue: 'emailaddress'
},{
title: 'Web Site',
field: 'doc._source.hasFeatureCollection.website_feature.website',
featureArray: 'doc._source.hasFeatureCollection.website_feature',
featureValue: 'website'
},{
title: 'Credit Cards',
field: 'doc._source.hasFeatureCollection.creditcardaccepted_feature.creditcardaccepted',
featureArray: 'doc._source.hasFeatureCollection.creditcardaccepted_feature',
featureValue: 'creditcardaccepted'
}]
},
"2": {
classes: 'listing-details',
fields: [{
title: 'Name',
field: 'doc._source.hasFeatureCollection.person_name_feature.person_name'
},{
title: 'Alias',
field: "doc['_source']['hasFeatureCollection']['person_alias_feature ']['person_alias']",
featureArray: "doc['_source']['hasFeatureCollection']['person_alias_feature ']",
featureValue: 'person_alias',
hideIfMissing: true
},{
title: 'Age',
field: 'doc._source.hasFeatureCollection.person_age_feature.person_age',
featureArray: 'doc._source.hasFeatureCollection.person_age_feature',
featureValue: 'person_age'
},{
title: 'Ethnicity',
field: 'doc._source.hasFeatureCollection.person_ethnicity_feature.person_ethnicity',
featureArray: 'doc._source.hasFeatureCollection.person_ethnicity_feature',
featureValue: 'person_ethnicity'
},{
title: 'Hair Color',
field: 'doc._source.hasFeatureCollection.person_haircolor_feature.person_haircolor',
featureArray: 'doc._source.hasFeatureCollection.person_haircolor_feature',
featureValue: 'person_haircolor'
},{
title: 'Height',
field: 'doc._source.hasFeatureCollection.person_height_feature.person_height',
featureArray: 'doc._source.hasFeatureCollection.person_height_feature',
featureValue: 'person_height'
},{
title: 'Weight',
field: "doc['_source']['hasFeatureCollection']['person_weight_feature ']['person_weight']",
featureArray: "doc['_source']['hasFeatureCollection']['person_weight_feature ']",
featureValue: 'person_weight'
},{
title: 'Eye Color',
field: 'doc._source.hasFeatureCollection.person_eyecolor_feature.person_eyecolor',
hideIfMissing: true
},{
title: 'Hair Type',
field: 'doc._source.hasFeatureCollection.person_hairtype_feature.person_hairtype',
featureArray: 'doc._source.hasFeatureCollection.person_hairtype_feature',
featureValue: 'person_hairtype',
hideIfMissing: true
},{
title: 'Hair Length',
field: 'doc._source.hasFeatureCollection.person_hairlength_feature.person_hairlength',
featureArray: 'doc._source.hasFeatureCollection.person_hairlength_feature',
featureValue: 'person_hairlength',
hideIfMissing: true
},{
title: 'Gender',
field: 'doc._source.hasFeatureCollection.person_gender_feature.person_gender',
featureArray: 'doc._source.hasFeatureCollection.person_gender_feature',
featureValue: 'person_gender',
hideIfMissing: true
},{
title: 'Piercings',
field: 'doc._source.hasFeatureCollection.person_piercings_feature.person_piercings',
featureArray: 'doc._source.hasFeatureCollection.person_piercings_feature',
featureValue: 'person_piercings',
hideIfMissing: true
},{
title: 'Tattoos',
field: 'doc._source.hasFeatureCollection.person_tattoocount_feature.person_tattoocount',
featureArray: 'doc._source.hasFeatureCollection.person_tattoocount_feature',
featureValue: 'person_tattoocount',
hideIfMissing: true
},{
title: 'Rate(s)',
field: 'doc._source.hasFeatureCollection.rate_feature.rate',
featureArray: 'doc._source.hasFeatureCollection.rate_feature',
featureValue: 'rate_feature',
hideIfMissing: true
},{
title: 'Hips Type',
field: 'doc._source.hasFeatureCollection.person_hipstype_feature.person_hipstype',
featureArray: 'doc._source.hasFeatureCollection.person_hipstype_feature',
featureValue: 'person_hipstype',
hideIfMissing: true
},{
title: 'Cup Size',
field: 'doc._source.hasFeatureCollection.person_cupsizeus_feature.person_cupsizeus',
featureArray: 'doc._source.hasFeatureCollection.person_cupsizeus_feature',
featureValue: 'person_cupsizeus',
hideIfMissing: true
},{
title: 'Waist Size',
field: "doc['_source']['hasFeatureCollection']['person_waistsize_feature ']['person_waistsize']",
featureArray: "doc['_source']['hasFeatureCollection']['person_waistsize_feature ']",
featureValue: 'person_waistsize',
hideIfMissing: true
},{
title: 'Bust Band Size',
field: 'doc._source.hasFeatureCollection.person_bustbandsize_feature.person_bustbandsize',
featureArray: 'doc._source.hasFeatureCollection.person_bustbandsize_feature',
featureValue: 'person_bustbandsize',
hideIfMissing: true
},{
title: 'Grooming',
field: 'doc._source.hasFeatureCollection.person_grooming_feature.person_grooming',
featureArray: 'doc._source.hasFeatureCollection.person_grooming_feature',
featureValue: 'person_grooming',
hideIfMissing: true
},{
title: 'Build',
field: 'doc._source.hasFeatureCollection.person_build_feature.person_build',
featureArray: 'doc._source.hasFeatureCollection.person_build_feature',
featureValue: 'person_build',
hideIfMissing: true
},{
title: 'Implants',
field: "doc['_source']['hasFeatureCollection']['person_implantspresent_feature ']['person_implantspresent']",
featureArray: "doc['_source']['hasFeatureCollection']['person_implantspresent_feature ']",
featureValue: 'person_implantspresent',
hideIfMissing: true
},{
title: 'In Call/Out Call',
field: 'doc._source.hasFeatureCollection.person_incalloutcall_feature.person_incalloutcall',
featureArray: 'doc._source.hasFeatureCollection.person_incalloutcall_feature',
featureValue: 'person_incalloutcall',
hideIfMissing: true
},{
title: 'Username',
field: 'doc._source.hasFeatureCollection.person_username_feature.person_username',
featureArray: 'doc._source.hasFeatureCollection.person_username_feature',
featureValue: 'person_username',
hideIfMissing: true
},{
title: 'Travel',
field: "doc['_source']['hasFeatureCollection']['person_travel_feature ']['person_travel']",
featureArray: "doc['_source']['hasFeatureCollection']['person_travel_feature ']",
featureValue: 'person_travel',
hideIfMissing: true
},{
title: 'Provider',
field: 'doc._source.hasFeatureCollection.provider_name_feature.provider_name',
featureArray: 'doc._source.hasFeatureCollection.provider_name_feature',
featureValue: 'provider_name'
}]
},
"3": {
classes: "",
fields: [{
field: 'doc.highlight["hasBodyPart.text"][0] || doc._source.hasBodyPart.text',
hideIfMissing: true
}]
}
},
imageField: 'hasImagePart.cacheUrl'
},
'dig-mrs-latest': {
facets: {
euiFilters: [],
//simFilter: {},
aggFilters: [{
title: 'Author',
type: 'eui-aggregation',
field: 'author_agg',
terms: 'hasFeatureCollection.author_feature.author',
count: 20
},{
title: 'Year',
type: 'eui-aggregation',
field: 'year_agg',
terms: 'hasFeatureCollection.publication_year_feature.publication_year',
count: 20
},{
title: 'Affiliation',
type: 'eui-aggregation',
field: 'affiliation_agg',
terms: 'hasFeatureCollection.affiliation_country_feature.affiliation_country',
count: 20
},{
title: 'Compound',
type: 'eui-aggregation',
field: 'compound_agg',
terms: 'hasFeatureCollection.compound_feature.compound',
count: 20
}]
},
listFields: {
title: [{
title: 'Title',
type: 'title',
field: 'doc._source.hasTitlePart.text',
section: 'title'
}],
short: [{
title: 'Date',
field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'",
classes: 'date'
},{
title: 'Author',
field: 'doc._source.hasFeatureCollection.author_feature.author || doc._source.hasFeatureCollection.author_feature[0].author',
classes: 'location'
},{
title: 'Affiliation',
field: 'doc._source.hasFeatureCollection.affiliation_country_feature.affiliation_country || doc._source.hasFeatureCollection.affiliation_country_feature[0].affiliation_country',
classes: 'location'
}],
full: {
"1": {
classes: 'listing-details',
fields: [{
title: 'Authors(s)',
field: 'doc._source.hasFeatureCollection.author_feature.author',
featureArray: 'doc._source.hasFeatureCollection.author_feature',
featureValue: 'author'
},{
title: 'Affiliation',
field: 'doc._source.hasFeatureCollection.affiliation_country_feature.affiliation_country',
featureArray: 'doc._source.hasFeatureCollection.affiliation_country_feature',
featureValue: 'affiliation_country'
},{
title: 'Compound(s)',
field: 'doc._source.hasFeatureCollection.compound_feature.compound',
featureArray: 'doc._source.hasFeatureCollection.compound_feature',
featureValue: 'compound'
},{
title: 'Abstract',
field: "doc['_source']['hasAbstractPart']['text']"
},{
title: 'Date',
field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'"
}]
}
}
},
detailFields: {
"1": {
classes: 'listing-details',
fields: [{
title: 'Date',
field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'",
classes: 'date'
},{
title: 'Authors(s)',
field: 'doc._source.hasFeatureCollection.author_feature.author',
featureArray: 'doc._source.hasFeatureCollection.author_feature',
featureValue: 'author'
},{
title: 'Affiliation',
field: 'doc._source.hasFeatureCollection.affiliation_country_feature.affiliation_country',
featureArray: 'doc._source.hasFeatureCollection.affiliation_country_feature',
featureValue: 'affiliation_country'
},{
title: 'Compound(s)',
field: 'doc._source.hasFeatureCollection.compound_feature.compound',
featureArray: 'doc._source.hasFeatureCollection.compound_feature',
featureValue: 'compound'
},{
title: 'Abstract',
field: "doc['_source']['hasAbstractPart']['text']"
}]
}
}
}
}
};
// Export the config object based on the NODE_ENV
// ==============================================
module.exports = _.merge(
all,
require('./' + process.env.NODE_ENV + '.js') || {});
| server/config/environment/index.js | 'use strict';
var path = require('path');
var _ = require('lodash');
var pjson = require('../../../package.json');
function requiredProcessEnv(name) {
if(!process.env[name]) {
throw new Error('You must set the ' + name + ' environment variable');
}
return process.env[name];
}
// All configurations will extend these options
// ============================================
var all = {
env: process.env.NODE_ENV,
// Root path of server
root: path.normalize(__dirname + '/../../..'),
// Server port
port: process.env.PORT || 9000,
// Should we populate the DB with sample data?
seedDB: false,
// Secret for session, you will want to change this and make it an environment variable
secrets: {
session: 'dig-secret'
},
// List of user roles
userRoles: ['guest', 'user', 'admin'],
// MongoDB connection options
mongo: {
options: {
db: {
safe: true
}
}
},
appVersion: pjson.version,
euiServerUrl: process.env.EUI_SERVER_URL || 'http://localhost',
euiServerPort: process.env.EUI_SERVER_PORT || 9200,
euiSearchIndex: process.env.EUI_SEARCH_INDEX || 'dig',
imageSimUrl: process.env.IMAGE_SIM_URL || 'http://localhost',
imageSimPort: process.env.IMAGE_SIM_PORT || 3001,
blurImages: ((!!process.env.BLUR_IMAGES && process.env.BLUR_IMAGES === 'false') ? false : (process.env.BLUR_IMAGES ? process.env.BLUR_IMAGES : 'blur')),
blurPercentage: process.env.BLUR_PERCENT || 2.5,
pixelatePercentage: process.env.PIXELATE_PERCENT || 5,
euiConfigs: {
'dig-latest': {
facets: {
euiFilters: [{
title: 'Phone',
type: 'eui-filter',
field: 'phonenumber',
terms: 'phone'
}],
simFilter: {
title: 'Image',
type: 'simFilter',
field: 'hasFeatureCollection.similar_images_feature.featureValue'
},
aggFilters: [{
title: 'City/Region',
type: 'eui-aggregation',
field: 'city_agg',
terms: 'hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality',
termsType: 'string',
count: 30
},{
title: 'Ethnicity',
type: 'eui-aggregation',
field: 'etn_agg',
terms: 'person_ethnicity',
termsType: 'string',
count: 20
},{
title: 'Hair Color',
type: 'eui-aggregation',
field: 'hc_agg',
terms: 'person_haircolor',
termsType: 'string',
count: 10
},{
title: 'Age',
type: 'eui-aggregation',
field: 'age_agg',
terms: 'person_age',
termsType: 'number',
count: 10
},{
title: 'Provider',
type: 'eui-aggregation',
field: 'provider_agg',
terms: 'provider_name',
termsType: 'string',
count: 10
}],
dateFilters: [{
title: 'Date',
aggName: 'date_agg',
field: 'dateCreated'
}]
},
highlight: {
fields: [
'hasBodyPart.text',
'hasTitlePart.text'
]
},
sort: {
field: 'dateCreated',
defaultOption: {
order: 'rank', title: 'Best Match'
},
options: [
{
order: 'rank',
title: 'Best Match'
},{
order: 'desc',
title: 'Newest First'
},{
order: 'asc',
title: 'Oldest First'
}
]
},
lastUpdateQuery: {
field: 'dateCreated'
},
listFields: {
title: [{
title: 'Title',
type: 'title',
field: 'doc.highlight["hasTitlePart.text"][0] || doc._source.hasTitlePart.text',
section: 'title'
}],
short: [{
title: 'Date',
field: "doc._source.dateCreated | toLocalTime",
classes: 'date'
},{
title: 'Location',
field: 'doc._source.hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality || doc._source.hasFeatureCollection.place_postalAddress_feature[0].place_postalAddress',
classes: 'location'
},{
title: 'Phone',
field: 'doc._source.hasFeatureCollection.phonenumber_feature.phonenumber || doc._source.hasFeatureCollection.phonenumber_feature[0].phonenumber',
classes: 'phone'
},{
title: 'Name',
field: 'doc._source.hasFeatureCollection.person_name_feature.person_name || doc._source.hasFeatureCollection.person_name_feature[0].person_name',
classes: 'name'
},{
title: 'Age',
field: 'doc._source.hasFeatureCollection.person_age_feature.person_age || doc._source.hasFeatureCollection.person_age_feature[0].person_age',
classes: 'age'
}],
full: {
"1": {
classes: 'listing-details',
fields: [{
title: 'Name(s)',
field: 'doc._source.hasFeatureCollection.person_name_feature.person_name',
featureArray: 'doc._source.hasFeatureCollection.person_name_feature',
featureValue: 'person_name'
},{
title: 'City',
field: 'doc._source.hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality',
featureArray: 'doc._source.hasFeatureCollection.place_postalAddress_feature',
featureValue: 'place_postalAddress'
},{
title: 'Phone Number',
field: 'doc._source.hasFeatureCollection.phonenumber_feature.phonenumber',
featureArray: 'doc._source.hasFeatureCollection.phonenumber_feature',
featureValue: 'phonenumber'
},{
title: 'Email',
field: 'doc._source.hasFeatureCollection.emailaddress_feature.emailaddress',
featureArray: 'doc._source.hasFeatureCollection.emailaddress_feature',
featureValue: 'emailaddress'
},{
title: 'Web Site',
field: 'doc._source.hasFeatureCollection.website_feature.website',
featureArray: 'doc._source.hasFeatureCollection.website_feature',
featureValue: 'website'
},{
title: 'Provider',
field: 'doc._source.hasFeatureCollection.provider_name_feature.provider_name',
featureArray: 'doc._source.hasFeatureCollection.provider_name_feature',
featureValue: 'provider_name'
},{
title: 'Created',
field: "doc._source.dateCreated | toLocalTime"
}]
},
"2": {
classes: 'person-details',
fields: [{
title: 'Age',
field: 'doc._source.hasFeatureCollection.person_age_feature.person_age',
featureArray: 'doc._source.hasFeatureCollection.person_age_feature',
featureValue: 'person_age'
},{
title: 'Ethnicity',
field: 'doc._source.hasFeatureCollection.person_ethnicity_feature.person_ethnicity',
featureArray: 'doc._source.hasFeatureCollection.person_ethnicity_feature',
featureValue: 'person_ethnicity'
},{
title: 'Hair Color',
field: 'doc._source.hasFeatureCollection.person_haircolor_feature.person_haircolor',
featureArray: 'doc._source.hasFeatureCollection.person_haircolor_feature',
featureValue: 'person_haircolor'
},{
title: 'Height',
field: 'doc._source.hasFeatureCollection.person_height_feature.person_height',
featureArray: 'doc._source.hasFeatureCollection.person_height_feature',
featureValue: 'person_height'
},{
title: 'Weight',
field: "doc['_source']['hasFeatureCollection']['person_weight_feature ']['person_weight']",
featureArray: "doc['_source']['hasFeatureCollection']['person_weight_feature ']",
featureValue: 'person_weight'
}]
}
}
},
debugFields: {
fields: ['doc._id']
},
detailFields: {
"1": {
classes: 'listing-details',
fields: [{
title: 'Created',
field: "doc._source.dateCreated | toLocalTime"
},{
title: 'City',
field: 'doc._source.hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality',
featureArray: 'doc._source.hasFeatureCollection.place_postalAddress_feature',
featureValue: 'place_postalAddress'
},{
title: 'Phone Number',
field: 'doc._source.hasFeatureCollection.phonenumber_feature.phonenumber',
featureArray: 'doc._source.hasFeatureCollection.phonenumber_feature',
featureValue: 'phonenumber'
},{
title: 'Email',
field: 'doc._source.hasFeatureCollection.emailaddress_feature.emailaddress',
featureArray: 'doc._source.hasFeatureCollection.emailaddress_feature',
featureValue: 'emailaddress'
},{
title: 'Web Site',
field: 'doc._source.hasFeatureCollection.website_feature.website',
featureArray: 'doc._source.hasFeatureCollection.website_feature',
featureValue: 'website'
},{
title: 'Credit Cards',
field: 'doc._source.hasFeatureCollection.creditcardaccepted_feature.creditcardaccepted',
featureArray: 'doc._source.hasFeatureCollection.creditcardaccepted_feature',
featureValue: 'creditcardaccepted'
}]
},
"2": {
classes: 'listing-details',
fields: [{
title: 'Name',
field: 'doc._source.hasFeatureCollection.person_name_feature.person_name'
},{
title: 'Alias',
field: "doc['_source']['hasFeatureCollection']['person_alias_feature ']['person_alias']",
featureArray: "doc['_source']['hasFeatureCollection']['person_alias_feature ']",
featureValue: 'person_alias',
hideIfMissing: true
},{
title: 'Age',
field: 'doc._source.hasFeatureCollection.person_age_feature.person_age',
featureArray: 'doc._source.hasFeatureCollection.person_age_feature',
featureValue: 'person_age'
},{
title: 'Ethnicity',
field: 'doc._source.hasFeatureCollection.person_ethnicity_feature.person_ethnicity',
featureArray: 'doc._source.hasFeatureCollection.person_ethnicity_feature',
featureValue: 'person_ethnicity'
},{
title: 'Hair Color',
field: 'doc._source.hasFeatureCollection.person_haircolor_feature.person_haircolor',
featureArray: 'doc._source.hasFeatureCollection.person_haircolor_feature',
featureValue: 'person_haircolor'
},{
title: 'Height',
field: 'doc._source.hasFeatureCollection.person_height_feature.person_height',
featureArray: 'doc._source.hasFeatureCollection.person_height_feature',
featureValue: 'person_height'
},{
title: 'Weight',
field: "doc['_source']['hasFeatureCollection']['person_weight_feature ']['person_weight']",
featureArray: "doc['_source']['hasFeatureCollection']['person_weight_feature ']",
featureValue: 'person_weight'
},{
title: 'Eye Color',
field: 'doc._source.hasFeatureCollection.person_eyecolor_feature.person_eyecolor',
hideIfMissing: true
},{
title: 'Hair Type',
field: 'doc._source.hasFeatureCollection.person_hairtype_feature.person_hairtype',
featureArray: 'doc._source.hasFeatureCollection.person_hairtype_feature',
featureValue: 'person_hairtype',
hideIfMissing: true
},{
title: 'Hair Length',
field: 'doc._source.hasFeatureCollection.person_hairlength_feature.person_hairlength',
featureArray: 'doc._source.hasFeatureCollection.person_hairlength_feature',
featureValue: 'person_hairlength',
hideIfMissing: true
},{
title: 'Gender',
field: 'doc._source.hasFeatureCollection.person_gender_feature.person_gender',
featureArray: 'doc._source.hasFeatureCollection.person_gender_feature',
featureValue: 'person_gender',
hideIfMissing: true
},{
title: 'Piercings',
field: 'doc._source.hasFeatureCollection.person_piercings_feature.person_piercings',
featureArray: 'doc._source.hasFeatureCollection.person_piercings_feature',
featureValue: 'person_piercings',
hideIfMissing: true
},{
title: 'Tattoos',
field: 'doc._source.hasFeatureCollection.person_tattoocount_feature.person_tattoocount',
featureArray: 'doc._source.hasFeatureCollection.person_tattoocount_feature',
featureValue: 'person_tattoocount',
hideIfMissing: true
},{
title: 'Rate(s)',
field: 'doc._source.hasFeatureCollection.rate_feature.rate',
featureArray: 'doc._source.hasFeatureCollection.rate_feature',
featureValue: 'rate_feature',
hideIfMissing: true
},{
title: 'Hips Type',
field: 'doc._source.hasFeatureCollection.person_hipstype_feature.person_hipstype',
featureArray: 'doc._source.hasFeatureCollection.person_hipstype_feature',
featureValue: 'person_hipstype',
hideIfMissing: true
},{
title: 'Cup Size',
field: 'doc._source.hasFeatureCollection.person_cupsizeus_feature.person_cupsizeus',
featureArray: 'doc._source.hasFeatureCollection.person_cupsizeus_feature',
featureValue: 'person_cupsizeus',
hideIfMissing: true
},{
title: 'Waist Size',
field: "doc['_source']['hasFeatureCollection']['person_waistsize_feature ']['person_waistsize']",
featureArray: "doc['_source']['hasFeatureCollection']['person_waistsize_feature ']",
featureValue: 'person_waistsize',
hideIfMissing: true
},{
title: 'Bust Band Size',
field: 'doc._source.hasFeatureCollection.person_bustbandsize_feature.person_bustbandsize',
featureArray: 'doc._source.hasFeatureCollection.person_bustbandsize_feature',
featureValue: 'person_bustbandsize',
hideIfMissing: true
},{
title: 'Grooming',
field: 'doc._source.hasFeatureCollection.person_grooming_feature.person_grooming',
featureArray: 'doc._source.hasFeatureCollection.person_grooming_feature',
featureValue: 'person_grooming',
hideIfMissing: true
},{
title: 'Build',
field: 'doc._source.hasFeatureCollection.person_build_feature.person_build',
featureArray: 'doc._source.hasFeatureCollection.person_build_feature',
featureValue: 'person_build',
hideIfMissing: true
},{
title: 'Implants',
field: "doc['_source']['hasFeatureCollection']['person_implantspresent_feature ']['person_implantspresent']",
featureArray: "doc['_source']['hasFeatureCollection']['person_implantspresent_feature ']",
featureValue: 'person_implantspresent',
hideIfMissing: true
},{
title: 'In Call/Out Call',
field: 'doc._source.hasFeatureCollection.person_incalloutcall_feature.person_incalloutcall',
featureArray: 'doc._source.hasFeatureCollection.person_incalloutcall_feature',
featureValue: 'person_incalloutcall',
hideIfMissing: true
},{
title: 'Username',
field: 'doc._source.hasFeatureCollection.person_username_feature.person_username',
featureArray: 'doc._source.hasFeatureCollection.person_username_feature',
featureValue: 'person_username',
hideIfMissing: true
},{
title: 'Travel',
field: "doc['_source']['hasFeatureCollection']['person_travel_feature ']['person_travel']",
featureArray: "doc['_source']['hasFeatureCollection']['person_travel_feature ']",
featureValue: 'person_travel',
hideIfMissing: true
},{
title: 'Provider',
field: 'doc._source.hasFeatureCollection.provider_name_feature.provider_name',
featureArray: 'doc._source.hasFeatureCollection.provider_name_feature',
featureValue: 'provider_name'
}]
},
"3": {
classes: "",
fields: [{
field: 'doc.highlight["hasBodyPart.text"][0] || doc._source.hasBodyPart.text',
hideIfMissing: true
}]
}
},
imageField: 'hasImagePart.cacheUrl'
},
'dig-mrs-latest': {
facets: {
euiFilters: [],
//simFilter: {},
aggFilters: [{
title: 'Author',
type: 'eui-aggregation',
field: 'author_agg',
terms: 'hasFeatureCollection.author_feature.author',
count: 20
},{
title: 'Year',
type: 'eui-aggregation',
field: 'year_agg',
terms: 'hasFeatureCollection.publication_year_feature.publication_year',
count: 20
},{
title: 'Affiliation',
type: 'eui-aggregation',
field: 'affiliation_agg',
terms: 'hasFeatureCollection.affiliation_country_feature.affiliation_country',
count: 20
},{
title: 'Compound',
type: 'eui-aggregation',
field: 'compound_agg',
terms: 'hasFeatureCollection.compound_feature.compound',
count: 20
}]
},
listFields: {
title: [{
title: 'Title',
type: 'title',
field: 'doc._source.hasTitlePart.text',
section: 'title'
}],
short: [{
title: 'Date',
field: "doc._source.dateCreated | toLocalTime",
classes: 'date'
},{
title: 'Author',
field: 'doc._source.hasFeatureCollection.author_feature.author || doc._source.hasFeatureCollection.author_feature[0].author',
classes: 'location'
},{
title: 'Affiliation',
field: 'doc._source.hasFeatureCollection.affiliation_country_feature.affiliation_country || doc._source.hasFeatureCollection.affiliation_country_feature[0].affiliation_country',
classes: 'location'
}],
full: {
"1": {
classes: 'listing-details',
fields: [{
title: 'Authors(s)',
field: 'doc._source.hasFeatureCollection.author_feature.author',
featureArray: 'doc._source.hasFeatureCollection.author_feature',
featureValue: 'author'
},{
title: 'Affiliation',
field: 'doc._source.hasFeatureCollection.affiliation_country_feature.affiliation_country',
featureArray: 'doc._source.hasFeatureCollection.affiliation_country_feature',
featureValue: 'affiliation_country'
},{
title: 'Compound(s)',
field: 'doc._source.hasFeatureCollection.compound_feature.compound',
featureArray: 'doc._source.hasFeatureCollection.compound_feature',
featureValue: 'compound'
},{
title: 'Abstract',
field: "doc['_source']['hasAbstractPart']['text']"
},{
title: 'Date',
field: "doc._source.dateCreated | toLocalTime"
}]
}
}
},
detailFields: {
"1": {
classes: 'listing-details',
fields: [{
title: 'Date',
field: "doc._source.dateCreated | toLocalTime",
classes: 'date'
},{
title: 'Authors(s)',
field: 'doc._source.hasFeatureCollection.author_feature.author',
featureArray: 'doc._source.hasFeatureCollection.author_feature',
featureValue: 'author'
},{
title: 'Affiliation',
field: 'doc._source.hasFeatureCollection.affiliation_country_feature.affiliation_country',
featureArray: 'doc._source.hasFeatureCollection.affiliation_country_feature',
featureValue: 'affiliation_country'
},{
title: 'Compound(s)',
field: 'doc._source.hasFeatureCollection.compound_feature.compound',
featureArray: 'doc._source.hasFeatureCollection.compound_feature',
featureValue: 'compound'
},{
title: 'Abstract',
field: "doc['_source']['hasAbstractPart']['text']"
}]
}
}
}
}
};
// Export the config object based on the NODE_ENV
// ==============================================
module.exports = _.merge(
all,
require('./' + process.env.NODE_ENV + '.js') || {});
| Revert localization, label times UTC
| server/config/environment/index.js | Revert localization, label times UTC | <ide><path>erver/config/environment/index.js
<ide> }],
<ide> short: [{
<ide> title: 'Date',
<del> field: "doc._source.dateCreated | toLocalTime",
<add> field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'",
<ide> classes: 'date'
<ide> },{
<ide> title: 'Location',
<ide> featureValue: 'provider_name'
<ide> },{
<ide> title: 'Created',
<del> field: "doc._source.dateCreated | toLocalTime"
<add> field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'"
<ide> }]
<ide> },
<ide> "2": {
<ide> classes: 'listing-details',
<ide> fields: [{
<ide> title: 'Created',
<del> field: "doc._source.dateCreated | toLocalTime"
<add> field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'"
<ide> },{
<ide> title: 'City',
<ide> field: 'doc._source.hasFeatureCollection.place_postalAddress_feature.featureObject.addressLocality',
<ide> }],
<ide> short: [{
<ide> title: 'Date',
<del> field: "doc._source.dateCreated | toLocalTime",
<add> field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'",
<ide> classes: 'date'
<ide> },{
<ide> title: 'Author',
<ide> field: "doc['_source']['hasAbstractPart']['text']"
<ide> },{
<ide> title: 'Date',
<del> field: "doc._source.dateCreated | toLocalTime"
<add> field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'"
<ide> }]
<ide> }
<ide> }
<ide> classes: 'listing-details',
<ide> fields: [{
<ide> title: 'Date',
<del> field: "doc._source.dateCreated | toLocalTime",
<add> field: "doc._source.dateCreated | date:'MM/dd/yyyy HH:mm:ss UTC'",
<ide> classes: 'date'
<ide> },{
<ide> title: 'Authors(s)', |
|
Java | mit | dbf2ee0101ebe3bca16e6fe4f371cd5d2ffb44da | 0 | pingw33n/malle,pingw33n/malle | package net.emphased.malle.javamail;
import net.emphased.malle.*;
import net.emphased.malle.util.SimpleFormat;
import javax.activation.DataHandler;
import javax.annotation.Nullable;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import static net.emphased.malle.util.Preconditions.checkArgument;
import static net.emphased.malle.util.Preconditions.checkNotNull;
class JavamailMessage implements Mail {
private final Javamail javamail;
private final MimeMessage mimeMessage = new MimeMessage((Session) null);
private boolean mimeMessageReady;
private MimeMultipart rootMimeMultipart;
private MimeMultipart mimeMultipart;
private Charset charset = DEFAULT_CHARSET;
private final Map<BodyType, Body> body = new EnumMap<>(BodyType.class);
private Encoding bodyEncoding = DEFAULT_BODY_ENCODING;
private Encoding attachmentEncoding = DEFAULT_ATTACHMENT_ENCODING;
private final Map<AddressType, List<InternetAddress>> addresses = new EnumMap<>(AddressType.class);
private static final Map<Encoding, String> ENCODING_TO_RFC;
static {
EnumMap<Encoding, String> m = new EnumMap<>(Encoding.class);
m.put(Encoding.BASE64, "base64");
m.put(Encoding.QUOTED_PRINTABLE, "quoted-printable");
m.put(Encoding.EIGHT_BIT, "8bit");
m.put(Encoding.SEVEN_BIT, "7bit");
m.put(Encoding.BINARY, "binary");
ENCODING_TO_RFC = Collections.unmodifiableMap(m);
if (Encoding.values().length != ENCODING_TO_RFC.size()) {
throw new AssertionError("Not all Encoding values have mappings in ENCODING_TO_RFC");
}
}
JavamailMessage(Javamail javamail, MultipartMode multipartMode) {
checkNotNull(javamail, "The 'javamail' can't be null");
checkNotNull(multipartMode, "The 'multipartMode' can't be null");
this.javamail = javamail;
try {
createMimeMultiparts(multipartMode);
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
}
public MimeMessage getMimeMessage() {
ensureMimeMessageReady();
return mimeMessage;
}
@Override
public Mail charset(Charset charset) {
checkNotNull(charset, "The 'charset' can't be null");
this.charset = charset;
return this;
}
@Override
public Mail charset(String charset) {
charset(Charset.forName(charset));
return this;
}
@Override
public Mail bodyEncoding(@Nullable Encoding encoding) {
bodyEncoding = encoding;
return this;
}
@Override
public Mail attachmentEncoding(@Nullable Encoding encoding) {
this.attachmentEncoding = encoding;
return this;
}
@Override
public Mail id(String id) {
checkNotNull(id, "The 'id' can't be null");
try {
mimeMessage.setHeader("Message-ID", '<' + id + '>');
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail priority(int priority) {
try {
mimeMessage.setHeader("X-Priority", String.valueOf(priority));
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail from(Iterable<String> addresses) {
return address(AddressType.FROM, addresses);
}
@Override
public Mail from(String[] addresses) {
return address(AddressType.FROM, addresses);
}
@Override
public Mail from(String addresses) {
return address(AddressType.FROM, addresses);
}
@Override
public Mail from(String address, @Nullable String personal) {
return address(AddressType.FROM, address, personal);
}
@Override
public Mail replyTo(Iterable<String> addresses) {
return address(AddressType.REPLY_TO, addresses);
}
@Override
public Mail replyTo(String[] addresses) {
return address(AddressType.REPLY_TO, addresses);
}
@Override
public Mail replyTo(String addresses) {
return address(AddressType.REPLY_TO, addresses);
}
@Override
public Mail replyTo(String address, @Nullable String personal) {
return address(AddressType.REPLY_TO, address, personal);
}
@Override
public Mail to(Iterable<String> addresses) {
return address(AddressType.TO, addresses);
}
@Override
public Mail to(String[] addresses) {
return address(AddressType.TO, addresses);
}
@Override
public Mail to(String addresses) {
return address(AddressType.TO, addresses);
}
@Override
public Mail to(String address, @Nullable String personal) {
return address(AddressType.TO, createAddress(address, personal));
}
@Override
public Mail cc(Iterable<String> addresses) {
return address(AddressType.CC, addresses);
}
@Override
public Mail cc(String[] addresses) {
return address(AddressType.CC, addresses);
}
@Override
public Mail cc(String addresses) {
return address(AddressType.CC, addresses);
}
@Override
public Mail cc(String address, @Nullable String personal) {
return address(AddressType.CC, createAddress(address, personal));
}
@Override
public Mail bcc(Iterable<String> addresses) {
return address(AddressType.BCC, addresses);
}
public Mail bcc(String addresses) {
return address(AddressType.BCC, addresses);
}
@Override
public Mail bcc(String[] addresses) {
return address(AddressType.BCC, addresses);
}
@Override
public Mail bcc(String address, @Nullable String personal) {
return address(AddressType.BCC, createAddress(address, personal));
}
@Override
public Mail address(AddressType type, Iterable<String> addresses) {
for (String a: addresses) {
address(type, a);
}
return this;
}
@Override
public Mail address(AddressType type, String[] addresses) {
return address(type, Utils.toIterable(addresses));
}
@Override
public Mail address(AddressType type, String addresses) {
for(InternetAddress ia: parseAddresses(addresses)) {
address(type, ia);
}
return this;
}
@Override
public Mail address(AddressType type, String address, @Nullable String personal) {
return address(type, createAddress(address, personal));
}
@Override
public Mail subject(String subject) {
checkNotNull(subject, "The 'subject' must not be null");
try {
mimeMessage.setSubject(subject, charset.name());
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail header(String name, String value) {
checkNotNull(name, "The 'name' must not be null");
checkNotNull(value, "The 'value' must not be null");
try {
mimeMessage.addHeader(name, MimeUtility.fold(9, MimeUtility.encodeText(value, charset.name(), null)));
} catch (MessagingException e) {
throw Utils.wrapException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Shouldn't happen", e);
}
return this;
}
@Override
public Mail header(String name, String pattern, Object... words) {
checkNotNull(name, "The 'name' must not be null");
checkNotNull(pattern, "The 'pattern' must not be null");
try {
if (words.length != 0) {
for (int i = 0; i < words.length; i++) {
Object arg = words[i];
words[i] = arg != null ? MimeUtility.encodeText(arg.toString(), charset.name(), null) : null;
}
pattern = SimpleFormat.format(pattern, words);
}
mimeMessage.addHeader(name, MimeUtility.fold(9, pattern));
} catch (MessagingException e) {
throw Utils.wrapException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Shouldn't happen", e);
}
return this;
}
@Override
public Mail plain(String plain) {
checkNotNull(plain, "The 'plain' must not be null");
return body(BodyType.PLAIN, plain);
}
@Override
public Mail html(String html) {
checkNotNull(html, "The 'html' must not be null");
return body(BodyType.HTML, html);
}
@Override
public Mail body(BodyType type, String value) {
checkNotNull(type, "The 'type' must not be null");
checkNotNull(value, "The 'value' must not be null");
body.put(type, new Body(value));
mimeMessageReady = false;
return this;
}
@Override
public Mail attachment(InputStreamSupplier content, String filename, String type) {
checkNotNull(content, "The 'content' can't be null");
checkNotNull(filename, "The 'filename' can't be null");
checkNotNull(type, "The 'type' can't be null");
try {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
try {
mimeBodyPart.setFileName(MimeUtility.encodeWord(filename, charset.name(), null));
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException("Shouldn't happen", ex);
}
mimeBodyPart.setDataHandler(new DataHandler(new InputStreamSupplierDatasource(content, type, filename)));
setContentTransferEncodingHeader(mimeBodyPart, attachmentEncoding);
getRootMimeMultipart().addBodyPart(mimeBodyPart);
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail attachment(InputStreamSupplier content, String filename) {
return attachment(content, filename, "application/octet-stream");
}
@Override
public Mail inline(InputStreamSupplier content, String id, String type) {
checkNotNull(content, "The 'content' can't be null");
checkNotNull(id, "The 'id' can't be null");
checkNotNull(type, "The 'type' can't be null");
try {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
mimeBodyPart.setContentID('<' + id + '>');
mimeBodyPart.setDataHandler(new DataHandler(new InputStreamSupplierDatasource(content, type, "inline")));
setContentTransferEncodingHeader(mimeBodyPart, attachmentEncoding);
getMimeMultipart().addBodyPart(mimeBodyPart);
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail template(String name, @Nullable Locale locale, Map<String, ?> context) {
javamail.applyTemplate(this, name, locale, context);
return this;
}
@Override
public Mail template(String name, Map<String, ?> context) {
return template(name, null, context);
}
@Override
public Mail template(String name, @Nullable Locale locale, Object... context) {
checkArgument(context.length % 2 == 0, "The 'context' varargs must contain an even number of values");
Map<String, Object> contextMap;
if (context.length != 0) {
int len = context.length / 2;
contextMap = new HashMap<>(len);
for (int i = 0; i < len; i++) {
Object key = context[i * 2];
if (!(key instanceof String)) {
checkArgument(false, "The keys in 'context' must be of String type");
}
Object value = context[i * 2 + 1];
contextMap.put((String) key, value);
}
} else {
contextMap = null;
}
return template(name, locale, contextMap);
}
@Override
public Mail template(String name, Object... context) {
return template(name, null, context);
}
@Override
public Mail send() {
javamail.send(this);
return this;
}
@Override
public Mail writeTo(OutputStream outputStream) {
try {
getMimeMessage().writeTo(outputStream);
} catch (IOException e) {
throw new MailIOException(e);
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail writeTo(File file) {
try (OutputStream os = new FileOutputStream(file)) {
return writeTo(os);
} catch (IOException e) {
throw new MailIOException(e);
}
}
private Mail address(AddressType type, InternetAddress address) {
List<InternetAddress> l = addresses.get(type);
if (l == null) {
l = new ArrayList<>();
addresses.put(type, l);
}
l.add(address);
mimeMessageReady = false;
return this;
}
private InternetAddress[] parseAddresses(String addresses) {
try {
InternetAddress[] r = InternetAddress.parse(addresses, false);
for (int i = 0; i < r.length; i++) {
InternetAddress ia = r[i];
String personal = ia.getPersonal();
// Force recoding of the personal part. This will also encode a possibly
// unencoded personal that needs encoding because of the non US-ASCII characters.
r[i] = new InternetAddress(ia.getAddress(), personal, charset.name());
}
return r;
} catch (AddressException e) {
throw Utils.wrapException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Shouldn't happen", e);
}
}
private InternetAddress createAddress(String address, @Nullable String personal) {
checkNotNull(address, "The 'address' can't be null");
InternetAddress r;
try {
r = new InternetAddress(address, personal, charset.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Shouldn't happen", e);
}
try {
r.validate();
} catch (AddressException e) {
throw Utils.wrapException(e);
}
return r;
}
private void createMimeMultiparts(MultipartMode multipartMode) throws MessagingException {
switch (multipartMode) {
case NONE:
rootMimeMultipart = null;
mimeMultipart = null;
break;
case MIXED:
rootMimeMultipart = new MimeMultipart("mixed");
mimeMessage.setContent(rootMimeMultipart);
mimeMultipart = rootMimeMultipart;
break;
case RELATED:
rootMimeMultipart = new MimeMultipart("related");
mimeMessage.setContent(rootMimeMultipart);
mimeMultipart = rootMimeMultipart;
break;
case MIXED_RELATED:
rootMimeMultipart = new MimeMultipart("mixed");
mimeMessage.setContent(rootMimeMultipart);
mimeMultipart = new MimeMultipart("related");
MimeBodyPart relatedBodyPart = new MimeBodyPart();
relatedBodyPart.setContent(mimeMultipart);
rootMimeMultipart.addBodyPart(relatedBodyPart);
break;
default:
throw new AssertionError();
}
}
private MimeBodyPart getMainPart() throws MessagingException {
checkMultipart();
MimeBodyPart bodyPart = null;
for (int i = 0; i < mimeMultipart.getCount(); i++) {
BodyPart bp = mimeMultipart.getBodyPart(i);
if (bp.getFileName() == null) {
bodyPart = (MimeBodyPart) bp;
}
}
if (bodyPart == null) {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeMultipart.addBodyPart(mimeBodyPart);
bodyPart = mimeBodyPart;
}
return bodyPart;
}
private void setText(Body plain, Body html) throws MessagingException {
MimeMultipart messageBody = new MimeMultipart("alternative");
getMainPart().setContent(messageBody, "text/alternative");
// Create the plain text part of the message.
MimeBodyPart plainTextPart = new MimeBodyPart();
setPlainTextToMimePart(plainTextPart, plain);
messageBody.addBodyPart(plainTextPart);
// Create the HTML text part of the message.
MimeBodyPart htmlTextPart = new MimeBodyPart();
setHtmlToMimePart(htmlTextPart, html);
messageBody.addBodyPart(htmlTextPart);
}
private void setText(Body text, boolean html) throws MessagingException {
MimePart partToUse;
if (isMultipart()) {
partToUse = getMainPart();
}
else {
partToUse = this.mimeMessage;
}
if (html) {
setHtmlToMimePart(partToUse, text);
}
else {
setPlainTextToMimePart(partToUse, text);
}
}
private void setTextToMimePart(MimePart mimePart, String text, String type, @Nullable Encoding encoding) throws MessagingException {
mimePart.setContent(text, type + "; charset=" + charset.name());
setContentTransferEncodingHeader(mimePart, encoding);
}
private void setContentTransferEncodingHeader(Part part, @Nullable Encoding encoding) throws MessagingException {
if (encoding != null) {
part.setHeader("Content-Transfer-Encoding", checkNotNull(ENCODING_TO_RFC.get(encoding)));
} else {
part.removeHeader("Content-Transfer-Encoding");
}
}
private void setPlainTextToMimePart(MimePart part, Body text) throws MessagingException {
setTextToMimePart(part, text.text, "text/plain", text.bodyEncoding);
}
private void setHtmlToMimePart(MimePart part, Body text) throws MessagingException {
setTextToMimePart(part, text.text, "text/html", text.bodyEncoding);
}
private boolean isMultipart() {
return rootMimeMultipart != null;
}
private void checkMultipart() {
if (!isMultipart()) {
throw new IllegalStateException("This message is not multipart");
}
}
private MimeMultipart getRootMimeMultipart() {
checkMultipart();
return rootMimeMultipart;
}
private MimeMultipart getMimeMultipart() throws IllegalStateException {
checkMultipart();
return mimeMultipart;
}
private void ensureMimeMessageReady() {
if (mimeMessageReady) {
return;
}
try {
for (Map.Entry<AddressType, List<InternetAddress>> entry: addresses.entrySet()) {
List<InternetAddress> l = entry.getValue();
switch (entry.getKey()) {
case FROM:
mimeMessage.removeHeader("From");
if (!l.isEmpty()) {
mimeMessage.addFrom(Utils.toArray(l, InternetAddress.class));
}
break;
case REPLY_TO:
if (!l.isEmpty()) {
mimeMessage.setReplyTo(Utils.toArray(l, InternetAddress.class));
}
break;
case TO:
mimeMessage.removeHeader("To");
if (!l.isEmpty()) {
mimeMessage.addRecipients(Message.RecipientType.TO, Utils.toArray(l, InternetAddress.class));
}
break;
case CC:
mimeMessage.removeHeader("CC");
if (!l.isEmpty()) {
mimeMessage.addRecipients(Message.RecipientType.CC, Utils.toArray(l, InternetAddress.class));
}
break;
case BCC:
mimeMessage.removeHeader("BCC");
if (!l.isEmpty()) {
mimeMessage.addRecipients(Message.RecipientType.BCC, Utils.toArray(l, InternetAddress.class));
}
break;
default:
throw new AssertionError("Unhandled RecipientType: " + entry.getKey());
}
}
Body plain = body.get(BodyType.PLAIN);
Body html = body.get(BodyType.HTML);
if (plain != null && html != null) {
checkMultipart();
setText(plain, html);
} else if (plain != null) {
setText(plain, false);
} else if (html != null) {
setText(html, true);
} else {
throw new IllegalStateException("The message must have plain and/or html text set");
}
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
mimeMessageReady = true;
}
private class Context {
final Charset charset;
final Encoding bodyEncoding;
public Context() {
charset = JavamailMessage.this.charset;
bodyEncoding = JavamailMessage.this.bodyEncoding;
}
}
private class Body extends Context {
final String text;
public Body(String text) {
this.text = text;
}
}
}
| modules/javamail/src/main/java/net/emphased/malle/javamail/JavamailMessage.java | package net.emphased.malle.javamail;
import net.emphased.malle.*;
import net.emphased.malle.util.SimpleFormat;
import javax.activation.DataHandler;
import javax.annotation.Nullable;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import static net.emphased.malle.util.Preconditions.checkArgument;
import static net.emphased.malle.util.Preconditions.checkNotNull;
class JavamailMessage implements Mail {
private final Javamail javamail;
private final MimeMessage mimeMessage = new MimeMessage((Session) null);
private boolean mimeMessageReady;
private MimeMultipart rootMimeMultipart;
private MimeMultipart mimeMultipart;
private Charset charset = DEFAULT_CHARSET;
private final Map<BodyType, Body> body = new EnumMap<>(BodyType.class);
private Encoding bodyEncoding = DEFAULT_BODY_ENCODING;
private Encoding attachmentEncoding = DEFAULT_ATTACHMENT_ENCODING;
private final Map<AddressType, List<InternetAddress>> addresses = new EnumMap<>(AddressType.class);
private static final Map<Encoding, String> ENCODING_TO_RFC;
static {
EnumMap<Encoding, String> m = new EnumMap<>(Encoding.class);
m.put(Encoding.BASE64, "base64");
m.put(Encoding.QUOTED_PRINTABLE, "quoted-printable");
m.put(Encoding.EIGHT_BIT, "8bit");
m.put(Encoding.SEVEN_BIT, "7bit");
m.put(Encoding.BINARY, "binary");
ENCODING_TO_RFC = Collections.unmodifiableMap(m);
if (Encoding.values().length != ENCODING_TO_RFC.size()) {
throw new AssertionError("Not all Encoding values have mappings in ENCODING_TO_RFC");
}
}
JavamailMessage(Javamail javamail, MultipartMode multipartMode) {
checkNotNull(javamail, "The 'javamail' can't be null");
checkNotNull(multipartMode, "The 'multipartMode' can't be null");
this.javamail = javamail;
try {
createMimeMultiparts(multipartMode);
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
}
public MimeMessage getMimeMessage() {
ensureMimeMessageReady();
return mimeMessage;
}
@Override
public Mail charset(Charset charset) {
checkNotNull(charset, "The 'charset' can't be null");
this.charset = charset;
return this;
}
@Override
public Mail charset(String charset) {
charset(Charset.forName(charset));
return this;
}
@Override
public Mail bodyEncoding(@Nullable Encoding encoding) {
bodyEncoding = encoding;
return this;
}
@Override
public Mail attachmentEncoding(@Nullable Encoding encoding) {
this.attachmentEncoding = encoding;
return this;
}
@Override
public Mail id(String id) {
checkNotNull(id, "The 'id' can't be null");
try {
mimeMessage.setHeader("Message-ID", '<' + id + '>');
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail priority(int priority) {
try {
mimeMessage.setHeader("X-Priority", String.valueOf(priority));
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail from(Iterable<String> addresses) {
return address(AddressType.FROM, addresses);
}
@Override
public Mail from(String[] addresses) {
return address(AddressType.FROM, addresses);
}
@Override
public Mail from(String addresses) {
return address(AddressType.FROM, addresses);
}
@Override
public Mail from(String address, @Nullable String personal) {
return address(AddressType.FROM, address, personal);
}
@Override
public Mail replyTo(Iterable<String> addresses) {
return address(AddressType.REPLY_TO, addresses);
}
@Override
public Mail replyTo(String[] addresses) {
return address(AddressType.REPLY_TO, addresses);
}
@Override
public Mail replyTo(String addresses) {
return address(AddressType.REPLY_TO, addresses);
}
@Override
public Mail replyTo(String address, @Nullable String personal) {
return address(AddressType.REPLY_TO, address, personal);
}
@Override
public Mail to(Iterable<String> addresses) {
return address(AddressType.TO, addresses);
}
@Override
public Mail to(String[] addresses) {
return address(AddressType.TO, addresses);
}
@Override
public Mail to(String addresses) {
return address(AddressType.TO, addresses);
}
@Override
public Mail to(String address, @Nullable String personal) {
return address(AddressType.TO, createAddress(address, personal));
}
@Override
public Mail cc(Iterable<String> addresses) {
return address(AddressType.CC, addresses);
}
@Override
public Mail cc(String[] addresses) {
return address(AddressType.CC, addresses);
}
@Override
public Mail cc(String addresses) {
return address(AddressType.CC, addresses);
}
@Override
public Mail cc(String address, @Nullable String personal) {
return address(AddressType.CC, createAddress(address, personal));
}
@Override
public Mail bcc(Iterable<String> addresses) {
return address(AddressType.BCC, addresses);
}
public Mail bcc(String addresses) {
return address(AddressType.BCC, addresses);
}
@Override
public Mail bcc(String[] addresses) {
return address(AddressType.BCC, addresses);
}
@Override
public Mail bcc(String address, @Nullable String personal) {
return address(AddressType.BCC, createAddress(address, personal));
}
@Override
public Mail address(AddressType type, Iterable<String> addresses) {
for (String a: addresses) {
address(type, a);
}
return this;
}
@Override
public Mail address(AddressType type, String[] addresses) {
return address(type, Utils.toIterable(addresses));
}
@Override
public Mail address(AddressType type, String addresses) {
for(InternetAddress ia: parseAddresses(addresses)) {
address(type, ia);
}
return this;
}
@Override
public Mail address(AddressType type, String address, @Nullable String personal) {
return address(type, createAddress(address, personal));
}
@Override
public Mail subject(String subject) {
checkNotNull(subject, "The 'subject' must not be null");
try {
mimeMessage.setSubject(subject, charset.name());
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail header(String name, String value) {
checkNotNull(name, "The 'name' must not be null");
checkNotNull(value, "The 'value' must not be null");
try {
mimeMessage.addHeader(name, MimeUtility.fold(9, MimeUtility.encodeText(value, charset.name(), null)));
} catch (MessagingException e) {
throw Utils.wrapException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Shouldn't happen", e);
}
return this;
}
@Override
public Mail header(String name, String pattern, Object... words) {
checkNotNull(name, "The 'name' must not be null");
checkNotNull(pattern, "The 'pattern' must not be null");
try {
if (words.length != 0) {
for (int i = 0; i < words.length; i++) {
Object arg = words[i];
words[i] = arg != null ? MimeUtility.encodeText(arg.toString(), charset.name(), null) : null;
}
pattern = SimpleFormat.format(pattern, words);
}
mimeMessage.addHeader(name, MimeUtility.fold(9, pattern));
} catch (MessagingException e) {
throw Utils.wrapException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Shouldn't happen", e);
}
return this;
}
@Override
public Mail plain(String plain) {
checkNotNull(plain, "The 'plain' must not be null");
return body(BodyType.PLAIN, plain);
}
@Override
public Mail html(String html) {
checkNotNull(html, "The 'html' must not be null");
return body(BodyType.HTML, html);
}
@Override
public Mail body(BodyType type, String value) {
checkNotNull(type, "The 'type' must not be null");
checkNotNull(value, "The 'value' must not be null");
body.put(type, new Body(value));
mimeMessageReady = false;
return this;
}
@Override
public Mail attachment(InputStreamSupplier content, String filename, String type) {
checkNotNull(content, "The 'content' can't be null");
checkNotNull(filename, "The 'filename' can't be null");
checkNotNull(type, "The 'type' can't be null");
try {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
try {
mimeBodyPart.setFileName(MimeUtility.encodeWord(filename, charset.name(), null));
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException("Shouldn't happen", ex);
}
mimeBodyPart.setDataHandler(new DataHandler(new InputStreamSupplierDatasource(content, type, filename)));
setContentTransferEncodingHeader(mimeBodyPart, attachmentEncoding);
getRootMimeMultipart().addBodyPart(mimeBodyPart);
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail attachment(InputStreamSupplier content, String filename) {
return attachment(content, filename, "application/octet-stream");
}
@Override
public Mail inline(InputStreamSupplier content, String id, String type) {
checkNotNull(content, "The 'content' can't be null");
checkNotNull(id, "The 'id' can't be null");
checkNotNull(type, "The 'type' can't be null");
try {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
mimeBodyPart.setContentID('<' + id + '>');
mimeBodyPart.setDataHandler(new DataHandler(new InputStreamSupplierDatasource(content, type, "inline")));
setContentTransferEncodingHeader(mimeBodyPart, attachmentEncoding);
getMimeMultipart().addBodyPart(mimeBodyPart);
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail template(String name, @Nullable Locale locale, Map<String, ?> context) {
javamail.applyTemplate(this, name, locale, context);
return this;
}
@Override
public Mail template(String name, Map<String, ?> context) {
return template(name, null, context);
}
@Override
public Mail template(String name, @Nullable Locale locale, Object... context) {
checkArgument(context.length % 2 == 0, "The 'context' varargs must contain an even number of values");
Map<String, Object> contextMap;
if (context.length != 0) {
int len = context.length / 2;
contextMap = new HashMap<>(len);
for (int i = 0; i < len; i++) {
Object key = context[i * 2];
if (!(key instanceof String)) {
checkArgument(false, "The key values in 'context' must be of String type");
}
Object value = context[i * 2 + 1];
contextMap.put((String) key, value);
}
} else {
contextMap = null;
}
return template(name, locale, contextMap);
}
@Override
public Mail template(String name, Object... context) {
return template(name, null, context);
}
@Override
public Mail send() {
javamail.send(this);
return this;
}
@Override
public Mail writeTo(OutputStream outputStream) {
try {
getMimeMessage().writeTo(outputStream);
} catch (IOException e) {
throw new MailIOException(e);
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
return this;
}
@Override
public Mail writeTo(File file) {
try (OutputStream os = new FileOutputStream(file)) {
return writeTo(os);
} catch (IOException e) {
throw new MailIOException(e);
}
}
private Mail address(AddressType type, InternetAddress address) {
List<InternetAddress> l = addresses.get(type);
if (l == null) {
l = new ArrayList<>();
addresses.put(type, l);
}
l.add(address);
mimeMessageReady = false;
return this;
}
private InternetAddress[] parseAddresses(String addresses) {
try {
InternetAddress[] r = InternetAddress.parse(addresses, false);
for (int i = 0; i < r.length; i++) {
InternetAddress ia = r[i];
String personal = ia.getPersonal();
// Force recoding of the personal part. This will also encode a possibly
// unencoded personal that needs encoding because of the non US-ASCII characters.
r[i] = new InternetAddress(ia.getAddress(), personal, charset.name());
}
return r;
} catch (AddressException e) {
throw Utils.wrapException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Shouldn't happen", e);
}
}
private InternetAddress createAddress(String address, @Nullable String personal) {
checkNotNull(address, "The 'address' can't be null");
InternetAddress r;
try {
r = new InternetAddress(address, personal, charset.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Shouldn't happen", e);
}
try {
r.validate();
} catch (AddressException e) {
throw Utils.wrapException(e);
}
return r;
}
private void createMimeMultiparts(MultipartMode multipartMode) throws MessagingException {
switch (multipartMode) {
case NONE:
rootMimeMultipart = null;
mimeMultipart = null;
break;
case MIXED:
rootMimeMultipart = new MimeMultipart("mixed");
mimeMessage.setContent(rootMimeMultipart);
mimeMultipart = rootMimeMultipart;
break;
case RELATED:
rootMimeMultipart = new MimeMultipart("related");
mimeMessage.setContent(rootMimeMultipart);
mimeMultipart = rootMimeMultipart;
break;
case MIXED_RELATED:
rootMimeMultipart = new MimeMultipart("mixed");
mimeMessage.setContent(rootMimeMultipart);
mimeMultipart = new MimeMultipart("related");
MimeBodyPart relatedBodyPart = new MimeBodyPart();
relatedBodyPart.setContent(mimeMultipart);
rootMimeMultipart.addBodyPart(relatedBodyPart);
break;
default:
throw new AssertionError();
}
}
private MimeBodyPart getMainPart() throws MessagingException {
checkMultipart();
MimeBodyPart bodyPart = null;
for (int i = 0; i < mimeMultipart.getCount(); i++) {
BodyPart bp = mimeMultipart.getBodyPart(i);
if (bp.getFileName() == null) {
bodyPart = (MimeBodyPart) bp;
}
}
if (bodyPart == null) {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeMultipart.addBodyPart(mimeBodyPart);
bodyPart = mimeBodyPart;
}
return bodyPart;
}
private void setText(Body plain, Body html) throws MessagingException {
MimeMultipart messageBody = new MimeMultipart("alternative");
getMainPart().setContent(messageBody, "text/alternative");
// Create the plain text part of the message.
MimeBodyPart plainTextPart = new MimeBodyPart();
setPlainTextToMimePart(plainTextPart, plain);
messageBody.addBodyPart(plainTextPart);
// Create the HTML text part of the message.
MimeBodyPart htmlTextPart = new MimeBodyPart();
setHtmlToMimePart(htmlTextPart, html);
messageBody.addBodyPart(htmlTextPart);
}
private void setText(Body text, boolean html) throws MessagingException {
MimePart partToUse;
if (isMultipart()) {
partToUse = getMainPart();
}
else {
partToUse = this.mimeMessage;
}
if (html) {
setHtmlToMimePart(partToUse, text);
}
else {
setPlainTextToMimePart(partToUse, text);
}
}
private void setTextToMimePart(MimePart mimePart, String text, String type, @Nullable Encoding encoding) throws MessagingException {
mimePart.setContent(text, type + "; charset=" + charset.name());
setContentTransferEncodingHeader(mimePart, encoding);
}
private void setContentTransferEncodingHeader(Part part, @Nullable Encoding encoding) throws MessagingException {
if (encoding != null) {
part.setHeader("Content-Transfer-Encoding", checkNotNull(ENCODING_TO_RFC.get(encoding)));
} else {
part.removeHeader("Content-Transfer-Encoding");
}
}
private void setPlainTextToMimePart(MimePart part, Body text) throws MessagingException {
setTextToMimePart(part, text.text, "text/plain", text.bodyEncoding);
}
private void setHtmlToMimePart(MimePart part, Body text) throws MessagingException {
setTextToMimePart(part, text.text, "text/html", text.bodyEncoding);
}
private boolean isMultipart() {
return rootMimeMultipart != null;
}
private void checkMultipart() {
if (!isMultipart()) {
throw new IllegalStateException("This message is not multipart");
}
}
private MimeMultipart getRootMimeMultipart() {
checkMultipart();
return rootMimeMultipart;
}
private MimeMultipart getMimeMultipart() throws IllegalStateException {
checkMultipart();
return mimeMultipart;
}
private void ensureMimeMessageReady() {
if (mimeMessageReady) {
return;
}
try {
for (Map.Entry<AddressType, List<InternetAddress>> entry: addresses.entrySet()) {
List<InternetAddress> l = entry.getValue();
switch (entry.getKey()) {
case FROM:
mimeMessage.removeHeader("From");
if (!l.isEmpty()) {
mimeMessage.addFrom(Utils.toArray(l, InternetAddress.class));
}
break;
case REPLY_TO:
if (!l.isEmpty()) {
mimeMessage.setReplyTo(Utils.toArray(l, InternetAddress.class));
}
break;
case TO:
mimeMessage.removeHeader("To");
if (!l.isEmpty()) {
mimeMessage.addRecipients(Message.RecipientType.TO, Utils.toArray(l, InternetAddress.class));
}
break;
case CC:
mimeMessage.removeHeader("CC");
if (!l.isEmpty()) {
mimeMessage.addRecipients(Message.RecipientType.CC, Utils.toArray(l, InternetAddress.class));
}
break;
case BCC:
mimeMessage.removeHeader("BCC");
if (!l.isEmpty()) {
mimeMessage.addRecipients(Message.RecipientType.BCC, Utils.toArray(l, InternetAddress.class));
}
break;
default:
throw new AssertionError("Unhandled RecipientType: " + entry.getKey());
}
}
Body plain = body.get(BodyType.PLAIN);
Body html = body.get(BodyType.HTML);
if (plain != null && html != null) {
checkMultipart();
setText(plain, html);
} else if (plain != null) {
setText(plain, false);
} else if (html != null) {
setText(html, true);
} else {
throw new IllegalStateException("The message must have plain and/or html text set");
}
} catch (MessagingException e) {
throw Utils.wrapException(e);
}
mimeMessageReady = true;
}
private class Context {
final Charset charset;
final Encoding bodyEncoding;
public Context() {
charset = JavamailMessage.this.charset;
bodyEncoding = JavamailMessage.this.bodyEncoding;
}
}
private class Body extends Context {
final String text;
public Body(String text) {
this.text = text;
}
}
}
| better message
| modules/javamail/src/main/java/net/emphased/malle/javamail/JavamailMessage.java | better message | <ide><path>odules/javamail/src/main/java/net/emphased/malle/javamail/JavamailMessage.java
<ide> for (int i = 0; i < len; i++) {
<ide> Object key = context[i * 2];
<ide> if (!(key instanceof String)) {
<del> checkArgument(false, "The key values in 'context' must be of String type");
<add> checkArgument(false, "The keys in 'context' must be of String type");
<ide> }
<ide> Object value = context[i * 2 + 1];
<ide> contextMap.put((String) key, value); |
|
Java | mit | 5a7fe9591913cdfbc67e360c6a7e4b860be732c9 | 0 | hhoang/CanvasAPI,nbutton23/CanvasAPI,Blackchai/CanvasAPI,matthewrice345/CanvasAPI,amozoss/CanvasAPI,instructure/CanvasAPI,bradylarson/CanvasAPI | package com.instructure.canvasapi.model;
import android.os.Parcel;
import com.instructure.canvasapi.utilities.APIHelpers;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Brady Larson
*
* Copyright (c) 2014 Instructure. All rights reserved.
*/
public class Submission extends CanvasModel<Submission>{
private long id;
private String grade;
private double score;
private String submitted_at;
private ArrayList<SubmissionComment> submission_comments = new ArrayList<SubmissionComment>();
private Date commentCreated;
private String mediaContentType;
private String mediaCommentUrl;
private String mediaCommentDisplay;
private ArrayList<Submission> submission_history = new ArrayList<Submission>();
private ArrayList<Attachment> attachments = new ArrayList<Attachment>();
private String body;
private HashMap<String,RubricCriterionRating> rubric_assessment = new HashMap<String, RubricCriterionRating>();
private boolean grade_matches_current_submission;
private String workflow_state;
private String submission_type;
private String preview_url;
private String url;
//Conversation Stuff
private long assignment_id;
private Assignment assignment;
private long user_id;
private long grader_id;
private User user;
//this value could be null. Currently will only be returned when getting the submission for
//a user when the submission_type is discussion_topic
private ArrayList<DiscussionEntry> discussion_entries = new ArrayList<DiscussionEntry>();
///////////////////////////////////////////////////////////////////////////
// Getters and Setters
///////////////////////////////////////////////////////////////////////////
@Override
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUser_id(){return user_id;}
public void setUser_id(long user_id){this.user_id = user_id;}
public ArrayList<SubmissionComment> getComments() {
return submission_comments;
}
public void setComment(ArrayList<SubmissionComment> comment) {
this.submission_comments = comment;
}
public Date getCommentCreated() {
return commentCreated;
}
public void setCommentCreated(Date commentCreated) {
this.commentCreated = commentCreated;
}
public String getMediaContentType() {
return mediaContentType;
}
public void setMediaContentType(String mediaContentType) {
this.mediaContentType = mediaContentType;
}
public String getMediaCommentUrl() {
return mediaCommentUrl;
}
public void setMediaCommentUrl(String mediaCommentUrl) {
this.mediaCommentUrl = mediaCommentUrl;
}
public String getMediaCommentDisplay() {
return mediaCommentDisplay;
}
public void setMediaCommentDisplay(String mediaCommentDisplay) {
this.mediaCommentDisplay = mediaCommentDisplay;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public long getAssignment_id() {return assignment_id;}
public void setAssignment_id(long assignment_id) {this.assignment_id = assignment_id;}
public Assignment getAssignment(){
return assignment;
}
public void setAssignment(Assignment assignment){this.assignment = assignment;}
public long getGraderID(){
return grader_id;
}
public Date getSubmitDate() {
if(submitted_at == null) {
return null;
}
return APIHelpers.stringToDate(submitted_at);
}
public void setSubmitDate(String submitDate) {
if(submitDate == null) {
this.submitted_at = null;
}
else {
this.submitted_at = submitDate;
}
}
public void setSubmissionHistory(ArrayList<Submission> history) {
this.submission_history = history;
}
public ArrayList<Submission> getSubmissionHistory() {
return submission_history;
}
public ArrayList<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(ArrayList<Attachment> attachments) {
this.attachments = attachments;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean isGradeMatchesCurrentSubmission() {
return grade_matches_current_submission;
}
public void setGradeMatchesCurrentSubmission(
boolean gradeMatchesCurrentSubmission) {
this.grade_matches_current_submission = gradeMatchesCurrentSubmission;
}
public String getWorkflowState() {
return workflow_state;
}
public void setWorkflowState(String workflowState) {
this.workflow_state = workflowState;
}
public String getSubmissionType() {
return submission_type;
}
public void setSubmissionType(String submissionType) {
this.submission_type = submissionType;
}
public String getPreviewUrl() {
return preview_url;
}
public void setPreviewUrl(String previewUrl) {
this.preview_url = previewUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public RubricAssessment getRubricAssessment() {
RubricAssessment assessment = new RubricAssessment();
ArrayList<RubricCriterionRating> ratings = new ArrayList<RubricCriterionRating>();
if (rubric_assessment != null) {
for (Map.Entry<String, RubricCriterionRating> entry : rubric_assessment.entrySet()) {
RubricCriterionRating rating = entry.getValue();
rating.setCriterionId(entry.getKey());
ratings.add(rating);
}
}
assessment.setRatings(ratings);
return assessment;
}
public ArrayList<DiscussionEntry> getDiscussion_entries() {
return discussion_entries;
}
public void setDiscussion_entries(ArrayList<DiscussionEntry> discussion_entries) {
this.discussion_entries = discussion_entries;
}
///////////////////////////////////////////////////////////////////////////
// Required Overrides
///////////////////////////////////////////////////////////////////////////
@Override
public Date getComparisonDate() {
return getSubmitDate();
}
@Override
public String getComparisonString() {
return getSubmissionType();
}
///////////////////////////////////////////////////////////////////////////
// Constructors
///////////////////////////////////////////////////////////////////////////
public Submission() {}
///////////////////////////////////////////////////////////////////////////
// Helpers
///////////////////////////////////////////////////////////////////////////
public ArrayList<Long> getUserIds()
{
ArrayList<Long> ids = new ArrayList<Long>();
for(int i = 0; i < submission_comments.size(); i++)
{
ids.add(submission_comments.get(i).getAuthorID());
}
return ids;
}
/*
* Submissions will have dummy submissions if they grade an assignment with no actual submissions.
* We want to see if any are not dummy submissions
*/
public boolean hasRealSubmission(){
for(Submission submission : submission_history){
if(submission.getSubmissionType() != null){
return true;
}
}
return false;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeString(this.grade);
dest.writeDouble(this.score);
dest.writeString(this.submitted_at);
dest.writeList(this.submission_comments);
dest.writeLong(commentCreated != null ? commentCreated.getTime() : -1);
dest.writeString(this.mediaContentType);
dest.writeString(this.mediaCommentUrl);
dest.writeString(this.mediaCommentDisplay);
dest.writeList(this.submission_history);
dest.writeList(this.attachments);
dest.writeString(this.body);
dest.writeSerializable(this.rubric_assessment);
dest.writeByte(grade_matches_current_submission ? (byte) 1 : (byte) 0);
dest.writeString(this.workflow_state);
dest.writeString(this.submission_type);
dest.writeString(this.preview_url);
dest.writeString(this.url);
dest.writeParcelable(this.assignment, flags);
dest.writeLong(this.user_id);
dest.writeLong(this.grader_id);
dest.writeLong(this.assignment_id);
dest.writeParcelable(this.user, flags);
}
private Submission(Parcel in) {
this.assignment = new Assignment();
this.id = in.readLong();
this.grade = in.readString();
this.score = in.readDouble();
this.submitted_at = in.readString();
in.readList(this.submission_comments, SubmissionComment.class.getClassLoader());
long tmpCommentCreated = in.readLong();
this.commentCreated = tmpCommentCreated == -1 ? null : new Date(tmpCommentCreated);
this.mediaContentType = in.readString();
this.mediaCommentUrl = in.readString();
this.mediaCommentDisplay = in.readString();
in.readList(this.submission_history, Submission.class.getClassLoader());
in.readList(this.attachments, Attachment.class.getClassLoader());
this.body = in.readString();
this.rubric_assessment =(HashMap<String,RubricCriterionRating>) in.readSerializable();
this.grade_matches_current_submission = in.readByte() != 0;
this.workflow_state = in.readString();
this.submission_type = in.readString();
this.preview_url = in.readString();
this.url = in.readString();
this.assignment = in.readParcelable(Assignment.class.getClassLoader());
this.user_id = in.readLong();
this.grader_id = in.readLong();
this.assignment_id = in.readLong();
this.user = in.readParcelable(User.class.getClassLoader());
}
public static Creator<Submission> CREATOR = new Creator<Submission>() {
public Submission createFromParcel(Parcel source) {
return new Submission(source);
}
public Submission[] newArray(int size) {
return new Submission[size];
}
};
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| src/main/java/com/instructure/canvasapi/model/Submission.java | package com.instructure.canvasapi.model;
import android.os.Parcel;
import com.instructure.canvasapi.utilities.APIHelpers;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Brady Larson
*
* Copyright (c) 2014 Instructure. All rights reserved.
*/
public class Submission extends CanvasModel<Submission>{
private long id;
private String grade;
private double score;
private String submitted_at;
private ArrayList<SubmissionComment> submission_comments = new ArrayList<SubmissionComment>();
private Date commentCreated;
private String mediaContentType;
private String mediaCommentUrl;
private String mediaCommentDisplay;
private ArrayList<Submission> submission_history = new ArrayList<Submission>();
private ArrayList<Attachment> attachments = new ArrayList<Attachment>();
private String body;
private HashMap<String,RubricCriterionRating> rubric_assessment = new HashMap<String, RubricCriterionRating>();
private boolean grade_matches_current_submission;
private String workflow_state;
private String submission_type;
private String preview_url;
private String url;
//Conversation Stuff
private long assignment_id;
private Assignment assignment;
private long user_id;
private long grader_id;
private User user;
///////////////////////////////////////////////////////////////////////////
// Getters and Setters
///////////////////////////////////////////////////////////////////////////
@Override
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUser_id(){return user_id;}
public void setUser_id(long user_id){this.user_id = user_id;}
public ArrayList<SubmissionComment> getComments() {
return submission_comments;
}
public void setComment(ArrayList<SubmissionComment> comment) {
this.submission_comments = comment;
}
public Date getCommentCreated() {
return commentCreated;
}
public void setCommentCreated(Date commentCreated) {
this.commentCreated = commentCreated;
}
public String getMediaContentType() {
return mediaContentType;
}
public void setMediaContentType(String mediaContentType) {
this.mediaContentType = mediaContentType;
}
public String getMediaCommentUrl() {
return mediaCommentUrl;
}
public void setMediaCommentUrl(String mediaCommentUrl) {
this.mediaCommentUrl = mediaCommentUrl;
}
public String getMediaCommentDisplay() {
return mediaCommentDisplay;
}
public void setMediaCommentDisplay(String mediaCommentDisplay) {
this.mediaCommentDisplay = mediaCommentDisplay;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public long getAssignment_id() {return assignment_id;}
public void setAssignment_id(long assignment_id) {this.assignment_id = assignment_id;}
public Assignment getAssignment(){
return assignment;
}
public void setAssignment(Assignment assignment){this.assignment = assignment;}
public long getGraderID(){
return grader_id;
}
public Date getSubmitDate() {
if(submitted_at == null) {
return null;
}
return APIHelpers.stringToDate(submitted_at);
}
public void setSubmitDate(String submitDate) {
if(submitDate == null) {
this.submitted_at = null;
}
else {
this.submitted_at = submitDate;
}
}
public void setSubmissionHistory(ArrayList<Submission> history) {
this.submission_history = history;
}
public ArrayList<Submission> getSubmissionHistory() {
return submission_history;
}
public ArrayList<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(ArrayList<Attachment> attachments) {
this.attachments = attachments;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean isGradeMatchesCurrentSubmission() {
return grade_matches_current_submission;
}
public void setGradeMatchesCurrentSubmission(
boolean gradeMatchesCurrentSubmission) {
this.grade_matches_current_submission = gradeMatchesCurrentSubmission;
}
public String getWorkflowState() {
return workflow_state;
}
public void setWorkflowState(String workflowState) {
this.workflow_state = workflowState;
}
public String getSubmissionType() {
return submission_type;
}
public void setSubmissionType(String submissionType) {
this.submission_type = submissionType;
}
public String getPreviewUrl() {
return preview_url;
}
public void setPreviewUrl(String previewUrl) {
this.preview_url = previewUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public RubricAssessment getRubricAssessment() {
RubricAssessment assessment = new RubricAssessment();
ArrayList<RubricCriterionRating> ratings = new ArrayList<RubricCriterionRating>();
if (rubric_assessment != null) {
for (Map.Entry<String, RubricCriterionRating> entry : rubric_assessment.entrySet()) {
RubricCriterionRating rating = entry.getValue();
rating.setCriterionId(entry.getKey());
ratings.add(rating);
}
}
assessment.setRatings(ratings);
return assessment;
}
///////////////////////////////////////////////////////////////////////////
// Required Overrides
///////////////////////////////////////////////////////////////////////////
@Override
public Date getComparisonDate() {
return getSubmitDate();
}
@Override
public String getComparisonString() {
return getSubmissionType();
}
///////////////////////////////////////////////////////////////////////////
// Constructors
///////////////////////////////////////////////////////////////////////////
public Submission() {}
///////////////////////////////////////////////////////////////////////////
// Helpers
///////////////////////////////////////////////////////////////////////////
public ArrayList<Long> getUserIds()
{
ArrayList<Long> ids = new ArrayList<Long>();
for(int i = 0; i < submission_comments.size(); i++)
{
ids.add(submission_comments.get(i).getAuthorID());
}
return ids;
}
/*
* Submissions will have dummy submissions if they grade an assignment with no actual submissions.
* We want to see if any are not dummy submissions
*/
public boolean hasRealSubmission(){
for(Submission submission : submission_history){
if(submission.getSubmissionType() != null){
return true;
}
}
return false;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeString(this.grade);
dest.writeDouble(this.score);
dest.writeString(this.submitted_at);
dest.writeList(this.submission_comments);
dest.writeLong(commentCreated != null ? commentCreated.getTime() : -1);
dest.writeString(this.mediaContentType);
dest.writeString(this.mediaCommentUrl);
dest.writeString(this.mediaCommentDisplay);
dest.writeList(this.submission_history);
dest.writeList(this.attachments);
dest.writeString(this.body);
dest.writeSerializable(this.rubric_assessment);
dest.writeByte(grade_matches_current_submission ? (byte) 1 : (byte) 0);
dest.writeString(this.workflow_state);
dest.writeString(this.submission_type);
dest.writeString(this.preview_url);
dest.writeString(this.url);
dest.writeParcelable(this.assignment, flags);
dest.writeLong(this.user_id);
dest.writeLong(this.grader_id);
dest.writeLong(this.assignment_id);
dest.writeParcelable(this.user, flags);
}
private Submission(Parcel in) {
this.assignment = new Assignment();
this.id = in.readLong();
this.grade = in.readString();
this.score = in.readDouble();
this.submitted_at = in.readString();
in.readList(this.submission_comments, SubmissionComment.class.getClassLoader());
long tmpCommentCreated = in.readLong();
this.commentCreated = tmpCommentCreated == -1 ? null : new Date(tmpCommentCreated);
this.mediaContentType = in.readString();
this.mediaCommentUrl = in.readString();
this.mediaCommentDisplay = in.readString();
in.readList(this.submission_history, Submission.class.getClassLoader());
in.readList(this.attachments, Attachment.class.getClassLoader());
this.body = in.readString();
this.rubric_assessment =(HashMap<String,RubricCriterionRating>) in.readSerializable();
this.grade_matches_current_submission = in.readByte() != 0;
this.workflow_state = in.readString();
this.submission_type = in.readString();
this.preview_url = in.readString();
this.url = in.readString();
this.assignment = in.readParcelable(Assignment.class.getClassLoader());
this.user_id = in.readLong();
this.grader_id = in.readLong();
this.assignment_id = in.readLong();
this.user = in.readParcelable(User.class.getClassLoader());
}
public static Creator<Submission> CREATOR = new Creator<Submission>() {
public Submission createFromParcel(Parcel source) {
return new Submission(source);
}
public Submission[] newArray(int size) {
return new Submission[size];
}
};
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| Added discussion_entries to Submission.
| src/main/java/com/instructure/canvasapi/model/Submission.java | Added discussion_entries to Submission. | <ide><path>rc/main/java/com/instructure/canvasapi/model/Submission.java
<ide> private long user_id;
<ide> private long grader_id;
<ide> private User user;
<add>
<add> //this value could be null. Currently will only be returned when getting the submission for
<add> //a user when the submission_type is discussion_topic
<add> private ArrayList<DiscussionEntry> discussion_entries = new ArrayList<DiscussionEntry>();
<add>
<ide> ///////////////////////////////////////////////////////////////////////////
<ide> // Getters and Setters
<ide> ///////////////////////////////////////////////////////////////////////////
<ide> }
<ide> assessment.setRatings(ratings);
<ide> return assessment;
<add> }
<add>
<add> public ArrayList<DiscussionEntry> getDiscussion_entries() {
<add> return discussion_entries;
<add> }
<add>
<add> public void setDiscussion_entries(ArrayList<DiscussionEntry> discussion_entries) {
<add> this.discussion_entries = discussion_entries;
<ide> }
<ide>
<ide> /////////////////////////////////////////////////////////////////////////// |
|
Java | bsd-3-clause | 2f561056be298ef860bd6cdbd3003ebf15f2d4a1 | 0 | lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon | /*
* $Id$
*
Copyright (c) 2012 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.util.zip.*;
import okhttp3.Cache;
import org.apache.commons.io.IOUtils;
import org.lockss.test.*;
import org.lockss.daemon.*;
import org.lockss.plugin.simulated.*;
import org.lockss.util.*;
import org.lockss.app.*;
import org.lockss.config.*;
/**
* Utilities for manipulating plugins and their components in tests
*/
public class PluginTestUtil {
static Logger log = Logger.getLogger("PluginTestUtil");
static List aulist = new LinkedList();
public static void registerArchivalUnit(Plugin plug, ArchivalUnit au) {
PluginManager mgr = getPluginManager();
log.debug3(mgr.toString());
String plugid = au.getPluginId();
log.debug("registerArchivalUnit plugin = " + plug +
"au = " + au);
if (plug != mgr.getPlugin(plugid)) {
try {
PrivilegedAccessor.invokeMethod(mgr, "setPlugin",
ListUtil.list(plugid, plug).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
}
PluginTestable tp = (PluginTestable)plug;
tp.registerArchivalUnit(au);
try {
PrivilegedAccessor.invokeMethod(mgr, "putAuInMap",
ListUtil.list(au).toArray());
} catch (InvocationTargetException e) {
log.error("Couldn't register AU", e);
log.error("Nested", e.getTargetException());
throw new RuntimeException(e.toString());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
aulist.add(au);
}
public static void registerArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
log.debug("registerArchivalUnit id = " + au.getAuId() +
", pluginid = " + plugid + ", plugin = " + plug);
if (plug == null) {
MockPlugin mp = new MockPlugin();
mp.setPluginId(plugid);
plug = mp;
}
registerArchivalUnit(plug, au);
}
/*
public static void registerArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
log.debug(mgr.toString());
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
log.debug("registerArchivalUnit id = " + au.getAuId() +
", pluginid = " + plugid + ", plugin = " + plug);
if (plug == null) {
MockPlugin mp = new MockPlugin();
mp.setPluginId(plugid);
plug = mp;
try {
PrivilegedAccessor.invokeMethod(mgr, "setPlugin",
ListUtil.list(plugid, mp).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
}
PluginTestable tp = (PluginTestable)plug;
tp.registerArchivalUnit(au);
try {
PrivilegedAccessor.invokeMethod(mgr, "putAuMap",
ListUtil.list(plug, au).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
aulist.add(au);
}
*/
public static void unregisterArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
if (plug != null) {
PluginTestable tp = (PluginTestable)plug;
tp.unregisterArchivalUnit(au);
aulist.remove(au);
}
mgr.stopAu(au, new AuEvent(AuEvent.Type.Delete, false));
}
public static void unregisterAllArchivalUnits() {
log.debug("unregisterAllArchivalUnits()");
List aus = new ArrayList(aulist);
for (Iterator iter = aus.iterator(); iter.hasNext(); ) {
unregisterArchivalUnit((ArchivalUnit)iter.next());
}
}
public static Plugin findPlugin(String pluginName) {
PluginManager pluginMgr = getPluginManager();
String key = pluginMgr.pluginKeyFromName(pluginName);
pluginMgr.ensurePluginLoaded(key);
return pluginMgr.getPlugin(key);
}
public static Plugin findPlugin(Class pluginClass) {
return findPlugin(pluginClass.getName());
}
public static ArchivalUnit createAu(Plugin plugin,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return getPluginManager().createAu(plugin, auConfig,
new AuEvent(AuEvent.Type.Create, false));
}
public static ArchivalUnit createAndStartAu(Plugin plugin,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(plugin, auConfig));
}
static ArchivalUnit startAu(ArchivalUnit au) {
LockssDaemon daemon = au.getPlugin().getDaemon();
daemon.getHistoryRepository(au).startService();
daemon.getLockssRepository(au).startService();
daemon.getNodeManager(au).startService();
return au;
}
public static ArchivalUnit createAu(String pluginName,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAu(findPlugin(pluginName), auConfig);
}
public static ArchivalUnit createAndStartAu(String pluginName,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartAu(findPlugin(pluginName), auConfig);
}
public static ArchivalUnit createAu(Class pluginClass,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAu(findPlugin(pluginClass.getName()), auConfig);
}
public static ArchivalUnit createAndStartAu(Class pluginClass,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartAu(findPlugin(pluginClass.getName()), auConfig);
}
public static SimulatedArchivalUnit createSimAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return (SimulatedArchivalUnit)createAu(findPlugin(SimulatedPlugin.class),
auConfig);
}
static Configuration getAuConfig(TdbAu tau) {
PluginManager mgr = getPluginManager();
Plugin plugin = tau.getPlugin(mgr);
TitleConfig tc = new TitleConfig(tau, plugin);
return tc.getConfig();
}
public static ArchivalUnit createAu(TdbAu tau)
throws ArchivalUnit.ConfigurationException {
PluginManager mgr = getPluginManager();
Plugin plugin = findPlugin(tau.getPluginId());
return createAu(plugin, getAuConfig(tau));
}
public static ArchivalUnit createAu(Plugin plugin, TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return createAu(plugin, getAuConfig(tau));
}
public static ArchivalUnit createAndStartAu(TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(tau));
}
public static ArchivalUnit createAndStartAu(Plugin plugin, TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(plugin, tau));
}
public static SimulatedArchivalUnit
createAndStartSimAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartSimAu(SimulatedPlugin.class, auConfig);
}
public static SimulatedArchivalUnit
createAndStartSimAu(Class pluginClass, Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return (SimulatedArchivalUnit)createAndStartAu(pluginClass, auConfig);
}
public static void crawlSimAu(SimulatedArchivalUnit sau) {
if (!sau.hasContentTree()) {
// log.debug("Creating simulated content tree: " + sau.getParamMap());
sau.generateContentTree();
}
log.debug("Crawling simulated content");
NoCrawlEndActionsFollowLinkCrawler crawler =
new NoCrawlEndActionsFollowLinkCrawler(sau, new MockAuState());
//crawler.setCrawlManager(crawlMgr);
crawler.doCrawl();
}
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu) throws MalformedURLException {
return copyAu(fromAu, toAu, null, null, null);
}
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu,
String ifMatch) throws MalformedURLException {
return copyAu(fromAu, toAu, ifMatch, null, null);
}
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu,
String ifMatch, String pat, String rep) throws MalformedURLException {
return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, pat, rep);
}
public static boolean copyAu(ArchivalUnit fromAu,
ArchivalUnit toAu,
String ifMatch,
List<PatternReplacementPair> patRepPairs) throws MalformedURLException {
return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, patRepPairs);
}
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu) throws MalformedURLException {
return copyCus(fromCus, toAu, null, null, null);
}
/**
* Utility to copy zip files from a simulated crawl to a mock archival unit.
* if only fromAu and toAu are provided, all zips encountered are copied without modification.
*
* @param fromCus
* @param toAu
* @param ifMatch
* @param pat
* @param rep
* @return true if all files copied, false otherwise
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
String ifMatch, String pat, String rep) {
boolean res = true;
ArchivalUnit fromAu = fromCus.getArchivalUnit();
Pattern pattern = null;
if (pat != null) {
pattern = Pattern.compile(pat);
}
Pattern ifMatchPat = null;
if (ifMatch != null) {
ifMatchPat = Pattern.compile(ifMatch);
}
for (CachedUrl cu : fromCus.getCuIterable()) {
try {
String fromUrl = cu.getUrl();
String toUrl = fromUrl;
if (ifMatchPat != null) {
Matcher mat = ifMatchPat.matcher(fromUrl);
if (!mat.find()) {
log.debug3("no match: " + fromUrl + ", " + ifMatchPat);
continue;
}
}
if (pattern != null) {
Matcher mat = pattern.matcher(fromUrl);
toUrl = mat.replaceAll(rep);
}
doCopyCu(cu, toAu, fromUrl, toUrl);
if (!toUrl.equals(fromUrl)) {
log.debug2("Copied " + fromUrl + " to " + toUrl);
} else {
log.debug2("Copied " + fromUrl);
}
} catch (Exception e) {
log.error("Couldn't copy " + cu.getUrl(), e);
res = false;
} finally {
cu.release();
}
}
return res;
}
/**
* Overloaded method of copyCus which takes pattern-replacement set
*
* @param fromCus the CachedUrlSet which has been crawled
* @param toAu the Archival Unit to copy content to
* @param patRepPairs A List of PatternReplacementPairs to selectively copy zipped content and rename it in the new zip.
* @return true, if all copies attempted succeeded, false otherwise
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
String ifMatch, List<PatternReplacementPair> patRepPairs)
throws MalformedURLException {
boolean res = true;
ArchivalUnit fromAu = fromCus.getArchivalUnit();
Pattern ifMatchPat = null;
if (ifMatch != null) {
ifMatchPat = Pattern.compile(ifMatch);
}
String isArchive;
for (CachedUrl cu : fromCus.getCuIterable()) {
try {
String fromUrl = cu.getUrl();
String toUrl = fromUrl;
if (ifMatchPat != null) {
Matcher mat = ifMatchPat.matcher(fromUrl);
if (!mat.find()) {
log.debug3("no match: " + fromUrl + ", " + ifMatchPat);
continue;
}
}
isArchive = toAu.getArchiveFileTypes().getFromCu(cu);
if (isArchive == null) {
if (patRepPairs != null) {
for (PatternReplacementPair prp : patRepPairs) {
Matcher mat = prp.pat.matcher(fromUrl);
toUrl = mat.replaceAll(prp.rep);
if (fromUrl != toUrl) {
doCopyCu(cu, toAu, fromUrl, toUrl);
break;
}
}
} else {
doCopyCu(cu, toAu, fromUrl, toUrl);
}
} else {
switch (isArchive) {
case ".zip":
copyZip(cu, toAu, patRepPairs);
break;
case ".tar":
//TODO
log.info("support for .tar coming");
break;
case ".tar.gz":
case ".tgz":
//TODO
log.info("support for .tgz coming");
break;
default:
throw new Exception("Unexpected Archive file type: '" + isArchive + "'");
}
}
} catch (Exception e) {
log.error("Couldn't copy " + cu.getUrl(), e);
res = false;
} finally {
cu.release();
}
}
return res;
}
private static void doCopyCu(CachedUrl cu,
ArchivalUnit toAu,
String fromUrl,
String toUrl
) throws IOException {
CIProperties props = cu.getProperties();
if (props == null) {
log.debug3("in copyCus() props was null for url: " + fromUrl);
}
UrlCacher uc = toAu.makeUrlCacher(
new UrlData(cu.getUnfilteredInputStream(), props, toUrl));
uc.storeContent();
if (!toUrl.equals(fromUrl)) {
log.info("Copied " + fromUrl + " to " + toUrl);
} else {
log.debug2("Copied " + fromUrl);
}
}
/**
* TODO: Take the plugin as param and check it for which types of files to see as archives
* e.g. toAu.getArchiveFileTypes().getFromCu(cu)
* if null
* copy cu as normal
* elsif in map:
* switch :
* zip - use the copyzip
* tar - either figure it out or Throw an error
* com.ice.tar.TarInputStream
* tgz - ibid
* double wrap - unwrap gzip, then TarInputStream
* else:
* Throw error
*/
/**
* Opens a single CachedUrl zip file, iterates over its contents and copies the contents if they pass
* given pattern(s) and replacements.
* @param cu A CachedUrl of compressed content.
* @param toAu The ArchivalUnit to copy the cu into.
* @param patRepPairs A List of PatternReplacementPairs to selectively copy zipped content and rename it in the new zip.
* @throws IOException When I/O zip files encounter any number of problems.
*/
private static void copyZip(CachedUrl cu, ArchivalUnit toAu, List<PatternReplacementPair> patRepPairs)
throws IOException {
boolean doCache = false;
String zipUrl = cu.getUrl() + "!/";
String toUrl; String toFile; String zippedFile; String fromFile;
ZipInputStream zis = null;
ZipOutputStream zos;
String outZip = null;
try {
InputStream cuis = new ReaderInputStream(cu.openForReading());
zis = new ZipInputStream(cuis);
zos = new ZipOutputStream(Files.newOutputStream(
Paths.get(cu.getArchivalUnit().getProperties().getString("root") +
"temp.zip")));
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(Deflater.BEST_COMPRESSION);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue;
} else if (entry.getName().endsWith(".zip") ) {
// TODO recurse through nested
// zipCopy(cu, toAu, zipUrl + );
}
fromFile = entry.getName();
zippedFile = zipUrl + fromFile;
for (PatternReplacementPair prp : patRepPairs) {
Matcher mat = prp.pat.matcher(zippedFile);
if (mat.find()) {
toUrl = mat.replaceAll(prp.rep);
if (!toUrl.equals(zippedFile)) {
log.debug("Found a zipped file match: " + zippedFile + " -> " + toUrl);
doCache = true;
outZip = toUrl.split("!/")[0];
toFile = toUrl.split("!/")[1];
ZipEntry outEntry = new ZipEntry(toFile);
zos.putNextEntry(outEntry);
StreamUtil.copy(zis, zos);
zos.closeEntry();
}
break;
}
}
}
zos.close();
// any copied file triggers saving the new zip stream
if (doCache) {
FileInputStream is = new FileInputStream(new File(
cu.getArchivalUnit().getProperties().getString("root"),
"temp.zip"));
// save all the copied zip entries to a new zip on the toAu
CIProperties props = cu.getProperties();
if (props == null) {
log.debug3("in copyCus() props was null for url: " + cu.getUrl());
}
log.debug("Storing new cu: " + outZip);
UrlCacher uc = toAu.makeUrlCacher(
new UrlData(is, props, outZip));
uc.storeContent();
is.close();
}
} finally {
IOUtil.safeClose(zis);
}
}
public static List<String> urlsOf(final Iterable<CachedUrl> cus) {
return new ArrayList<String>() {{
for (CachedUrl cu : cus) {
add(cu.getUrl());
}
}};
}
private static PluginManager getPluginManager() {
return
(PluginManager)LockssDaemon.getManager(LockssDaemon.PLUGIN_MANAGER);
}
public static PatternReplacementPair makePatRepPair(String pat, String rep) {
return new PatternReplacementPair(pat , rep);
}
public static class PatternReplacementPair {
public Pattern pat;
public String rep;
/**
* Simple Container class for Regex pattern -> Replacement pairs.
* @param pat String regex, gets compiled to a Pattern
* @param rep Replacement string
*/
PatternReplacementPair(String pat, String rep) {
this.pat = Pattern.compile(pat, Pattern.CASE_INSENSITIVE);
this.rep = rep;
}
}
}
| test/src/org/lockss/plugin/PluginTestUtil.java | /*
* $Id$
*
Copyright (c) 2012 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.util.zip.*;
import okhttp3.Cache;
import org.apache.commons.io.IOUtils;
import org.lockss.test.*;
import org.lockss.daemon.*;
import org.lockss.plugin.simulated.*;
import org.lockss.util.*;
import org.lockss.app.*;
import org.lockss.config.*;
/**
* Utilities for manipulating plugins and their components in tests
*/
public class PluginTestUtil {
static Logger log = Logger.getLogger("PluginTestUtil");
static List aulist = new LinkedList();
static final Pattern COMPRESSED_PATTERN = Pattern.compile(
"\\.(zip|tar\\.gz|tgz)$",
Pattern.CASE_INSENSITIVE
);
public static void registerArchivalUnit(Plugin plug, ArchivalUnit au) {
PluginManager mgr = getPluginManager();
log.debug3(mgr.toString());
String plugid = au.getPluginId();
log.debug("registerArchivalUnit plugin = " + plug +
"au = " + au);
if (plug != mgr.getPlugin(plugid)) {
try {
PrivilegedAccessor.invokeMethod(mgr, "setPlugin",
ListUtil.list(plugid, plug).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
}
PluginTestable tp = (PluginTestable)plug;
tp.registerArchivalUnit(au);
try {
PrivilegedAccessor.invokeMethod(mgr, "putAuInMap",
ListUtil.list(au).toArray());
} catch (InvocationTargetException e) {
log.error("Couldn't register AU", e);
log.error("Nested", e.getTargetException());
throw new RuntimeException(e.toString());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
aulist.add(au);
}
public static void registerArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
log.debug("registerArchivalUnit id = " + au.getAuId() +
", pluginid = " + plugid + ", plugin = " + plug);
if (plug == null) {
MockPlugin mp = new MockPlugin();
mp.setPluginId(plugid);
plug = mp;
}
registerArchivalUnit(plug, au);
}
/*
public static void registerArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
log.debug(mgr.toString());
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
log.debug("registerArchivalUnit id = " + au.getAuId() +
", pluginid = " + plugid + ", plugin = " + plug);
if (plug == null) {
MockPlugin mp = new MockPlugin();
mp.setPluginId(plugid);
plug = mp;
try {
PrivilegedAccessor.invokeMethod(mgr, "setPlugin",
ListUtil.list(plugid, mp).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
}
PluginTestable tp = (PluginTestable)plug;
tp.registerArchivalUnit(au);
try {
PrivilegedAccessor.invokeMethod(mgr, "putAuMap",
ListUtil.list(plug, au).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
aulist.add(au);
}
*/
public static void unregisterArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
if (plug != null) {
PluginTestable tp = (PluginTestable)plug;
tp.unregisterArchivalUnit(au);
aulist.remove(au);
}
mgr.stopAu(au, new AuEvent(AuEvent.Type.Delete, false));
}
public static void unregisterAllArchivalUnits() {
log.debug("unregisterAllArchivalUnits()");
List aus = new ArrayList(aulist);
for (Iterator iter = aus.iterator(); iter.hasNext(); ) {
unregisterArchivalUnit((ArchivalUnit)iter.next());
}
}
public static Plugin findPlugin(String pluginName) {
PluginManager pluginMgr = getPluginManager();
String key = pluginMgr.pluginKeyFromName(pluginName);
pluginMgr.ensurePluginLoaded(key);
return pluginMgr.getPlugin(key);
}
public static Plugin findPlugin(Class pluginClass) {
return findPlugin(pluginClass.getName());
}
public static ArchivalUnit createAu(Plugin plugin,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return getPluginManager().createAu(plugin, auConfig,
new AuEvent(AuEvent.Type.Create, false));
}
public static ArchivalUnit createAndStartAu(Plugin plugin,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(plugin, auConfig));
}
static ArchivalUnit startAu(ArchivalUnit au) {
LockssDaemon daemon = au.getPlugin().getDaemon();
daemon.getHistoryRepository(au).startService();
daemon.getLockssRepository(au).startService();
daemon.getNodeManager(au).startService();
return au;
}
public static ArchivalUnit createAu(String pluginName,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAu(findPlugin(pluginName), auConfig);
}
public static ArchivalUnit createAndStartAu(String pluginName,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartAu(findPlugin(pluginName), auConfig);
}
public static ArchivalUnit createAu(Class pluginClass,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAu(findPlugin(pluginClass.getName()), auConfig);
}
public static ArchivalUnit createAndStartAu(Class pluginClass,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartAu(findPlugin(pluginClass.getName()), auConfig);
}
public static SimulatedArchivalUnit createSimAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return (SimulatedArchivalUnit)createAu(findPlugin(SimulatedPlugin.class),
auConfig);
}
static Configuration getAuConfig(TdbAu tau) {
PluginManager mgr = getPluginManager();
Plugin plugin = tau.getPlugin(mgr);
TitleConfig tc = new TitleConfig(tau, plugin);
return tc.getConfig();
}
public static ArchivalUnit createAu(TdbAu tau)
throws ArchivalUnit.ConfigurationException {
PluginManager mgr = getPluginManager();
Plugin plugin = findPlugin(tau.getPluginId());
return createAu(plugin, getAuConfig(tau));
}
public static ArchivalUnit createAu(Plugin plugin, TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return createAu(plugin, getAuConfig(tau));
}
public static ArchivalUnit createAndStartAu(TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(tau));
}
public static ArchivalUnit createAndStartAu(Plugin plugin, TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(plugin, tau));
}
public static SimulatedArchivalUnit
createAndStartSimAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartSimAu(SimulatedPlugin.class, auConfig);
}
public static SimulatedArchivalUnit
createAndStartSimAu(Class pluginClass, Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return (SimulatedArchivalUnit)createAndStartAu(pluginClass, auConfig);
}
public static void crawlSimAu(SimulatedArchivalUnit sau) {
if (!sau.hasContentTree()) {
// log.debug("Creating simulated content tree: " + sau.getParamMap());
sau.generateContentTree();
}
log.debug("Crawling simulated content");
NoCrawlEndActionsFollowLinkCrawler crawler =
new NoCrawlEndActionsFollowLinkCrawler(sau, new MockAuState());
//crawler.setCrawlManager(crawlMgr);
crawler.doCrawl();
}
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu) throws MalformedURLException {
return copyAu(fromAu, toAu, null, null, null);
}
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu,
String ifMatch) throws MalformedURLException {
return copyAu(fromAu, toAu, ifMatch, null, null);
}
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu,
String ifMatch, String pat, String rep) throws MalformedURLException {
return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, pat, rep);
}
public static boolean copyAu(ArchivalUnit fromAu,
ArchivalUnit toAu,
String ifMatch,
List<PatternReplacementPair> patRepPairs) throws MalformedURLException {
return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, patRepPairs);
}
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu) throws MalformedURLException {
return copyCus(fromCus, toAu, null, null, null);
}
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
String ifMatch, String pat, String rep) throws MalformedURLException {
boolean res = true;
ArchivalUnit fromAu = fromCus.getArchivalUnit();
Pattern pattern = null;
if (pat != null) {
pattern = Pattern.compile(pat);
}
Pattern ifMatchPat = null;
if (ifMatch != null) {
ifMatchPat = Pattern.compile(ifMatch);
}
for (CachedUrl cu : fromCus.getCuIterable()) {
try {
String fromUrl = cu.getUrl();
String toUrl = fromUrl;
if (ifMatchPat != null) {
Matcher mat = ifMatchPat.matcher(fromUrl);
if (!mat.find()) {
log.debug3("no match: " + fromUrl + ", " + ifMatchPat);
continue;
}
}
if (pattern != null) {
Matcher mat = pattern.matcher(fromUrl);
toUrl = mat.replaceAll(rep);
}
doCopyCu(cu, toAu, fromUrl, toUrl);
if (!toUrl.equals(fromUrl)) {
log.debug2("Copied " + fromUrl + " to " + toUrl);
} else {
log.debug2("Copied " + fromUrl);
}
} catch (Exception e) {
log.error("Couldn't copy " + cu.getUrl(), e);
res = false;
} finally {
cu.release();
}
}
return res;
}
/**
* Overloaded method of copyCus which takes pattern-replacement set
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
String ifMatch, List<PatternReplacementPair> patRepPairs)
throws MalformedURLException {
boolean res = true;
ArchivalUnit fromAu = fromCus.getArchivalUnit();
Pattern ifMatchPat = null;
if (ifMatch != null) {
ifMatchPat = Pattern.compile(ifMatch);
}
String isArchive;
for (CachedUrl cu : fromCus.getCuIterable()) {
try {
String fromUrl = cu.getUrl();
String toUrl = fromUrl;
if (ifMatchPat != null) {
Matcher mat = ifMatchPat.matcher(fromUrl);
if (!mat.find()) {
log.debug3("no match: " + fromUrl + ", " + ifMatchPat);
continue;
}
}
isArchive = toAu.getArchiveFileTypes().getFromCu(cu);
if (isArchive == null) {
if (patRepPairs != null) {
for (PatternReplacementPair prp : patRepPairs) {
Matcher mat = prp.pat.matcher(fromUrl);
toUrl = mat.replaceAll(prp.rep);
if (fromUrl != toUrl) {
doCopyCu(cu, toAu, fromUrl, toUrl);
break;
}
}
} else {
doCopyCu(cu, toAu, fromUrl, toUrl);
}
} else {
switch (isArchive) {
case ".zip":
copyZip(cu, toAu, patRepPairs);
break;
case ".tar":
//TODO
log.info("support for .tar coming");
break;
case ".tar.gz":
case ".tgz":
//TODO
log.info("support for .tgz coming");
break;
default:
throw new Exception("Unexpected Archive file type: '" + isArchive + "'");
}
}
} catch (Exception e) {
log.error("Couldn't copy " + cu.getUrl(), e);
res = false;
} finally {
cu.release();
}
}
return res;
}
private static void doCopyCu(CachedUrl cu,
ArchivalUnit toAu,
String fromUrl,
String toUrl
) throws IOException {
CIProperties props = cu.getProperties();
if (props == null) {
log.debug3("in copyCus() props was null for url: " + fromUrl);
}
UrlCacher uc = toAu.makeUrlCacher(
new UrlData(cu.getUnfilteredInputStream(), props, toUrl));
uc.storeContent();
if (!toUrl.equals(fromUrl)) {
log.info("Copied " + fromUrl + " to " + toUrl);
} else {
log.debug2("Copied " + fromUrl);
}
}
/**
* TODO: Take the plugin as param and check it for which types of files to see as archives
* e.g. toAu.getArchiveFileTypes().getFromCu(cu)
* if null
* copy cu as normal
* elsif in map:
* switch :
* zip - use the copyzip
* tar - either figure it out or Throw an error
* com.ice.tar.TarInputStream
* tgz - ibid
* double wrap - unwrap gzip, then TarInputStream
* else:
* Throw error
*/
/**
* Copies all zips in from one crawl into another without modification.
*
*/
public static boolean copyAuZip(ArchivalUnit fromAu, ArchivalUnit toAu) throws MalformedURLException {
return copyZipCus(fromAu.getAuCachedUrlSet(), toAu, null);
}
/**
* Works just like {@link PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List)}.
* Just gets the cachedUrlSet in fromAU and Makes lists from pat & rep.
*
* @see PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List)
*/
public static boolean copyAuZip(ArchivalUnit fromAu, ArchivalUnit toAu, String pat, String rep) throws Exception {
return copyZipCus(fromAu.getAuCachedUrlSet(), toAu, Collections.singletonList(makePatRepPair(pat, rep)));
}
/**
* Works just like {@link PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List)}.
* Just makes lists and adds pat and rep to them.
*
*/
public static boolean copyZipCus(CachedUrlSet fromCus, ArchivalUnit toAu, String pat, String rep) throws Exception {
return copyZipCus(fromCus, toAu, Collections.singletonList(makePatRepPair(pat, rep)));
}
/**
* Utility to copy zip files from a simulated crawl to a mock archival unit.
* if only fromAu and toAu are provided, all zips encountered are copied without modification.
*
* @param fromCus the CachedUrlSet which has been crawled
* @param toAu the Archival Unit to copy content to
* @param patReps A List of PatternReplacementPairs to selectively copy zipped content and rename it in the new zip.
* @return true, if all copies attempted succeeded, false otherwise
*/
private static boolean copyZipCus(CachedUrlSet fromCus, ArchivalUnit toAu, List<PatternReplacementPair> patReps) throws MalformedURLException {
boolean res = true;
for (CachedUrl cu : fromCus.getCuIterable()) {
log.info(toAu.getArchiveFileTypes().getFromCu(cu));
try {
String fromUrl = cu.getUrl();
// only copy the file if it is a zip.
Matcher mat = COMPRESSED_PATTERN.matcher(fromUrl);
if (mat.find()) {
if (patReps!=null) {
log.debug("entering zip file to copy contents");
copyZip(cu, toAu, patReps);
} else {
log.debug("copying unmodified zip");
CIProperties props = cu.getProperties();
UrlCacher uc = toAu.makeUrlCacher(
new UrlData(cu.getUnfilteredInputStream(), props, fromUrl));
uc.storeContent();
}
}
} catch (Exception e) {
log.error("Couldn't copy " + cu.getUrl(), e);
res = false;
} finally {
cu.release();
}
}
return res;
}
/**
* Opens a single CachedUrl zip file, iterates over its contents and copies the contents if they pass
* given pattern(s) and replacements.
* @param cu A CachedUrl of compressed content.
* @param toAu The ArchivalUnit to copy the cu into.
* @param patRepPairs A List of PatternReplacementPairs to selectively copy zipped content and rename it in the new zip.
* @throws IOException When I/O zip files encounter any number of problems.
*/
private static void copyZip(CachedUrl cu, ArchivalUnit toAu, List<PatternReplacementPair> patRepPairs)
throws IOException {
boolean doCache = false;
String zipUrl = cu.getUrl() + "!/";
String toUrl; String toFile; String zippedFile; String fromFile;
ZipInputStream zis = null;
ZipOutputStream zos;
String outZip = null;
try {
InputStream cuis = new ReaderInputStream(cu.openForReading());
zis = new ZipInputStream(cuis);
zos = new ZipOutputStream(Files.newOutputStream(
Paths.get(cu.getArchivalUnit().getProperties().getString("root") +
"temp.zip")));
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(Deflater.BEST_COMPRESSION);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue;
} else if (entry.getName().endsWith(".zip") ) {
// TODO recurse through nested
// zipCopy(cu, toAu, zipUrl + );
}
fromFile = entry.getName();
zippedFile = zipUrl + fromFile;
for (PatternReplacementPair prp : patRepPairs) {
Matcher mat = prp.pat.matcher(zippedFile);
if (mat.find()) {
toUrl = mat.replaceAll(prp.rep);
if (!toUrl.equals(zippedFile)) {
log.debug("Found a zipped file match: " + zippedFile + " -> " + toUrl);
doCache = true;
outZip = toUrl.split("!/")[0];
toFile = toUrl.split("!/")[1];
ZipEntry outEntry = new ZipEntry(toFile);
zos.putNextEntry(outEntry);
StreamUtil.copy(zis, zos);
zos.closeEntry();
}
break;
}
}
}
zos.close();
// any copied file triggers saving the new zip stream
if (doCache) {
FileInputStream is = new FileInputStream(new File(
cu.getArchivalUnit().getProperties().getString("root"),
"temp.zip"));
// save all the copied zip entries to a new zip on the toAu
CIProperties props = cu.getProperties();
if (props == null) {
log.debug3("in copyCus() props was null for url: " + cu.getUrl());
}
log.debug("Storing new cu: " + outZip);
UrlCacher uc = toAu.makeUrlCacher(
new UrlData(is, props, outZip));
uc.storeContent();
is.close();
}
} finally {
IOUtil.safeClose(zis);
}
}
public static List<String> urlsOf(final Iterable<CachedUrl> cus) {
return new ArrayList<String>() {{
for (CachedUrl cu : cus) {
add(cu.getUrl());
}
}};
}
private static PluginManager getPluginManager() {
return
(PluginManager)LockssDaemon.getManager(LockssDaemon.PLUGIN_MANAGER);
}
public static PatternReplacementPair makePatRepPair(String pat, String rep) {
return new PatternReplacementPair(pat , rep);
}
public static class PatternReplacementPair {
public Pattern pat;
public String rep;
/**
* Simple Container class for Regex pattern -> Replacement pairs.
* @param pat String regex, gets compiled to a Pattern
* @param rep Replacement string
*/
PatternReplacementPair(String pat, String rep) {
this.pat = Pattern.compile(pat, Pattern.CASE_INSENSITIVE);
this.rep = rep;
}
}
}
| removed all copy*Zip* specific methods
| test/src/org/lockss/plugin/PluginTestUtil.java | removed all copy*Zip* specific methods | <ide><path>est/src/org/lockss/plugin/PluginTestUtil.java
<ide> public class PluginTestUtil {
<ide> static Logger log = Logger.getLogger("PluginTestUtil");
<ide> static List aulist = new LinkedList();
<del> static final Pattern COMPRESSED_PATTERN = Pattern.compile(
<del> "\\.(zip|tar\\.gz|tgz)$",
<del> Pattern.CASE_INSENSITIVE
<del> );
<ide>
<ide> public static void registerArchivalUnit(Plugin plug, ArchivalUnit au) {
<ide> PluginManager mgr = getPluginManager();
<ide> return copyCus(fromCus, toAu, null, null, null);
<ide> }
<ide>
<add> /**
<add> * Utility to copy zip files from a simulated crawl to a mock archival unit.
<add> * if only fromAu and toAu are provided, all zips encountered are copied without modification.
<add> *
<add> * @param fromCus
<add> * @param toAu
<add> * @param ifMatch
<add> * @param pat
<add> * @param rep
<add> * @return true if all files copied, false otherwise
<add> */
<ide> public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
<del> String ifMatch, String pat, String rep) throws MalformedURLException {
<add> String ifMatch, String pat, String rep) {
<ide> boolean res = true;
<ide> ArchivalUnit fromAu = fromCus.getArchivalUnit();
<ide> Pattern pattern = null;
<ide>
<ide> /**
<ide> * Overloaded method of copyCus which takes pattern-replacement set
<add> *
<add> * @param fromCus the CachedUrlSet which has been crawled
<add> * @param toAu the Archival Unit to copy content to
<add> * @param patRepPairs A List of PatternReplacementPairs to selectively copy zipped content and rename it in the new zip.
<add> * @return true, if all copies attempted succeeded, false otherwise
<ide> */
<ide> public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
<ide> String ifMatch, List<PatternReplacementPair> patRepPairs)
<ide> */
<ide>
<ide> /**
<del> * Copies all zips in from one crawl into another without modification.
<del> *
<del> */
<del> public static boolean copyAuZip(ArchivalUnit fromAu, ArchivalUnit toAu) throws MalformedURLException {
<del> return copyZipCus(fromAu.getAuCachedUrlSet(), toAu, null);
<del> }
<del>
<del> /**
<del> * Works just like {@link PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List)}.
<del> * Just gets the cachedUrlSet in fromAU and Makes lists from pat & rep.
<del> *
<del> * @see PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List)
<del> */
<del> public static boolean copyAuZip(ArchivalUnit fromAu, ArchivalUnit toAu, String pat, String rep) throws Exception {
<del> return copyZipCus(fromAu.getAuCachedUrlSet(), toAu, Collections.singletonList(makePatRepPair(pat, rep)));
<del> }
<del>
<del>
<del> /**
<del> * Works just like {@link PluginTestUtil#copyZipCus(CachedUrlSet, ArchivalUnit, List)}.
<del> * Just makes lists and adds pat and rep to them.
<del> *
<del> */
<del> public static boolean copyZipCus(CachedUrlSet fromCus, ArchivalUnit toAu, String pat, String rep) throws Exception {
<del> return copyZipCus(fromCus, toAu, Collections.singletonList(makePatRepPair(pat, rep)));
<del> }
<del>
<del> /**
<del> * Utility to copy zip files from a simulated crawl to a mock archival unit.
<del> * if only fromAu and toAu are provided, all zips encountered are copied without modification.
<del> *
<del> * @param fromCus the CachedUrlSet which has been crawled
<del> * @param toAu the Archival Unit to copy content to
<del> * @param patReps A List of PatternReplacementPairs to selectively copy zipped content and rename it in the new zip.
<del> * @return true, if all copies attempted succeeded, false otherwise
<del> */
<del> private static boolean copyZipCus(CachedUrlSet fromCus, ArchivalUnit toAu, List<PatternReplacementPair> patReps) throws MalformedURLException {
<del> boolean res = true;
<del> for (CachedUrl cu : fromCus.getCuIterable()) {
<del> log.info(toAu.getArchiveFileTypes().getFromCu(cu));
<del> try {
<del> String fromUrl = cu.getUrl();
<del> // only copy the file if it is a zip.
<del> Matcher mat = COMPRESSED_PATTERN.matcher(fromUrl);
<del> if (mat.find()) {
<del> if (patReps!=null) {
<del> log.debug("entering zip file to copy contents");
<del> copyZip(cu, toAu, patReps);
<del> } else {
<del> log.debug("copying unmodified zip");
<del> CIProperties props = cu.getProperties();
<del> UrlCacher uc = toAu.makeUrlCacher(
<del> new UrlData(cu.getUnfilteredInputStream(), props, fromUrl));
<del> uc.storeContent();
<del> }
<del> }
<del> } catch (Exception e) {
<del> log.error("Couldn't copy " + cu.getUrl(), e);
<del> res = false;
<del> } finally {
<del> cu.release();
<del> }
<del> }
<del> return res;
<del> }
<del>
<del> /**
<ide> * Opens a single CachedUrl zip file, iterates over its contents and copies the contents if they pass
<ide> * given pattern(s) and replacements.
<ide> * @param cu A CachedUrl of compressed content. |
|
Java | agpl-3.0 | e7ce62fda1f7c3ac96876149e499e1a8c8ee5b73 | 0 | where2help/android | package app.iamin.iamin.ui;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.otto.Subscribe;
import app.iamin.iamin.BusProvider;
import app.iamin.iamin.LoginTask;
import app.iamin.iamin.R;
import app.iamin.iamin.RegisterTask;
import app.iamin.iamin.event.LoginEvent;
import app.iamin.iamin.event.RegisterEvent;
import app.iamin.iamin.util.UiUtils;
public class LoginActivity extends AppCompatActivity {
private static final int UI_MODE_LOGIN = 0;
private static final int UI_MODE_PROGRESS = 1;
private int uiMode = UI_MODE_LOGIN;
TextView titleTextView;
TextView descTextView;
EditText emailEditText;
EditText passwordEditText;
LinearLayout userScreen;
LinearLayout progressScreen;
LinearLayout btnBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userScreen = (LinearLayout) findViewById(R.id.login_screen);
progressScreen = (LinearLayout) findViewById(R.id.progress_screen);
titleTextView = (TextView) findViewById(R.id.header_title);
descTextView = (TextView) findViewById(R.id.header_desc);
emailEditText = (EditText) findViewById(R.id.email);
passwordEditText = (EditText) findViewById(R.id.password);
btnBar = (LinearLayout) findViewById(R.id.btnBar);
setUiMode(uiMode);
}
private void setUiMode(int uiMode) {
switch(uiMode) {
case UI_MODE_LOGIN:
userScreen.setVisibility(View.VISIBLE);
progressScreen.setVisibility(View.GONE);
emailEditText.setVisibility(View.VISIBLE);
passwordEditText.setVisibility(View.VISIBLE);
btnBar.setVisibility(View.VISIBLE);
titleTextView.setText(R.string.welcome);
descTextView.setText(R.string.login_message);
break;
case UI_MODE_PROGRESS:
userScreen.setVisibility(View.GONE);
progressScreen.setVisibility(View.VISIBLE);
break;
}
}
@Override
protected void onResume() {
super.onResume();
BusProvider.getInstance().register(this);
}
@Override
public void onPause() {
super.onPause();
BusProvider.getInstance().unregister(this);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
public void onActionRegister(View view) {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
new RegisterTask(email, password, password).execute(this);
setUiMode(UI_MODE_PROGRESS);
}
}
public void onActionLogin(View view) {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
new LoginTask(email, password).execute(this);
setUiMode(UI_MODE_PROGRESS);
}
}
@Subscribe
public void onRegisterUpdate(RegisterEvent event) {
boolean isSuccsess = event.isSuccsess(); // TODO: Handle errors
if (isSuccsess) {
findViewById(R.id.btn_register).setVisibility(View.GONE);
Toast.makeText(this, "SUCCSESS... LOG IN!", Toast.LENGTH_LONG).show();
setUiMode(UI_MODE_LOGIN);
}
}
@Subscribe
public void onLoginUpdate(LoginEvent event) {
boolean isSuccsess = event.isSuccsess(); // TODO: Handle errors
if (isSuccsess) {
// TODO: Launch MainActivity
UiUtils.fireMainIntent(this);
// overridePendingTransition(R.anim.enter_right, R.anim.leave_left);
finish();
}
}
} | app/src/main/java/app/iamin/iamin/ui/LoginActivity.java | package app.iamin.iamin.ui;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.otto.Subscribe;
import app.iamin.iamin.BusProvider;
import app.iamin.iamin.LoginTask;
import app.iamin.iamin.R;
import app.iamin.iamin.RegisterTask;
import app.iamin.iamin.event.LoginEvent;
import app.iamin.iamin.event.RegisterEvent;
import app.iamin.iamin.util.UiUtils;
public class LoginActivity extends AppCompatActivity {
private static final int UI_MODE_LOGIN = 0;
private static final int UI_MODE_PROGRESS = 1;
private int uiMode = UI_MODE_LOGIN;
TextView titleTextView;
TextView descTextView;
EditText emailEditText;
EditText passwordEditText;
LinearLayout userScreen;
LinearLayout progressScreen;
LinearLayout btnBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userScreen = (LinearLayout) findViewById(R.id.login_screen);
progressScreen = (LinearLayout) findViewById(R.id.progress_screen);
titleTextView = (TextView) findViewById(R.id.header_title);
descTextView = (TextView) findViewById(R.id.header_desc);
emailEditText = (EditText) findViewById(R.id.email);
passwordEditText = (EditText) findViewById(R.id.password);
btnBar = (LinearLayout) findViewById(R.id.btnBar);
setUiMode(uiMode);
}
private void setUiMode(int uiMode) {
switch(uiMode) {
case UI_MODE_LOGIN:
userScreen.setVisibility(View.VISIBLE);
progressScreen.setVisibility(View.GONE);
emailEditText.setVisibility(View.VISIBLE);
passwordEditText.setVisibility(View.VISIBLE);
btnBar.setVisibility(View.VISIBLE);
titleTextView.setText(R.string.welcome);
descTextView.setText(R.string.login_message);
break;
case UI_MODE_PROGRESS:
userScreen.setVisibility(View.GONE);
progressScreen.setVisibility(View.VISIBLE);
break;
}
}
@Override
protected void onResume() {
super.onResume();
BusProvider.getInstance().register(this);
}
@Override
public void onPause() {
super.onPause();
BusProvider.getInstance().unregister(this);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
public void onActionRegister(View view) {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
new RegisterTask(email, password, password).execute(this);
setUiMode(UI_MODE_PROGRESS);
}
}
public void onActionLogin(View view) {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
new LoginTask(email, password).execute(this);
setUiMode(UI_MODE_PROGRESS);
}
}
@Subscribe
public void onRegisterUpdate(RegisterEvent event) {
boolean isSuccsess = event.isSuccsess(); // TODO: Handle errors
if (isSuccsess) {
Toast.makeText(this, "SUCCSESS... LOG IN!", Toast.LENGTH_LONG).show();
setUiMode(UI_MODE_LOGIN);
}
}
@Subscribe
public void onLoginUpdate(LoginEvent event) {
boolean isSuccsess = event.isSuccsess(); // TODO: Handle errors
if (isSuccsess) {
// TODO: Launch MainActivity
UiUtils.fireMainIntent(this);
// overridePendingTransition(R.anim.enter_right, R.anim.leave_left);
finish();
}
}
} | Hide btn_register after user signs up
| app/src/main/java/app/iamin/iamin/ui/LoginActivity.java | Hide btn_register after user signs up | <ide><path>pp/src/main/java/app/iamin/iamin/ui/LoginActivity.java
<ide> public void onRegisterUpdate(RegisterEvent event) {
<ide> boolean isSuccsess = event.isSuccsess(); // TODO: Handle errors
<ide> if (isSuccsess) {
<add> findViewById(R.id.btn_register).setVisibility(View.GONE);
<ide> Toast.makeText(this, "SUCCSESS... LOG IN!", Toast.LENGTH_LONG).show();
<ide> setUiMode(UI_MODE_LOGIN);
<ide> } |
|
Java | mit | 2971c1c33d5d2968a713a8b232c0a26bf9199e6e | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.application.readonly.viewmodel;
import org.innovateuk.ifs.application.readonly.ApplicationReadOnlyData;
import org.innovateuk.ifs.form.resource.QuestionResource;
import java.math.BigDecimal;
import java.util.List;
public class GenericQuestionReadOnlyViewModel extends AbstractQuestionReadOnlyViewModel {
private final String displayName;
private final String question;
private final String answer;
private final List<GenericQuestionFileViewModel> appendices;
private final GenericQuestionFileViewModel templateFile;
private final String templateDocumentTitle;
private final long competitionId;
private final List<String> feedback;
private final List<BigDecimal> scores;
private final QuestionResource questionResource;
private final int inScope;
private final int totalScope;
public GenericQuestionReadOnlyViewModel(ApplicationReadOnlyData data, QuestionResource questionResource, String displayName, String question, String answer, List<GenericQuestionFileViewModel> appendices, GenericQuestionFileViewModel templateFile, String templateDocumentTitle, List<String> feedback, List<BigDecimal> scores, int inScope, int totalScope) {
super(data, questionResource);
this.displayName = displayName;
this.question = question;
this.answer = answer;
this.appendices = appendices;
this.templateFile = templateFile;
this.templateDocumentTitle = templateDocumentTitle;
this.competitionId = data.getCompetition().getId();
this.feedback = feedback;
this.scores = scores;
this.questionResource = questionResource;
this.inScope = inScope;
this.totalScope = totalScope;
}
public int getInScope() { return inScope; }
public int getTotalScope() { return totalScope; }
public String getDisplayName() {
return displayName;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
public List<GenericQuestionFileViewModel> getAppendices() {
return appendices;
}
public GenericQuestionFileViewModel getTemplateFile() {
return templateFile;
}
public String getTemplateDocumentTitle() {
return templateDocumentTitle;
}
public long getCompetitionId() {
return competitionId;
}
public List<String> getFeedback() {
return feedback;
}
public List<BigDecimal> getScores() {
return scores;
}
@Override
public String getName() {
return displayName;
}
@Override
public String getFragment() {
return "generic";
}
public boolean hasFeedback() {
return !feedback.isEmpty();
}
@Override
public boolean hasScore() { return !scores.isEmpty(); }
public boolean hasAssessorResponse() {
return hasFeedback() && hasScore();
}
public int getAssessorMaximumScore() {
if(!hasScore()) {
return 0;
}
return questionResource.getAssessorMaximumScore();
};
public BigDecimal getAverageScore() {
BigDecimal totalScore = BigDecimal.ZERO;
for (int i = 0; i < scores.size(); i++){
totalScore = totalScore.add(scores.get(i));
};
BigDecimal average = totalScore.divide(BigDecimal.valueOf(scores.size()), 1, BigDecimal.ROUND_HALF_UP);
return average;
};
}
| ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/readonly/viewmodel/GenericQuestionReadOnlyViewModel.java | package org.innovateuk.ifs.application.readonly.viewmodel;
import org.innovateuk.ifs.application.readonly.ApplicationReadOnlyData;
import org.innovateuk.ifs.form.resource.QuestionResource;
import java.math.BigDecimal;
import java.util.List;
public class GenericQuestionReadOnlyViewModel extends AbstractQuestionReadOnlyViewModel {
private final String displayName;
private final String question;
private final String answer;
private final List<GenericQuestionFileViewModel> appendices;
private final GenericQuestionFileViewModel templateFile;
private final String templateDocumentTitle;
private final long competitionId;
private final List<String> feedback;
private final List<BigDecimal> scores;
private final QuestionResource questionResource;
private final int inScope;
private final int totalScope;
public GenericQuestionReadOnlyViewModel(ApplicationReadOnlyData data, QuestionResource questionResource, String displayName, String question, String answer, List<GenericQuestionFileViewModel> appendices, GenericQuestionFileViewModel templateFile, String templateDocumentTitle, List<String> feedback, List<BigDecimal> scores, int inScope, int totalScope) {
super(data, questionResource);
this.displayName = displayName;
this.question = question;
this.answer = answer;
this.appendices = appendices;
this.templateFile = templateFile;
this.templateDocumentTitle = templateDocumentTitle;
this.competitionId = data.getCompetition().getId();
this.feedback = feedback;
this.scores = scores;
this.questionResource = questionResource;
this.inScope = inScope;
this.totalScope = totalScope;
}
public int getInScope() { return inScope; }
public int getTotalScope() { return totalScope; }
public String getDisplayName() {
return displayName;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
public List<GenericQuestionFileViewModel> getAppendices() {
return appendices;
}
public GenericQuestionFileViewModel getTemplateFile() {
return templateFile;
}
public String getTemplateDocumentTitle() {
return templateDocumentTitle;
}
public long getCompetitionId() {
return competitionId;
}
public List<String> getFeedback() {
return feedback;
}
public List<BigDecimal> getScores() {
return scores;
}
@Override
public String getName() {
return displayName;
}
@Override
public String getFragment() {
return "generic";
}
public boolean hasFeedback() {
return !feedback.isEmpty();
}
public boolean hasScore() { return !scores.isEmpty(); }
public boolean hasAssessorResponse() {
return hasFeedback() && hasScore();
}
public int getAssessorMaximumScore() {
if(!hasScore()) {
return 0;
}
return questionResource.getAssessorMaximumScore();
};
public BigDecimal getAverageScore() {
BigDecimal totalScore = BigDecimal.ZERO;
for (int i = 0; i < scores.size(); i++){
totalScore = totalScore.add(scores.get(i));
};
BigDecimal average = totalScore.divide(BigDecimal.valueOf(scores.size()), 1, BigDecimal.ROUND_HALF_UP);
return average;
};
}
| IFS-8012: adding missing notation
| ifs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/readonly/viewmodel/GenericQuestionReadOnlyViewModel.java | IFS-8012: adding missing notation | <ide><path>fs-web-service/ifs-application-commons/src/main/java/org/innovateuk/ifs/application/readonly/viewmodel/GenericQuestionReadOnlyViewModel.java
<ide> return !feedback.isEmpty();
<ide> }
<ide>
<add> @Override
<ide> public boolean hasScore() { return !scores.isEmpty(); }
<ide>
<ide> public boolean hasAssessorResponse() { |
|
Java | epl-1.0 | 95773def047e653ee9098ad2726332c34a5ac83a | 0 | sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.core.model.schematic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.eclipse.birt.report.designer.core.DesignerConstants;
import org.eclipse.birt.report.designer.core.model.IModelAdaptHelper;
import org.eclipse.birt.report.designer.core.model.ITableAdaptHelper;
import org.eclipse.birt.report.designer.core.model.ReportItemtHandleAdapter;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.activity.SemanticException;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.ColumnHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.DimensionHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.TableGroupHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.command.ContentException;
import org.eclipse.birt.report.model.command.NameException;
import org.eclipse.birt.report.model.elements.Cell;
import org.eclipse.birt.report.model.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.elements.GroupElement;
import org.eclipse.birt.report.model.elements.Style;
import org.eclipse.birt.report.model.elements.TableGroup;
import org.eclipse.birt.report.model.elements.TableItem;
import org.eclipse.birt.report.model.elements.TableRow;
import org.eclipse.birt.report.model.metadata.DimensionValue;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.jface.util.Assert;
/**
* Adapter class to adapt model handle. This adapter provides convenience
* methods to GUI requirement CellHandleAdapter responds to model CellHandle
*
*/
public class TableHandleAdapter extends ReportItemtHandleAdapter
{
// private static Log log = LogFactory.getLog( TableHandleAdapter.class );
private static final String TRANS_LABEL_INSERT_ROW = Messages.getString( "TableHandleAdapter.transLabel.insertRow" ); //$NON-NLS-1$
private static final String NAME_NULL = ""; //$NON-NLS-1$
private static final String NAME_DETAIL = Messages.getString( "TableHandleAdapter.name.detail" ); //$NON-NLS-1$
private static final String NAME_FOOTER = Messages.getString( "TableHandleAdapter.name.footer" ); //$NON-NLS-1$
private static final String NAME_HEADRER = Messages.getString( "TableHandleAdapter.name.header" ); //$NON-NLS-1$
private static final String TRANS_LABEL_NOT_INCLUDE = Messages.getString( "TableHandleAdapter.transLabel.notInclude" ); //$NON-NLS-1$
private static final String TRANS_LABEL_INCLUDE = Messages.getString( "TableHandleAdapter.transLabel.include" ); //$NON-NLS-1$
private static final String TRANS_LABEL_INSERT_GROUP = Messages.getString( "TableHandleAdapter.transLabel.insertGroup" ); //$NON-NLS-1$
private static final String TRANS_LABEL_SPLIT_CELLS = Messages.getString( "TableHandleAdapter.transLabel.splitCells" ); //$NON-NLS-1$
private static final String TRANS_LABEL_DELETE_ROW = Messages.getString( "TableHandleAdapter.transLabel.deleteRow" ); //$NON-NLS-1$
private static final String TRANS_LABEL_DELETE_ROWS = Messages.getString( "TableHandleAdapter.transLabel.deleteRows" ); //$NON-NLS-1$
private static final String TRANS_LABEL_DELETE_COLUMN = Messages.getString( "TableHandleAdapter.transLabel.deleteColumn" ); //$NON-NLS-1$
private static final String TRANS_LABEL_DELETE_COLUMNS = Messages.getString( "TableHandleAdapter.transLabel.deleteColumns" ); //$NON-NLS-1$
private static final String TRANS_LABEL_INSERT_COLUMN = Messages.getString( "TableHandleAdapter.transLabel.insertColumn" ); //$NON-NLS-1$
public static final int HEADER = TableItem.HEADER_SLOT;
public static final int DETAIL = TableItem.DETAIL_SLOT;
public static final int FOOTER = TableItem.FOOTER_SLOT;
public static final String TABLE_HEADER = "H"; //$NON-NLS-1$
public static final String TABLE_FOOTER = "F"; //$NON-NLS-1$
public static final String TABLE_DETAIL = "D"; //$NON-NLS-1$
public static final String TABLE_GROUP_HEADER = "gh"; //$NON-NLS-1$
public static final String TABLE_GROUP_FOOTER = "gf"; //$NON-NLS-1$
/* the name model should support */
private HashMap rowInfo = new HashMap( );
protected List rows = new ArrayList( );
/**
* Constructor
*
* @param table
* The handle of report item.
*
* @param mark
*/
public TableHandleAdapter( ReportItemHandle table, IModelAdaptHelper mark )
{
super( table, mark );
}
/**
* Gets the Children list.
*
* @return Children iterator
*/
public List getChildren( )
{
List children = new ArrayList( );
SlotHandle header = getTableHandle( ).getHeader( );
for ( Iterator it = header.iterator( ); it.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) it.next( ) ).getCells( )
.iterator( ), children );
}
SlotHandle group = getTableHandle( ).getGroups( );
for ( Iterator it = group.iterator( ); it.hasNext( ); )
{
TableGroupHandle tableGroups = (TableGroupHandle) it.next( );
SlotHandle groupHeaders = tableGroups.getSlot( GroupElement.HEADER_SLOT );
for ( Iterator heards = groupHeaders.iterator( ); heards.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) heards.next( ) ).getCells( )
.iterator( ), children );
}
}
SlotHandle detail = getTableHandle( ).getDetail( );
for ( Iterator detailRows = detail.iterator( ); detailRows.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) detailRows.next( ) ).getCells( )
.iterator( ), children );
}
group = getTableHandle( ).getGroups( );
for ( ListIterator it = convertIteratorToListIterator( group.iterator( ) ); it.hasPrevious( ); )
{
TableGroupHandle tableGroups = (TableGroupHandle) it.previous( );
SlotHandle groupFooters = tableGroups.getSlot( GroupElement.FOOTER_SLOT );
for ( Iterator heards = groupFooters.iterator( ); heards.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) heards.next( ) ).getCells( )
.iterator( ), children );
}
}
SlotHandle footer = getTableHandle( ).getFooter( );
for ( Iterator footerIT = footer.iterator( ); footerIT.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) footerIT.next( ) ).getCells( )
.iterator( ), children );
}
removePhantomCells(children);
return children;
}
/**
* Some cells might not be relevant, because overriden by colspan/rowspan of other cells
* Example in a three columns table:
* <row>
* <cell>
* <property name="colSpan">3</property>
* <property name="rowSpan">1</property>
* <cell>
* <cell/>
* <cell/>
* <row>
*
* The last two cells are phantom, the layout cannot handle them so we remove them
* at that stage. Ideally the model should not return those cells.
* @param children
*/
protected void removePhantomCells(List children)
{
ArrayList phantomCells = new ArrayList();
for ( Iterator iter = children.iterator(); iter.hasNext();)
{
Object cell = iter.next();
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cell );
if ( cellAdapt.getRowNumber() == 0 || cellAdapt.getColumnNumber() == 0)
{
phantomCells.add( cell );
}
}
for ( Iterator iter = phantomCells.iterator();iter.hasNext();)
{
children.remove(iter.next());
}
}
private ListIterator convertIteratorToListIterator( Iterator iterator )
{
ArrayList list = new ArrayList( );
for ( Iterator it = iterator; it.hasNext( ); )
{
list.add( it.next( ) );
}
return list.listIterator( list.size( ) );
}
private void insertIteratorToList( Iterator iterator,
TableHandleAdapter.RowUIInfomation info )
{
List addList = new ArrayList( );
for ( Iterator it = iterator; it.hasNext( ); )
{
addList.add( it.next( ) );
}
info.addChildren( addList );
}
/**
* Inserts the iterator to the given list
*
* @param iterator
* The iterator
* @param list
* The list
*/
protected void insertIteratorToList( Iterator iterator, List list,
String displayNmae, String type )
{
for ( Iterator it = iterator; it.hasNext( ); )
{
RowHandle handle = (RowHandle) it.next( );
list.add( handle );
TableHandleAdapter.RowUIInfomation info = new TableHandleAdapter.RowUIInfomation( getColumnCount( ) );
info.setType( type );
info.setRowDisplayName( displayNmae );
insertIteratorToList( handle.getCells( ).iterator( ), info );
rowInfo.put( handle, info );
}
}
public List getRows( )
{
if ( checkDirty( ) || rowInfo.isEmpty( ) )
{
reload( );
}
return rows;
}
protected void clearBuffer( )
{
rowInfo.clear( );
rows.clear( );
}
/**
* Gets all rows list.
*
* @return The rows list.
*/
public List initRowsInfo( )
{
clearBuffer( );
SlotHandle header = getTableHandle( ).getHeader( );
insertIteratorToList( header.iterator( ),
rows,
TABLE_HEADER,
TABLE_HEADER );
SlotHandle group = getTableHandle( ).getGroups( );
int number = 0;
for ( Iterator it = group.iterator( ); it.hasNext( ); )
{
number++;
TableGroupHandle tableGroups = (TableGroupHandle) it.next( );
SlotHandle groupHeaders = tableGroups.getSlot( GroupElement.HEADER_SLOT );
insertIteratorToList( groupHeaders.iterator( ),
rows,
( TABLE_GROUP_HEADER + number ),
TABLE_GROUP_HEADER );
}
SlotHandle detail = getTableHandle( ).getDetail( );
insertIteratorToList( detail.iterator( ),
rows,
TABLE_DETAIL,
TABLE_DETAIL );
group = getTableHandle( ).getGroups( );
number = 0;
for ( Iterator it = group.iterator( ); it.hasNext( ); )
{
TableGroupHandle tableGroups = (TableGroupHandle) it.next( );
SlotHandle groupFooters = tableGroups.getSlot( GroupElement.FOOTER_SLOT );
number++;
}
for ( ListIterator it = convertIteratorToListIterator( group.iterator( ) ); it.hasPrevious( ); )
{
TableGroupHandle tableGroups = (TableGroupHandle) it.previous( );
SlotHandle groupFooters = tableGroups.getSlot( GroupElement.FOOTER_SLOT );
insertIteratorToList( groupFooters.iterator( ),
rows,
TABLE_GROUP_FOOTER + number,
TABLE_GROUP_FOOTER );
number--;
}
SlotHandle footer = getTableHandle( ).getFooter( );
insertIteratorToList( footer.iterator( ),
rows,
TABLE_FOOTER,
TABLE_FOOTER );
caleRowInfo( rows );
return rows;
}
/**
* @param children
*/
protected void caleRowInfo( List children )
{
int size = children.size( );
for ( int i = 0; i < size; i++ )
{
RowHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( children.get( i ) );
List cellChildren = adapt.getChildren( );
int len = cellChildren.size( );
TableHandleAdapter.RowUIInfomation info = (TableHandleAdapter.RowUIInfomation) rowInfo.get( children.get( i ) );
for ( int j = 0; j < len; j++ )
{
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellChildren.get( j ) );
int cellIndex = info.getAllChildren( )
.indexOf( cellChildren.get( j ) );
if ( cellAdapt.getColumnSpan( ) != 1 )
{
if ( cellIndex + 2 <= info.getAllChildren( ).size( )
&& cellIndex >= 0 )
{
fillRowInfoChildrenList( children.get( i ),
cellIndex + 2,
cellAdapt.getColumnSpan( ) - 1,
cellChildren.get( j ) );
}
}
if ( cellAdapt.getRowSpan( ) != 1 )
{
for ( int k = i + 1; k < i + cellAdapt.getRowSpan( ); k++ )
{
if ( cellIndex < 0
|| cellIndex + cellAdapt.getColumnSpan( ) > info.getAllChildren( )
.size( ) )
{
continue;
}
fillRowInfoChildrenList( children.get( k ),
cellIndex + 1,
cellAdapt.getColumnSpan( ),
cellChildren.get( j ) );
}
}
}
}
}
private void fillRowInfoChildrenList( Object row, int columnNumber,
int colSpan, Object cell )
{
TableHandleAdapter.RowUIInfomation info = (TableHandleAdapter.RowUIInfomation) rowInfo.get( row );
if ( info == null )
{
return;
}
for ( int i = 0; i < colSpan; i++ )
{
info.addChildren( cell, columnNumber + i - 1 );
}
}
/**
* Get GUI infromation of row. For CSS table support auto layout, the GUI
* infor is different with model info.
*
* @param row
* @return
*/
public TableHandleAdapter.RowUIInfomation getRowInfo( Object row )
{
if ( checkDirty( ) )
{
reload( );
}
return (TableHandleAdapter.RowUIInfomation) rowInfo.get( row );
}
/**
*
* @see org.eclipse.birt.designer.core.facade.DesignElementHandleAdapter#reload()
*/
public void reload( )
{
super.reload( );
initRowsInfo( );
if (getModelAdaptHelper() != null)
{
getModelAdaptHelper( ).markDirty( false );
}
}
/**
* Gets the all columns list.
*
* @return The columns list.
*/
public List getColumns( )
{
List list = new ArrayList( );
insertIteratorToList( getTableHandle( ).getColumns( ).iterator( ), list );
return list;
}
/**
* Gets the special row
*
* @param i
* The row number.
* @return The special row.
*/
public Object getRow( int i )
{
List list = getRows( );
if ( i >= 1 && i <= list.size( ) )
{
return list.get( i - 1 );
}
return null;
}
/**
* Gets the special column
*
* @param i
* The column number.
* @return The special column.
*/
public Object getColumn( int i )
{
List list = getColumns( );
if ( i >= 1 && i <= list.size( ) )
{
return list.get( i - 1 );
}
return null;
}
/**
* Gets the special cell.
*
* @param rowNumber
* The row number.
* @param columnNumber
* The column number.
* @param bool
* @return The special cell.
*/
public Object getCell( int rowNumber, int columnNumber, boolean bool )
{
Object obj = getRow( rowNumber );
TableHandleAdapter.RowUIInfomation info = getRowInfo( obj );
Object retValue = info.getAllChildren( ).get( columnNumber - 1 );
if ( bool )
{
return retValue;
}
if ( HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( retValue )
.getRowNumber( ) != rowNumber
|| HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( retValue )
.getColumnNumber( ) != columnNumber )
{
retValue = null;
}
return retValue;
}
/**
* Gets the special cell.
*
* @param i
* The row number.
* @param j
* The column number.
* @return The special cell.
*/
public Object getCell( int i, int j )
{
return getCell( i, j, true );
}
/**
* Calculates table layout size. For table supports auto layout, the layout
* size need to be calculated when drawing.
*
* @return
*/
public Dimension calculateSize( )
{
if ( !( getModelAdaptHelper( ) instanceof ITableAdaptHelper ) )
{
return new Dimension( );
}
ITableAdaptHelper tableHelper = (ITableAdaptHelper) getModelAdaptHelper( );
int columnCount = getColumnCount( );
int samColumnWidth = 0;
for ( int i = 0; i < columnCount; i++ )
{
samColumnWidth = samColumnWidth
+ tableHelper.caleVisualWidth( i + 1 );
}
int rowCount = getRowCount( );
int samRowHeight = 0;
for ( int i = 0; i < rowCount; i++ )
{
samRowHeight = samRowHeight + tableHelper.caleVisualHeight( i + 1 );
}
return new Dimension( samColumnWidth, samRowHeight ).expand( tableHelper.getInsets( )
.getWidth( ),
tableHelper.getInsets( ).getHeight( ) );
}
/**
* Adjust size of table layout.
*
* @param size
* is all figure size
* @throws SemanticException
*/
public void ajustSize( Dimension size ) throws SemanticException
{
if ( !( getModelAdaptHelper( ) instanceof ITableAdaptHelper ) )
{
return;
}
ITableAdaptHelper tableHelper = (ITableAdaptHelper) getModelAdaptHelper( );
size = size.shrink( tableHelper.getInsets( ).getWidth( ),
tableHelper.getInsets( ).getHeight( ) );
int columnCount = getColumnCount( );
int samColumnWidth = 0;
for ( int i = 0; i < columnCount; i++ )
{
if ( i != columnCount - 1 )
{
samColumnWidth = samColumnWidth
+ tableHelper.caleVisualWidth( i + 1 );
}
}
int lastColumnWidth = size.width - samColumnWidth;
if ( lastColumnWidth < tableHelper.getMinWidth( columnCount ) )
{
lastColumnWidth = tableHelper.getMinWidth( columnCount );
HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( getColumn( columnCount ) )
.setWidth( lastColumnWidth );
}
else if ( lastColumnWidth != tableHelper.caleVisualWidth( columnCount ) )
{
HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( getColumn( columnCount ) )
.setWidth( lastColumnWidth );
}
int rowCount = getRowCount( );
int samRowHeight = 0;
for ( int i = 0; i < rowCount; i++ )
{
if ( i != rowCount - 1 )
{
samRowHeight = samRowHeight
+ tableHelper.caleVisualHeight( i + 1 );
}
}
int lastRowHeight = size.height - samRowHeight;
if ( lastRowHeight < tableHelper.getMinHeight( rowCount ) )
{
lastRowHeight = tableHelper.getMinHeight( rowCount );
HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( getRow( rowCount ) )
.setHeight( lastRowHeight );
}
else if ( lastRowHeight != tableHelper.caleVisualHeight( rowCount ) )
{
HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( getRow( rowCount ) )
.setHeight( lastRowHeight );
}
HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( getRow( rowCount ) )
.setHeight( lastRowHeight );
setSize( new Dimension( samColumnWidth + lastColumnWidth, samRowHeight
+ lastRowHeight ).expand( tableHelper.getInsets( ).getWidth( ),
tableHelper.getInsets( ).getHeight( ) ) );
}
/**
* Get the minimum height.of a specific row.
*
* @param rowNumber
* @return The minimum height.
*/
public int getMinHeight( int rowNumber )
{
// TODO Auto-generated method stub
return RowHandleAdapter.DEFAULT_MINHEIGHT;
}
/**
* Get the minimum width a specific row.
*
* @param columnNumber
* @return The minimum width.
*/
public int getMinWidth( int columnNumber )
{
// TODO Auto-generated method stub
return ColumnHandleAdapter.DEFAULT_MINWIDTH;
}
/**
* @return client area
*/
public Dimension getClientAreaSize( )
{
if ( getModelAdaptHelper( ) instanceof ITableAdaptHelper )
{
return ( (ITableAdaptHelper) getModelAdaptHelper( ) ).getClientAreaSize( );
}
return new Dimension( );
}
private TableHandle getTableHandle( )
{
return (TableHandle) getHandle( );
}
/**
* Returns the defined width in model in Pixel.
*
* @return
*/
public String getDefinedWidth( )
{
DimensionHandle handle = ( (ReportItemHandle) getHandle( ) ).getWidth( );
if ( handle.getUnits( ) == null || handle.getUnits( ).length( ) == 0 )
{
return null;
}
else if ( DesignChoiceConstants.UNITS_PERCENTAGE.equals( handle.getUnits( ) ) )
{
return handle.getMeasure( )
+ DesignChoiceConstants.UNITS_PERCENTAGE;
}
else
{
int px = (int) DEUtil.convertoToPixel( handle );
if ( px <= 0 )
{
return null;
}
return String.valueOf( px );
}
}
/**
* Get the default width.
*
* @param colNumber
* The column number.
* @return The default width.
*/
public int getDefaultWidth( int colNumber )
{
Dimension size = getDefaultSize( );
Object obj = getRow( 1 );
if ( obj == null )
{
return size.width;
}
int allNumbers = getColumnCount( );
if ( allNumbers <= 0 )
{
return size.width;
}
if ( colNumber <= 0 )
{
return size.width;
}
int width = size.width;
int columnNumber = allNumbers;
for ( int i = 1; i < columnNumber + 1; i++ )
{
Object column = getColumn( i );
ColumnHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( column );
if ( adapt.isCustomWidth( ) )
{
allNumbers = allNumbers - 1;
width = width - adapt.getWidth( );
}
}
if ( colNumber == allNumbers )
{
return width / allNumbers + width % allNumbers;
}
return ( width / allNumbers );
}
/**
* Gets the row count
*
* @return The row count.
*/
public int getRowCount( )
{
return getRows( ).size( );
}
/**
* Gets the column count
*
* @return The column count.
*/
public int getColumnCount( )
{
return getColumns( ).size( );
}
/**
* @return The data set.
*/
public Object getDataSet( )
{
return getTableHandle( ).getDataSet( );
}
/**
* Insert a row to a specific position.
*
* @param rowNumber
* The row number.
* @param parentRowNumber
* The row number of parent.
* @throws SemanticException
*/
public void insertRow( int rowNumber, int parentRowNumber )
throws SemanticException
{
transStar( TRANS_LABEL_INSERT_ROW );
Assert.isLegal( rowNumber != 0 );
int realRowNumber = rowNumber > 0 ? parentRowNumber + rowNumber
: parentRowNumber + rowNumber + 1;
int shiftPos = rowNumber > 0 ? rowNumber : rowNumber + 1;
RowHandle row = (RowHandle) getRow( parentRowNumber );
RowHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( row );
RowHandle copy = (RowHandle) adapt.copy( );
TableHandleAdapter.RowUIInfomation rowInfo = getRowInfo( row );
List rowList = rowInfo.getAllChildren( );
int rowSize = rowList.size( );
for ( int i = 0; i < rowSize; i++ )
{
CellHandle parentCell = (CellHandle) rowList.get( i );
CellHandle cell = getCellHandleCopy( parentCell );
copy.getSlot( TableRow.CONTENT_SLOT ).add( cell );
}
SlotHandle parentHandle = row.getContainerSlotHandle( );
parentHandle.add( ( copy ) );
int pos = parentHandle.findPosn( row.getElement( ) );
parentHandle.shift( copy, pos + shiftPos );
RowHandleAdapter copyAdapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( copy );
List copyChildren = copyAdapt.getChildren( );
TableHandleAdapter.RowUIInfomation info = getRowInfo( copy );
List list = info.getAllChildren( );
List temp = new ArrayList( );
int size = list.size( );
List hasAdjust = new ArrayList( );
for ( int i = 0; i < size; i++ )
{
Object fillCell = list.get( i );
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( fillCell );
if ( cellAdapt.getRowNumber( ) != realRowNumber )
{
if ( !hasAdjust.contains( fillCell ) )
{
cellAdapt.setRowSpan( cellAdapt.getRowSpan( ) + 1 );
hasAdjust.add( fillCell );
}
temp.add( new Integer( i ) );
}
}
int copyRowSize = copyChildren.size( );
for ( int i = 0; i < copyRowSize; i++ )
{
if ( temp.contains( new Integer( i ) ) )
{
( (CellHandle) copyChildren.get( i ) ).drop( );
}
}
transEnd( );
}
/**
* Insert a column to a specific position.
*
* @param columnNumber
* The column number.
* @param parentColumnNumber
* The column number of parent.
* @throws SemanticException
*/
public void insertColumn( int columnNumber, int parentColumnNumber )
throws SemanticException
{
transStar( TRANS_LABEL_INSERT_COLUMN );
assert columnNumber != 0;
int realColumnNumber = columnNumber > 0 ? parentColumnNumber
+ columnNumber : parentColumnNumber + columnNumber + 1;
int shiftPos = columnNumber > 0 ? columnNumber : columnNumber + 1;
ColumnHandle column = (ColumnHandle) getColumn( parentColumnNumber );
ColumnHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( column );
ColumnHandle copy = (ColumnHandle) adapt.copy( );
int rowNumber = getRowCount( );
List copyChildren = new ArrayList( );
for ( int i = 0; i < rowNumber; i++ )
{
RowHandle row = (RowHandle) getRow( i + 1 );
TableHandleAdapter.RowUIInfomation rowInfo = getRowInfo( getRow( i + 1 ) );
List rowList = rowInfo.getAllChildren( );
CellHandle parentCell = (CellHandle) rowList.get( parentColumnNumber - 1 );
CellHandle cell = getCellHandleCopy( parentCell );
copyChildren.add( cell );
}
int copyRowSize = copyChildren.size( );
for ( int i = 0; i < copyRowSize; i++ )
{
RowHandle row = (RowHandle) getRow( i + 1 );
row.getSlot( TableRow.CONTENT_SLOT )
.add( (CellHandle) ( copyChildren.get( i ) ),
realColumnNumber - 1 );
}
SlotHandle parentHandle = column.getContainerSlotHandle( );
parentHandle.add( ( copy ) );
int pos = parentHandle.findPosn( column.getElement( ) );
parentHandle.shift( copy, pos + shiftPos );
List temp = new ArrayList( );
List hasAdjust = new ArrayList( );
for ( int i = 0; i < rowNumber; i++ )
{
TableHandleAdapter.RowUIInfomation rowInfo = getRowInfo( getRow( i + 1 ) );
List rowList = rowInfo.getAllChildren( );
Object fillCell = rowList.get( realColumnNumber - 1 );
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( fillCell );
if ( cellAdapt.getColumnNumber( ) != realColumnNumber )
{
if ( !hasAdjust.contains( fillCell ) )
{
cellAdapt.setColumnSpan( cellAdapt.getColumnSpan( ) + 1 );
hasAdjust.add( fillCell );
}
temp.add( new Integer( i ) );
}
}
for ( int i = 0; i < copyRowSize; i++ )
{
if ( temp.contains( new Integer( i ) ) )
{
( (CellHandle) copyChildren.get( i ) ).drop( );
}
}
transEnd( );
}
/**
* @param model
* The object to be removed.
* @throws SemanticException
*/
public void removeChild( Object model ) throws SemanticException
{
assert ( model instanceof DesignElementHandle );
DesignElementHandle ele = (DesignElementHandle) model;
ele.drop( );
}
/**
* Get the padding of the current table.
*
* @param retValue
* The padding value of the current table.
* @return The padding's new value of the current table.
*/
public Insets getPadding( Insets retValue )
{
if ( retValue == null )
{
retValue = new Insets( );
}
else
{
retValue = new Insets( retValue );
}
DimensionHandle fontHandle = getHandle( ).getPrivateStyle( )
.getFontSize( );
int fontSize = 12;//??
if ( fontHandle.getValue( ) instanceof String )
{
fontSize = Integer.valueOf( (String) DesignerConstants.fontMap.get( DEUtil.getFontSize( getHandle( ) ) ) )
.intValue( );
}
else if ( fontHandle.getValue( ) instanceof DimensionValue )
{
DEUtil.convertToPixel( fontHandle.getValue( ), fontSize );
}
DimensionValue dimensionValue = (DimensionValue) getReportItemHandle( ).getProperty( Style.PADDING_TOP_PROP );
double px = DEUtil.convertToPixel( dimensionValue, fontSize );
dimensionValue = (DimensionValue) getReportItemHandle( ).getProperty( Style.PADDING_BOTTOM_PROP );
double py = DEUtil.convertToPixel( dimensionValue, fontSize );
retValue.top = (int) px;
retValue.bottom = (int) py;
dimensionValue = (DimensionValue) getReportItemHandle( ).getProperty( Style.PADDING_LEFT_PROP );
px = DEUtil.convertToPixel( dimensionValue, fontSize );
dimensionValue = (DimensionValue) getReportItemHandle( ).getProperty( Style.PADDING_RIGHT_PROP );
py = DEUtil.convertToPixel( dimensionValue, fontSize );
retValue.left = (int) px;
retValue.right = (int) py;
return retValue;
}
/**
* Delete specific columns from the current table.
*
* @param columns
* The columns to be deleted.
* @throws SemanticException
*/
public void deleteColumn( int[] columns ) throws SemanticException
{
if ( getColumnCount( ) == 1 )
{
getTableHandle( ).drop( );
return;
}
transStar( TRANS_LABEL_DELETE_COLUMNS );
int len = columns.length;
for ( int i = 0; i < len; i++ )
{
deleteColumn( columns[i] );
}
transEnd( );
}
/**
* Delete a specific column from the current table.
*
* @param columnNumber
* The column to be deleted.
* @throws SemanticException
*/
public void deleteColumn( int columnNumber ) throws SemanticException
{
transStar( TRANS_LABEL_DELETE_COLUMN );
int rowCount = getRowCount( );
ColumnHandle column = (ColumnHandle) getColumn( columnNumber );
List deleteCells = new ArrayList( );
for ( int i = 0; i < rowCount; i++ )
{
Object row = getRow( i + 1 );
TableHandleAdapter.RowUIInfomation info = getRowInfo( row );
deleteCells.add( info.getAllChildren( ).get( columnNumber - 1 ) );
}
List trueDeleteCells = new ArrayList( );
int size = deleteCells.size( );
for ( int i = 0; i < size; i++ )
{
Object cell = deleteCells.get( i );
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cell );
if ( cellAdapt.getColumnNumber( ) == columnNumber
&& cellAdapt.getColumnSpan( ) == 1
&& !trueDeleteCells.contains( cell ) )
{
trueDeleteCells.add( cell );
}
}
List temp = new ArrayList( );
for ( int i = 0; i < size; i++ )
{
Object cell = deleteCells.get( i );
if ( !trueDeleteCells.contains( cell ) && !temp.contains( cell ) )
{
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cell );
cellAdapt.setColumnSpan( cellAdapt.getColumnSpan( ) - 1 );
temp.add( cell );
}
}
size = trueDeleteCells.size( );
for ( int i = 0; i < size; i++ )
{
CellHandle cell = (CellHandle) trueDeleteCells.get( i );
cell.drop( );
}
column.drop( );
transEnd( );
reload( );
}
/**
* Delete specific rows from the current table.
*
* @param rows
* The rows to be deleted.
* @throws SemanticException
*/
public void deleteRow( int[] rows ) throws SemanticException
{
if ( getRowCount( ) == 1 )
{
getTableHandle( ).drop( );
return;
}
transStar( TRANS_LABEL_DELETE_ROWS );
Arrays.sort( rows );
int len = rows.length;
for ( int i = len - 1; i >= 0; i-- )
{
deleteRow( rows[i] );
}
transEnd( );
}
/**
* Delete a specific row from the current table.
*
* @param rowsNumber
* The row to be deleted.
* @throws SemanticException
*/
public void deleteRow( int rowsNumber ) throws SemanticException
{
transStar( TRANS_LABEL_DELETE_ROW );
int rowCount = getRowCount( );
RowHandle row = (RowHandle) getRow( rowsNumber );
RowHandleAdapter rowAdapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( row );
List temp = new ArrayList( );
RowHandle nextRow = null;
List shiftCellInfo = new ArrayList( );
if ( rowsNumber + 1 <= rowCount )
{
List trueChildren = rowAdapt.getChildren( );
int cellSize = trueChildren.size( );
nextRow = (RowHandle) getRow( rowsNumber + 1 );
TableHandleAdapter.RowUIInfomation nextRowInfo = getRowInfo( nextRow );
List nextRowChildren = nextRowInfo.getAllChildren( );
for ( int i = 0; i < cellSize; i++ )
{
Object cellHandle = trueChildren.get( i );
CellHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellHandle );
if ( adapt.getRowSpan( ) != 1 )
{
int numberInfo = 0;
int index = nextRowChildren.indexOf( cellHandle );
for ( int j = 0; j < index; j++ )
{
Object nextRowCell = nextRowChildren.get( j );
CellHandleAdapter nextRowCellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( nextRowCell );
if ( nextRowCellAdapt.getRowNumber( ) == rowsNumber + 1
&& !temp.contains( nextRowCell ) )
{
numberInfo = numberInfo + 1;
}
temp.add( nextRowCell );
}
numberInfo = numberInfo + shiftCellInfo.size( );
shiftCellInfo.add( new ShiftNexRowInfo( numberInfo,
cellHandle ) );
}
}
}
TableHandleAdapter.RowUIInfomation info = getRowInfo( row );
List cells = info.getAllChildren( );
temp.clear( );
int cellSize = cells.size( );
for ( int j = 0; j < cellSize; j++ )
{
Object cellHandle = cells.get( j );
CellHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellHandle );
if ( adapt.getRowNumber( ) != rowsNumber
&& !temp.contains( cellHandle ) )
{
adapt.setRowSpan( adapt.getRowSpan( ) - 1 );
temp.add( cellHandle );
}
}
//row.drop( );
for ( int i = 0; i < shiftCellInfo.size( ); i++ )
{
ShiftNexRowInfo shiftInfo = (ShiftNexRowInfo) shiftCellInfo.get( i );
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( shiftInfo.cell );
cellAdapt.setRowSpan( cellAdapt.getRowSpan( ) - 1 );
SlotHandle slotHandle = row.getCells( );
slotHandle.move( (DesignElementHandle) shiftInfo.cell,
nextRow,
TableRow.CONTENT_SLOT,
shiftInfo.index );
}
row.drop( );
transEnd( );
reload( );
}
class ShiftNexRowInfo
{
protected int index;
protected Object cell;
/**
* @param index
* @param cell
*/
public ShiftNexRowInfo( int index, Object cell )
{
super( );
this.index = index;
this.cell = cell;
}
}
static class RowUIInfomation
{
protected static final String GRID_ROW = NAME_NULL; //$NON-NLS-1$
private String type = ""; //$NON-NLS-1$
private String rowDisplayName = ""; //$NON-NLS-1$
Object[] cells = null;
int[] infactAdd = new int[0];
private RowUIInfomation( int columnMunber )
{
cells = new Object[columnMunber];
}
public String getRowDisplayName( )
{
return rowDisplayName;
}
public void setRowDisplayName( String rowDisplayName )
{
this.rowDisplayName = rowDisplayName;
}
public String getType( )
{
return type;
}
public void setType( String type )
{
this.type = type;
}
public void addChildren( Object obj, int index )
{
int cellSize = cells.length;
if ( index >= cellSize )
{
return;
}
ArrayList list = new ArrayList( );
if ( cells[index] != null )
{
Object[] newArray = new Object[cellSize];
for ( int i = 0; i < cellSize; i++ )
{
if ( containIndex( i ) )
{
newArray[i] = cells[i];
}
else if ( cells[i] != null )
{
list.add( cells[i] );
}
}
newArray[index] = obj;
int listSize = list.size( );
for ( int i = 0; i < listSize; i++ )
{
for ( int j = 0; j < cellSize; j++ )
{
if ( newArray[j] == null )
{
newArray[j] = list.get( i );
break;
}
}
}
cells = newArray;
}
else
{
cells[index] = obj;
}
int lenegth = infactAdd.length;
int[] temp = new int[lenegth + 1];
System.arraycopy( infactAdd, 0, temp, 0, lenegth );
temp[lenegth] = index;
infactAdd = temp;
}
private boolean containIndex( int index )
{
int length = infactAdd.length;
for ( int i = 0; i < length; i++ )
{
if ( infactAdd[i] == index )
{
return true;
}
}
return false;
}
public void addChildren( Collection c )
{
Iterator itor = c.iterator( );
int cellSize = cells.length;
while ( itor.hasNext( ) )
{
Object obj = itor.next( );
for ( int i = 0; i < cellSize; i++ )
{
if ( cells[i] == null )
{
cells[i] = obj;
break;
}
}
}
}
public List getAllChildren( )
{
ArrayList retValue = new ArrayList( );
int cellSize = cells.length;
for ( int i = 0; i < cellSize; i++ )
{
retValue.add( cells[i] );
}
return retValue;
}
}
/**
* @param list
* @return If can merge return true, else false.
*/
public boolean canMerge( List list )
{
assert list != null;
int size = list.size( );
if ( size <= 1 )
{
return false;
}
String first = getRowInfo( ( (CellHandle) list.get( 0 ) ).getContainer( ) ).getRowDisplayName( );
for ( int i = 1; i < size; i++ )
{
RowUIInfomation info = getRowInfo( ( (CellHandle) list.get( i ) ).getContainer( ) );
if ( info == null )
{
return false;
}
String str = info.getRowDisplayName( );
if ( !first.equals( str ) )
{
return false;
}
}
return true;
}
/**
* Split a cell to cells.
*
* @param model
* @throws SemanticException
* @throws NameException
* @throws ContentException
*/
public void splitCell( Object model ) throws ContentException,
NameException, SemanticException
{
// TODO Auto-generated method stub
transStar( TRANS_LABEL_SPLIT_CELLS );
assert model instanceof CellHandle;
CellHandle cellHandle = (CellHandle) model;
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellHandle );
int rowNumber = cellAdapt.getRowNumber( );
int rowSpan = cellAdapt.getRowSpan( );
int colSpan = cellAdapt.getColumnSpan( );
//fill the cell row
if ( colSpan != 1 )
{
int index = getIndexofParent( cellHandle );
RowHandle rowHandle = (RowHandle) cellHandle.getContainer( );
for ( int i = 1; i < colSpan; i++ )
{
rowHandle.addElement( getCellHandleCopy( cellHandle ),
TableRow.CONTENT_SLOT,
i + index );
}
}
if ( rowSpan != 1 )
{
for ( int i = rowNumber + 1; i < rowNumber + rowSpan; i++ )
{
RowHandle rowHandle = (RowHandle) getRow( i );
int index = getIndexofParent( cellHandle );
for ( int j = 0; j < colSpan; j++ )
{
rowHandle.addElement( getCellHandleCopy( cellHandle ),
TableRow.CONTENT_SLOT,
j + index );
}
}
}
cellAdapt.setRowSpan( 1 );
cellAdapt.setColumnSpan( 1 );
transEnd( );
}
private int getIndexofParent( CellHandle cellHandle )
{
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellHandle );
TableHandleAdapter.RowUIInfomation info = getRowInfo( cellHandle.getContainer( ) );
List list = info.getAllChildren( );
int index = list.indexOf( cellHandle );
List temp = new ArrayList( );
int number = 0;
for ( int j = 0; j < index; j++ )
{
CellHandleAdapter childCellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( list.get( j ) );
if ( childCellAdapt.getRowNumber( ) == cellAdapt.getRowNumber( )
&& !temp.contains( list.get( j ) ) )
{
number = number + 1;
}
temp.add( list.get( j ) );
}
return number;
}
/**
* Gets the cell handle copoy to support row/column insert.
*
* @param cellHandle
* @return
* @throws SemanticException
*/
public CellHandle getCellHandleCopy( CellHandle cellHandle )
throws SemanticException
{
if ( cellHandle == null )
{
return null;
}
CellHandle cell = cellHandle.getElementFactory( ).newCell( );
Iterator iter = cellHandle.getPropertyIterator( );
while ( iter.hasNext( ) )
{
PropertyHandle handle = (PropertyHandle) iter.next( );
String key = handle.getDefn( ).getName( );
if ( handle.isLocal( )
&& ( !( Cell.COL_SPAN_PROP.equals( key ) || Cell.ROW_SPAN_PROP.equals( key ) ) ) )
{
cell.setProperty( key, cellHandle.getProperty( key ) );
}
}
return cell;
}
/**
* Provides insert group function.
*
* @return
* @throws ContentException
* @throws NameException
*/
public TableGroupHandle insertGroup( ) throws ContentException,
NameException
{
if ( DEUtil.getDataSetList( getTableHandle( ) ).isEmpty( ) )
{
return null;
}
transStar( TRANS_LABEL_INSERT_GROUP );
RowHandle header = getTableHandle( ).getElementFactory( ).newTableRow( );
RowHandle footer = getTableHandle( ).getElementFactory( ).newTableRow( );
addCell( header );
addCell( footer );
TableGroupHandle groupHandle = getTableHandle( ).getElementFactory( )
.newTableGroup( );
groupHandle.getSlot( TableGroup.HEADER_SLOT ).add( header );
groupHandle.getSlot( TableGroup.FOOTER_SLOT ).add( footer );
SlotHandle handle = getTableHandle( ).getGroups( );
handle.add( groupHandle );
transEnd( );
return groupHandle;
}
/**
* Provides remove group function
*
* @throws SemanticException
*
*/
public void removeGroup( Object group ) throws SemanticException
{
( (RowHandle) group ).getContainer( ).drop( );
}
private void addCell( RowHandle handle ) throws ContentException,
NameException
{
int count = getColumnCount( );
for ( int i = 0; i < count; i++ )
{
CellHandle cell = handle.getElementFactory( ).newCell( );
handle.addElement( cell, TableRow.CONTENT_SLOT );
}
}
/**
* Insert row in model
*
* @param id
* @throws ContentException
* @throws NameException
*/
public void insertRowInSlotHandle( int id ) throws ContentException,
NameException
{
transStar( TRANS_LABEL_INCLUDE + getOperationName( id ) );
RowHandle rowHandle = getTableHandle( ).getElementFactory( )
.newTableRow( );
addCell( rowHandle );
getTableHandle( ).getSlot( id ).add( rowHandle );
transEnd( );
}
/**
* Delete row in model
*
* @param id
* @throws SemanticException
*/
public void deleteRowInSlotHandle( int id ) throws SemanticException
{
transStar( TRANS_LABEL_NOT_INCLUDE + getOperationName( id ) );
int[] rows = new int[0];
Iterator itor = getTableHandle( ).getSlot( id ).iterator( );
while ( itor.hasNext( ) )
{
Object obj = itor.next( );
RowHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( obj );
int lenegth = rows.length;
int[] temp = new int[lenegth + 1];
System.arraycopy( rows, 0, temp, 0, lenegth );
temp[lenegth] = adapt.getRowNumber( );
rows = temp;
}
deleteRow( rows );
transEnd( );
}
private String getOperationName( int id )
{
switch ( id )
{
case HEADER :
return NAME_HEADRER;
case FOOTER :
return NAME_FOOTER;
case DETAIL :
return NAME_DETAIL;
default :
return NAME_NULL; //$NON-NLS-1$
}
}
/**
* Check if the slot handle contains specified id.
*
* @param id
* @return
*/
public boolean hasSlotHandleRow( int id )
{
Iterator itor = getTableHandle( ).getSlot( id ).iterator( );
while ( itor.hasNext( ) )
{
return true;
}
return false;
}
} | UI/org.eclipse.birt.report.designer.core/src/org/eclipse/birt/report/designer/core/model/schematic/TableHandleAdapter.java | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.core.model.schematic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.eclipse.birt.report.designer.core.DesignerConstants;
import org.eclipse.birt.report.designer.core.model.IModelAdaptHelper;
import org.eclipse.birt.report.designer.core.model.ITableAdaptHelper;
import org.eclipse.birt.report.designer.core.model.ReportItemtHandleAdapter;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.activity.SemanticException;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.ColumnHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.DimensionHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.TableGroupHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.command.ContentException;
import org.eclipse.birt.report.model.command.NameException;
import org.eclipse.birt.report.model.elements.Cell;
import org.eclipse.birt.report.model.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.elements.GroupElement;
import org.eclipse.birt.report.model.elements.Style;
import org.eclipse.birt.report.model.elements.TableGroup;
import org.eclipse.birt.report.model.elements.TableItem;
import org.eclipse.birt.report.model.elements.TableRow;
import org.eclipse.birt.report.model.metadata.DimensionValue;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.jface.util.Assert;
/**
* Adapter class to adapt model handle. This adapter provides convenience
* methods to GUI requirement CellHandleAdapter responds to model CellHandle
*
*/
public class TableHandleAdapter extends ReportItemtHandleAdapter
{
// private static Log log = LogFactory.getLog( TableHandleAdapter.class );
private static final String TRANS_LABEL_INSERT_ROW = Messages.getString( "TableHandleAdapter.transLabel.insertRow" ); //$NON-NLS-1$
private static final String NAME_NULL = ""; //$NON-NLS-1$
private static final String NAME_DETAIL = Messages.getString( "TableHandleAdapter.name.detail" ); //$NON-NLS-1$
private static final String NAME_FOOTER = Messages.getString( "TableHandleAdapter.name.footer" ); //$NON-NLS-1$
private static final String NAME_HEADRER = Messages.getString( "TableHandleAdapter.name.header" ); //$NON-NLS-1$
private static final String TRANS_LABEL_NOT_INCLUDE = Messages.getString( "TableHandleAdapter.transLabel.notInclude" ); //$NON-NLS-1$
private static final String TRANS_LABEL_INCLUDE = Messages.getString( "TableHandleAdapter.transLabel.include" ); //$NON-NLS-1$
private static final String TRANS_LABEL_INSERT_GROUP = Messages.getString( "TableHandleAdapter.transLabel.insertGroup" ); //$NON-NLS-1$
private static final String TRANS_LABEL_SPLIT_CELLS = Messages.getString( "TableHandleAdapter.transLabel.splitCells" ); //$NON-NLS-1$
private static final String TRANS_LABEL_DELETE_ROW = Messages.getString( "TableHandleAdapter.transLabel.deleteRow" ); //$NON-NLS-1$
private static final String TRANS_LABEL_DELETE_ROWS = Messages.getString( "TableHandleAdapter.transLabel.deleteRows" ); //$NON-NLS-1$
private static final String TRANS_LABEL_DELETE_COLUMN = Messages.getString( "TableHandleAdapter.transLabel.deleteColumn" ); //$NON-NLS-1$
private static final String TRANS_LABEL_DELETE_COLUMNS = Messages.getString( "TableHandleAdapter.transLabel.deleteColumns" ); //$NON-NLS-1$
private static final String TRANS_LABEL_INSERT_COLUMN = Messages.getString( "TableHandleAdapter.transLabel.insertColumn" ); //$NON-NLS-1$
public static final int HEADER = TableItem.HEADER_SLOT;
public static final int DETAIL = TableItem.DETAIL_SLOT;
public static final int FOOTER = TableItem.FOOTER_SLOT;
public static final String TABLE_HEADER = "H"; //$NON-NLS-1$
public static final String TABLE_FOOTER = "F"; //$NON-NLS-1$
public static final String TABLE_DETAIL = "D"; //$NON-NLS-1$
public static final String TABLE_GROUP_HEADER = "gh"; //$NON-NLS-1$
public static final String TABLE_GROUP_FOOTER = "gf"; //$NON-NLS-1$
/* the name model should support */
private HashMap rowInfo = new HashMap( );
protected List rows = new ArrayList( );
/**
* Constructor
*
* @param table
* The handle of report item.
*
* @param mark
*/
public TableHandleAdapter( ReportItemHandle table, IModelAdaptHelper mark )
{
super( table, mark );
}
/**
* Gets the Children list.
*
* @return Children iterator
*/
public List getChildren( )
{
List children = new ArrayList( );
SlotHandle header = getTableHandle( ).getHeader( );
for ( Iterator it = header.iterator( ); it.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) it.next( ) ).getCells( )
.iterator( ), children );
}
SlotHandle group = getTableHandle( ).getGroups( );
for ( Iterator it = group.iterator( ); it.hasNext( ); )
{
TableGroupHandle tableGroups = (TableGroupHandle) it.next( );
SlotHandle groupHeaders = tableGroups.getSlot( GroupElement.HEADER_SLOT );
for ( Iterator heards = groupHeaders.iterator( ); heards.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) heards.next( ) ).getCells( )
.iterator( ), children );
}
}
SlotHandle detail = getTableHandle( ).getDetail( );
for ( Iterator detailRows = detail.iterator( ); detailRows.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) detailRows.next( ) ).getCells( )
.iterator( ), children );
}
group = getTableHandle( ).getGroups( );
for ( ListIterator it = convertIteratorToListIterator( group.iterator( ) ); it.hasPrevious( ); )
{
TableGroupHandle tableGroups = (TableGroupHandle) it.previous( );
SlotHandle groupFooters = tableGroups.getSlot( GroupElement.FOOTER_SLOT );
for ( Iterator heards = groupFooters.iterator( ); heards.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) heards.next( ) ).getCells( )
.iterator( ), children );
}
}
SlotHandle footer = getTableHandle( ).getFooter( );
for ( Iterator footerIT = footer.iterator( ); footerIT.hasNext( ); )
{
insertIteratorToList( ( (RowHandle) footerIT.next( ) ).getCells( )
.iterator( ), children );
}
removePhantomCells(children);
return children;
}
/**
* Some cells might not be relevant, because overriden by colspan/rowspan of other cells
* Example in a three columns table:
* <row>
* <cell>
* <property name="colSpan">3</property>
* <property name="rowSpan">1</property>
* <cell>
* <cell/>
* <cell/>
* <row>
*
* The last two cells are phantom, the layout cannot handle them so we remove them
* at that stage. Ideally the model should not return those cells.
* @param children
*/
protected void removePhantomCells(List children)
{
ArrayList phantomCells = new ArrayList();
for ( Iterator iter = children.iterator(); iter.hasNext();)
{
Object cell = iter.next();
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cell );
if ( cellAdapt.getRowNumber() == 0 || cellAdapt.getColumnNumber() == 0)
{
phantomCells.add( cell );
}
}
for ( Iterator iter = phantomCells.iterator();iter.hasNext();)
{
children.remove(iter.next());
}
}
private ListIterator convertIteratorToListIterator( Iterator iterator )
{
ArrayList list = new ArrayList( );
for ( Iterator it = iterator; it.hasNext( ); )
{
list.add( it.next( ) );
}
return list.listIterator( list.size( ) );
}
private void insertIteratorToList( Iterator iterator,
TableHandleAdapter.RowUIInfomation info )
{
List addList = new ArrayList( );
for ( Iterator it = iterator; it.hasNext( ); )
{
addList.add( it.next( ) );
}
info.addChildren( addList );
}
/**
* Inserts the iterator to the given list
*
* @param iterator
* The iterator
* @param list
* The list
*/
protected void insertIteratorToList( Iterator iterator, List list,
String displayNmae, String type )
{
for ( Iterator it = iterator; it.hasNext( ); )
{
RowHandle handle = (RowHandle) it.next( );
list.add( handle );
TableHandleAdapter.RowUIInfomation info = new TableHandleAdapter.RowUIInfomation( getColumnCount( ) );
info.setType( type );
info.setRowDisplayName( displayNmae );
insertIteratorToList( handle.getCells( ).iterator( ), info );
rowInfo.put( handle, info );
}
}
public List getRows( )
{
if ( checkDirty( ) || rowInfo.isEmpty( ) )
{
reload( );
}
return rows;
}
protected void clearBuffer( )
{
rowInfo.clear( );
rows.clear( );
}
/**
* Gets all rows list.
*
* @return The rows list.
*/
public List initRowsInfo( )
{
clearBuffer( );
SlotHandle header = getTableHandle( ).getHeader( );
insertIteratorToList( header.iterator( ),
rows,
TABLE_HEADER,
TABLE_HEADER );
SlotHandle group = getTableHandle( ).getGroups( );
int number = 0;
for ( Iterator it = group.iterator( ); it.hasNext( ); )
{
number++;
TableGroupHandle tableGroups = (TableGroupHandle) it.next( );
SlotHandle groupHeaders = tableGroups.getSlot( GroupElement.HEADER_SLOT );
insertIteratorToList( groupHeaders.iterator( ),
rows,
( TABLE_GROUP_HEADER + number ),
TABLE_GROUP_HEADER );
}
SlotHandle detail = getTableHandle( ).getDetail( );
insertIteratorToList( detail.iterator( ),
rows,
TABLE_DETAIL,
TABLE_DETAIL );
group = getTableHandle( ).getGroups( );
number = 0;
for ( Iterator it = group.iterator( ); it.hasNext( ); )
{
TableGroupHandle tableGroups = (TableGroupHandle) it.next( );
SlotHandle groupFooters = tableGroups.getSlot( GroupElement.FOOTER_SLOT );
number++;
}
for ( ListIterator it = convertIteratorToListIterator( group.iterator( ) ); it.hasPrevious( ); )
{
TableGroupHandle tableGroups = (TableGroupHandle) it.previous( );
SlotHandle groupFooters = tableGroups.getSlot( GroupElement.FOOTER_SLOT );
insertIteratorToList( groupFooters.iterator( ),
rows,
TABLE_GROUP_FOOTER + number,
TABLE_GROUP_FOOTER );
number--;
}
SlotHandle footer = getTableHandle( ).getFooter( );
insertIteratorToList( footer.iterator( ),
rows,
TABLE_FOOTER,
TABLE_FOOTER );
caleRowInfo( rows );
return rows;
}
/**
* @param children
*/
protected void caleRowInfo( List children )
{
int size = children.size( );
for ( int i = 0; i < size; i++ )
{
RowHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( children.get( i ) );
List cellChildren = adapt.getChildren( );
int len = cellChildren.size( );
TableHandleAdapter.RowUIInfomation info = (TableHandleAdapter.RowUIInfomation) rowInfo.get( children.get( i ) );
for ( int j = 0; j < len; j++ )
{
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellChildren.get( j ) );
int cellIndex = info.getAllChildren( )
.indexOf( cellChildren.get( j ) );
if ( cellAdapt.getColumnSpan( ) != 1 )
{
if ( cellIndex + 2 <= info.getAllChildren( ).size( )
&& cellIndex >= 0 )
{
fillRowInfoChildrenList( children.get( i ),
cellIndex + 2,
cellAdapt.getColumnSpan( ) - 1,
cellChildren.get( j ) );
}
}
if ( cellAdapt.getRowSpan( ) != 1 )
{
for ( int k = i + 1; k < i + cellAdapt.getRowSpan( ); k++ )
{
if ( cellIndex < 0
|| cellIndex + cellAdapt.getColumnSpan( ) > info.getAllChildren( )
.size( ) )
{
continue;
}
fillRowInfoChildrenList( children.get( k ),
cellIndex + 1,
cellAdapt.getColumnSpan( ),
cellChildren.get( j ) );
}
}
}
}
}
private void fillRowInfoChildrenList( Object row, int columnNumber,
int colSpan, Object cell )
{
TableHandleAdapter.RowUIInfomation info = (TableHandleAdapter.RowUIInfomation) rowInfo.get( row );
if ( info == null )
{
return;
}
for ( int i = 0; i < colSpan; i++ )
{
info.addChildren( cell, columnNumber + i - 1 );
}
}
/**
* Get GUI infromation of row. For CSS table support auto layout, the GUI
* infor is different with model info.
*
* @param row
* @return
*/
public TableHandleAdapter.RowUIInfomation getRowInfo( Object row )
{
if ( checkDirty( ) )
{
reload( );
}
return (TableHandleAdapter.RowUIInfomation) rowInfo.get( row );
}
/**
*
* @see org.eclipse.birt.designer.core.facade.DesignElementHandleAdapter#reload()
*/
public void reload( )
{
super.reload( );
initRowsInfo( );
getModelAdaptHelper( ).markDirty( false );
}
/**
* Gets the all columns list.
*
* @return The columns list.
*/
public List getColumns( )
{
List list = new ArrayList( );
insertIteratorToList( getTableHandle( ).getColumns( ).iterator( ), list );
return list;
}
/**
* Gets the special row
*
* @param i
* The row number.
* @return The special row.
*/
public Object getRow( int i )
{
List list = getRows( );
if ( i >= 1 && i <= list.size( ) )
{
return list.get( i - 1 );
}
return null;
}
/**
* Gets the special column
*
* @param i
* The column number.
* @return The special column.
*/
public Object getColumn( int i )
{
List list = getColumns( );
if ( i >= 1 && i <= list.size( ) )
{
return list.get( i - 1 );
}
return null;
}
/**
* Gets the special cell.
*
* @param rowNumber
* The row number.
* @param columnNumber
* The column number.
* @param bool
* @return The special cell.
*/
public Object getCell( int rowNumber, int columnNumber, boolean bool )
{
Object obj = getRow( rowNumber );
TableHandleAdapter.RowUIInfomation info = getRowInfo( obj );
Object retValue = info.getAllChildren( ).get( columnNumber - 1 );
if ( bool )
{
return retValue;
}
if ( HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( retValue )
.getRowNumber( ) != rowNumber
|| HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( retValue )
.getColumnNumber( ) != columnNumber )
{
retValue = null;
}
return retValue;
}
/**
* Gets the special cell.
*
* @param i
* The row number.
* @param j
* The column number.
* @return The special cell.
*/
public Object getCell( int i, int j )
{
return getCell( i, j, true );
}
/**
* Calculates table layout size. For table supports auto layout, the layout
* size need to be calculated when drawing.
*
* @return
*/
public Dimension calculateSize( )
{
if ( !( getModelAdaptHelper( ) instanceof ITableAdaptHelper ) )
{
return new Dimension( );
}
ITableAdaptHelper tableHelper = (ITableAdaptHelper) getModelAdaptHelper( );
int columnCount = getColumnCount( );
int samColumnWidth = 0;
for ( int i = 0; i < columnCount; i++ )
{
samColumnWidth = samColumnWidth
+ tableHelper.caleVisualWidth( i + 1 );
}
int rowCount = getRowCount( );
int samRowHeight = 0;
for ( int i = 0; i < rowCount; i++ )
{
samRowHeight = samRowHeight + tableHelper.caleVisualHeight( i + 1 );
}
return new Dimension( samColumnWidth, samRowHeight ).expand( tableHelper.getInsets( )
.getWidth( ),
tableHelper.getInsets( ).getHeight( ) );
}
/**
* Adjust size of table layout.
*
* @param size
* is all figure size
* @throws SemanticException
*/
public void ajustSize( Dimension size ) throws SemanticException
{
if ( !( getModelAdaptHelper( ) instanceof ITableAdaptHelper ) )
{
return;
}
ITableAdaptHelper tableHelper = (ITableAdaptHelper) getModelAdaptHelper( );
size = size.shrink( tableHelper.getInsets( ).getWidth( ),
tableHelper.getInsets( ).getHeight( ) );
int columnCount = getColumnCount( );
int samColumnWidth = 0;
for ( int i = 0; i < columnCount; i++ )
{
if ( i != columnCount - 1 )
{
samColumnWidth = samColumnWidth
+ tableHelper.caleVisualWidth( i + 1 );
}
}
int lastColumnWidth = size.width - samColumnWidth;
if ( lastColumnWidth < tableHelper.getMinWidth( columnCount ) )
{
lastColumnWidth = tableHelper.getMinWidth( columnCount );
HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( getColumn( columnCount ) )
.setWidth( lastColumnWidth );
}
else if ( lastColumnWidth != tableHelper.caleVisualWidth( columnCount ) )
{
HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( getColumn( columnCount ) )
.setWidth( lastColumnWidth );
}
int rowCount = getRowCount( );
int samRowHeight = 0;
for ( int i = 0; i < rowCount; i++ )
{
if ( i != rowCount - 1 )
{
samRowHeight = samRowHeight
+ tableHelper.caleVisualHeight( i + 1 );
}
}
int lastRowHeight = size.height - samRowHeight;
if ( lastRowHeight < tableHelper.getMinHeight( rowCount ) )
{
lastRowHeight = tableHelper.getMinHeight( rowCount );
HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( getRow( rowCount ) )
.setHeight( lastRowHeight );
}
else if ( lastRowHeight != tableHelper.caleVisualHeight( rowCount ) )
{
HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( getRow( rowCount ) )
.setHeight( lastRowHeight );
}
HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( getRow( rowCount ) )
.setHeight( lastRowHeight );
setSize( new Dimension( samColumnWidth + lastColumnWidth, samRowHeight
+ lastRowHeight ).expand( tableHelper.getInsets( ).getWidth( ),
tableHelper.getInsets( ).getHeight( ) ) );
}
/**
* Get the minimum height.of a specific row.
*
* @param rowNumber
* @return The minimum height.
*/
public int getMinHeight( int rowNumber )
{
// TODO Auto-generated method stub
return RowHandleAdapter.DEFAULT_MINHEIGHT;
}
/**
* Get the minimum width a specific row.
*
* @param columnNumber
* @return The minimum width.
*/
public int getMinWidth( int columnNumber )
{
// TODO Auto-generated method stub
return ColumnHandleAdapter.DEFAULT_MINWIDTH;
}
/**
* @return client area
*/
public Dimension getClientAreaSize( )
{
if ( getModelAdaptHelper( ) instanceof ITableAdaptHelper )
{
return ( (ITableAdaptHelper) getModelAdaptHelper( ) ).getClientAreaSize( );
}
return new Dimension( );
}
private TableHandle getTableHandle( )
{
return (TableHandle) getHandle( );
}
/**
* Returns the defined width in model in Pixel.
*
* @return
*/
public String getDefinedWidth( )
{
DimensionHandle handle = ( (ReportItemHandle) getHandle( ) ).getWidth( );
if ( handle.getUnits( ) == null || handle.getUnits( ).length( ) == 0 )
{
return null;
}
else if ( DesignChoiceConstants.UNITS_PERCENTAGE.equals( handle.getUnits( ) ) )
{
return handle.getMeasure( )
+ DesignChoiceConstants.UNITS_PERCENTAGE;
}
else
{
int px = (int) DEUtil.convertoToPixel( handle );
if ( px <= 0 )
{
return null;
}
return String.valueOf( px );
}
}
/**
* Get the default width.
*
* @param colNumber
* The column number.
* @return The default width.
*/
public int getDefaultWidth( int colNumber )
{
Dimension size = getDefaultSize( );
Object obj = getRow( 1 );
if ( obj == null )
{
return size.width;
}
int allNumbers = getColumnCount( );
if ( allNumbers <= 0 )
{
return size.width;
}
if ( colNumber <= 0 )
{
return size.width;
}
int width = size.width;
int columnNumber = allNumbers;
for ( int i = 1; i < columnNumber + 1; i++ )
{
Object column = getColumn( i );
ColumnHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( column );
if ( adapt.isCustomWidth( ) )
{
allNumbers = allNumbers - 1;
width = width - adapt.getWidth( );
}
}
if ( colNumber == allNumbers )
{
return width / allNumbers + width % allNumbers;
}
return ( width / allNumbers );
}
/**
* Gets the row count
*
* @return The row count.
*/
public int getRowCount( )
{
return getRows( ).size( );
}
/**
* Gets the column count
*
* @return The column count.
*/
public int getColumnCount( )
{
return getColumns( ).size( );
}
/**
* @return The data set.
*/
public Object getDataSet( )
{
return getTableHandle( ).getDataSet( );
}
/**
* Insert a row to a specific position.
*
* @param rowNumber
* The row number.
* @param parentRowNumber
* The row number of parent.
* @throws SemanticException
*/
public void insertRow( int rowNumber, int parentRowNumber )
throws SemanticException
{
transStar( TRANS_LABEL_INSERT_ROW );
Assert.isLegal( rowNumber != 0 );
int realRowNumber = rowNumber > 0 ? parentRowNumber + rowNumber
: parentRowNumber + rowNumber + 1;
int shiftPos = rowNumber > 0 ? rowNumber : rowNumber + 1;
RowHandle row = (RowHandle) getRow( parentRowNumber );
RowHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( row );
RowHandle copy = (RowHandle) adapt.copy( );
TableHandleAdapter.RowUIInfomation rowInfo = getRowInfo( row );
List rowList = rowInfo.getAllChildren( );
int rowSize = rowList.size( );
for ( int i = 0; i < rowSize; i++ )
{
CellHandle parentCell = (CellHandle) rowList.get( i );
CellHandle cell = getCellHandleCopy( parentCell );
copy.getSlot( TableRow.CONTENT_SLOT ).add( cell );
}
SlotHandle parentHandle = row.getContainerSlotHandle( );
parentHandle.add( ( copy ) );
int pos = parentHandle.findPosn( row.getElement( ) );
parentHandle.shift( copy, pos + shiftPos );
RowHandleAdapter copyAdapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( copy );
List copyChildren = copyAdapt.getChildren( );
TableHandleAdapter.RowUIInfomation info = getRowInfo( copy );
List list = info.getAllChildren( );
List temp = new ArrayList( );
int size = list.size( );
List hasAdjust = new ArrayList( );
for ( int i = 0; i < size; i++ )
{
Object fillCell = list.get( i );
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( fillCell );
if ( cellAdapt.getRowNumber( ) != realRowNumber )
{
if ( !hasAdjust.contains( fillCell ) )
{
cellAdapt.setRowSpan( cellAdapt.getRowSpan( ) + 1 );
hasAdjust.add( fillCell );
}
temp.add( new Integer( i ) );
}
}
int copyRowSize = copyChildren.size( );
for ( int i = 0; i < copyRowSize; i++ )
{
if ( temp.contains( new Integer( i ) ) )
{
( (CellHandle) copyChildren.get( i ) ).drop( );
}
}
transEnd( );
}
/**
* Insert a column to a specific position.
*
* @param columnNumber
* The column number.
* @param parentColumnNumber
* The column number of parent.
* @throws SemanticException
*/
public void insertColumn( int columnNumber, int parentColumnNumber )
throws SemanticException
{
transStar( TRANS_LABEL_INSERT_COLUMN );
assert columnNumber != 0;
int realColumnNumber = columnNumber > 0 ? parentColumnNumber
+ columnNumber : parentColumnNumber + columnNumber + 1;
int shiftPos = columnNumber > 0 ? columnNumber : columnNumber + 1;
ColumnHandle column = (ColumnHandle) getColumn( parentColumnNumber );
ColumnHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( column );
ColumnHandle copy = (ColumnHandle) adapt.copy( );
int rowNumber = getRowCount( );
List copyChildren = new ArrayList( );
for ( int i = 0; i < rowNumber; i++ )
{
RowHandle row = (RowHandle) getRow( i + 1 );
TableHandleAdapter.RowUIInfomation rowInfo = getRowInfo( getRow( i + 1 ) );
List rowList = rowInfo.getAllChildren( );
CellHandle parentCell = (CellHandle) rowList.get( parentColumnNumber - 1 );
CellHandle cell = getCellHandleCopy( parentCell );
copyChildren.add( cell );
}
int copyRowSize = copyChildren.size( );
for ( int i = 0; i < copyRowSize; i++ )
{
RowHandle row = (RowHandle) getRow( i + 1 );
row.getSlot( TableRow.CONTENT_SLOT )
.add( (CellHandle) ( copyChildren.get( i ) ),
realColumnNumber - 1 );
}
SlotHandle parentHandle = column.getContainerSlotHandle( );
parentHandle.add( ( copy ) );
int pos = parentHandle.findPosn( column.getElement( ) );
parentHandle.shift( copy, pos + shiftPos );
List temp = new ArrayList( );
List hasAdjust = new ArrayList( );
for ( int i = 0; i < rowNumber; i++ )
{
TableHandleAdapter.RowUIInfomation rowInfo = getRowInfo( getRow( i + 1 ) );
List rowList = rowInfo.getAllChildren( );
Object fillCell = rowList.get( realColumnNumber - 1 );
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( fillCell );
if ( cellAdapt.getColumnNumber( ) != realColumnNumber )
{
if ( !hasAdjust.contains( fillCell ) )
{
cellAdapt.setColumnSpan( cellAdapt.getColumnSpan( ) + 1 );
hasAdjust.add( fillCell );
}
temp.add( new Integer( i ) );
}
}
for ( int i = 0; i < copyRowSize; i++ )
{
if ( temp.contains( new Integer( i ) ) )
{
( (CellHandle) copyChildren.get( i ) ).drop( );
}
}
transEnd( );
}
/**
* @param model
* The object to be removed.
* @throws SemanticException
*/
public void removeChild( Object model ) throws SemanticException
{
assert ( model instanceof DesignElementHandle );
DesignElementHandle ele = (DesignElementHandle) model;
ele.drop( );
}
/**
* Get the padding of the current table.
*
* @param retValue
* The padding value of the current table.
* @return The padding's new value of the current table.
*/
public Insets getPadding( Insets retValue )
{
if ( retValue == null )
{
retValue = new Insets( );
}
else
{
retValue = new Insets( retValue );
}
DimensionHandle fontHandle = getHandle( ).getPrivateStyle( )
.getFontSize( );
int fontSize = 12;//??
if ( fontHandle.getValue( ) instanceof String )
{
fontSize = Integer.valueOf( (String) DesignerConstants.fontMap.get( DEUtil.getFontSize( getHandle( ) ) ) )
.intValue( );
}
else if ( fontHandle.getValue( ) instanceof DimensionValue )
{
DEUtil.convertToPixel( fontHandle.getValue( ), fontSize );
}
DimensionValue dimensionValue = (DimensionValue) getReportItemHandle( ).getProperty( Style.PADDING_TOP_PROP );
double px = DEUtil.convertToPixel( dimensionValue, fontSize );
dimensionValue = (DimensionValue) getReportItemHandle( ).getProperty( Style.PADDING_BOTTOM_PROP );
double py = DEUtil.convertToPixel( dimensionValue, fontSize );
retValue.top = (int) px;
retValue.bottom = (int) py;
dimensionValue = (DimensionValue) getReportItemHandle( ).getProperty( Style.PADDING_LEFT_PROP );
px = DEUtil.convertToPixel( dimensionValue, fontSize );
dimensionValue = (DimensionValue) getReportItemHandle( ).getProperty( Style.PADDING_RIGHT_PROP );
py = DEUtil.convertToPixel( dimensionValue, fontSize );
retValue.left = (int) px;
retValue.right = (int) py;
return retValue;
}
/**
* Delete specific columns from the current table.
*
* @param columns
* The columns to be deleted.
* @throws SemanticException
*/
public void deleteColumn( int[] columns ) throws SemanticException
{
if ( getColumnCount( ) == 1 )
{
getTableHandle( ).drop( );
return;
}
transStar( TRANS_LABEL_DELETE_COLUMNS );
int len = columns.length;
for ( int i = 0; i < len; i++ )
{
deleteColumn( columns[i] );
}
transEnd( );
}
/**
* Delete a specific column from the current table.
*
* @param columnNumber
* The column to be deleted.
* @throws SemanticException
*/
public void deleteColumn( int columnNumber ) throws SemanticException
{
transStar( TRANS_LABEL_DELETE_COLUMN );
int rowCount = getRowCount( );
ColumnHandle column = (ColumnHandle) getColumn( columnNumber );
List deleteCells = new ArrayList( );
for ( int i = 0; i < rowCount; i++ )
{
Object row = getRow( i + 1 );
TableHandleAdapter.RowUIInfomation info = getRowInfo( row );
deleteCells.add( info.getAllChildren( ).get( columnNumber - 1 ) );
}
List trueDeleteCells = new ArrayList( );
int size = deleteCells.size( );
for ( int i = 0; i < size; i++ )
{
Object cell = deleteCells.get( i );
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cell );
if ( cellAdapt.getColumnNumber( ) == columnNumber
&& cellAdapt.getColumnSpan( ) == 1
&& !trueDeleteCells.contains( cell ) )
{
trueDeleteCells.add( cell );
}
}
List temp = new ArrayList( );
for ( int i = 0; i < size; i++ )
{
Object cell = deleteCells.get( i );
if ( !trueDeleteCells.contains( cell ) && !temp.contains( cell ) )
{
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cell );
cellAdapt.setColumnSpan( cellAdapt.getColumnSpan( ) - 1 );
temp.add( cell );
}
}
size = trueDeleteCells.size( );
for ( int i = 0; i < size; i++ )
{
CellHandle cell = (CellHandle) trueDeleteCells.get( i );
cell.drop( );
}
column.drop( );
transEnd( );
reload( );
}
/**
* Delete specific rows from the current table.
*
* @param rows
* The rows to be deleted.
* @throws SemanticException
*/
public void deleteRow( int[] rows ) throws SemanticException
{
if ( getRowCount( ) == 1 )
{
getTableHandle( ).drop( );
return;
}
transStar( TRANS_LABEL_DELETE_ROWS );
Arrays.sort( rows );
int len = rows.length;
for ( int i = len - 1; i >= 0; i-- )
{
deleteRow( rows[i] );
}
transEnd( );
}
/**
* Delete a specific row from the current table.
*
* @param rowsNumber
* The row to be deleted.
* @throws SemanticException
*/
public void deleteRow( int rowsNumber ) throws SemanticException
{
transStar( TRANS_LABEL_DELETE_ROW );
int rowCount = getRowCount( );
RowHandle row = (RowHandle) getRow( rowsNumber );
RowHandleAdapter rowAdapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( row );
List temp = new ArrayList( );
RowHandle nextRow = null;
List shiftCellInfo = new ArrayList( );
if ( rowsNumber + 1 <= rowCount )
{
List trueChildren = rowAdapt.getChildren( );
int cellSize = trueChildren.size( );
nextRow = (RowHandle) getRow( rowsNumber + 1 );
TableHandleAdapter.RowUIInfomation nextRowInfo = getRowInfo( nextRow );
List nextRowChildren = nextRowInfo.getAllChildren( );
for ( int i = 0; i < cellSize; i++ )
{
Object cellHandle = trueChildren.get( i );
CellHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellHandle );
if ( adapt.getRowSpan( ) != 1 )
{
int numberInfo = 0;
int index = nextRowChildren.indexOf( cellHandle );
for ( int j = 0; j < index; j++ )
{
Object nextRowCell = nextRowChildren.get( j );
CellHandleAdapter nextRowCellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( nextRowCell );
if ( nextRowCellAdapt.getRowNumber( ) == rowsNumber + 1
&& !temp.contains( nextRowCell ) )
{
numberInfo = numberInfo + 1;
}
temp.add( nextRowCell );
}
numberInfo = numberInfo + shiftCellInfo.size( );
shiftCellInfo.add( new ShiftNexRowInfo( numberInfo,
cellHandle ) );
}
}
}
TableHandleAdapter.RowUIInfomation info = getRowInfo( row );
List cells = info.getAllChildren( );
temp.clear( );
int cellSize = cells.size( );
for ( int j = 0; j < cellSize; j++ )
{
Object cellHandle = cells.get( j );
CellHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellHandle );
if ( adapt.getRowNumber( ) != rowsNumber
&& !temp.contains( cellHandle ) )
{
adapt.setRowSpan( adapt.getRowSpan( ) - 1 );
temp.add( cellHandle );
}
}
//row.drop( );
for ( int i = 0; i < shiftCellInfo.size( ); i++ )
{
ShiftNexRowInfo shiftInfo = (ShiftNexRowInfo) shiftCellInfo.get( i );
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( shiftInfo.cell );
cellAdapt.setRowSpan( cellAdapt.getRowSpan( ) - 1 );
SlotHandle slotHandle = row.getCells( );
slotHandle.move( (DesignElementHandle) shiftInfo.cell,
nextRow,
TableRow.CONTENT_SLOT,
shiftInfo.index );
}
row.drop( );
transEnd( );
reload( );
}
class ShiftNexRowInfo
{
protected int index;
protected Object cell;
/**
* @param index
* @param cell
*/
public ShiftNexRowInfo( int index, Object cell )
{
super( );
this.index = index;
this.cell = cell;
}
}
static class RowUIInfomation
{
protected static final String GRID_ROW = NAME_NULL; //$NON-NLS-1$
private String type = ""; //$NON-NLS-1$
private String rowDisplayName = ""; //$NON-NLS-1$
Object[] cells = null;
int[] infactAdd = new int[0];
private RowUIInfomation( int columnMunber )
{
cells = new Object[columnMunber];
}
public String getRowDisplayName( )
{
return rowDisplayName;
}
public void setRowDisplayName( String rowDisplayName )
{
this.rowDisplayName = rowDisplayName;
}
public String getType( )
{
return type;
}
public void setType( String type )
{
this.type = type;
}
public void addChildren( Object obj, int index )
{
int cellSize = cells.length;
if ( index >= cellSize )
{
return;
}
ArrayList list = new ArrayList( );
if ( cells[index] != null )
{
Object[] newArray = new Object[cellSize];
for ( int i = 0; i < cellSize; i++ )
{
if ( containIndex( i ) )
{
newArray[i] = cells[i];
}
else if ( cells[i] != null )
{
list.add( cells[i] );
}
}
newArray[index] = obj;
int listSize = list.size( );
for ( int i = 0; i < listSize; i++ )
{
for ( int j = 0; j < cellSize; j++ )
{
if ( newArray[j] == null )
{
newArray[j] = list.get( i );
break;
}
}
}
cells = newArray;
}
else
{
cells[index] = obj;
}
int lenegth = infactAdd.length;
int[] temp = new int[lenegth + 1];
System.arraycopy( infactAdd, 0, temp, 0, lenegth );
temp[lenegth] = index;
infactAdd = temp;
}
private boolean containIndex( int index )
{
int length = infactAdd.length;
for ( int i = 0; i < length; i++ )
{
if ( infactAdd[i] == index )
{
return true;
}
}
return false;
}
public void addChildren( Collection c )
{
Iterator itor = c.iterator( );
int cellSize = cells.length;
while ( itor.hasNext( ) )
{
Object obj = itor.next( );
for ( int i = 0; i < cellSize; i++ )
{
if ( cells[i] == null )
{
cells[i] = obj;
break;
}
}
}
}
public List getAllChildren( )
{
ArrayList retValue = new ArrayList( );
int cellSize = cells.length;
for ( int i = 0; i < cellSize; i++ )
{
retValue.add( cells[i] );
}
return retValue;
}
}
/**
* @param list
* @return If can merge return true, else false.
*/
public boolean canMerge( List list )
{
assert list != null;
int size = list.size( );
if ( size <= 1 )
{
return false;
}
String first = getRowInfo( ( (CellHandle) list.get( 0 ) ).getContainer( ) ).getRowDisplayName( );
for ( int i = 1; i < size; i++ )
{
RowUIInfomation info = getRowInfo( ( (CellHandle) list.get( i ) ).getContainer( ) );
if ( info == null )
{
return false;
}
String str = info.getRowDisplayName( );
if ( !first.equals( str ) )
{
return false;
}
}
return true;
}
/**
* Split a cell to cells.
*
* @param model
* @throws SemanticException
* @throws NameException
* @throws ContentException
*/
public void splitCell( Object model ) throws ContentException,
NameException, SemanticException
{
// TODO Auto-generated method stub
transStar( TRANS_LABEL_SPLIT_CELLS );
assert model instanceof CellHandle;
CellHandle cellHandle = (CellHandle) model;
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellHandle );
int rowNumber = cellAdapt.getRowNumber( );
int rowSpan = cellAdapt.getRowSpan( );
int colSpan = cellAdapt.getColumnSpan( );
//fill the cell row
if ( colSpan != 1 )
{
int index = getIndexofParent( cellHandle );
RowHandle rowHandle = (RowHandle) cellHandle.getContainer( );
for ( int i = 1; i < colSpan; i++ )
{
rowHandle.addElement( getCellHandleCopy( cellHandle ),
TableRow.CONTENT_SLOT,
i + index );
}
}
if ( rowSpan != 1 )
{
for ( int i = rowNumber + 1; i < rowNumber + rowSpan; i++ )
{
RowHandle rowHandle = (RowHandle) getRow( i );
int index = getIndexofParent( cellHandle );
for ( int j = 0; j < colSpan; j++ )
{
rowHandle.addElement( getCellHandleCopy( cellHandle ),
TableRow.CONTENT_SLOT,
j + index );
}
}
}
cellAdapt.setRowSpan( 1 );
cellAdapt.setColumnSpan( 1 );
transEnd( );
}
private int getIndexofParent( CellHandle cellHandle )
{
CellHandleAdapter cellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cellHandle );
TableHandleAdapter.RowUIInfomation info = getRowInfo( cellHandle.getContainer( ) );
List list = info.getAllChildren( );
int index = list.indexOf( cellHandle );
List temp = new ArrayList( );
int number = 0;
for ( int j = 0; j < index; j++ )
{
CellHandleAdapter childCellAdapt = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( list.get( j ) );
if ( childCellAdapt.getRowNumber( ) == cellAdapt.getRowNumber( )
&& !temp.contains( list.get( j ) ) )
{
number = number + 1;
}
temp.add( list.get( j ) );
}
return number;
}
/**
* Gets the cell handle copoy to support row/column insert.
*
* @param cellHandle
* @return
* @throws SemanticException
*/
public CellHandle getCellHandleCopy( CellHandle cellHandle )
throws SemanticException
{
if ( cellHandle == null )
{
return null;
}
CellHandle cell = cellHandle.getElementFactory( ).newCell( );
Iterator iter = cellHandle.getPropertyIterator( );
while ( iter.hasNext( ) )
{
PropertyHandle handle = (PropertyHandle) iter.next( );
String key = handle.getDefn( ).getName( );
if ( handle.isLocal( )
&& ( !( Cell.COL_SPAN_PROP.equals( key ) || Cell.ROW_SPAN_PROP.equals( key ) ) ) )
{
cell.setProperty( key, cellHandle.getProperty( key ) );
}
}
return cell;
}
/**
* Provides insert group function.
*
* @return
* @throws ContentException
* @throws NameException
*/
public TableGroupHandle insertGroup( ) throws ContentException,
NameException
{
if ( DEUtil.getDataSetList( getTableHandle( ) ).isEmpty( ) )
{
return null;
}
transStar( TRANS_LABEL_INSERT_GROUP );
RowHandle header = getTableHandle( ).getElementFactory( ).newTableRow( );
RowHandle footer = getTableHandle( ).getElementFactory( ).newTableRow( );
addCell( header );
addCell( footer );
TableGroupHandle groupHandle = getTableHandle( ).getElementFactory( )
.newTableGroup( );
groupHandle.getSlot( TableGroup.HEADER_SLOT ).add( header );
groupHandle.getSlot( TableGroup.FOOTER_SLOT ).add( footer );
SlotHandle handle = getTableHandle( ).getGroups( );
handle.add( groupHandle );
transEnd( );
return groupHandle;
}
/**
* Provides remove group function
*
* @throws SemanticException
*
*/
public void removeGroup( Object group ) throws SemanticException
{
( (RowHandle) group ).getContainer( ).drop( );
}
private void addCell( RowHandle handle ) throws ContentException,
NameException
{
int count = getColumnCount( );
for ( int i = 0; i < count; i++ )
{
CellHandle cell = handle.getElementFactory( ).newCell( );
handle.addElement( cell, TableRow.CONTENT_SLOT );
}
}
/**
* Insert row in model
*
* @param id
* @throws ContentException
* @throws NameException
*/
public void insertRowInSlotHandle( int id ) throws ContentException,
NameException
{
transStar( TRANS_LABEL_INCLUDE + getOperationName( id ) );
RowHandle rowHandle = getTableHandle( ).getElementFactory( )
.newTableRow( );
addCell( rowHandle );
getTableHandle( ).getSlot( id ).add( rowHandle );
transEnd( );
}
/**
* Delete row in model
*
* @param id
* @throws SemanticException
*/
public void deleteRowInSlotHandle( int id ) throws SemanticException
{
transStar( TRANS_LABEL_NOT_INCLUDE + getOperationName( id ) );
int[] rows = new int[0];
Iterator itor = getTableHandle( ).getSlot( id ).iterator( );
while ( itor.hasNext( ) )
{
Object obj = itor.next( );
RowHandleAdapter adapt = HandleAdapterFactory.getInstance( )
.getRowHandleAdapter( obj );
int lenegth = rows.length;
int[] temp = new int[lenegth + 1];
System.arraycopy( rows, 0, temp, 0, lenegth );
temp[lenegth] = adapt.getRowNumber( );
rows = temp;
}
deleteRow( rows );
transEnd( );
}
private String getOperationName( int id )
{
switch ( id )
{
case HEADER :
return NAME_HEADRER;
case FOOTER :
return NAME_FOOTER;
case DETAIL :
return NAME_DETAIL;
default :
return NAME_NULL; //$NON-NLS-1$
}
}
/**
* Check if the slot handle contains specified id.
*
* @param id
* @return
*/
public boolean hasSlotHandleRow( int id )
{
Iterator itor = getTableHandle( ).getSlot( id ).iterator( );
while ( itor.hasNext( ) )
{
return true;
}
return false;
}
} | - SCR(s) Resolved:
- Description: Fix null point error.
- Regression ( Yes/No ): no
- Code Owner: DaZhen Gao
- Code Reviewers: GUI SHA,Hongxia Wang, Sissi Zhu
- Tests: Yes
- Test Automated (Yes/No, if No? then explain why): No, gui feature
- Branches Involved: Head
- Case Entries Resolved:
- Notes to Developers:
- Notes to QA:
- Notes to Documentation:
- Notes to Configuration Management:
- Notes to Support:
- Notes to Product Marketing:
| UI/org.eclipse.birt.report.designer.core/src/org/eclipse/birt/report/designer/core/model/schematic/TableHandleAdapter.java | - SCR(s) Resolved: | <ide><path>I/org.eclipse.birt.report.designer.core/src/org/eclipse/birt/report/designer/core/model/schematic/TableHandleAdapter.java
<ide> {
<ide> super.reload( );
<ide> initRowsInfo( );
<del> getModelAdaptHelper( ).markDirty( false );
<add> if (getModelAdaptHelper() != null)
<add> {
<add> getModelAdaptHelper( ).markDirty( false );
<add> }
<add>
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | cbd98b68645e6f6cfd4b9cdd07a086ac8b82c574 | 0 | RenzoH89/hsac-fitnesse-fixtures,RenzoH89/hsac-fitnesse-fixtures,RenzoH89/hsac-fitnesse-fixtures,RenzoH89/hsac-fitnesse-fixtures | package nl.hsac.fitnesse.fixture.slim.web;
import fitnesse.slim.fixtureInteraction.FixtureInteraction;
import nl.hsac.fitnesse.fixture.slim.SlimFixture;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.StopTestException;
import nl.hsac.fitnesse.fixture.slim.web.annotation.TimeoutPolicy;
import nl.hsac.fitnesse.fixture.slim.web.annotation.WaitUntil;
import nl.hsac.fitnesse.fixture.util.BinaryHttpResponse;
import nl.hsac.fitnesse.fixture.util.FileUtil;
import nl.hsac.fitnesse.fixture.util.HttpResponse;
import nl.hsac.fitnesse.fixture.util.ReflectionHelper;
import nl.hsac.fitnesse.fixture.util.selenium.SeleniumHelper;
import nl.hsac.fitnesse.slim.interaction.ExceptionHelper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BrowserTest extends SlimFixture {
private SeleniumHelper seleniumHelper = getEnvironment().getSeleniumHelper();
private ReflectionHelper reflectionHelper = getEnvironment().getReflectionHelper();
private NgBrowserTest ngBrowserTest;
private boolean implicitWaitForAngular = false;
private boolean implicitFindInFrames = true;
private int secondsBeforeTimeout;
private int secondsBeforePageLoadTimeout;
private int waitAfterScroll = 150;
private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/";
private String screenshotHeight = "200";
private String downloadBase = new File(filesDir, "downloads").getPath() + "/";
private String pageSourceBase = new File(filesDir, "pagesources").getPath() + "/";
@Override
protected void beforeInvoke(Method method, Object[] arguments) {
super.beforeInvoke(method, arguments);
waitForAngularIfNeeded(method);
}
@Override
protected Object invoke(final FixtureInteraction interaction, final Method method, final Object[] arguments)
throws Throwable {
Object result;
WaitUntil waitUntil = reflectionHelper.getAnnotation(WaitUntil.class, method);
if (waitUntil == null) {
result = superInvoke(interaction, method, arguments);
} else {
result = invokedWrappedInWaitUntil(waitUntil, interaction, method, arguments);
}
return result;
}
protected Object invokedWrappedInWaitUntil(WaitUntil waitUntil, final FixtureInteraction interaction, final Method method, final Object[] arguments) {
ExpectedCondition<Object> condition = new ExpectedCondition<Object>() {
@Override
public Object apply(WebDriver webDriver) {
try {
return superInvoke(interaction, method, arguments);
} catch (Throwable e) {
Throwable realEx = ExceptionHelper.stripReflectionException(e);
if (realEx instanceof RuntimeException) {
throw (RuntimeException) realEx;
} else if (realEx instanceof Error) {
throw (Error) realEx;
} else {
throw new RuntimeException(realEx);
}
}
}
};
if (implicitFindInFrames) {
condition = getSeleniumHelper().conditionForAllFrames(condition);
}
Object result;
switch (waitUntil.value()) {
case STOP_TEST:
result = waitUntilOrStop(condition);
break;
case RETURN_NULL:
result = waitUntilOrNull(condition);
break;
case RETURN_FALSE:
result = waitUntilOrNull(condition) != null;
break;
case THROW:
default:
result = waitUntil(condition);
break;
}
return result;
}
protected Object superInvoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable {
return super.invoke(interaction, method, arguments);
}
/**
* Determines whether the current method might require waiting for angular given the currently open site,
* and ensure it does if needed.
* @param method
*/
protected void waitForAngularIfNeeded(Method method) {
if (isImplicitWaitForAngularEnabled()) {
try {
if (ngBrowserTest == null) {
ngBrowserTest = new NgBrowserTest();
}
if (ngBrowserTest.requiresWaitForAngular(method) && currentSiteUsesAngular()) {
try {
ngBrowserTest.waitForAngularRequestsToFinish();
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Found Angular, but encountered an error while waiting for it to be ready. ");
e.printStackTrace();
}
}
} catch (UnhandledAlertException e) {
System.err.println("Cannot determine whether Angular is present while alert is active.");
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Error while determining whether Angular is present. ");
e.printStackTrace();
}
}
}
protected boolean currentSiteUsesAngular() {
Object windowHasAngular = getSeleniumHelper().executeJavascript("return window.angular?1:0;");
return Long.valueOf(1).equals(windowHasAngular);
}
@Override
protected Throwable handleException(Method method, Object[] arguments, Throwable t) {
Throwable result;
if (t instanceof UnhandledAlertException) {
UnhandledAlertException e = (UnhandledAlertException) t;
String alertText = e.getAlertText();
if (alertText == null) {
alertText = alertText();
}
String msgBase = "Unhandled alert: alert must be confirmed or dismissed before test can continue. Alert text: " + alertText;
String msg = getSlimFixtureExceptionMessage("alertException", msgBase, e);
result = new StopTestException(false, msg, t);
} else if (t instanceof SlimFixtureException) {
result = super.handleException(method, arguments, t);
} else {
String msg = getSlimFixtureExceptionMessage("exception", null, t);
result = new SlimFixtureException(false, msg, t);
}
return result;
}
public BrowserTest() {
secondsBeforeTimeout(seleniumHelper.getDefaultTimeoutSeconds());
ensureActiveTabIsNotClosed();
}
public BrowserTest(int secondsBeforeTimeout) {
secondsBeforeTimeout(secondsBeforeTimeout);
ensureActiveTabIsNotClosed();
}
public boolean open(String address) {
final String url = getUrl(address);
try {
getNavigation().to(url);
} catch (TimeoutException e) {
handleTimeoutException(e);
} finally {
switchToDefaultContent();
}
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
String readyState = getSeleniumHelper().executeJavascript("return document.readyState").toString();
// IE 7 is reported to return "loaded"
boolean done = "complete".equalsIgnoreCase(readyState) || "loaded".equalsIgnoreCase(readyState);
if (!done) {
System.err.printf("Open of %s returned while document.readyState was %s", url, readyState);
System.err.println();
}
return done;
}
});
return true;
}
public String location() {
return driver().getCurrentUrl();
}
public boolean back() {
getNavigation().back();
switchToDefaultContent();
// firefox sometimes prevents immediate back, if previous page was reached via POST
waitMilliseconds(500);
WebElement element = findElement(By.id("errorTryAgain"));
if (element != null) {
element.click();
// don't use confirmAlert as this may be overridden in subclass and to get rid of the
// firefox pop-up we need the basic behavior
getSeleniumHelper().getAlert().accept();
}
return true;
}
public boolean forward() {
getNavigation().forward();
switchToDefaultContent();
return true;
}
public boolean refresh() {
getNavigation().refresh();
switchToDefaultContent();
return true;
}
private WebDriver.Navigation getNavigation() {
return getSeleniumHelper().navigate();
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String alertText() {
Alert alert = getAlert();
String text = null;
if (alert != null) {
text = alert.getText();
}
return text;
}
@WaitUntil
public boolean confirmAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.accept();
onAlertHandled(true);
result = true;
}
return result;
}
@WaitUntil
public boolean dismissAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.dismiss();
onAlertHandled(false);
result = true;
}
return result;
}
/**
* Called when an alert is either dismissed or accepted.
* @param accepted true if the alert was accepted, false if dismissed.
*/
protected void onAlertHandled(boolean accepted) {
// if we were looking in nested frames, we could not go back to original frame
// because of the alert. Ensure we do so now the alert is handled.
getSeleniumHelper().resetFrameDepthOnAlertError();
}
protected Alert getAlert() {
return getSeleniumHelper().getAlert();
}
public boolean openInNewTab(String url) {
String cleanUrl = getUrl(url);
final int tabCount = tabCount();
getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl);
// ensure new window is open
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return tabCount() > tabCount;
}
});
return switchToNextTab();
}
@WaitUntil
public boolean switchToNextTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab + 1;
if (nextTab == tabs.size()) {
nextTab = 0;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
@WaitUntil
public boolean switchToPreviousTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab - 1;
if (nextTab < 0) {
nextTab = tabs.size() - 1;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
public boolean closeTab() {
boolean result = false;
List<String> tabs = getTabHandles();
int currentTab = getCurrentTabIndex(tabs);
int tabToGoTo = -1;
if (currentTab > 0) {
tabToGoTo = currentTab - 1;
} else {
if (tabs.size() > 1) {
tabToGoTo = 1;
}
}
if (tabToGoTo > -1) {
WebDriver driver = driver();
driver.close();
goToTab(tabs, tabToGoTo);
result = true;
}
return result;
}
public void ensureOnlyOneTab() {
ensureActiveTabIsNotClosed();
int tabCount = tabCount();
for (int i = 1; i < tabCount; i++) {
closeTab();
}
}
public boolean ensureActiveTabIsNotClosed() {
boolean result = false;
List<String> tabHandles = getTabHandles();
int currentTab = getCurrentTabIndex(tabHandles);
if (currentTab < 0) {
result = true;
goToTab(tabHandles, 0);
}
return result;
}
public int tabCount() {
return getTabHandles().size();
}
public int currentTabIndex() {
return getCurrentTabIndex(getTabHandles()) + 1;
}
protected int getCurrentTabIndex(List<String> tabHandles) {
return getSeleniumHelper().getCurrentTabIndex(tabHandles);
}
protected void goToTab(List<String> tabHandles, int indexToGoTo) {
getSeleniumHelper().goToTab(tabHandles, indexToGoTo);
}
protected List<String> getTabHandles() {
return getSeleniumHelper().getTabHandles();
}
/**
* Activates main/top-level iframe (i.e. makes it the current frame).
*/
public void switchToDefaultContent() {
getSeleniumHelper().switchToDefaultContent();
clearSearchContext();
}
/**
* Activates specified child frame of current iframe.
* @param technicalSelector selector to find iframe.
* @return true if iframe was found.
*/
public boolean switchToFrame(String technicalSelector) {
boolean result = false;
WebElement iframe = getElement(technicalSelector);
if (iframe != null) {
getSeleniumHelper().switchToFrame(iframe);
result = true;
}
return result;
}
/**
* Activates parent frame of current iframe.
* Does nothing if when current frame is the main/top-level one.
*/
public void switchToParentFrame() {
getSeleniumHelper().switchToParentFrame();
}
public String pageTitle() {
return getSeleniumHelper().getPageTitle();
}
/**
* @return current page's content type.
*/
public String pageContentType() {
String result = null;
Object ct = getSeleniumHelper().executeJavascript("return document.contentType;");
if (ct != null) {
result = ct.toString();
}
return result;
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAs(String value, String place) {
return enterAsIn(value, place, null);
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAsIn(String value, String place, String container) {
return enter(value, place, container, true);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterFor(String value, String place) {
return enterForIn(value, place, null);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterForIn(String value, String place, String container) {
return enter(value, place, container, false);
}
protected boolean enter(String value, String place, boolean shouldClear) {
return enter(value, place, null, shouldClear);
}
protected boolean enter(String value, String place, String container, boolean shouldClear) {
WebElement element = getElementToSendValue(place, container);
boolean result = element != null && isInteractable(element);
if (result) {
if (shouldClear) {
element.clear();
}
sendValue(element, value);
}
return result;
}
protected WebElement getElementToSendValue(String place) {
return getElementToSendValue(place, null);
}
protected WebElement getElementToSendValue(String place, String container) {
return getElement(place, container);
}
/**
* Simulates pressing the 'Tab' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressTab() {
return sendKeysToActiveElement(Keys.TAB);
}
/**
* Simulates pressing the 'Enter' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEnter() {
return sendKeysToActiveElement(Keys.ENTER);
}
/**
* Simulates pressing the 'Esc' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEsc() {
return sendKeysToActiveElement(Keys.ESCAPE);
}
/**
* Simulates typing a text to the current active element.
* @param text text to type.
* @return true, if an element was active the text could be sent to.
*/
public boolean type(String text) {
String value = cleanupValue(text);
return sendKeysToActiveElement(value);
}
/**
* Simulates pressing a key (or a combination of keys).
* (Unfortunately not all combinations seem to be accepted by all drivers, e.g.
* Chrome on OSX seems to ignore Command+A or Command+T; https://code.google.com/p/selenium/issues/detail?id=5919).
* @param key key to press, can be a normal letter (e.g. 'M') or a special key (e.g. 'down').
* Combinations can be passed by separating the keys to send with '+' (e.g. Command + T).
* @return true, if an element was active the key could be sent to.
*/
public boolean press(String key) {
CharSequence s;
String[] parts = key.split("\\s*\\+\\s*");
if (parts.length > 1
&& !"".equals(parts[0]) && !"".equals(parts[1])) {
CharSequence[] sequence = new CharSequence[parts.length];
for (int i = 0; i < parts.length; i++) {
sequence[i] = parseKey(parts[i]);
}
s = Keys.chord(sequence);
} else {
s = parseKey(key);
}
return sendKeysToActiveElement(s);
}
protected CharSequence parseKey(String key) {
CharSequence s;
try {
s = Keys.valueOf(key.toUpperCase());
} catch (IllegalArgumentException e) {
s = key;
}
return s;
}
/**
* Simulates pressing keys.
* @param keys keys to press.
* @return true, if an element was active the keys could be sent to.
*/
protected boolean sendKeysToActiveElement(CharSequence keys) {
boolean result = false;
WebElement element = getSeleniumHelper().getActiveElement();
if (element != null) {
element.sendKeys(keys);
result = true;
}
return result;
}
/**
* Sends Fitnesse cell content to element.
* @param element element to call sendKeys() on.
* @param value cell content.
*/
protected void sendValue(WebElement element, String value) {
if (StringUtils.isNotEmpty(value)) {
String keys = cleanupValue(value);
element.sendKeys(keys);
}
}
@WaitUntil
public boolean selectAs(String value, String place) {
return selectFor(value, place);
}
@WaitUntil
public boolean selectFor(String value, String place) {
return selectForIn(value, place, null);
}
@WaitUntil
public boolean selectForIn(String value, String place, String container) {
SearchContext searchContext = setSearchContextToContainer(container);
try {
// choose option for select, if possible
boolean result = clickSelectOption(place, value);
if (!result) {
// try to click the first element with right value
result = click(value);
}
return result;
} finally {
resetSearchContext(searchContext);
}
}
@WaitUntil
public boolean enterForHidden(final String value, final String idOrName) {
return getSeleniumHelper().setHiddenInputValue(idOrName, value);
}
private boolean clickSelectOption(String selectPlace, String optionValue) {
WebElement element = getElementToSelectFor(selectPlace);
return clickSelectOption(element, optionValue);
}
protected WebElement getElementToSelectFor(String selectPlace) {
return getElement(selectPlace);
}
protected boolean clickSelectOption(WebElement element, String optionValue) {
boolean result = false;
if (element != null) {
if (isSelect(element)) {
optionValue = cleanupValue(optionValue);
By xpath = getSeleniumHelper().byXpath(".//option[normalized(text()) = '%s']", optionValue);
WebElement option = getSeleniumHelper().findElement(element, false, xpath);
if (option == null) {
xpath = getSeleniumHelper().byXpath(".//option[contains(normalized(text()), '%s')]", optionValue);
option = getSeleniumHelper().findElement(element, false, xpath);
}
if (option != null) {
result = clickElement(option);
}
}
}
return result;
}
@WaitUntil
public boolean click(final String place) {
return clickImp(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailable(String place) {
return clickIfAvailableIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailableIn(String place, String container) {
return clickImp(place, container);
}
@WaitUntil
public boolean clickIn(String place, String container) {
return clickImp(place, container);
}
protected boolean clickImp(String place, String container) {
boolean result = false;
place = cleanupValue(place);
try {
WebElement element = getElementToClick(place, container);
result = clickElement(element);
} catch (WebDriverException e) {
// if other element hides the element (in Chrome) an exception is thrown
String msg = e.getMessage();
if (msg == null || !msg.contains("Other element would receive the click")) {
throw e;
}
}
return result;
}
@WaitUntil
public boolean doubleClick(final String place) {
WebElement element = getElementToClick(place);
return doubleClick(element);
}
protected boolean doubleClick(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
Actions actions = getActions();
actions.doubleClick(element).perform();
result = true;
}
}
return result;
}
protected Actions getActions() {
WebDriver driver = driver();
return new Actions(driver);
}
protected WebElement getElementToClick(String place) {
return getElementToClick(place, null);
}
protected WebElement getElementToClick(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
return getSeleniumHelper().getElementToClick(place);
} finally {
resetSearchContext(currentSearchContext);
}
}
@WaitUntil
public boolean setSearchContextTo(String container) {
boolean result = false;
WebElement containerElement = getContainerElement(container);
if (containerElement != null) {
getSeleniumHelper().setCurrentContext(containerElement);
result = true;
}
return result;
}
protected SearchContext setSearchContextToContainer(String container) {
SearchContext result = null;
if (container != null) {
SearchContext currentSearchContext = getSeleniumHelper().getCurrentContext();
if (setSearchContextTo(container)) {
result = currentSearchContext;
}
}
return result;
}
public void clearSearchContext() {
getSeleniumHelper().setCurrentContext(null);
}
protected void resetSearchContext(SearchContext currentSearchContext) {
if (currentSearchContext != null) {
getSeleniumHelper().setCurrentContext(currentSearchContext);
}
}
protected WebElement getContainerElement(String container) {
WebElement containerElement = null;
By by = getSeleniumHelper().placeToBy(container);
if (by != null) {
containerElement = findElement(by);
} else {
containerElement = findByXPath(".//fieldset[.//legend/text()[normalized(.) = '%s']]", container);
if (containerElement == null) {
containerElement = getSeleniumHelper().getElementByAriaLabel(container, -1);
if (containerElement == null) {
containerElement = findByXPath(".//fieldset[.//legend/text()[contains(normalized(.), '%s')]]", container);
if (containerElement == null) {
containerElement = getSeleniumHelper().getElementByPartialAriaLabel(container, -1);
}
}
}
}
return containerElement;
}
protected boolean clickElement(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
element.click();
result = true;
}
}
return result;
}
protected boolean isInteractable(WebElement element) {
return getSeleniumHelper().isInteractable(element);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForPage(String pageName) {
return pageTitle().equals(pageName);
}
public boolean waitForTagWithText(String tagName, String expectedText) {
return waitForElementWithText(By.tagName(tagName), expectedText);
}
public boolean waitForClassWithText(String cssClassName, String expectedText) {
return waitForElementWithText(By.className(cssClassName), expectedText);
}
protected boolean waitForElementWithText(final By by, String expectedText) {
final String textToLookFor = cleanExpectedValue(expectedText);
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
boolean ok = false;
List<WebElement> elements = webDriver.findElements(by);
if (elements != null) {
for (WebElement element : elements) {
// we don't want stale elements to make single
// element false, but instead we stop processing
// current list and do a new findElements
ok = hasText(element, textToLookFor);
if (ok) {
// no need to continue to check other elements
break;
}
}
}
return ok;
}
});
}
protected String cleanExpectedValue(String expectedText) {
return cleanupValue(expectedText);
}
protected boolean hasText(WebElement element, String textToLookFor) {
boolean ok;
String actual = getElementText(element);
if (textToLookFor == null) {
ok = actual == null;
} else {
if (StringUtils.isEmpty(actual)) {
String value = element.getAttribute("value");
if (!StringUtils.isEmpty(value)) {
actual = value;
}
}
if (actual != null) {
actual = actual.trim();
}
ok = textToLookFor.equals(actual);
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForClass(String cssClassName) {
boolean ok = false;
WebElement element = findElement(By.className(cssClassName));
if (element != null) {
ok = true;
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisible(String place) {
return waitForVisibleIn(place, null);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisibleIn(String place, String container) {
Boolean result = Boolean.FALSE;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
/**
* @deprecated use #waitForVisible(xpath=) instead
*/
@Deprecated
public boolean waitForXPathVisible(String xPath) {
By by = By.xpath(xPath);
return waitForVisible(by);
}
@Deprecated
protected boolean waitForVisible(final By by) {
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
Boolean result = Boolean.FALSE;
WebElement element = findElement(by);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
});
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOf(String place) {
return valueFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueFor(String place) {
return valueForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfIn(String place, String container) {
return valueForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueForIn(String place, String container) {
WebElement element = getElementToRetrieveValue(place, container);
return valueFor(element);
}
protected WebElement getElementToRetrieveValue(String place, String container) {
return getElement(place, container);
}
protected String valueFor(WebElement element) {
String result = null;
if (element != null) {
if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
if (options.size() > 0) {
result = getElementText(options.get(0));
}
} else {
String elementType = element.getAttribute("type");
if ("checkbox".equals(elementType)
|| "radio".equals(elementType)) {
result = String.valueOf(element.isSelected());
} else if ("li".equalsIgnoreCase(element.getTagName())) {
result = getElementText(element);
} else {
result = element.getAttribute("value");
if (result == null) {
result = getElementText(element);
}
}
}
}
return result;
}
private boolean isSelect(WebElement element) {
return "select".equalsIgnoreCase(element.getTagName());
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOf(String place) {
return valuesFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOfIn(String place, String container) {
return valuesForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesFor(String place) {
return valuesForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesForIn(String place, String container) {
ArrayList<String> values = null;
WebElement element = getElementToRetrieveValue(place, container);
if (element != null) {
values = new ArrayList<String>();
String tagName = element.getTagName();
if ("ul".equalsIgnoreCase(tagName)
|| "ol".equalsIgnoreCase(tagName)) {
List<WebElement> items = element.findElements(By.tagName("li"));
for (WebElement item : items) {
if (item.isDisplayed()) {
values.add(getElementText(item));
}
}
} else if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
for (WebElement item : options) {
values.add(getElementText(item));
}
} else {
values.add(valueFor(element));
}
}
return values;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberFor(String place) {
return numberForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberForIn(String place, String container) {
SearchContext searchContext = setSearchContextToContainer(container);
try {
Integer number = null;
WebElement element = findByXPath(".//ol/li/descendant-or-self::text()[normalized(.)='%s']/ancestor-or-self::li", place);
if (element == null) {
element = findByXPath(".//ol/li/descendant-or-self::text()[contains(normalized(.),'%s')]/ancestor-or-self::li", place);
}
if (element != null) {
scrollIfNotOnScreen(element);
number = getSeleniumHelper().getNumberFor(element);
}
return number;
} finally {
resetSearchContext(searchContext);
}
}
public ArrayList<String> availableOptionsFor(String place) {
ArrayList<String> result = null;
WebElement element = getElementToSelectFor(place);
if (element != null) {
scrollIfNotOnScreen(element);
result = getSeleniumHelper().getAvailableOptions(element);
}
return result;
}
@WaitUntil
public boolean clear(String place) {
return clearIn(place, null);
}
@WaitUntil
public boolean clearIn(String place, String container) {
boolean result = false;
WebElement element = getElementToClear(place, container);
if (element != null) {
element.clear();
result = true;
}
return result;
}
protected WebElement getElementToClear(String place, String container) {
return getElementToSendValue(place, container);
}
@WaitUntil
public boolean enterAsInRowWhereIs(String value, String requestedColumnName, String selectOnColumn, String selectOnValue) {
boolean result = false;
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
String requestedIndex = getXPathForColumnIndex(requestedColumnName);
WebElement cell = findByXPath("%s[%s]", columnXPath, requestedIndex);
if (cell != null) {
WebElement element = getSeleniumHelper().getNestedElementForValue(cell);
if (isSelect(element)) {
result = clickSelectOption(element, value);
} else {
if (isInteractable(element)) {
result = true;
element.clear();
sendValue(element, value);
}
}
}
return result;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfColumnNumberInRowNumber(int columnIndex, int rowIndex) {
return getValueByXPath("(.//tr[boolean(td)])[%s]/td[%s]", Integer.toString(rowIndex), Integer.toString(columnIndex));
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowNumber(String requestedColumnName, int rowIndex) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowIndex);
return valueInRow(columnXPath, requestedColumnName);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowWhereIs(String requestedColumnName, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return valueInRow(columnXPath, requestedColumnName);
}
protected String valueInRow(String columnXPath, String requestedColumnName) {
String requestedIndex = getXPathForColumnIndex(requestedColumnName);
return getValueByXPath("%s[%s]", columnXPath, requestedIndex);
}
protected String getValueByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
if (element != null) {
WebElement nested = getSeleniumHelper().getNestedElementForValue(element);
if (isInteractable(nested)) {
element = nested;
}
}
return valueFor(element);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean rowExistsWhereIs(String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return findByXPath(columnXPath) != null;
}
@WaitUntil
public boolean clickInRowNumber(String place, int rowIndex) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowIndex);
return clickInRow(columnXPath, place);
}
@WaitUntil
public boolean clickInRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return clickInRow(columnXPath, place);
}
protected boolean clickInRow(String columnXPath, String place) {
// find an input to click in the row
WebElement element = findByXPath("%s//*[(local-name()='input' and contains(@value, '%s'))" +
" or contains(normalized(text()),'%s') or contains(@title, '%s')]",
columnXPath, place,
place, place);
return clickElement(element);
}
/**
* Downloads the target of a link in a grid's row.
* @param place which link to download.
* @param rowNumber (1-based) row number to retrieve link from.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowNumber(String place, int rowNumber) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowNumber);
return downloadFromRow(columnXPath, place);
}
/**
* Downloads the target of a link in a grid, finding the row based on one of the other columns' value.
* @param place which link to download.
* @param selectOnColumn column header of cell whose value must be selectOnValue.
* @param selectOnValue value to be present in selectOnColumn to find correct row.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return downloadFromRow(columnXPath, place);
}
protected String downloadFromRow(String columnXPath, String place) {
String result = null;
// find an a to download from based on its text()
WebElement element = findByXPath("%s//a[contains(normalized(text()),'%s')]", columnXPath, place);
if (element == null) {
// find an a to download based on its column header
String requestedIndex = getXPathForColumnIndex(place);
element = findByXPath("%s[%s]//a", columnXPath, requestedIndex);
if (element == null) {
// find an a to download in the row by its title (aka tooltip)
element = findByXPath("%s//a[contains(@title, '%s')]", columnXPath, place);
}
}
if (element != null) {
result = downloadLinkTarget(element);
}
return result;
}
/**
* Creates an XPath expression that will find a cell in a row, selecting the row based on the
* text in a specific column (identified by its header text).
* @param columnName header text of the column to find value in.
* @param value text to find in column with the supplied header.
* @return XPath expression selecting a td in the row
*/
protected String getXPathForColumnInRowByValueInOtherColumn(String columnName, String value) {
String selectIndex = getXPathForColumnIndex(columnName);
return String.format(".//tr[td[%s]/descendant-or-self::text()[normalized(.)='%s']]/td", selectIndex, value);
}
/**
* Creates an XPath expression that will determine, for a row, which index to use to select the cell in the column
* with the supplied header text value.
* @param columnName name of column in header (th)
* @return XPath expression which can be used to select a td in a row
*/
protected String getXPathForColumnIndex(String columnName) {
// determine how many columns are before the column with the requested name
// the column with the requested name will have an index of the value +1 (since XPath indexes are 1 based)
return String.format("count(ancestor::table[1]//tr/th/descendant-or-self::text()[normalized(.)='%s']/ancestor-or-self::th[1]/preceding-sibling::th)+1", columnName);
}
protected WebElement getElement(String place) {
return getElement(place, null);
}
protected WebElement getElement(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
return getSeleniumHelper().getElement(place);
} finally {
resetSearchContext(currentSearchContext);
}
}
/**
* @deprecated use #click(xpath=) instead.
*/
@WaitUntil
@Deprecated
public boolean clickByXPath(String xPath) {
WebElement element = findByXPath(xPath);
return clickElement(element);
}
/**
* @deprecated use #valueOf(xpath=) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByXPath(String xPath) {
return getTextByXPath(xPath);
}
protected String getTextByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
return getElementText(element);
}
/**
* @deprecated use #valueOf(css=.) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByClassName(String className) {
return getTextByClassName(className);
}
protected String getTextByClassName(String className) {
WebElement element = findByClassName(className);
return getElementText(element);
}
protected WebElement findByClassName(String className) {
By by = By.className(className);
return findElement(by);
}
protected WebElement findByXPath(String xpathPattern, String... params) {
return getSeleniumHelper().findByXPath(xpathPattern, params);
}
protected WebElement findByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElement(by);
}
protected List<WebElement> findAllByXPath(String xpathPattern, String... params) {
By by = getSeleniumHelper().byXpath(xpathPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByCss(String cssPattern, String... params) {
By by = getSeleniumHelper().byCss(cssPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElements(by);
}
protected List<WebElement> findElements(By by) {
return driver().findElements(by);
}
public void waitMilliSecondAfterScroll(int msToWait) {
waitAfterScroll = msToWait;
}
protected String getElementText(WebElement element) {
String result = null;
if (element != null) {
scrollIfNotOnScreen(element);
result = element.getText();
}
return result;
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
*/
@WaitUntil
public boolean scrollTo(String place) {
return scrollToIn(place, null);
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
* @param container parent of place.
*/
@WaitUntil
public boolean scrollToIn(String place, String container) {
boolean result = false;
WebElement element = getElementToScrollTo(place, container);
if (element != null) {
scrollTo(element);
result = true;
}
return result;
}
protected WebElement getElementToScrollTo(String place, String container) {
return getElementToCheckVisibility(place, container);
}
/**
* Scrolls browser window so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollTo(WebElement element) {
getSeleniumHelper().scrollTo(element);
if (waitAfterScroll > 0) {
waitMilliseconds(waitAfterScroll);
}
}
/**
* Scrolls browser window if element is not currently visible so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollIfNotOnScreen(WebElement element) {
if (!element.isDisplayed() || !isElementOnScreen(element)) {
scrollTo(element);
}
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabled(String place) {
return isEnabledIn(place, null);
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @param container parent of place.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabledIn(String place, String container) {
boolean result = false;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
result = element.isEnabled();
}
return result;
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisible(String place) {
return isVisibleIn(place, null);
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleIn(String place, String container) {
return isVisibleImpl(place, container, true);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPage(String place) {
return isVisibleOnPageIn(place, null);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPageIn(String place, String container) {
return isVisibleImpl(place, container, false);
}
protected boolean isVisibleImpl(String place, String container, boolean checkOnScreen) {
boolean result = false;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null && element.isDisplayed()) {
if (checkOnScreen) {
result = isElementOnScreen(element);
} else {
result = true;
}
}
return result;
}
protected WebElement getElementToCheckVisibility(String place) {
return getElementToCheckVisibility(place, null);
}
protected WebElement getElementToCheckVisibility(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
return getElementToClick(place);
} finally {
resetSearchContext(currentSearchContext);
}
}
/**
* Checks whether element is in browser's viewport.
* @param element element to check
* @return true if element is in browser's viewport.
*/
protected boolean isElementOnScreen(WebElement element) {
Boolean onScreen = getSeleniumHelper().isElementOnScreen(element);
return onScreen == null || onScreen.booleanValue();
}
@WaitUntil
public boolean hoverOver(String place) {
return hoverOverIn(place, null);
}
@WaitUntil
public boolean hoverOverIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return hoverOver(element);
}
protected boolean hoverOver(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (element.isDisplayed()) {
getSeleniumHelper().hoverOver(element);
result = true;
}
}
return result;
}
/**
* @param timeout number of seconds before waitUntil() and waitForJavascriptCallback() throw TimeOutException.
*/
public void secondsBeforeTimeout(int timeout) {
secondsBeforeTimeout = timeout;
secondsBeforePageLoadTimeout(timeout);
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setScriptWait(timeoutInMs);
}
/**
* @return number of seconds waitUntil() will wait at most.
*/
public int secondsBeforeTimeout() {
return secondsBeforeTimeout;
}
/**
* @param timeout number of seconds before waiting for a new page to load will throw a TimeOutException.
*/
public void secondsBeforePageLoadTimeout(int timeout) {
secondsBeforePageLoadTimeout = timeout;
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setPageLoadWait(timeoutInMs);
}
/**
* @return number of seconds Selenium will wait at most for a request to load a page.
*/
public int secondsBeforePageLoadTimeout() {
return secondsBeforePageLoadTimeout;
}
/**
* Clears HTML5's localStorage (for the domain of the current open page in the browser).
*/
public void clearLocalStorage() {
getSeleniumHelper().executeJavascript("localStorage.clear();");
}
/**
* Deletes all cookies(for the domain of the current open page in the browser).
*/
public void deleteAllCookies() {
getSeleniumHelper().deleteAllCookies();
}
/**
* @param directory sets base directory where screenshots will be stored.
*/
public void screenshotBaseDirectory(String directory) {
if (directory.equals("")
|| directory.endsWith("/")
|| directory.endsWith("\\")) {
screenshotBase = directory;
} else {
screenshotBase = directory + "/";
}
}
/**
* @param height height to use to display screenshot images
*/
public void screenshotShowHeight(String height) {
screenshotHeight = height;
}
/**
* @return (escaped) HTML content of current page.
*/
public String pageSource() {
String result = null;
String html = getSeleniumHelper().getHtml();
if (html != null) {
result = "<pre>" + StringEscapeUtils.escapeHtml4(html) + "</pre>";
}
return result;
}
/**
* Saves current page's source to the wiki'f files section and returns a link to the
* created file.
* @return hyperlink to the file containing the page source.
*/
public String savePageSource() {
String fileName = getResourceNameFromLocation();
return savePageSource(fileName, fileName + ".html");
}
protected String savePageSource(String fileName, String linkText) {
// make href to file
String url = savePageSourceWithFrames(fileName);
return String.format("<a href=\"%s\">%s</a>", url, linkText);
}
protected String getResourceNameFromLocation() {
String fileName = "pageSource";
try {
String location = location();
URL u = new URL(location);
String file = FilenameUtils.getName(u.getPath());
file = file.replaceAll("^(.*?)(\\.html?)?$", "$1");
if (!"".equals(file)) {
fileName = file;
}
} catch (MalformedURLException e) {
// ignore
}
return fileName;
}
protected String savePageSourceWithFrames(String fileName) {
Map<String, String> sourceReplacements = new HashMap<>();
List<WebElement> frames = findAllByCss("iframe,frame");
for (WebElement frame : frames) {
String newLocation = saveFrameSource(frame);
String fullUrlOfFrame = frame.getAttribute("src");
addSourceReplacementsForFrame(sourceReplacements, newLocation, fullUrlOfFrame);
}
String html = getCurrentFrameHtml(sourceReplacements);
return saveHtmlAsPageSource(fileName, html);
}
protected String saveFrameSource(WebElement frame) {
try {
getSeleniumHelper().switchToFrame(frame);
String fileName = getResourceNameFromLocation();
return savePageSourceWithFrames(fileName);
} finally {
getSeleniumHelper().switchToParentFrame();
}
}
protected String getCurrentFrameHtml(Map<String, String> sourceReplacements) {
String html = getSeleniumHelper().getHtml();
if (sourceReplacements != null && !sourceReplacements.isEmpty()) {
html = replaceSourceOfFrames(sourceReplacements, html);
}
return html;
}
protected String replaceSourceOfFrames(Map<String, String> sourceReplacements, String html) {
for (Map.Entry<String, String> entry : sourceReplacements.entrySet()) {
String originalLocation = entry.getKey();
String newLocation = entry.getValue();
html = html.replace("src=\"" + originalLocation + "\"", "src=\"/" + newLocation + "\"");
}
return html;
}
protected void addSourceReplacementsForFrame(Map<String, String> sourceReplacements, String savedLocation, String fullUrlOfFrame) {
String fullUrlOfParent = location();
int lastSlash = fullUrlOfParent.lastIndexOf("/");
String baseUrl = fullUrlOfParent.substring(0, lastSlash + 1);
String relativeUrlOfFrame = fullUrlOfFrame.replace(baseUrl, "");
sourceReplacements.put(fullUrlOfFrame, savedLocation);
sourceReplacements.put(relativeUrlOfFrame, savedLocation);
String framePath = getPath(fullUrlOfFrame);
if (framePath != null) {
sourceReplacements.put(framePath, savedLocation);
}
}
protected String getPath(String urlString) {
String path = null;
try {
URL url = new URL(urlString);
path = url.getPath();
} catch (MalformedURLException e) {
// leave path null
}
return path;
}
protected String saveHtmlAsPageSource(String fileName, String html) {
String result;
try {
String pageSourceName = getPageSourceName(fileName);
String file = FileUtil.saveToFile(pageSourceName, "html", html.getBytes("utf-8"));
String wikiUrl = getWikiUrl(file);
if (wikiUrl != null) {
// format file name
result = wikiUrl;
} else {
result = file;
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unable to save source", e);
}
return result;
}
protected String getPageSourceName(String fileName) {
return pageSourceBase + fileName;
}
/**
* Takes screenshot from current page
* @param basename filename (below screenshot base directory).
* @return location of screenshot.
*/
public String takeScreenshot(String basename) {
try {
String screenshotFile = createScreenshot(basename);
if (screenshotFile == null) {
throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?");
} else {
screenshotFile = getScreenshotLink(screenshotFile);
}
return screenshotFile;
} catch (UnhandledAlertException e) {
// standard behavior will stop test, this breaks storyboard that will attempt to take screenshot
// after triggering alert, but before the alert can be handled.
// so we output a message but no exception. We rely on a next line to actually handle alert
// (which may mean either really handle or stop test).
return String.format(
"<div><strong>Unable to take screenshot</strong>, alert is active. Alert text:<br/>" +
"'<span>%s</span>'</div>",
StringEscapeUtils.escapeHtml4(alertText()));
}
}
private String getScreenshotLink(String screenshotFile) {
String wikiUrl = getWikiUrl(screenshotFile);
if (wikiUrl != null) {
// make href to screenshot
if ("".equals(screenshotHeight)) {
wikiUrl = String.format("<a href=\"%s\">%s</a>",
wikiUrl, screenshotFile);
} else {
wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"/></a>",
wikiUrl, screenshotFile, screenshotHeight);
}
screenshotFile = wikiUrl;
}
return screenshotFile;
}
private String createScreenshot(String basename) {
String name = getScreenshotBasename(basename);
return getSeleniumHelper().takeScreenshot(name);
}
private String createScreenshot(String basename, Throwable t) {
String screenshotFile;
byte[] screenshotInException = getSeleniumHelper().findScreenshot(t);
if (screenshotInException == null || screenshotInException.length == 0) {
screenshotFile = createScreenshot(basename);
} else {
String name = getScreenshotBasename(basename);
screenshotFile = getSeleniumHelper().writeScreenshot(name, screenshotInException);
}
return screenshotFile;
}
private String getScreenshotBasename(String basename) {
return screenshotBase + basename;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws SlimFixtureException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntil(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
String message = getTimeoutMessage(e);
return lastAttemptBeforeThrow(condition, new SlimFixtureException(false, message, e));
}
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur the whole test is stopped.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws TimeoutStopTestException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntilOrStop(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
try {
return handleTimeoutException(e);
} catch (TimeoutStopTestException tste) {
return lastAttemptBeforeThrow(condition, tste);
}
}
}
/**
* Tries the condition one last time before throwing an exception.
* This to prevent exception messages in the wiki that show no problem, which could happen if the browser's
* window content has changed between last (failing) try at condition and generation of the exception.
* @param <T> the return type of the method, which must not be Void
* @param condition condition that caused exception.
* @param e exception that will be thrown if condition does not return a result.
* @return last attempt results, if not null.
* @throws SlimFixtureException throws e if last attempt returns null.
*/
protected <T> T lastAttemptBeforeThrow(ExpectedCondition<T> condition, SlimFixtureException e) {
T lastAttemptResult = null;
try {
// last attempt to ensure condition has not been met
// this to prevent messages that show no problem
lastAttemptResult = condition.apply(getSeleniumHelper().driver());
} catch (Throwable t) {
// ignore
}
if (lastAttemptResult != null) {
return lastAttemptResult;
}
throw e;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur null is returned.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @return result of condition.
*/
protected <T> T waitUntilOrNull(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
return null;
}
}
protected <T> T waitUntilImpl(ExpectedCondition<T> condition) {
return getSeleniumHelper().waitUntil(secondsBeforeTimeout(), condition);
}
protected <T> T handleTimeoutException(TimeoutException e) {
String message = getTimeoutMessage(e);
throw new TimeoutStopTestException(false, message, e);
}
private String getTimeoutMessage(TimeoutException e) {
String messageBase = String.format("Timed-out waiting (after %ss)", secondsBeforeTimeout());
return getSlimFixtureExceptionMessage("timeouts", "timeout", messageBase, e);
}
protected void handleRequiredElementNotFound(String toFind) {
handleRequiredElementNotFound(toFind, null);
}
protected void handleRequiredElementNotFound(String toFind, Throwable t) {
String messageBase = String.format("Unable to find: %s", toFind);
String message = getSlimFixtureExceptionMessage("notFound", toFind, messageBase, t);
throw new SlimFixtureException(false, message, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotFolder, String screenshotFile, String messageBase, Throwable t) {
String screenshotBaseName = String.format("%s/%s/%s", screenshotFolder, getClass().getSimpleName(), screenshotFile);
return getSlimFixtureExceptionMessage(screenshotBaseName, messageBase, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotBaseName, String messageBase, Throwable t) {
// take a screenshot of what was on screen
String screenShotFile = null;
try {
screenShotFile = createScreenshot(screenshotBaseName, t);
} catch (UnhandledAlertException e) {
// https://code.google.com/p/selenium/issues/detail?id=4412
System.err.println("Unable to take screenshot while alert is present for exception: " + messageBase);
} catch (Exception sse) {
System.err.println("Unable to take screenshot for exception: " + messageBase);
sse.printStackTrace();
}
String message = messageBase;
if (message == null) {
if (t == null) {
message = "";
} else {
message = ExceptionUtils.getStackTrace(t);
}
}
if (screenShotFile != null) {
String label = "Page content";
try {
String fileName;
if (t != null) {
fileName = t.getClass().getName();
} else if (screenshotBaseName != null) {
fileName = screenshotBaseName;
} else {
fileName = "exception";
}
label = savePageSource(fileName, label);
} catch (UnhandledAlertException e) {
// https://code.google.com/p/selenium/issues/detail?id=4412
System.err.println("Unable to capture page source while alert is present for exception: " + messageBase);
} catch (Exception e) {
System.err.println("Unable to capture page source for exception: " + messageBase);
e.printStackTrace();
}
String exceptionMsg = formatExceptionMsg(message);
message = String.format("<div><div>%s.</div><div>%s:%s</div></div>",
exceptionMsg, label, getScreenshotLink(screenShotFile));
}
return message;
}
protected String formatExceptionMsg(String value) {
return StringEscapeUtils.escapeHtml4(value);
}
private WebDriver driver() {
return getSeleniumHelper().driver();
}
private WebDriverWait waitDriver() {
return getSeleniumHelper().waitDriver();
}
/**
* @return helper to use.
*/
protected final SeleniumHelper getSeleniumHelper() {
return seleniumHelper;
}
/**
* Sets SeleniumHelper to use, for testing purposes.
* @param helper helper to use.
*/
void setSeleniumHelper(SeleniumHelper helper) {
seleniumHelper = helper;
}
public int currentBrowserWidth() {
return getWindowSize().getWidth();
}
public int currentBrowserHeight() {
return getWindowSize().getHeight();
}
public void setBrowserWidth(int newWidth) {
int currentHeight = currentBrowserHeight();
setBrowserSizeToBy(newWidth, currentHeight);
}
public void setBrowserHeight(int newHeight) {
int currentWidth = currentBrowserWidth();
setBrowserSizeToBy(currentWidth, newHeight);
}
public void setBrowserSizeToBy(int newWidth, int newHeight) {
getSeleniumHelper().setWindowSize(newWidth, newHeight);
Dimension actualSize = getWindowSize();
if (actualSize.getHeight() != newHeight || actualSize.getWidth() != newWidth) {
String message = String.format("Unable to change size to: %s x %s; size is: %s x %s",
newWidth, newHeight, actualSize.getWidth(), actualSize.getHeight());
throw new SlimFixtureException(false, message);
}
}
protected Dimension getWindowSize() {
return getSeleniumHelper().getWindowSize();
}
public void setBrowserSizeToMaximum() {
getSeleniumHelper().setWindowSizeToMaximum();
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String download(String place) {
return downloadIn(place, null);
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @param container part of screen containing link.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadIn(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
By selector = By.linkText(place);
WebElement element = findElement(selector);
if (element == null) {
selector = By.partialLinkText(place);
element = findElement(selector);
if (element == null) {
selector = By.id(place);
element = findElement(selector);
if (element == null) {
selector = By.name(place);
element = findElement(selector);
}
}
}
return downloadLinkTarget(element);
} finally {
resetSearchContext(currentSearchContext);
}
}
protected WebElement findElement(By selector) {
return getSeleniumHelper().findElement(selector);
}
/**
* Downloads the target of the supplied link.
* @param element link to follow.
* @return downloaded file if any, null otherwise.
*/
protected String downloadLinkTarget(WebElement element) {
String result = null;
if (element != null) {
String href = element.getAttribute("href");
if (href != null) {
result = downloadContentFrom(href);
} else {
throw new SlimFixtureException(false, "Could not determine url to download from");
}
}
return result;
}
/**
* Downloads binary content from specified url (using the browser's cookies).
* @param urlOrLink url to download from
* @return link to downloaded file
*/
public String downloadContentFrom(String urlOrLink) {
String result = null;
if (urlOrLink != null) {
String url = getUrl(urlOrLink);
BinaryHttpResponse resp = new BinaryHttpResponse();
getUrlContent(url, resp);
byte[] content = resp.getResponseContent();
if (content == null) {
result = resp.getResponse();
} else {
String fileName = resp.getFileName();
String baseName = FilenameUtils.getBaseName(fileName);
String ext = FilenameUtils.getExtension(fileName);
String downloadedFile = FileUtil.saveToFile(getDownloadName(baseName), ext, content);
String wikiUrl = getWikiUrl(downloadedFile);
if (wikiUrl != null) {
// make href to file
result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName);
} else {
result = downloadedFile;
}
}
}
return result;
}
/**
* Selects a file using the first file upload control.
* @param fileName file to upload
* @return true, if a file input was found and file existed.
*/
@WaitUntil
public boolean selectFile(String fileName) {
return selectFileFor(fileName, "css=input[type='file']");
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileFor(String fileName, String place) {
return selectFileForIn(fileName, place, null);
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @param container part of screen containing place
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileForIn(String fileName, String place, String container) {
boolean result = false;
if (fileName != null) {
String fullPath = getFilePathFromWikiUrl(fileName);
if (new File(fullPath).exists()) {
WebElement element = getElementToSelectFile(place, container);
if (element != null) {
element.sendKeys(fullPath);
result = true;
}
} else {
throw new SlimFixtureException(false, "Unable to find file: " + fullPath);
}
}
return result;
}
protected WebElement getElementToSelectFile(String place, String container) {
WebElement result = null;
WebElement element = getElement(place, container);
if (element != null
&& "input".equalsIgnoreCase(element.getTagName())
&& "file".equalsIgnoreCase(element.getAttribute("type"))) {
result = element;
}
return result;
}
private String getDownloadName(String baseName) {
return downloadBase + baseName;
}
/**
* GETs content of specified URL, using the browsers cookies.
* @param url url to retrieve content from
* @param resp response to store content in
*/
protected void getUrlContent(String url, HttpResponse resp) {
getEnvironment().addSeleniumCookies(resp, -1);
getEnvironment().doGet(url, resp);
}
/**
* Gets the value of the cookie with the supplied name.
* @param cookieName name of cookie to get value from.
* @return cookie's value if any.
*/
public String cookieValue(String cookieName) {
String result = null;
Cookie cookie = getSeleniumHelper().getCookie(cookieName);
if (cookie != null) {
result = cookie.getValue();
}
return result;
}
protected Object waitForJavascriptCallback(String statement, Object... parameters) {
try {
return getSeleniumHelper().waitForJavascriptCallback(statement, parameters);
} catch (TimeoutException e) {
return handleTimeoutException(e);
}
}
public NgBrowserTest getNgBrowserTest() {
return ngBrowserTest;
}
public void setNgBrowserTest(NgBrowserTest ngBrowserTest) {
this.ngBrowserTest = ngBrowserTest;
}
public boolean isImplicitWaitForAngularEnabled() {
return implicitWaitForAngular;
}
public void setImplicitWaitForAngularTo(boolean implicitWaitForAngular) {
this.implicitWaitForAngular = implicitWaitForAngular;
}
public void setImplicitFindInFramesTo(boolean implicitFindInFrames) {
this.implicitFindInFrames = implicitFindInFrames;
}
}
| src/main/java/nl/hsac/fitnesse/fixture/slim/web/BrowserTest.java | package nl.hsac.fitnesse.fixture.slim.web;
import fitnesse.slim.fixtureInteraction.FixtureInteraction;
import nl.hsac.fitnesse.fixture.slim.SlimFixture;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.StopTestException;
import nl.hsac.fitnesse.fixture.slim.web.annotation.TimeoutPolicy;
import nl.hsac.fitnesse.fixture.slim.web.annotation.WaitUntil;
import nl.hsac.fitnesse.fixture.util.BinaryHttpResponse;
import nl.hsac.fitnesse.fixture.util.FileUtil;
import nl.hsac.fitnesse.fixture.util.HttpResponse;
import nl.hsac.fitnesse.fixture.util.ReflectionHelper;
import nl.hsac.fitnesse.fixture.util.selenium.SeleniumHelper;
import nl.hsac.fitnesse.slim.interaction.ExceptionHelper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BrowserTest extends SlimFixture {
private SeleniumHelper seleniumHelper = getEnvironment().getSeleniumHelper();
private ReflectionHelper reflectionHelper = getEnvironment().getReflectionHelper();
private NgBrowserTest ngBrowserTest;
private boolean implicitWaitForAngular = false;
private boolean implicitFindInFrames = true;
private int secondsBeforeTimeout;
private int secondsBeforePageLoadTimeout;
private int waitAfterScroll = 150;
private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/";
private String screenshotHeight = "200";
private String downloadBase = new File(filesDir, "downloads").getPath() + "/";
private String pageSourceBase = new File(filesDir, "pagesources").getPath() + "/";
@Override
protected void beforeInvoke(Method method, Object[] arguments) {
super.beforeInvoke(method, arguments);
waitForAngularIfNeeded(method);
}
@Override
protected Object invoke(final FixtureInteraction interaction, final Method method, final Object[] arguments)
throws Throwable {
Object result;
WaitUntil waitUntil = reflectionHelper.getAnnotation(WaitUntil.class, method);
if (waitUntil == null) {
result = superInvoke(interaction, method, arguments);
} else {
result = invokedWrappedInWaitUntil(waitUntil, interaction, method, arguments);
}
return result;
}
protected Object invokedWrappedInWaitUntil(WaitUntil waitUntil, final FixtureInteraction interaction, final Method method, final Object[] arguments) {
ExpectedCondition<Object> condition = new ExpectedCondition<Object>() {
@Override
public Object apply(WebDriver webDriver) {
try {
return superInvoke(interaction, method, arguments);
} catch (Throwable e) {
Throwable realEx = ExceptionHelper.stripReflectionException(e);
if (realEx instanceof RuntimeException) {
throw (RuntimeException) realEx;
} else if (realEx instanceof Error) {
throw (Error) realEx;
} else {
throw new RuntimeException(realEx);
}
}
}
};
if (implicitFindInFrames) {
condition = getSeleniumHelper().conditionForAllFrames(condition);
}
Object result;
switch (waitUntil.value()) {
case STOP_TEST:
result = waitUntilOrStop(condition);
break;
case RETURN_NULL:
result = waitUntilOrNull(condition);
break;
case RETURN_FALSE:
result = waitUntilOrNull(condition) != null;
break;
case THROW:
default:
result = waitUntil(condition);
break;
}
return result;
}
protected Object superInvoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable {
return super.invoke(interaction, method, arguments);
}
/**
* Determines whether the current method might require waiting for angular given the currently open site,
* and ensure it does if needed.
* @param method
*/
protected void waitForAngularIfNeeded(Method method) {
if (isImplicitWaitForAngularEnabled()) {
try {
if (ngBrowserTest == null) {
ngBrowserTest = new NgBrowserTest();
}
if (ngBrowserTest.requiresWaitForAngular(method) && currentSiteUsesAngular()) {
try {
ngBrowserTest.waitForAngularRequestsToFinish();
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Found Angular, but encountered an error while waiting for it to be ready. ");
e.printStackTrace();
}
}
} catch (UnhandledAlertException e) {
System.err.println("Cannot determine whether Angular is present while alert is active.");
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Error while determining whether Angular is present. ");
e.printStackTrace();
}
}
}
protected boolean currentSiteUsesAngular() {
Object windowHasAngular = getSeleniumHelper().executeJavascript("return window.angular?1:0;");
return Long.valueOf(1).equals(windowHasAngular);
}
@Override
protected Throwable handleException(Method method, Object[] arguments, Throwable t) {
Throwable result;
if (t instanceof UnhandledAlertException) {
UnhandledAlertException e = (UnhandledAlertException) t;
String alertText = e.getAlertText();
if (alertText == null) {
alertText = alertText();
}
String msgBase = "Unhandled alert: alert must be confirmed or dismissed before test can continue. Alert text: " + alertText;
String msg = getSlimFixtureExceptionMessage("alertException", msgBase, e);
result = new StopTestException(false, msg, t);
} else if (t instanceof SlimFixtureException) {
result = super.handleException(method, arguments, t);
} else {
String msg = getSlimFixtureExceptionMessage("exception", null, t);
result = new SlimFixtureException(false, msg, t);
}
return result;
}
public BrowserTest() {
secondsBeforeTimeout(seleniumHelper.getDefaultTimeoutSeconds());
ensureActiveTabIsNotClosed();
}
public BrowserTest(int secondsBeforeTimeout) {
secondsBeforeTimeout(secondsBeforeTimeout);
ensureActiveTabIsNotClosed();
}
public boolean open(String address) {
final String url = getUrl(address);
try {
getNavigation().to(url);
} catch (TimeoutException e) {
handleTimeoutException(e);
} finally {
switchToDefaultContent();
}
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
String readyState = getSeleniumHelper().executeJavascript("return document.readyState").toString();
// IE 7 is reported to return "loaded"
boolean done = "complete".equalsIgnoreCase(readyState) || "loaded".equalsIgnoreCase(readyState);
if (!done) {
System.err.printf("Open of %s returned while document.readyState was %s", url, readyState);
System.err.println();
}
return done;
}
});
return true;
}
public String location() {
return driver().getCurrentUrl();
}
public boolean back() {
getNavigation().back();
switchToDefaultContent();
// firefox sometimes prevents immediate back, if previous page was reached via POST
waitMilliseconds(500);
WebElement element = findElement(By.id("errorTryAgain"));
if (element != null) {
element.click();
// don't use confirmAlert as this may be overridden in subclass and to get rid of the
// firefox pop-up we need the basic behavior
getSeleniumHelper().getAlert().accept();
}
return true;
}
public boolean forward() {
getNavigation().forward();
switchToDefaultContent();
return true;
}
public boolean refresh() {
getNavigation().refresh();
switchToDefaultContent();
return true;
}
private WebDriver.Navigation getNavigation() {
return getSeleniumHelper().navigate();
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String alertText() {
Alert alert = getAlert();
String text = null;
if (alert != null) {
text = alert.getText();
}
return text;
}
@WaitUntil
public boolean confirmAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.accept();
onAlertHandled(true);
result = true;
}
return result;
}
@WaitUntil
public boolean dismissAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.dismiss();
onAlertHandled(false);
result = true;
}
return result;
}
/**
* Called when an alert is either dismissed or accepted.
* @param accepted true if the alert was accepted, false if dismissed.
*/
protected void onAlertHandled(boolean accepted) {
// if we were looking in nested frames, we could not go back to original frame
// because of the alert. Ensure we do so now the alert is handled.
getSeleniumHelper().resetFrameDepthOnAlertError();
}
protected Alert getAlert() {
return getSeleniumHelper().getAlert();
}
public boolean openInNewTab(String url) {
String cleanUrl = getUrl(url);
final int tabCount = tabCount();
getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl);
// ensure new window is open
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return tabCount() > tabCount;
}
});
return switchToNextTab();
}
@WaitUntil
public boolean switchToNextTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab + 1;
if (nextTab == tabs.size()) {
nextTab = 0;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
@WaitUntil
public boolean switchToPreviousTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab - 1;
if (nextTab < 0) {
nextTab = tabs.size() - 1;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
public boolean closeTab() {
boolean result = false;
List<String> tabs = getTabHandles();
int currentTab = getCurrentTabIndex(tabs);
int tabToGoTo = -1;
if (currentTab > 0) {
tabToGoTo = currentTab - 1;
} else {
if (tabs.size() > 1) {
tabToGoTo = 1;
}
}
if (tabToGoTo > -1) {
WebDriver driver = driver();
driver.close();
goToTab(tabs, tabToGoTo);
result = true;
}
return result;
}
public void ensureOnlyOneTab() {
ensureActiveTabIsNotClosed();
int tabCount = tabCount();
for (int i = 1; i < tabCount; i++) {
closeTab();
}
}
public boolean ensureActiveTabIsNotClosed() {
boolean result = false;
List<String> tabHandles = getTabHandles();
int currentTab = getCurrentTabIndex(tabHandles);
if (currentTab < 0) {
result = true;
goToTab(tabHandles, 0);
}
return result;
}
public int tabCount() {
return getTabHandles().size();
}
public int currentTabIndex() {
return getCurrentTabIndex(getTabHandles()) + 1;
}
protected int getCurrentTabIndex(List<String> tabHandles) {
return getSeleniumHelper().getCurrentTabIndex(tabHandles);
}
protected void goToTab(List<String> tabHandles, int indexToGoTo) {
getSeleniumHelper().goToTab(tabHandles, indexToGoTo);
}
protected List<String> getTabHandles() {
return getSeleniumHelper().getTabHandles();
}
/**
* Activates main/top-level iframe (i.e. makes it the current frame).
*/
public void switchToDefaultContent() {
getSeleniumHelper().switchToDefaultContent();
clearSearchContext();
}
/**
* Activates specified child frame of current iframe.
* @param technicalSelector selector to find iframe.
* @return true if iframe was found.
*/
public boolean switchToFrame(String technicalSelector) {
boolean result = false;
WebElement iframe = getElement(technicalSelector);
if (iframe != null) {
getSeleniumHelper().switchToFrame(iframe);
result = true;
}
return result;
}
/**
* Activates parent frame of current iframe.
* Does nothing if when current frame is the main/top-level one.
*/
public void switchToParentFrame() {
getSeleniumHelper().switchToParentFrame();
}
public String pageTitle() {
return getSeleniumHelper().getPageTitle();
}
/**
* @return current page's content type.
*/
public String pageContentType() {
String result = null;
Object ct = getSeleniumHelper().executeJavascript("return document.contentType;");
if (ct != null) {
result = ct.toString();
}
return result;
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAs(String value, String place) {
return enterAsIn(value, place, null);
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAsIn(String value, String place, String container) {
return enter(value, place, container, true);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterFor(String value, String place) {
return enterForIn(value, place, null);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterForIn(String value, String place, String container) {
return enter(value, place, container, false);
}
protected boolean enter(String value, String place, boolean shouldClear) {
return enter(value, place, null, shouldClear);
}
protected boolean enter(String value, String place, String container, boolean shouldClear) {
WebElement element = getElementToSendValue(place, container);
boolean result = element != null && isInteractable(element);
if (result) {
if (shouldClear) {
element.clear();
}
sendValue(element, value);
}
return result;
}
protected WebElement getElementToSendValue(String place) {
return getElementToSendValue(place, null);
}
protected WebElement getElementToSendValue(String place, String container) {
return getElement(place, container);
}
/**
* Simulates pressing the 'Tab' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressTab() {
return sendKeysToActiveElement(Keys.TAB);
}
/**
* Simulates pressing the 'Enter' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEnter() {
return sendKeysToActiveElement(Keys.ENTER);
}
/**
* Simulates pressing the 'Esc' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEsc() {
return sendKeysToActiveElement(Keys.ESCAPE);
}
/**
* Simulates typing a text to the current active element.
* @param text text to type.
* @return true, if an element was active the text could be sent to.
*/
public boolean type(String text) {
String value = cleanupValue(text);
return sendKeysToActiveElement(value);
}
/**
* Simulates pressing a key (or a combination of keys).
* (Unfortunately not all combinations seem to be accepted by all drivers, e.g.
* Chrome on OSX seems to ignore Command+A or Command+T; https://code.google.com/p/selenium/issues/detail?id=5919).
* @param key key to press, can be a normal letter (e.g. 'M') or a special key (e.g. 'down').
* Combinations can be passed by separating the keys to send with '+' (e.g. Command + T).
* @return true, if an element was active the key could be sent to.
*/
public boolean press(String key) {
CharSequence s;
String[] parts = key.split("\\s*\\+\\s*");
if (parts.length > 1
&& !"".equals(parts[0]) && !"".equals(parts[1])) {
CharSequence[] sequence = new CharSequence[parts.length];
for (int i = 0; i < parts.length; i++) {
sequence[i] = parseKey(parts[i]);
}
s = Keys.chord(sequence);
} else {
s = parseKey(key);
}
return sendKeysToActiveElement(s);
}
protected CharSequence parseKey(String key) {
CharSequence s;
try {
s = Keys.valueOf(key.toUpperCase());
} catch (IllegalArgumentException e) {
s = key;
}
return s;
}
/**
* Simulates pressing keys.
* @param keys keys to press.
* @return true, if an element was active the keys could be sent to.
*/
protected boolean sendKeysToActiveElement(CharSequence keys) {
boolean result = false;
WebElement element = getSeleniumHelper().getActiveElement();
if (element != null) {
element.sendKeys(keys);
result = true;
}
return result;
}
/**
* Sends Fitnesse cell content to element.
* @param element element to call sendKeys() on.
* @param value cell content.
*/
protected void sendValue(WebElement element, String value) {
if (StringUtils.isNotEmpty(value)) {
String keys = cleanupValue(value);
element.sendKeys(keys);
}
}
@WaitUntil
public boolean selectAs(String value, String place) {
return selectFor(value, place);
}
@WaitUntil
public boolean selectFor(String value, String place) {
return selectForIn(value, place, null);
}
@WaitUntil
public boolean selectForIn(String value, String place, String container) {
SearchContext searchContext = setSearchContextToContainer(container);
try {
// choose option for select, if possible
boolean result = clickSelectOption(place, value);
if (!result) {
// try to click the first element with right value
result = click(value);
}
return result;
} finally {
resetSearchContext(searchContext);
}
}
@WaitUntil
public boolean enterForHidden(final String value, final String idOrName) {
return getSeleniumHelper().setHiddenInputValue(idOrName, value);
}
private boolean clickSelectOption(String selectPlace, String optionValue) {
WebElement element = getElementToSelectFor(selectPlace);
return clickSelectOption(element, optionValue);
}
protected WebElement getElementToSelectFor(String selectPlace) {
return getElement(selectPlace);
}
protected boolean clickSelectOption(WebElement element, String optionValue) {
boolean result = false;
if (element != null) {
if (isSelect(element)) {
optionValue = cleanupValue(optionValue);
By xpath = getSeleniumHelper().byXpath(".//option[normalized(text()) = '%s']", optionValue);
WebElement option = getSeleniumHelper().findElement(element, false, xpath);
if (option == null) {
xpath = getSeleniumHelper().byXpath(".//option[contains(normalized(text()), '%s')]", optionValue);
option = getSeleniumHelper().findElement(element, false, xpath);
}
if (option != null) {
result = clickElement(option);
}
}
}
return result;
}
@WaitUntil
public boolean click(final String place) {
return clickImp(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailable(String place) {
return clickIfAvailableIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailableIn(String place, String container) {
return clickImp(place, container);
}
@WaitUntil
public boolean clickIn(String place, String container) {
return clickImp(place, container);
}
protected boolean clickImp(String place, String container) {
boolean result = false;
place = cleanupValue(place);
try {
WebElement element = getElementToClick(place, container);
result = clickElement(element);
} catch (WebDriverException e) {
// if other element hides the element (in Chrome) an exception is thrown
String msg = e.getMessage();
if (msg == null || !msg.contains("Other element would receive the click")) {
throw e;
}
}
return result;
}
@WaitUntil
public boolean doubleClick(final String place) {
WebElement element = getElementToClick(place);
return doubleClick(element);
}
protected boolean doubleClick(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
Actions actions = getActions();
actions.doubleClick(element).perform();
result = true;
}
}
return result;
}
protected Actions getActions() {
WebDriver driver = driver();
return new Actions(driver);
}
protected WebElement getElementToClick(String place) {
return getElementToClick(place, null);
}
protected WebElement getElementToClick(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
return getSeleniumHelper().getElementToClick(place);
} finally {
resetSearchContext(currentSearchContext);
}
}
@WaitUntil
public boolean setSearchContextTo(String container) {
boolean result = false;
WebElement containerElement = getContainerElement(container);
if (containerElement != null) {
getSeleniumHelper().setCurrentContext(containerElement);
result = true;
}
return result;
}
protected SearchContext setSearchContextToContainer(String container) {
SearchContext result = null;
if (container != null) {
SearchContext currentSearchContext = getSeleniumHelper().getCurrentContext();
if (setSearchContextTo(container)) {
result = currentSearchContext;
}
}
return result;
}
public void clearSearchContext() {
getSeleniumHelper().setCurrentContext(null);
}
protected void resetSearchContext(SearchContext currentSearchContext) {
if (currentSearchContext != null) {
getSeleniumHelper().setCurrentContext(currentSearchContext);
}
}
protected WebElement getContainerElement(String container) {
WebElement containerElement = null;
By by = getSeleniumHelper().placeToBy(container);
if (by != null) {
containerElement = findElement(by);
} else {
containerElement = findByXPath(".//fieldset[.//legend/text()[normalized(.) = '%s']]", container);
if (containerElement == null) {
containerElement = getSeleniumHelper().getElementByAriaLabel(container, -1);
if (containerElement == null) {
containerElement = findByXPath(".//fieldset[.//legend/text()[contains(normalized(.), '%s')]]", container);
if (containerElement == null) {
containerElement = getSeleniumHelper().getElementByPartialAriaLabel(container, -1);
}
}
}
}
return containerElement;
}
protected boolean clickElement(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
element.click();
result = true;
}
}
return result;
}
protected boolean isInteractable(WebElement element) {
return getSeleniumHelper().isInteractable(element);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForPage(String pageName) {
return pageTitle().equals(pageName);
}
public boolean waitForTagWithText(String tagName, String expectedText) {
return waitForElementWithText(By.tagName(tagName), expectedText);
}
public boolean waitForClassWithText(String cssClassName, String expectedText) {
return waitForElementWithText(By.className(cssClassName), expectedText);
}
protected boolean waitForElementWithText(final By by, String expectedText) {
final String textToLookFor = cleanExpectedValue(expectedText);
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
boolean ok = false;
List<WebElement> elements = webDriver.findElements(by);
if (elements != null) {
for (WebElement element : elements) {
// we don't want stale elements to make single
// element false, but instead we stop processing
// current list and do a new findElements
ok = hasText(element, textToLookFor);
if (ok) {
// no need to continue to check other elements
break;
}
}
}
return ok;
}
});
}
protected String cleanExpectedValue(String expectedText) {
return cleanupValue(expectedText);
}
protected boolean hasText(WebElement element, String textToLookFor) {
boolean ok;
String actual = getElementText(element);
if (textToLookFor == null) {
ok = actual == null;
} else {
if (StringUtils.isEmpty(actual)) {
String value = element.getAttribute("value");
if (!StringUtils.isEmpty(value)) {
actual = value;
}
}
if (actual != null) {
actual = actual.trim();
}
ok = textToLookFor.equals(actual);
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForClass(String cssClassName) {
boolean ok = false;
WebElement element = findElement(By.className(cssClassName));
if (element != null) {
ok = true;
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisible(String place) {
return waitForVisibleIn(place, null);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisibleIn(String place, String container) {
Boolean result = Boolean.FALSE;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
/**
* @deprecated use #waitForVisible(xpath=) instead
*/
@Deprecated
public boolean waitForXPathVisible(String xPath) {
By by = By.xpath(xPath);
return waitForVisible(by);
}
@Deprecated
protected boolean waitForVisible(final By by) {
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
Boolean result = Boolean.FALSE;
WebElement element = findElement(by);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
});
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOf(String place) {
return valueFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueFor(String place) {
return valueForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfIn(String place, String container) {
return valueForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueForIn(String place, String container) {
WebElement element = getElementToRetrieveValue(place, container);
return valueFor(element);
}
protected WebElement getElementToRetrieveValue(String place, String container) {
return getElement(place, container);
}
protected String valueFor(WebElement element) {
String result = null;
if (element != null) {
if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
if (options.size() > 0) {
result = getElementText(options.get(0));
}
} else {
String elementType = element.getAttribute("type");
if ("checkbox".equals(elementType)
|| "radio".equals(elementType)) {
result = String.valueOf(element.isSelected());
} else if ("li".equalsIgnoreCase(element.getTagName())) {
result = getElementText(element);
} else {
result = element.getAttribute("value");
if (result == null) {
result = getElementText(element);
}
}
}
}
return result;
}
private boolean isSelect(WebElement element) {
return "select".equalsIgnoreCase(element.getTagName());
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOf(String place) {
return valuesFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOfIn(String place, String container) {
return valuesForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesFor(String place) {
return valuesForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesForIn(String place, String container) {
ArrayList<String> values = null;
WebElement element = getElementToRetrieveValue(place, container);
if (element != null) {
values = new ArrayList<String>();
String tagName = element.getTagName();
if ("ul".equalsIgnoreCase(tagName)
|| "ol".equalsIgnoreCase(tagName)) {
List<WebElement> items = element.findElements(By.tagName("li"));
for (WebElement item : items) {
if (item.isDisplayed()) {
values.add(getElementText(item));
}
}
} else if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
for (WebElement item : options) {
values.add(getElementText(item));
}
} else {
values.add(valueFor(element));
}
}
return values;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberFor(String place) {
return numberForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberForIn(String place, String container) {
SearchContext searchContext = setSearchContextToContainer(container);
try {
Integer number = null;
WebElement element = findByXPath(".//ol/li/descendant-or-self::text()[normalized(.)='%s']/ancestor-or-self::li", place);
if (element == null) {
element = findByXPath(".//ol/li/descendant-or-self::text()[contains(normalized(.),'%s')]/ancestor-or-self::li", place);
}
if (element != null) {
scrollIfNotOnScreen(element);
number = getSeleniumHelper().getNumberFor(element);
}
return number;
} finally {
resetSearchContext(searchContext);
}
}
public ArrayList<String> availableOptionsFor(String place) {
ArrayList<String> result = null;
WebElement element = getElementToSelectFor(place);
if (element != null) {
scrollIfNotOnScreen(element);
result = getSeleniumHelper().getAvailableOptions(element);
}
return result;
}
@WaitUntil
public boolean clear(String place) {
return clearIn(place, null);
}
@WaitUntil
public boolean clearIn(String place, String container) {
boolean result = false;
WebElement element = getElementToClear(place, container);
if (element != null) {
element.clear();
result = true;
}
return result;
}
protected WebElement getElementToClear(String place, String container) {
return getElementToSendValue(place, container);
}
@WaitUntil
public boolean enterAsInRowWhereIs(String value, String requestedColumnName, String selectOnColumn, String selectOnValue) {
boolean result = false;
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
String requestedIndex = getXPathForColumnIndex(requestedColumnName);
WebElement cell = findByXPath("%s[%s]", columnXPath, requestedIndex);
if (cell != null) {
WebElement element = getSeleniumHelper().getNestedElementForValue(cell);
if (isSelect(element)) {
result = clickSelectOption(element, value);
} else {
if (isInteractable(element)) {
result = true;
element.clear();
sendValue(element, value);
}
}
}
return result;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfColumnNumberInRowNumber(int columnIndex, int rowIndex) {
return getValueByXPath("(.//tr[boolean(td)])[%s]/td[%s]", Integer.toString(rowIndex), Integer.toString(columnIndex));
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowNumber(String requestedColumnName, int rowIndex) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowIndex);
return valueInRow(columnXPath, requestedColumnName);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowWhereIs(String requestedColumnName, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return valueInRow(columnXPath, requestedColumnName);
}
protected String valueInRow(String columnXPath, String requestedColumnName) {
String requestedIndex = getXPathForColumnIndex(requestedColumnName);
return getValueByXPath("%s[%s]", columnXPath, requestedIndex);
}
protected String getValueByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
if (element != null) {
WebElement nested = getSeleniumHelper().getNestedElementForValue(element);
if (isInteractable(nested)) {
element = nested;
}
}
return valueFor(element);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean rowExistsWhereIs(String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return findByXPath(columnXPath) != null;
}
@WaitUntil
public boolean clickInRowNumber(String place, int rowIndex) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowIndex);
return clickInRow(columnXPath, place);
}
@WaitUntil
public boolean clickInRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return clickInRow(columnXPath, place);
}
protected boolean clickInRow(String columnXPath, String place) {
// find an input to click in the row
WebElement element = findByXPath("%s//*[(local-name()='input' and contains(@value, '%s'))" +
" or contains(normalized(text()),'%s') or contains(@title, '%s')]",
columnXPath, place,
place, place);
return clickElement(element);
}
/**
* Downloads the target of a link in a grid's row.
* @param place which link to download.
* @param rowNumber (1-based) row number to retrieve link from.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowNumber(String place, int rowNumber) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowNumber);
return downloadFromRow(columnXPath, place);
}
/**
* Downloads the target of a link in a grid, finding the row based on one of the other columns' value.
* @param place which link to download.
* @param selectOnColumn column header of cell whose value must be selectOnValue.
* @param selectOnValue value to be present in selectOnColumn to find correct row.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return downloadFromRow(columnXPath, place);
}
protected String downloadFromRow(String columnXPath, String place) {
String result = null;
// find an a to download from based on its text()
WebElement element = findByXPath("%s//a[contains(normalized(text()),'%s')]", columnXPath, place);
if (element == null) {
// find an a to download based on its column header
String requestedIndex = getXPathForColumnIndex(place);
element = findByXPath("%s[%s]//a", columnXPath, requestedIndex);
if (element == null) {
// find an a to download in the row by its title (aka tooltip)
element = findByXPath("%s//a[contains(@title, '%s')]", columnXPath, place);
}
}
if (element != null) {
result = downloadLinkTarget(element);
}
return result;
}
/**
* Creates an XPath expression that will find a cell in a row, selecting the row based on the
* text in a specific column (identified by its header text).
* @param columnName header text of the column to find value in.
* @param value text to find in column with the supplied header.
* @return XPath expression selecting a td in the row
*/
protected String getXPathForColumnInRowByValueInOtherColumn(String columnName, String value) {
String selectIndex = getXPathForColumnIndex(columnName);
return String.format(".//tr[td[%s]/descendant-or-self::text()[normalized(.)='%s']]/td", selectIndex, value);
}
/**
* Creates an XPath expression that will determine, for a row, which index to use to select the cell in the column
* with the supplied header text value.
* @param columnName name of column in header (th)
* @return XPath expression which can be used to select a td in a row
*/
protected String getXPathForColumnIndex(String columnName) {
// determine how many columns are before the column with the requested name
// the column with the requested name will have an index of the value +1 (since XPath indexes are 1 based)
return String.format("count(ancestor::table[1]//tr/th/descendant-or-self::text()[normalized(.)='%s']/ancestor-or-self::th[1]/preceding-sibling::th)+1", columnName);
}
protected WebElement getElement(String place) {
return getElement(place, null);
}
protected WebElement getElement(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
return getSeleniumHelper().getElement(place);
} finally {
resetSearchContext(currentSearchContext);
}
}
/**
* @deprecated use #click(xpath=) instead.
*/
@WaitUntil
@Deprecated
public boolean clickByXPath(String xPath) {
WebElement element = findByXPath(xPath);
return clickElement(element);
}
/**
* @deprecated use #valueOf(xpath=) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByXPath(String xPath) {
return getTextByXPath(xPath);
}
protected String getTextByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
return getElementText(element);
}
/**
* @deprecated use #valueOf(css=.) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByClassName(String className) {
return getTextByClassName(className);
}
protected String getTextByClassName(String className) {
WebElement element = findByClassName(className);
return getElementText(element);
}
protected WebElement findByClassName(String className) {
By by = By.className(className);
return findElement(by);
}
protected WebElement findByXPath(String xpathPattern, String... params) {
return getSeleniumHelper().findByXPath(xpathPattern, params);
}
protected WebElement findByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElement(by);
}
protected List<WebElement> findAllByXPath(String xpathPattern, String... params) {
By by = getSeleniumHelper().byXpath(xpathPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByCss(String cssPattern, String... params) {
By by = getSeleniumHelper().byCss(cssPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElements(by);
}
protected List<WebElement> findElements(By by) {
return driver().findElements(by);
}
public void waitMilliSecondAfterScroll(int msToWait) {
waitAfterScroll = msToWait;
}
protected String getElementText(WebElement element) {
String result = null;
if (element != null) {
scrollIfNotOnScreen(element);
result = element.getText();
}
return result;
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
*/
@WaitUntil
public boolean scrollTo(String place) {
return scrollToIn(place, null);
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
* @param container parent of place.
*/
@WaitUntil
public boolean scrollToIn(String place, String container) {
boolean result = false;
WebElement element = getElementToScrollTo(place, container);
if (element != null) {
scrollTo(element);
result = true;
}
return result;
}
protected WebElement getElementToScrollTo(String place, String container) {
return getElementToCheckVisibility(place, container);
}
/**
* Scrolls browser window so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollTo(WebElement element) {
getSeleniumHelper().scrollTo(element);
if (waitAfterScroll > 0) {
waitMilliseconds(waitAfterScroll);
}
}
/**
* Scrolls browser window if element is not currently visible so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollIfNotOnScreen(WebElement element) {
if (!element.isDisplayed() || !isElementOnScreen(element)) {
scrollTo(element);
}
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabled(String place) {
return isEnabledIn(place, null);
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @param container parent of place.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabledIn(String place, String container) {
boolean result = false;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
result = element.isEnabled();
}
return result;
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisible(String place) {
return isVisibleIn(place, null);
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleIn(String place, String container) {
return isVisibleImpl(place, container, true);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPage(String place) {
return isVisibleOnPageIn(place, null);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPageIn(String place, String container) {
return isVisibleImpl(place, container, false);
}
protected boolean isVisibleImpl(String place, String container, boolean checkOnScreen) {
boolean result = false;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null && element.isDisplayed()) {
if (checkOnScreen) {
result = isElementOnScreen(element);
} else {
result = true;
}
}
return result;
}
protected WebElement getElementToCheckVisibility(String place) {
return getElementToCheckVisibility(place, null);
}
protected WebElement getElementToCheckVisibility(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
return getElementToClick(place);
} finally {
resetSearchContext(currentSearchContext);
}
}
/**
* Checks whether element is in browser's viewport.
* @param element element to check
* @return true if element is in browser's viewport.
*/
protected boolean isElementOnScreen(WebElement element) {
Boolean onScreen = getSeleniumHelper().isElementOnScreen(element);
return onScreen == null || onScreen.booleanValue();
}
@WaitUntil
public boolean hoverOver(String place) {
return hoverOverIn(place, null);
}
@WaitUntil
public boolean hoverOverIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return hoverOver(element);
}
protected boolean hoverOver(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (element.isDisplayed()) {
getSeleniumHelper().hoverOver(element);
result = true;
}
}
return result;
}
/**
* @param timeout number of seconds before waitUntil() and waitForJavascriptCallback() throw TimeOutException.
*/
public void secondsBeforeTimeout(int timeout) {
secondsBeforeTimeout = timeout;
secondsBeforePageLoadTimeout(timeout);
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setScriptWait(timeoutInMs);
}
/**
* @return number of seconds waitUntil() will wait at most.
*/
public int secondsBeforeTimeout() {
return secondsBeforeTimeout;
}
/**
* @param timeout number of seconds before waiting for a new page to load will throw a TimeOutException.
*/
public void secondsBeforePageLoadTimeout(int timeout) {
secondsBeforePageLoadTimeout = timeout;
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setPageLoadWait(timeoutInMs);
}
/**
* @return number of seconds Selenium will wait at most for a request to load a page.
*/
public int secondsBeforePageLoadTimeout() {
return secondsBeforePageLoadTimeout;
}
/**
* Clears HTML5's localStorage (for the domain of the current open page in the browser).
*/
public void clearLocalStorage() {
getSeleniumHelper().executeJavascript("localStorage.clear();");
}
/**
* Deletes all cookies(for the domain of the current open page in the browser).
*/
public void deleteAllCookies() {
getSeleniumHelper().deleteAllCookies();
}
/**
* @param directory sets base directory where screenshots will be stored.
*/
public void screenshotBaseDirectory(String directory) {
if (directory.equals("")
|| directory.endsWith("/")
|| directory.endsWith("\\")) {
screenshotBase = directory;
} else {
screenshotBase = directory + "/";
}
}
/**
* @param height height to use to display screenshot images
*/
public void screenshotShowHeight(String height) {
screenshotHeight = height;
}
/**
* @return (escaped) HTML content of current page.
*/
public String pageSource() {
String result = null;
String html = getSeleniumHelper().getHtml();
if (html != null) {
result = "<pre>" + StringEscapeUtils.escapeHtml4(html) + "</pre>";
}
return result;
}
/**
* Saves current page's source to the wiki'f files section and returns a link to the
* created file.
* @return hyperlink to the file containing the page source.
*/
public String savePageSource() {
String fileName = getResourceNameFromLocation();
return savePageSourceToLink(fileName, fileName + ".html");
}
protected String savePageSourceToLink(String fileName, String linkText) {
// make href to file
String url = savePageSourceWithFrames(fileName);
return String.format("<a href=\"%s\">%s</a>", url, linkText);
}
protected String getResourceNameFromLocation() {
String fileName = "pageSource";
try {
String location = location();
URL u = new URL(location);
String file = FilenameUtils.getName(u.getPath());
file = file.replaceAll("^(.*?)(\\.html?)?$", "$1");
if (!"".equals(file)) {
fileName = file;
}
} catch (MalformedURLException e) {
// ignore
}
return fileName;
}
protected String savePageSourceWithFrames(String fileName) {
Map<String, String> sourceReplacements = new HashMap<>();
List<WebElement> frames = findAllByCss("iframe,frame");
for (WebElement frame : frames) {
String newLocation = saveFrameSource(frame);
String fullUrlOfFrame = frame.getAttribute("src");
addSourceReplacementsForFrame(sourceReplacements, newLocation, fullUrlOfFrame);
}
String html = getCurrentFrameHtml(sourceReplacements);
return savePageSource(fileName, html);
}
protected String saveFrameSource(WebElement frame) {
try {
getSeleniumHelper().switchToFrame(frame);
String fileName = getResourceNameFromLocation();
return savePageSourceWithFrames(fileName);
} finally {
getSeleniumHelper().switchToParentFrame();
}
}
protected String getCurrentFrameHtml(Map<String, String> sourceReplacements) {
String html = getSeleniumHelper().getHtml();
if (sourceReplacements != null && !sourceReplacements.isEmpty()) {
html = replaceSourceOfFrames(sourceReplacements, html);
}
return html;
}
protected String replaceSourceOfFrames(Map<String, String> sourceReplacements, String html) {
for (Map.Entry<String, String> entry : sourceReplacements.entrySet()) {
String originalLocation = entry.getKey();
String newLocation = entry.getValue();
html = html.replace("src=\"" + originalLocation + "\"", "src=\"/" + newLocation + "\"");
}
return html;
}
protected void addSourceReplacementsForFrame(Map<String, String> sourceReplacements, String savedLocation, String fullUrlOfFrame) {
String fullUrlOfParent = location();
int lastSlash = fullUrlOfParent.lastIndexOf("/");
String baseUrl = fullUrlOfParent.substring(0, lastSlash + 1);
String relativeUrlOfFrame = fullUrlOfFrame.replace(baseUrl, "");
sourceReplacements.put(fullUrlOfFrame, savedLocation);
sourceReplacements.put(relativeUrlOfFrame, savedLocation);
String framePath = getPath(fullUrlOfFrame);
if (framePath != null) {
sourceReplacements.put(framePath, savedLocation);
}
}
protected String getPath(String urlString) {
String path = null;
try {
URL url = new URL(urlString);
path = url.getPath();
} catch (MalformedURLException e) {
// leave path null
}
return path;
}
private String savePageSource(String fileName, String html) {
String result;
try {
String pageSourceName = getPageSourceName(fileName);
String file = FileUtil.saveToFile(pageSourceName, "html", html.getBytes("utf-8"));
String wikiUrl = getWikiUrl(file);
if (wikiUrl != null) {
// format file name
result = wikiUrl;
} else {
result = file;
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unable to save source", e);
}
return result;
}
protected String getPageSourceName(String fileName) {
return pageSourceBase + fileName;
}
/**
* Takes screenshot from current page
* @param basename filename (below screenshot base directory).
* @return location of screenshot.
*/
public String takeScreenshot(String basename) {
try {
String screenshotFile = createScreenshot(basename);
if (screenshotFile == null) {
throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?");
} else {
screenshotFile = getScreenshotLink(screenshotFile);
}
return screenshotFile;
} catch (UnhandledAlertException e) {
// standard behavior will stop test, this breaks storyboard that will attempt to take screenshot
// after triggering alert, but before the alert can be handled.
// so we output a message but no exception. We rely on a next line to actually handle alert
// (which may mean either really handle or stop test).
return String.format(
"<div><strong>Unable to take screenshot</strong>, alert is active. Alert text:<br/>" +
"'<span>%s</span>'</div>",
StringEscapeUtils.escapeHtml4(alertText()));
}
}
private String getScreenshotLink(String screenshotFile) {
String wikiUrl = getWikiUrl(screenshotFile);
if (wikiUrl != null) {
// make href to screenshot
if ("".equals(screenshotHeight)) {
wikiUrl = String.format("<a href=\"%s\">%s</a>",
wikiUrl, screenshotFile);
} else {
wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"/></a>",
wikiUrl, screenshotFile, screenshotHeight);
}
screenshotFile = wikiUrl;
}
return screenshotFile;
}
private String createScreenshot(String basename) {
String name = getScreenshotBasename(basename);
return getSeleniumHelper().takeScreenshot(name);
}
private String createScreenshot(String basename, Throwable t) {
String screenshotFile;
byte[] screenshotInException = getSeleniumHelper().findScreenshot(t);
if (screenshotInException == null || screenshotInException.length == 0) {
screenshotFile = createScreenshot(basename);
} else {
String name = getScreenshotBasename(basename);
screenshotFile = getSeleniumHelper().writeScreenshot(name, screenshotInException);
}
return screenshotFile;
}
private String getScreenshotBasename(String basename) {
return screenshotBase + basename;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws SlimFixtureException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntil(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
String message = getTimeoutMessage(e);
return lastAttemptBeforeThrow(condition, new SlimFixtureException(false, message, e));
}
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur the whole test is stopped.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws TimeoutStopTestException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntilOrStop(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
try {
return handleTimeoutException(e);
} catch (TimeoutStopTestException tste) {
return lastAttemptBeforeThrow(condition, tste);
}
}
}
/**
* Tries the condition one last time before throwing an exception.
* This to prevent exception messages in the wiki that show no problem, which could happen if the browser's
* window content has changed between last (failing) try at condition and generation of the exception.
* @param <T> the return type of the method, which must not be Void
* @param condition condition that caused exception.
* @param e exception that will be thrown if condition does not return a result.
* @return last attempt results, if not null.
* @throws SlimFixtureException throws e if last attempt returns null.
*/
protected <T> T lastAttemptBeforeThrow(ExpectedCondition<T> condition, SlimFixtureException e) {
T lastAttemptResult = null;
try {
// last attempt to ensure condition has not been met
// this to prevent messages that show no problem
lastAttemptResult = condition.apply(getSeleniumHelper().driver());
} catch (Throwable t) {
// ignore
}
if (lastAttemptResult != null) {
return lastAttemptResult;
}
throw e;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur null is returned.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @return result of condition.
*/
protected <T> T waitUntilOrNull(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
return null;
}
}
protected <T> T waitUntilImpl(ExpectedCondition<T> condition) {
return getSeleniumHelper().waitUntil(secondsBeforeTimeout(), condition);
}
protected <T> T handleTimeoutException(TimeoutException e) {
String message = getTimeoutMessage(e);
throw new TimeoutStopTestException(false, message, e);
}
private String getTimeoutMessage(TimeoutException e) {
String messageBase = String.format("Timed-out waiting (after %ss)", secondsBeforeTimeout());
return getSlimFixtureExceptionMessage("timeouts", "timeout", messageBase, e);
}
protected void handleRequiredElementNotFound(String toFind) {
handleRequiredElementNotFound(toFind, null);
}
protected void handleRequiredElementNotFound(String toFind, Throwable t) {
String messageBase = String.format("Unable to find: %s", toFind);
String message = getSlimFixtureExceptionMessage("notFound", toFind, messageBase, t);
throw new SlimFixtureException(false, message, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotFolder, String screenshotFile, String messageBase, Throwable t) {
String screenshotBaseName = String.format("%s/%s/%s", screenshotFolder, getClass().getSimpleName(), screenshotFile);
return getSlimFixtureExceptionMessage(screenshotBaseName, messageBase, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotBaseName, String messageBase, Throwable t) {
// take a screenshot of what was on screen
String screenShotFile = null;
try {
screenShotFile = createScreenshot(screenshotBaseName, t);
} catch (UnhandledAlertException e) {
// https://code.google.com/p/selenium/issues/detail?id=4412
System.err.println("Unable to take screenshot while alert is present for exception: " + messageBase);
} catch (Exception sse) {
System.err.println("Unable to take screenshot for exception: " + messageBase);
sse.printStackTrace();
}
String message = messageBase;
if (message == null) {
if (t == null) {
message = "";
} else {
message = ExceptionUtils.getStackTrace(t);
}
}
if (screenShotFile != null) {
String label = "Page content";
try {
String fileName;
if (t != null) {
fileName = t.getClass().getName();
} else if (screenshotBaseName != null) {
fileName = screenshotBaseName;
} else {
fileName = "exception";
}
label = savePageSourceToLink(fileName, label);
} catch (UnhandledAlertException e) {
// https://code.google.com/p/selenium/issues/detail?id=4412
System.err.println("Unable to capture page source while alert is present for exception: " + messageBase);
} catch (Exception e) {
System.err.println("Unable to capture page source for exception: " + messageBase);
e.printStackTrace();
}
String exceptionMsg = formatExceptionMsg(message);
message = String.format("<div><div>%s.</div><div>%s:%s</div></div>",
exceptionMsg, label, getScreenshotLink(screenShotFile));
}
return message;
}
protected String formatExceptionMsg(String value) {
return StringEscapeUtils.escapeHtml4(value);
}
private WebDriver driver() {
return getSeleniumHelper().driver();
}
private WebDriverWait waitDriver() {
return getSeleniumHelper().waitDriver();
}
/**
* @return helper to use.
*/
protected final SeleniumHelper getSeleniumHelper() {
return seleniumHelper;
}
/**
* Sets SeleniumHelper to use, for testing purposes.
* @param helper helper to use.
*/
void setSeleniumHelper(SeleniumHelper helper) {
seleniumHelper = helper;
}
public int currentBrowserWidth() {
return getWindowSize().getWidth();
}
public int currentBrowserHeight() {
return getWindowSize().getHeight();
}
public void setBrowserWidth(int newWidth) {
int currentHeight = currentBrowserHeight();
setBrowserSizeToBy(newWidth, currentHeight);
}
public void setBrowserHeight(int newHeight) {
int currentWidth = currentBrowserWidth();
setBrowserSizeToBy(currentWidth, newHeight);
}
public void setBrowserSizeToBy(int newWidth, int newHeight) {
getSeleniumHelper().setWindowSize(newWidth, newHeight);
Dimension actualSize = getWindowSize();
if (actualSize.getHeight() != newHeight || actualSize.getWidth() != newWidth) {
String message = String.format("Unable to change size to: %s x %s; size is: %s x %s",
newWidth, newHeight, actualSize.getWidth(), actualSize.getHeight());
throw new SlimFixtureException(false, message);
}
}
protected Dimension getWindowSize() {
return getSeleniumHelper().getWindowSize();
}
public void setBrowserSizeToMaximum() {
getSeleniumHelper().setWindowSizeToMaximum();
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String download(String place) {
return downloadIn(place, null);
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @param container part of screen containing link.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadIn(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
By selector = By.linkText(place);
WebElement element = findElement(selector);
if (element == null) {
selector = By.partialLinkText(place);
element = findElement(selector);
if (element == null) {
selector = By.id(place);
element = findElement(selector);
if (element == null) {
selector = By.name(place);
element = findElement(selector);
}
}
}
return downloadLinkTarget(element);
} finally {
resetSearchContext(currentSearchContext);
}
}
protected WebElement findElement(By selector) {
return getSeleniumHelper().findElement(selector);
}
/**
* Downloads the target of the supplied link.
* @param element link to follow.
* @return downloaded file if any, null otherwise.
*/
protected String downloadLinkTarget(WebElement element) {
String result = null;
if (element != null) {
String href = element.getAttribute("href");
if (href != null) {
result = downloadContentFrom(href);
} else {
throw new SlimFixtureException(false, "Could not determine url to download from");
}
}
return result;
}
/**
* Downloads binary content from specified url (using the browser's cookies).
* @param urlOrLink url to download from
* @return link to downloaded file
*/
public String downloadContentFrom(String urlOrLink) {
String result = null;
if (urlOrLink != null) {
String url = getUrl(urlOrLink);
BinaryHttpResponse resp = new BinaryHttpResponse();
getUrlContent(url, resp);
byte[] content = resp.getResponseContent();
if (content == null) {
result = resp.getResponse();
} else {
String fileName = resp.getFileName();
String baseName = FilenameUtils.getBaseName(fileName);
String ext = FilenameUtils.getExtension(fileName);
String downloadedFile = FileUtil.saveToFile(getDownloadName(baseName), ext, content);
String wikiUrl = getWikiUrl(downloadedFile);
if (wikiUrl != null) {
// make href to file
result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName);
} else {
result = downloadedFile;
}
}
}
return result;
}
/**
* Selects a file using the first file upload control.
* @param fileName file to upload
* @return true, if a file input was found and file existed.
*/
@WaitUntil
public boolean selectFile(String fileName) {
return selectFileFor(fileName, "css=input[type='file']");
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileFor(String fileName, String place) {
return selectFileForIn(fileName, place, null);
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @param container part of screen containing place
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileForIn(String fileName, String place, String container) {
boolean result = false;
if (fileName != null) {
String fullPath = getFilePathFromWikiUrl(fileName);
if (new File(fullPath).exists()) {
WebElement element = getElementToSelectFile(place, container);
if (element != null) {
element.sendKeys(fullPath);
result = true;
}
} else {
throw new SlimFixtureException(false, "Unable to find file: " + fullPath);
}
}
return result;
}
protected WebElement getElementToSelectFile(String place, String container) {
WebElement result = null;
WebElement element = getElement(place, container);
if (element != null
&& "input".equalsIgnoreCase(element.getTagName())
&& "file".equalsIgnoreCase(element.getAttribute("type"))) {
result = element;
}
return result;
}
private String getDownloadName(String baseName) {
return downloadBase + baseName;
}
/**
* GETs content of specified URL, using the browsers cookies.
* @param url url to retrieve content from
* @param resp response to store content in
*/
protected void getUrlContent(String url, HttpResponse resp) {
getEnvironment().addSeleniumCookies(resp, -1);
getEnvironment().doGet(url, resp);
}
/**
* Gets the value of the cookie with the supplied name.
* @param cookieName name of cookie to get value from.
* @return cookie's value if any.
*/
public String cookieValue(String cookieName) {
String result = null;
Cookie cookie = getSeleniumHelper().getCookie(cookieName);
if (cookie != null) {
result = cookie.getValue();
}
return result;
}
protected Object waitForJavascriptCallback(String statement, Object... parameters) {
try {
return getSeleniumHelper().waitForJavascriptCallback(statement, parameters);
} catch (TimeoutException e) {
return handleTimeoutException(e);
}
}
public NgBrowserTest getNgBrowserTest() {
return ngBrowserTest;
}
public void setNgBrowserTest(NgBrowserTest ngBrowserTest) {
this.ngBrowserTest = ngBrowserTest;
}
public boolean isImplicitWaitForAngularEnabled() {
return implicitWaitForAngular;
}
public void setImplicitWaitForAngularTo(boolean implicitWaitForAngular) {
this.implicitWaitForAngular = implicitWaitForAngular;
}
public void setImplicitFindInFramesTo(boolean implicitFindInFrames) {
this.implicitFindInFrames = implicitFindInFrames;
}
}
| Rename method to save html
| src/main/java/nl/hsac/fitnesse/fixture/slim/web/BrowserTest.java | Rename method to save html | <ide><path>rc/main/java/nl/hsac/fitnesse/fixture/slim/web/BrowserTest.java
<ide> */
<ide> public String savePageSource() {
<ide> String fileName = getResourceNameFromLocation();
<del> return savePageSourceToLink(fileName, fileName + ".html");
<del> }
<del>
<del> protected String savePageSourceToLink(String fileName, String linkText) {
<add> return savePageSource(fileName, fileName + ".html");
<add> }
<add>
<add> protected String savePageSource(String fileName, String linkText) {
<ide> // make href to file
<ide> String url = savePageSourceWithFrames(fileName);
<ide> return String.format("<a href=\"%s\">%s</a>", url, linkText);
<ide> addSourceReplacementsForFrame(sourceReplacements, newLocation, fullUrlOfFrame);
<ide> }
<ide> String html = getCurrentFrameHtml(sourceReplacements);
<del> return savePageSource(fileName, html);
<add> return saveHtmlAsPageSource(fileName, html);
<ide> }
<ide>
<ide> protected String saveFrameSource(WebElement frame) {
<ide> return path;
<ide> }
<ide>
<del> private String savePageSource(String fileName, String html) {
<add> protected String saveHtmlAsPageSource(String fileName, String html) {
<ide> String result;
<ide> try {
<ide> String pageSourceName = getPageSourceName(fileName);
<ide> } else {
<ide> fileName = "exception";
<ide> }
<del> label = savePageSourceToLink(fileName, label);
<add> label = savePageSource(fileName, label);
<ide> } catch (UnhandledAlertException e) {
<ide> // https://code.google.com/p/selenium/issues/detail?id=4412
<ide> System.err.println("Unable to capture page source while alert is present for exception: " + messageBase); |
|
Java | apache-2.0 | f5b59350cc1b4580154df047f409a6c7a4095f0b | 0 | smgoller/geode,davebarnes97/geode,smgoller/geode,davinash/geode,smgoller/geode,davebarnes97/geode,jdeppe-pivotal/geode,davinash/geode,davebarnes97/geode,davebarnes97/geode,masaki-yamakawa/geode,davinash/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,smgoller/geode,jdeppe-pivotal/geode,davinash/geode,davinash/geode,jdeppe-pivotal/geode,davinash/geode,masaki-yamakawa/geode,smgoller/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,davinash/geode,davebarnes97/geode,smgoller/geode,davebarnes97/geode,davebarnes97/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,smgoller/geode,masaki-yamakawa/geode | /*
* 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.geode.internal.cache;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.logging.log4j.Logger;
import org.apache.geode.DataSerializer;
import org.apache.geode.Instantiator;
import org.apache.geode.annotations.internal.MakeNotStatic;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.client.PoolFactory;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.ExecutablePool;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache.client.internal.RegisterDataSerializersOp;
import org.apache.geode.cache.client.internal.RegisterInstantiatorsOp;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.InternalDataSerializer.SerializerAttributesHolder;
import org.apache.geode.internal.InternalInstantiator;
import org.apache.geode.internal.InternalInstantiator.InstantiatorAttributesHolder;
import org.apache.geode.internal.cache.tier.sockets.ServerConnection;
import org.apache.geode.internal.cache.xmlcache.CacheCreation;
import org.apache.geode.logging.internal.log4j.api.LogService;
/**
* Implementation used by PoolManager.
*
* @since GemFire 5.7
*/
public class PoolManagerImpl {
private static final Logger logger = LogService.getLogger();
@MakeNotStatic
private static final PoolManagerImpl impl = new PoolManagerImpl(true);
public static PoolManagerImpl getPMI() {
PoolManagerImpl result = CacheCreation.getCurrentPoolManager();
if (result == null) {
result = impl;
}
return result;
}
private volatile Map<String, Pool> pools = Collections.emptyMap();
private volatile Iterator<Map.Entry<String, Pool>> itrForEmergencyClose = null;
private final Object poolLock = new Object();
/**
* True if this manager is a normal one owned by the PoolManager. False if this is a special one
* owned by a xml CacheCreation.
*/
private final boolean normalManager;
/**
* @param addListener will be true if the is a real manager that needs to register a connect
* listener. False if it is a fake manager used internally by the XML code.
*/
public PoolManagerImpl(boolean addListener) {
normalManager = addListener;
}
/**
* Returns true if this is a normal manager; false if it is a fake one used for xml parsing.
*/
public boolean isNormal() {
return normalManager;
}
/**
* Creates a new {@link PoolFactory pool factory}, which is used to configure and create new
* {@link Pool}s.
*
* @return the new pool factory
*/
public PoolFactory createFactory() {
return new PoolFactoryImpl(this);
}
/**
* Find by name an existing connection pool returning the existing pool or <code>null</code> if it
* does not exist.
*
* @param name the name of the connection pool
* @return the existing connection pool or <code>null</code> if it does not exist.
*/
public Pool find(String name) {
return pools.get(name);
}
/**
* Destroys all created pool in this manager.
*/
public void close(boolean keepAlive) {
// destroying connection pools
boolean foundClientPool = false;
synchronized (poolLock) {
for (Entry<String, Pool> entry : pools.entrySet()) {
Pool pool = entry.getValue();
if (pool instanceof PoolImpl) {
((PoolImpl) pool).basicDestroy(keepAlive);
foundClientPool = true;
}
}
pools = Collections.emptyMap();
itrForEmergencyClose = null;
if (foundClientPool) {
// Now that the client has all the pools destroyed free up the pooled comm buffers
ServerConnection.emptyCommBufferPool();
}
}
}
/**
* @return a copy of the Pools Map
*/
public Map<String, Pool> getMap() {
return new HashMap<>(pools);
}
/**
* This is called by {@link PoolImpl#create}
*
* @throws IllegalStateException if a pool with same name is already registered.
*/
public void register(Pool pool) {
synchronized (poolLock) {
Map<String, Pool> copy = new HashMap<>(pools);
String name = pool.getName();
// debugStack("register pool=" + name);
Object old = copy.put(name, pool);
if (old != null) {
throw new IllegalStateException(
String.format("A pool named %s already exists", name));
}
// Boolean specialCase=Boolean.getBoolean("gemfire.SPECIAL_DURABLE");
// if(specialCase && copy.size()>1){
// throw new IllegalStateException("Using SPECIAL_DURABLE system property"
// + " and more than one pool already exists in client.");
// }
pools = Collections.unmodifiableMap(copy);
itrForEmergencyClose = copy.entrySet().iterator();
}
}
/**
* This is called by {@link Pool#destroy(boolean)}
*
* @return true if pool unregistered from cache; false if someone else already did it
*/
public boolean unregister(Pool pool) {
// Continue only if the pool is not currently being used by any region and/or service.
int attachCount = 0;
if (pool instanceof PoolImpl) {
attachCount = ((PoolImpl) pool).getAttachCount();
}
if (attachCount > 0) {
throw new IllegalStateException(String.format(
"Pool could not be destroyed because it is still in use by %s regions", attachCount));
}
synchronized (poolLock) {
Map<String, Pool> copy = new HashMap<>(pools);
String name = pool.getName();
// debugStack("unregister pool=" + name);
Object rmPool = copy.remove(name);
if (rmPool == null || rmPool != pool) {
return false;
} else {
pools = Collections.unmodifiableMap(copy);
itrForEmergencyClose = copy.entrySet().iterator();
return true;
}
}
}
@Override
public String toString() {
return super.toString() + "-" + (normalManager ? "normal" : "xml");
}
/**
* @param xmlPoolsOnly if true then only call readyForEvents on pools declared in XML.
*/
public static void readyForEvents(InternalDistributedSystem system, boolean xmlPoolsOnly) {
boolean foundDurablePool = false;
Map<String, Pool> pools = PoolManager.getAll();
for (Pool pool : pools.values()) {
if (pool instanceof PoolImpl) {
PoolImpl p = (PoolImpl) pool;
if (p.isDurableClient()) {
// TODO - handle an exception and attempt on all pools?
foundDurablePool = true;
if (!xmlPoolsOnly) {
p.readyForEvents(system);
}
}
}
}
if (pools.size() > 0 && !foundDurablePool) {
throw new IllegalStateException(
"Only durable clients should call readyForEvents()");
}
}
public static void allPoolsRegisterInstantiator(Instantiator instantiator) {
Instantiator[] instantiators = new Instantiator[] {instantiator};
for (Pool pool : PoolManager.getAll().values()) {
try {
EventID eventId = InternalInstantiator.generateEventId();
if (eventId != null) {
RegisterInstantiatorsOp.execute((ExecutablePool) pool, instantiators, eventId);
}
} catch (RuntimeException e) {
logger.warn("Error registering instantiator on pool:", e);
}
}
}
public static void allPoolsRegisterInstantiator(InstantiatorAttributesHolder holder) {
InstantiatorAttributesHolder[] holders = new InstantiatorAttributesHolder[] {holder};
for (Pool pool : PoolManager.getAll().values()) {
try {
EventID eventId = InternalInstantiator.generateEventId();
if (eventId != null) {
RegisterInstantiatorsOp.execute((ExecutablePool) pool, holders, eventId);
}
} catch (RuntimeException e) {
logger.warn("Error registering instantiator on pool:", e);
}
}
}
public static void allPoolsRegisterDataSerializers(DataSerializer dataSerializer) {
DataSerializer[] dataSerializers = new DataSerializer[] {dataSerializer};
for (Pool pool : PoolManager.getAll().values()) {
try {
EventID eventId = (EventID) dataSerializer.getEventId();
if (eventId == null) {
eventId = InternalDataSerializer.generateEventId();
}
if (eventId != null) {
RegisterDataSerializersOp.execute((ExecutablePool) pool, dataSerializers, eventId);
}
} catch (RuntimeException e) {
logger.warn("Error registering instantiator on pool:", e);
}
}
}
public static void allPoolsRegisterDataSerializers(SerializerAttributesHolder holder) {
SerializerAttributesHolder[] holders = new SerializerAttributesHolder[] {holder};
for (Pool pool : PoolManager.getAll().values()) {
try {
EventID eventId = holder.getEventId();
if (eventId == null) {
eventId = InternalDataSerializer.generateEventId();
}
if (eventId != null) {
RegisterDataSerializersOp.execute((ExecutablePool) pool, holders, eventId);
}
} catch (RuntimeException e) {
logger.warn("Error registering instantiator on pool:", e);
}
}
}
public static void emergencyClose() {
if (impl == null) {
return;
}
Iterator<Map.Entry<String, Pool>> itr = impl.itrForEmergencyClose;
if (itr == null) {
return;
}
while (itr.hasNext()) {
Entry<String, Pool> next = itr.next();
((PoolImpl) next.getValue()).emergencyClose();
}
}
public static void loadEmergencyClasses() {
PoolImpl.loadEmergencyClasses();
}
public Pool find(Region<?, ?> region) {
return find(region.getAttributes().getPoolName());
}
}
| geode-core/src/main/java/org/apache/geode/internal/cache/PoolManagerImpl.java | /*
* 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.geode.internal.cache;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.logging.log4j.Logger;
import org.apache.geode.DataSerializer;
import org.apache.geode.Instantiator;
import org.apache.geode.annotations.internal.MakeNotStatic;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.client.PoolFactory;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache.client.internal.RegisterDataSerializersOp;
import org.apache.geode.cache.client.internal.RegisterInstantiatorsOp;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.InternalDataSerializer.SerializerAttributesHolder;
import org.apache.geode.internal.InternalInstantiator;
import org.apache.geode.internal.InternalInstantiator.InstantiatorAttributesHolder;
import org.apache.geode.internal.cache.tier.sockets.ServerConnection;
import org.apache.geode.internal.cache.xmlcache.CacheCreation;
import org.apache.geode.logging.internal.log4j.api.LogService;
/**
* Implementation used by PoolManager.
*
* @since GemFire 5.7
*
*/
public class PoolManagerImpl {
private static final Logger logger = LogService.getLogger();
@MakeNotStatic
private static final PoolManagerImpl impl = new PoolManagerImpl(true);
public static PoolManagerImpl getPMI() {
PoolManagerImpl result = CacheCreation.getCurrentPoolManager();
if (result == null) {
result = impl;
}
return result;
}
private volatile Map<String, Pool> pools = Collections.emptyMap();
private volatile Iterator<Map.Entry<String, Pool>> itrForEmergencyClose = null;
private final Object poolLock = new Object();
/**
* True if this manager is a normal one owned by the PoolManager. False if this is a special one
* owned by a xml CacheCreation.
*/
private final boolean normalManager;
/**
* @param addListener will be true if the is a real manager that needs to register a connect
* listener. False if it is a fake manager used internally by the XML code.
*/
public PoolManagerImpl(boolean addListener) {
normalManager = addListener;
}
/**
* Returns true if this is a normal manager; false if it is a fake one used for xml parsing.
*/
public boolean isNormal() {
return normalManager;
}
/**
* Creates a new {@link PoolFactory pool factory}, which is used to configure and create new
* {@link Pool}s.
*
* @return the new pool factory
*/
public PoolFactory createFactory() {
return new PoolFactoryImpl(this);
}
/**
* Find by name an existing connection pool returning the existing pool or <code>null</code> if it
* does not exist.
*
* @param name the name of the connection pool
* @return the existing connection pool or <code>null</code> if it does not exist.
*/
public Pool find(String name) {
return pools.get(name);
}
/**
* Destroys all created pool in this manager.
*/
public void close(boolean keepAlive) {
// destroying connection pools
boolean foundClientPool = false;
synchronized (poolLock) {
for (Entry<String, Pool> entry : pools.entrySet()) {
PoolImpl pool = (PoolImpl) entry.getValue();
pool.basicDestroy(keepAlive);
foundClientPool = true;
}
pools = Collections.emptyMap();
itrForEmergencyClose = null;
if (foundClientPool) {
// Now that the client has all the pools destroyed free up the pooled comm buffers
ServerConnection.emptyCommBufferPool();
}
}
}
/**
* @return a copy of the Pools Map
*/
public Map<String, Pool> getMap() {
return new HashMap<>(pools);
}
/**
* This is called by {@link PoolImpl#create}
*
* @throws IllegalStateException if a pool with same name is already registered.
*/
public void register(Pool pool) {
synchronized (poolLock) {
Map<String, Pool> copy = new HashMap<>(pools);
String name = pool.getName();
// debugStack("register pool=" + name);
Object old = copy.put(name, pool);
if (old != null) {
throw new IllegalStateException(
String.format("A pool named %s already exists", name));
}
// Boolean specialCase=Boolean.getBoolean("gemfire.SPECIAL_DURABLE");
// if(specialCase && copy.size()>1){
// throw new IllegalStateException("Using SPECIAL_DURABLE system property"
// + " and more than one pool already exists in client.");
// }
pools = Collections.unmodifiableMap(copy);
itrForEmergencyClose = copy.entrySet().iterator();
}
}
/**
* This is called by {@link Pool#destroy(boolean)}
*
* @return true if pool unregistered from cache; false if someone else already did it
*/
public boolean unregister(Pool pool) {
// Continue only if the pool is not currently being used by any region and/or service.
int attachCount = ((PoolImpl) pool).getAttachCount();
if (attachCount > 0) {
throw new IllegalStateException(String.format(
"Pool could not be destroyed because it is still in use by %s regions", attachCount));
}
synchronized (poolLock) {
Map<String, Pool> copy = new HashMap<>(pools);
String name = pool.getName();
// debugStack("unregister pool=" + name);
Object rmPool = copy.remove(name);
if (rmPool == null || rmPool != pool) {
return false;
} else {
pools = Collections.unmodifiableMap(copy);
itrForEmergencyClose = copy.entrySet().iterator();
return true;
}
}
}
@Override
public String toString() {
return super.toString() + "-" + (normalManager ? "normal" : "xml");
}
/**
* @param xmlPoolsOnly if true then only call readyForEvents on pools declared in XML.
*/
public static void readyForEvents(InternalDistributedSystem system, boolean xmlPoolsOnly) {
boolean foundDurablePool = false;
Map<String, Pool> pools = PoolManager.getAll();
for (Pool pool : pools.values()) {
PoolImpl p = (PoolImpl) pool;
if (p.isDurableClient()) {
// TODO - handle an exception and attempt on all pools?
foundDurablePool = true;
if (!xmlPoolsOnly) {
p.readyForEvents(system);
}
}
}
if (pools.size() > 0 && !foundDurablePool) {
throw new IllegalStateException(
"Only durable clients should call readyForEvents()");
}
}
public static void allPoolsRegisterInstantiator(Instantiator instantiator) {
Instantiator[] instantiators = new Instantiator[] {instantiator};
for (Pool pool : PoolManager.getAll().values()) {
PoolImpl next = (PoolImpl) pool;
try {
EventID eventId = InternalInstantiator.generateEventId();
if (eventId != null) {
RegisterInstantiatorsOp.execute(next, instantiators, eventId);
}
} catch (RuntimeException e) {
logger.warn("Error registering instantiator on pool:", e);
}
}
}
public static void allPoolsRegisterInstantiator(InstantiatorAttributesHolder holder) {
InstantiatorAttributesHolder[] holders = new InstantiatorAttributesHolder[] {holder};
for (Pool pool : PoolManager.getAll().values()) {
PoolImpl next = (PoolImpl) pool;
try {
EventID eventId = InternalInstantiator.generateEventId();
if (eventId != null) {
RegisterInstantiatorsOp.execute(next, holders, eventId);
}
} catch (RuntimeException e) {
logger.warn("Error registering instantiator on pool:", e);
}
}
}
public static void allPoolsRegisterDataSerializers(DataSerializer dataSerializer) {
DataSerializer[] dataSerializers = new DataSerializer[] {dataSerializer};
for (Pool pool : PoolManager.getAll().values()) {
PoolImpl next = (PoolImpl) pool;
try {
EventID eventId = (EventID) dataSerializer.getEventId();
if (eventId == null) {
eventId = InternalDataSerializer.generateEventId();
}
if (eventId != null) {
RegisterDataSerializersOp.execute(next, dataSerializers, eventId);
}
} catch (RuntimeException e) {
logger.warn("Error registering instantiator on pool:", e);
}
}
}
public static void allPoolsRegisterDataSerializers(SerializerAttributesHolder holder) {
SerializerAttributesHolder[] holders = new SerializerAttributesHolder[] {holder};
for (Pool pool : PoolManager.getAll().values()) {
PoolImpl next = (PoolImpl) pool;
try {
EventID eventId = holder.getEventId();
if (eventId == null) {
eventId = InternalDataSerializer.generateEventId();
}
if (eventId != null) {
RegisterDataSerializersOp.execute(next, holders, eventId);
}
} catch (RuntimeException e) {
logger.warn("Error registering instantiator on pool:", e);
}
}
}
public static void emergencyClose() {
if (impl == null) {
return;
}
Iterator<Map.Entry<String, Pool>> itr = impl.itrForEmergencyClose;
if (itr == null) {
return;
}
while (itr.hasNext()) {
Entry<String, Pool> next = itr.next();
((PoolImpl) next.getValue()).emergencyClose();
}
}
public static void loadEmergencyClasses() {
PoolImpl.loadEmergencyClasses();
}
public Pool find(Region<?, ?> region) {
return find(region.getAttributes().getPoolName());
}
}
| GEODE-7531: Added type checking before casting generic `Pool.java` to `PoolImpl.java` (#4490)
| geode-core/src/main/java/org/apache/geode/internal/cache/PoolManagerImpl.java | GEODE-7531: Added type checking before casting generic `Pool.java` to `PoolImpl.java` (#4490) | <ide><path>eode-core/src/main/java/org/apache/geode/internal/cache/PoolManagerImpl.java
<ide> import org.apache.geode.cache.client.Pool;
<ide> import org.apache.geode.cache.client.PoolFactory;
<ide> import org.apache.geode.cache.client.PoolManager;
<add>import org.apache.geode.cache.client.internal.ExecutablePool;
<ide> import org.apache.geode.cache.client.internal.PoolImpl;
<ide> import org.apache.geode.cache.client.internal.RegisterDataSerializersOp;
<ide> import org.apache.geode.cache.client.internal.RegisterInstantiatorsOp;
<ide> * Implementation used by PoolManager.
<ide> *
<ide> * @since GemFire 5.7
<del> *
<ide> */
<ide> public class PoolManagerImpl {
<ide> private static final Logger logger = LogService.getLogger();
<ide> boolean foundClientPool = false;
<ide> synchronized (poolLock) {
<ide> for (Entry<String, Pool> entry : pools.entrySet()) {
<del> PoolImpl pool = (PoolImpl) entry.getValue();
<del> pool.basicDestroy(keepAlive);
<del> foundClientPool = true;
<add> Pool pool = entry.getValue();
<add> if (pool instanceof PoolImpl) {
<add> ((PoolImpl) pool).basicDestroy(keepAlive);
<add> foundClientPool = true;
<add> }
<add>
<ide> }
<ide> pools = Collections.emptyMap();
<ide> itrForEmergencyClose = null;
<ide> */
<ide> public boolean unregister(Pool pool) {
<ide> // Continue only if the pool is not currently being used by any region and/or service.
<del> int attachCount = ((PoolImpl) pool).getAttachCount();
<add> int attachCount = 0;
<add> if (pool instanceof PoolImpl) {
<add> attachCount = ((PoolImpl) pool).getAttachCount();
<add> }
<ide> if (attachCount > 0) {
<ide> throw new IllegalStateException(String.format(
<ide> "Pool could not be destroyed because it is still in use by %s regions", attachCount));
<ide> boolean foundDurablePool = false;
<ide> Map<String, Pool> pools = PoolManager.getAll();
<ide> for (Pool pool : pools.values()) {
<del> PoolImpl p = (PoolImpl) pool;
<del> if (p.isDurableClient()) {
<del> // TODO - handle an exception and attempt on all pools?
<del> foundDurablePool = true;
<del> if (!xmlPoolsOnly) {
<del> p.readyForEvents(system);
<add> if (pool instanceof PoolImpl) {
<add> PoolImpl p = (PoolImpl) pool;
<add> if (p.isDurableClient()) {
<add> // TODO - handle an exception and attempt on all pools?
<add> foundDurablePool = true;
<add> if (!xmlPoolsOnly) {
<add> p.readyForEvents(system);
<add> }
<ide> }
<ide> }
<ide> }
<ide> public static void allPoolsRegisterInstantiator(Instantiator instantiator) {
<ide> Instantiator[] instantiators = new Instantiator[] {instantiator};
<ide> for (Pool pool : PoolManager.getAll().values()) {
<del> PoolImpl next = (PoolImpl) pool;
<ide> try {
<ide> EventID eventId = InternalInstantiator.generateEventId();
<ide> if (eventId != null) {
<del> RegisterInstantiatorsOp.execute(next, instantiators, eventId);
<add> RegisterInstantiatorsOp.execute((ExecutablePool) pool, instantiators, eventId);
<ide> }
<ide> } catch (RuntimeException e) {
<ide> logger.warn("Error registering instantiator on pool:", e);
<ide> public static void allPoolsRegisterInstantiator(InstantiatorAttributesHolder holder) {
<ide> InstantiatorAttributesHolder[] holders = new InstantiatorAttributesHolder[] {holder};
<ide> for (Pool pool : PoolManager.getAll().values()) {
<del> PoolImpl next = (PoolImpl) pool;
<ide> try {
<ide> EventID eventId = InternalInstantiator.generateEventId();
<ide> if (eventId != null) {
<del> RegisterInstantiatorsOp.execute(next, holders, eventId);
<add> RegisterInstantiatorsOp.execute((ExecutablePool) pool, holders, eventId);
<ide> }
<ide> } catch (RuntimeException e) {
<ide> logger.warn("Error registering instantiator on pool:", e);
<ide> public static void allPoolsRegisterDataSerializers(DataSerializer dataSerializer) {
<ide> DataSerializer[] dataSerializers = new DataSerializer[] {dataSerializer};
<ide> for (Pool pool : PoolManager.getAll().values()) {
<del> PoolImpl next = (PoolImpl) pool;
<ide> try {
<ide> EventID eventId = (EventID) dataSerializer.getEventId();
<ide> if (eventId == null) {
<ide> eventId = InternalDataSerializer.generateEventId();
<ide> }
<ide> if (eventId != null) {
<del> RegisterDataSerializersOp.execute(next, dataSerializers, eventId);
<add> RegisterDataSerializersOp.execute((ExecutablePool) pool, dataSerializers, eventId);
<ide> }
<ide> } catch (RuntimeException e) {
<ide> logger.warn("Error registering instantiator on pool:", e);
<ide> public static void allPoolsRegisterDataSerializers(SerializerAttributesHolder holder) {
<ide> SerializerAttributesHolder[] holders = new SerializerAttributesHolder[] {holder};
<ide> for (Pool pool : PoolManager.getAll().values()) {
<del> PoolImpl next = (PoolImpl) pool;
<ide> try {
<ide> EventID eventId = holder.getEventId();
<ide> if (eventId == null) {
<ide> eventId = InternalDataSerializer.generateEventId();
<ide> }
<ide> if (eventId != null) {
<del> RegisterDataSerializersOp.execute(next, holders, eventId);
<add> RegisterDataSerializersOp.execute((ExecutablePool) pool, holders, eventId);
<ide> }
<ide> } catch (RuntimeException e) {
<ide> logger.warn("Error registering instantiator on pool:", e); |
|
Java | apache-2.0 | 8379674ce46f00d25bd806a0ab8a9fe1e8d4065d | 0 | ViDA-NYU/ache,ViDA-NYU/ache,ViDA-NYU/ache | package focusedCrawler.memex.cdr;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import focusedCrawler.target.model.TargetModelJson;
import focusedCrawler.target.repository.FileSystemTargetRepository;
import focusedCrawler.target.repository.FileSystemTargetRepository.DataFormat;
import focusedCrawler.target.repository.FilesTargetRepository;
import focusedCrawler.tools.SimpleBulkIndexer;
import focusedCrawler.util.CliTool;
import focusedCrawler.util.persistence.PersistentHashtable;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
@Command(name="AcheToCdrExporter", description="Exports crawled data to CDR format")
public class AcheToCdrExporter extends CliTool {
private static final ObjectMapper jsonMapper = new ObjectMapper();
//
// Input data options
//
@Option(name = "--input-path", description="Path to ACHE data target folder", required=true)
private String inputPath;
@Option(name={"--repository-type", "-rt"}, description="Which repository type should be used")
private RepositoryType repositoryType = RepositoryType.FILES;
public enum RepositoryType {
FILES, FILESYSTEM_JSON;
}
@Option(name="--fs-hashed", description="Whether ACHE filesystem repository files names are hashed")
private boolean hashFilename = false;
@Option(name="--fs-compressed", description="Whether ACHE filesystem repository files is compressed")
private boolean compressData = false;
//
// Options for output data format
//
@Option(name="--cdr-version", description="Which CDR version should be used")
private CDRVersion cdrVersion = CDRVersion.CDRv31;
public enum CDRVersion {
CDRv2, CDRv3, CDRv31
}
@Option(name="--output-file", description="Gziped output file containing data formmated as per CDR schema")
private String outputFile;
@Option(name="--skip-relevant", description="Whether relevant pages should be skipped")
private boolean skipRelevant = false;
@Option(name="--skip-irrelevant", description="Whether irrelevant pages should be skipped")
private boolean skipIrrelevant = false;
// Elastic Search output options
@Option(name={"--output-es-index", "-oi"}, description="ElasticSearch index name (output)")
String outputIndex;
@Option(name={"--output-es-type", "-ot"}, description="ElasticSearch index type (output)")
String outputType;
@Option(name={"--output-es-url", "-ou"}, description="ElasticSearch full HTTP URL address")
String elasticSearchServer = null;
@Option(name={"--output-es-auth", "-oa"}, description="User and password for ElasticSearch in format: user:pass")
String userPass = null;
@Option(name={"--output-es-bulk-size", "-obs"}, description="ElasticSearch bulk size")
int bulkSize = 25;
//AWS S3 Support
@Option(name={"--accesskey", "-ak"}, description="AWS ACCESS KEY ID")
String accessKeyID = "";
@Option(name={"--secretkey", "-sk"}, description="AWS SECRET KEY ID")
String secretKeyID = "";
@Option(name = {"--bucket", "-bk"}, description = "AWS S3 BUCKET NAME")
String bucketName = "";
@Option(name = {"--region", "-rg"}, description = "AWS S3 Region name")
String region = "us-east-1";
@Option(name = {"--skip-upload", "-su"}, description = "Disable upload of objects to S3")
private boolean skipUpload = false;
@Option(name = {"--tmp-path", "-tmp"}, description = "Path to temporary working folder")
String temp = null;
private PersistentHashtable<CDR31MediaObject> mediaObjectCache;
private S3Uploader s3Uploader;
//
// Runtime variables
//
private int processedPages = 0;
private PrintWriter out;
private SimpleBulkIndexer bulkIndexer;
private String id;
private Object doc;
public static void main(String[] args) throws Exception {
CliTool.run(args, new AcheToCdrExporter());
}
@Override
public void execute() throws Exception {
System.out.println("Reading ACHE data from: "+inputPath);
System.out.println("Generating CDR file at: "+outputFile);
System.out.println(" Compressed repository: "+compressData);
System.out.println(" Hashed file name: "+hashFilename);
if (temp == null) {
Path tmpPath = Files.createTempDirectory("cdr-export-tmp");
Files.createDirectories(tmpPath);
temp = tmpPath.toString();
}
if (!skipUpload) {
s3Uploader = new S3Uploader(this.accessKeyID, this.secretKeyID, this.bucketName,
this.region);
}
mediaObjectCache = new PersistentHashtable<CDR31MediaObject>(temp, 1000, CDR31MediaObject.class);
if (outputFile != null) {
GZIPOutputStream gzipStream = new GZIPOutputStream(new FileOutputStream(outputFile));
out = new PrintWriter(gzipStream, true);
}
if (elasticSearchServer != null) {
if (this.outputIndex == null || this.outputIndex.isEmpty())
throw new IllegalArgumentException(
"Argument for Elasticsearch index can't be empty");
if (this.outputType == null || this.outputType.isEmpty())
throw new IllegalArgumentException(
"Argument for Elasticsearch type can't be empty");
bulkIndexer = new SimpleBulkIndexer(elasticSearchServer, userPass, bulkSize);
}
//Process media files
System.out.println("Pre-processing media files...");
Iterator<TargetModelJson> it = createIterator();
while (it.hasNext()) {
TargetModelJson pageModel = it.next();
try {
processMediaFile(pageModel);
} catch (Exception e) {
System.err.println("Failed to process record.\n" + e.toString());
}
}
mediaObjectCache.commit();
//Process html files
System.out.println("Processing HTML pages...");
it = createIterator();
while (it.hasNext()) {
TargetModelJson pageModel = it.next();
try {
processRecord(pageModel);
processedPages++;
if (processedPages % 100 == 0) {
System.out.printf("Processed %d pages\n", processedPages);
}
} catch (Exception e) {
System.err.println("Failed to process record.\n" + e.toString());
}
}
System.out.printf("Processed %d pages\n", processedPages);
if(out != null) out.close();
if(bulkIndexer!= null) bulkIndexer.close();
System.out.println("done.");
}
private Iterator<TargetModelJson> createIterator() {
if(repositoryType == RepositoryType.FILESYSTEM_JSON) {
FileSystemTargetRepository repository = new FileSystemTargetRepository(inputPath,
DataFormat.JSON, hashFilename, compressData);
return repository.iterator();
} else {
FilesTargetRepository repository = new FilesTargetRepository(inputPath);
return repository.iterator();
}
}
private void processMediaFile(TargetModelJson pageModel) throws IOException {
// What if contentType is empty but the object is an image.
//
String contentType = pageModel.getContentType();
if (contentType == null || contentType.isEmpty()) {
System.err.println("Ignoring URL with no content-type: " + pageModel.getUrl());
return;
}
if (!contentType.startsWith("image")) {
return;
}
if (cdrVersion != CDRVersion.CDRv31) {
return;
}
createCDR31MediaObject(pageModel);
}
private void processRecord(TargetModelJson pageModel) throws IOException {
String contentType = pageModel.getContentType();
if (contentType == null || contentType.isEmpty()) {
System.err.println("Ignoring URL with no content-type: " + pageModel.getUrl());
return;
}
if (!contentType.startsWith("text/html")) {
return;
}
if (skipRelevant && pageModel.getRelevance().isRelevant()) {
return;
}
if (skipIrrelevant && !pageModel.getRelevance().isRelevant()) {
return;
}
if (cdrVersion == CDRVersion.CDRv31) {
createCDR31DocumentJson(pageModel);
} else if (cdrVersion == CDRVersion.CDRv2) {
createCDR2DocumentJson(pageModel);
} else {
createCDR3DocumentJson(pageModel);
}
if (doc != null && out != null) {
out.println(jsonMapper.writeValueAsString(doc));
}
if (bulkIndexer != null) {
bulkIndexer.addDocument(outputIndex, outputType, doc, id);
}
}
public void createCDR2DocumentJson(TargetModelJson pageModel) {
HashMap<String, Object> crawlData = new HashMap<>();
crawlData.put("response_headers", pageModel.getResponseHeaders());
CDR2Document.Builder builder = new CDR2Document.Builder()
.setUrl(pageModel.getUrl())
.setTimestamp(pageModel.getFetchTime())
.setContentType(pageModel.getContentType())
.setVersion("2.0")
.setTeam("NYU")
.setCrawler("ACHE")
.setRawContent(pageModel.getContentAsString())
.setCrawlData(crawlData);
CDR2Document doc = builder.build();
this.id = doc.getId();
this.doc = doc;
}
public void createCDR3DocumentJson(TargetModelJson pageModel) {
HashMap<String, Object> crawlData = new HashMap<>();
crawlData.put("response_headers", pageModel.getResponseHeaders());
CDR3Document.Builder builder = new CDR3Document.Builder()
.setUrl(pageModel.getUrl())
.setTimestampCrawl(new Date(pageModel.getFetchTime()))
.setTimestampIndex(new Date())
.setContentType(pageModel.getContentType())
.setTeam("NYU")
.setCrawler("ACHE")
.setRawContent(pageModel.getContentAsString());
CDR3Document doc = builder.build();
this.id = doc.getId();
this.doc = doc;
}
public void createCDR31MediaObject(TargetModelJson pageModel) throws IOException {
// Hash and upload to S3
String storedUrl = this.uploadMediaFile(pageModel.getContent(), pageModel.getUrl());
// Create Media Object for the image
CDR31MediaObject obj = new CDR31MediaObject();
obj.setContentType(pageModel.getContentType());
obj.setTimestampCrawl(new Date(pageModel.getFetchTime()));
obj.setObjOriginalUrl(pageModel.getUrl());
obj.setObjStoredUrl(storedUrl);
obj.setResponseHeaders(pageModel.getResponseHeaders());
//Save it for including into the HTML pages later
this.mediaObjectCache.put(pageModel.getUrl(), obj);
}
private String uploadMediaFile(byte[] content, String url) throws IOException {
HashFunction hf = Hashing.sha256();
Hasher hasher = hf.newHasher();
hasher.putBytes(content);
String host = new URL(url).getHost();
String hs = reverseDomain(host) + "/" + hasher.hash().toString();
if (skipUpload == false) {
this.s3Uploader.upload(hs, content);
System.out.println("Uploaded object: " + hs);
} else {
System.out.println("Created object: " + hs);
}
return hs;
}
// public String[] extractImgLinks(TargetModelJson pageModel) {
// try {
// PaginaURL pageParser = new PaginaURL(new Page(pageModel));
// URL[] parsedLinks = pageParser.links();
// HashSet<String> links = new HashSet<>();
// for (URL url : parsedLinks) {
// links.add(url.toString());
// }
// return links.toArray(new String[links.size()]);
// } catch (MalformedURLException e) {
// return new String[0];
// }
// }
public String[] extractImgLinks(TargetModelJson pageModel) {
HashSet<String> links = new HashSet<>();
Document doc = Jsoup.parse(pageModel.getContentAsString());
Elements media = doc.select("[src]");
for (Element src : media) {
if (src.tagName().equals("img")) {
links.add(src.attr("abs:src"));
}
}
return links.toArray(new String[links.size()]);
}
public void createCDR31DocumentJson(TargetModelJson pageModel) {
List<CDR31MediaObject> mediaObjects = new ArrayList<>();
if (!skipUpload) {
String[] imgLinks = extractImgLinks(pageModel);
for (String link : imgLinks) {
CDR31MediaObject object = this.mediaObjectCache.get(link);
if (object != null) {
mediaObjects.add(object);
}
}
}
CDR31Document.Builder builder = new CDR31Document.Builder()
.setUrl(pageModel.getUrl())
.setTimestampCrawl(new Date(pageModel.getFetchTime()))
.setTimestampIndex(new Date())
.setContentType(pageModel.getContentType())
.setResponseHeaders(pageModel.getResponseHeaders())
.setRawContent(pageModel.getContentAsString())
.setObjects(mediaObjects)
.setTeam("NYU")
.setCrawler("ACHE");
CDR31Document doc = builder.build();
this.id = doc.getId();
this.doc = doc;
}
private String reverseDomain(String domain) {
if(domain == null || domain.isEmpty()) {
return null;
}
String[] hostParts = domain.split("\\.");
if(hostParts.length == 0 ) {
return null;
}
StringBuilder reverseDomain = new StringBuilder();
reverseDomain.append(hostParts[hostParts.length-1]);
for (int i = hostParts.length-2; i >= 0; i--) {
reverseDomain.append('/');
reverseDomain.append(hostParts[i]);
}
return reverseDomain.toString();
}
}
| src/main/java/focusedCrawler/memex/cdr/AcheToCdrExporter.java | package focusedCrawler.memex.cdr;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import focusedCrawler.target.model.Page;
import focusedCrawler.target.model.TargetModelJson;
import focusedCrawler.target.repository.FileSystemTargetRepository;
import focusedCrawler.target.repository.FileSystemTargetRepository.DataFormat;
import focusedCrawler.target.repository.FilesTargetRepository;
import focusedCrawler.tools.SimpleBulkIndexer;
import focusedCrawler.util.CliTool;
import focusedCrawler.util.parser.PaginaURL;
import focusedCrawler.util.persistence.PersistentHashtable;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
@Command(name="AcheToCdrExporter", description="Exports crawled data to CDR format")
public class AcheToCdrExporter extends CliTool {
private static final ObjectMapper jsonMapper = new ObjectMapper();
//
// Input data options
//
@Option(name = "--input-path", description="Path to ACHE data target folder", required=true)
private String inputPath;
@Option(name={"--repository-type", "-rt"}, description="Which repository type should be used")
private RepositoryType repositoryType = RepositoryType.FILES;
public enum RepositoryType {
FILES, FILESYSTEM_JSON;
}
@Option(name="--fs-hashed", description="Whether ACHE filesystem repository files names are hashed")
private boolean hashFilename = false;
@Option(name="--fs-compressed", description="Whether ACHE filesystem repository files is compressed")
private boolean compressData = false;
//
// Options for output data format
//
@Option(name="--cdr-version", description="Which CDR version should be used")
private CDRVersion cdrVersion = CDRVersion.CDRv31;
public enum CDRVersion {
CDRv2, CDRv3, CDRv31
}
@Option(name="--output-file", description="Gziped output file containing data formmated as per CDR schema")
private String outputFile;
// Elastic Search output options
@Option(name={"--output-es-index", "-oi"}, description="ElasticSearch index name (output)")
String outputIndex;
@Option(name={"--output-es-type", "-ot"}, description="ElasticSearch index type (output)")
String outputType;
@Option(name={"--output-es-url", "-ou"}, description="ElasticSearch full HTTP URL address")
String elasticSearchServer = null;
@Option(name={"--output-es-auth", "-oa"}, description="User and password for ElasticSearch in format: user:pass")
String userPass = null;
@Option(name={"--output-es-bulk-size", "-obs"}, description="ElasticSearch bulk size")
int bulkSize = 25;
//AWS S3 Support
@Option(name={"--accesskey", "-ak"}, description="AWS ACCESS KEY ID")
String accessKeyID = "";
@Option(name={"--secretkey", "-sk"}, description="AWS SECRET KEY ID")
String secretKeyID = "";
@Option(name = {"--bucket", "-bk"}, description = "AWS S3 BUCKET NAME")
String bucketName = "";
@Option(name = {"--region", "-rg"}, description = "AWS S3 Region name")
String region = "us-east-1";
@Option(name = {"--skip-upload", "-su"}, description = "Disable upload of objects to S3")
private boolean skipUpload = false;
@Option(name = {"--tmp-path", "-tmp"}, description = "Path to temporary working folder")
String temp = null;
private PersistentHashtable<CDR31MediaObject> mediaObjectCache;
private S3Uploader s3Uploader;
//
// Runtime variables
//
private int processedPages = 0;
private PrintWriter out;
private SimpleBulkIndexer bulkIndexer;
private String id;
private Object doc;
public static void main(String[] args) throws Exception {
CliTool.run(args, new AcheToCdrExporter());
}
@Override
public void execute() throws Exception {
System.out.println("Reading ACHE data from: "+inputPath);
System.out.println("Generating CDR file at: "+outputFile);
System.out.println(" Compressed repository: "+compressData);
System.out.println(" Hashed file name: "+hashFilename);
if (temp == null) {
Path tmpPath = Files.createTempDirectory("cdr-export-tmp");
Files.createDirectories(tmpPath);
temp = tmpPath.toString();
}
s3Uploader = new S3Uploader(this.accessKeyID, this.secretKeyID, this.bucketName, this.region);
mediaObjectCache =
new PersistentHashtable<CDR31MediaObject>(temp, 1000, CDR31MediaObject.class);
if (outputFile != null) {
GZIPOutputStream gzipStream = new GZIPOutputStream(new FileOutputStream(outputFile));
out = new PrintWriter(gzipStream, true);
}
if (elasticSearchServer != null) {
if (this.outputIndex == null || this.outputIndex.isEmpty())
throw new IllegalArgumentException(
"Argument for Elasticsearch index can't be empty");
if (this.outputType == null || this.outputType.isEmpty())
throw new IllegalArgumentException(
"Argument for Elasticsearch type can't be empty");
bulkIndexer = new SimpleBulkIndexer(elasticSearchServer, userPass, bulkSize);
}
Iterator<TargetModelJson> it;
Iterator<TargetModelJson> it1;
if(repositoryType == RepositoryType.FILESYSTEM_JSON) {
FileSystemTargetRepository repository = new FileSystemTargetRepository(inputPath,
DataFormat.JSON, hashFilename, compressData);
it = repository.iterator();
it1 = repository.iterator();
} else {
FilesTargetRepository repository = new FilesTargetRepository(inputPath);
it = repository.iterator();
it1 = repository.iterator();
}
//Process media files
while (it.hasNext()) {
TargetModelJson pageModel = it.next();
try {
processMediaFile(pageModel);
} catch (Exception e) {
System.err.println("Failed to process record.\n" + e.toString());
}
}
mediaObjectCache.commit();
//Process html files
while (it1.hasNext()) {
TargetModelJson pageModel = it1.next();
try{
processRecord(pageModel);
processedPages++;
if(processedPages % 100 == 0) {
System.out.printf("Processed %d pages\n", processedPages);
}
} catch(Exception e) {
System.err.println("Failed to process record.\n" + e.toString());
}
}
System.out.printf("Processed %d pages\n", processedPages);
if(out != null) out.close();
if(bulkIndexer!= null) bulkIndexer.close();
System.out.println("done.");
}
private void processMediaFile(TargetModelJson pageModel) throws IOException {
// What if contentType is empty but the object is an image.
//
String contentType = pageModel.getContentType();
if (contentType == null || contentType.isEmpty()) {
System.err.println("Ignoring URL with no content-type: " + pageModel.getUrl());
return;
}
if (!contentType.startsWith("image")) {
return;
}
if (cdrVersion != CDRVersion.CDRv31) {
return;
}
createCDR31MediaObject(pageModel);
}
private void processRecord(TargetModelJson pageModel) throws IOException {
String contentType = pageModel.getContentType();
if (contentType == null || contentType.isEmpty()) {
System.err.println("Ignoring URL with no content-type: " + pageModel.getUrl());
return;
}
if (!contentType.startsWith("text/html")) {
return;
}
if (cdrVersion == CDRVersion.CDRv31) {
createCDR31DocumentJson(pageModel);
} else if (cdrVersion == CDRVersion.CDRv2) {
createCDR2DocumentJson(pageModel);
} else {
createCDR3DocumentJson(pageModel);
}
if (doc != null && out != null) {
out.println(jsonMapper.writeValueAsString(doc));
}
if (bulkIndexer != null) {
bulkIndexer.addDocument(outputIndex, outputType, doc, id);
}
}
public void createCDR2DocumentJson(TargetModelJson pageModel) {
HashMap<String, Object> crawlData = new HashMap<>();
crawlData.put("response_headers", pageModel.getResponseHeaders());
CDR2Document.Builder builder = new CDR2Document.Builder()
.setUrl(pageModel.getUrl())
.setTimestamp(pageModel.getFetchTime())
.setContentType(pageModel.getContentType())
.setVersion("2.0")
.setTeam("NYU")
.setCrawler("ACHE")
.setRawContent(pageModel.getContentAsString())
.setCrawlData(crawlData);
CDR2Document doc = builder.build();
this.id = doc.getId();
this.doc = doc;
}
public void createCDR3DocumentJson(TargetModelJson pageModel) {
HashMap<String, Object> crawlData = new HashMap<>();
crawlData.put("response_headers", pageModel.getResponseHeaders());
CDR3Document.Builder builder = new CDR3Document.Builder()
.setUrl(pageModel.getUrl())
.setTimestampCrawl(new Date(pageModel.getFetchTime()))
.setTimestampIndex(new Date())
.setContentType(pageModel.getContentType())
.setTeam("NYU")
.setCrawler("ACHE")
.setRawContent(pageModel.getContentAsString());
CDR3Document doc = builder.build();
this.id = doc.getId();
this.doc = doc;
}
public void createCDR31MediaObject(TargetModelJson pageModel) throws IOException {
// Hash and upload to S3
String storedUrl = this.uploadMediaFile(pageModel.getContent(), pageModel.getUrl());
// Create Media Object for the image
CDR31MediaObject obj = new CDR31MediaObject();
obj.setContentType(pageModel.getContentType());
obj.setTimestampCrawl(new Date(pageModel.getFetchTime()));
obj.setObjOriginalUrl(pageModel.getUrl());
obj.setObjStoredUrl(storedUrl);
obj.setResponseHeaders(pageModel.getResponseHeaders());
//Save it for including into the HTML pages later
this.mediaObjectCache.put(pageModel.getUrl(), obj);
}
private String uploadMediaFile(byte[] content, String url) throws IOException {
HashFunction hf = Hashing.sha256();
Hasher hasher = hf.newHasher();
hasher.putBytes(content);
String host = new URL(url).getHost();
String hs = reverseDomain(host) + "/" + hasher.hash().toString();
if (skipUpload == false) {
this.s3Uploader.upload(hs, content);
System.out.println("Uploaded object: " + hs);
} else {
System.out.println("Created object: " + hs);
}
return hs;
}
public String[] extractImgLinks(TargetModelJson pageModel) {
try {
PaginaURL pageParser = new PaginaURL(new Page(pageModel));
URL[] parsedLinks = pageParser.links();
HashSet<String> links = new HashSet<>();
for (URL url : parsedLinks) {
links.add(url.toString());
}
return links.toArray(new String[links.size()]);
} catch (MalformedURLException e) {
return new String[0];
}
}
public void createCDR31DocumentJson(TargetModelJson pageModel) {
List<CDR31MediaObject> mediaObjects = new ArrayList<>();
String[] imgLinks = extractImgLinks(pageModel);
for (String link : imgLinks) {
CDR31MediaObject object = this.mediaObjectCache.get(link);
if (object != null) {
mediaObjects.add(object);
}
}
CDR31Document.Builder builder = new CDR31Document.Builder()
.setUrl(pageModel.getUrl())
.setTimestampCrawl(new Date(pageModel.getFetchTime()))
.setTimestampIndex(new Date())
.setContentType(pageModel.getContentType())
.setResponseHeaders(pageModel.getResponseHeaders())
.setRawContent(pageModel.getContentAsString())
.setObjects(mediaObjects)
.setTeam("NYU")
.setCrawler("ACHE");
CDR31Document doc = builder.build();
this.id = doc.getId();
this.doc = doc;
}
private String reverseDomain(String domain) {
if(domain == null || domain.isEmpty()) {
return null;
}
String[] hostParts = domain.split("\\.");
if(hostParts.length == 0 ) {
return null;
}
StringBuilder reverseDomain = new StringBuilder();
reverseDomain.append(hostParts[hostParts.length-1]);
for (int i = hostParts.length-2; i >= 0; i--) {
reverseDomain.append('/');
reverseDomain.append(hostParts[i]);
}
return reverseDomain.toString();
}
}
| Add --skip-relevant argument to CDR exporter
| src/main/java/focusedCrawler/memex/cdr/AcheToCdrExporter.java | Add --skip-relevant argument to CDR exporter | <ide><path>rc/main/java/focusedCrawler/memex/cdr/AcheToCdrExporter.java
<ide> import java.io.FileOutputStream;
<ide> import java.io.IOException;
<ide> import java.io.PrintWriter;
<del>import java.net.MalformedURLException;
<ide> import java.net.URL;
<ide> import java.nio.file.Files;
<ide> import java.nio.file.Path;
<ide> import java.util.List;
<ide> import java.util.zip.GZIPOutputStream;
<ide>
<add>import org.jsoup.Jsoup;
<add>import org.jsoup.nodes.Document;
<add>import org.jsoup.nodes.Element;
<add>import org.jsoup.select.Elements;
<add>
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.google.common.hash.HashFunction;
<ide> import com.google.common.hash.Hasher;
<ide> import com.google.common.hash.Hashing;
<ide>
<del>import focusedCrawler.target.model.Page;
<ide> import focusedCrawler.target.model.TargetModelJson;
<ide> import focusedCrawler.target.repository.FileSystemTargetRepository;
<ide> import focusedCrawler.target.repository.FileSystemTargetRepository.DataFormat;
<ide> import focusedCrawler.target.repository.FilesTargetRepository;
<ide> import focusedCrawler.tools.SimpleBulkIndexer;
<ide> import focusedCrawler.util.CliTool;
<del>import focusedCrawler.util.parser.PaginaURL;
<ide> import focusedCrawler.util.persistence.PersistentHashtable;
<ide> import io.airlift.airline.Command;
<ide> import io.airlift.airline.Option;
<ide>
<ide> @Option(name="--output-file", description="Gziped output file containing data formmated as per CDR schema")
<ide> private String outputFile;
<add>
<add> @Option(name="--skip-relevant", description="Whether relevant pages should be skipped")
<add> private boolean skipRelevant = false;
<add>
<add> @Option(name="--skip-irrelevant", description="Whether irrelevant pages should be skipped")
<add> private boolean skipIrrelevant = false;
<ide>
<ide> // Elastic Search output options
<ide>
<ide> temp = tmpPath.toString();
<ide> }
<ide>
<del> s3Uploader = new S3Uploader(this.accessKeyID, this.secretKeyID, this.bucketName, this.region);
<del> mediaObjectCache =
<del> new PersistentHashtable<CDR31MediaObject>(temp, 1000, CDR31MediaObject.class);
<add> if (!skipUpload) {
<add> s3Uploader = new S3Uploader(this.accessKeyID, this.secretKeyID, this.bucketName,
<add> this.region);
<add> }
<add> mediaObjectCache = new PersistentHashtable<CDR31MediaObject>(temp, 1000, CDR31MediaObject.class);
<ide>
<ide> if (outputFile != null) {
<ide> GZIPOutputStream gzipStream = new GZIPOutputStream(new FileOutputStream(outputFile));
<ide> bulkIndexer = new SimpleBulkIndexer(elasticSearchServer, userPass, bulkSize);
<ide> }
<ide>
<del> Iterator<TargetModelJson> it;
<del> Iterator<TargetModelJson> it1;
<del> if(repositoryType == RepositoryType.FILESYSTEM_JSON) {
<del> FileSystemTargetRepository repository = new FileSystemTargetRepository(inputPath,
<del> DataFormat.JSON, hashFilename, compressData);
<del> it = repository.iterator();
<del> it1 = repository.iterator();
<del> } else {
<del> FilesTargetRepository repository = new FilesTargetRepository(inputPath);
<del> it = repository.iterator();
<del> it1 = repository.iterator();
<del> }
<del>
<del> //Process media files
<add> //Process media files
<add> System.out.println("Pre-processing media files...");
<add> Iterator<TargetModelJson> it = createIterator();
<ide> while (it.hasNext()) {
<ide> TargetModelJson pageModel = it.next();
<ide> try {
<ide> System.err.println("Failed to process record.\n" + e.toString());
<ide> }
<ide> }
<add>
<ide> mediaObjectCache.commit();
<ide>
<ide> //Process html files
<del> while (it1.hasNext()) {
<del> TargetModelJson pageModel = it1.next();
<del> try{
<add> System.out.println("Processing HTML pages...");
<add> it = createIterator();
<add> while (it.hasNext()) {
<add> TargetModelJson pageModel = it.next();
<add> try {
<ide> processRecord(pageModel);
<ide> processedPages++;
<del> if(processedPages % 100 == 0) {
<add> if (processedPages % 100 == 0) {
<ide> System.out.printf("Processed %d pages\n", processedPages);
<ide> }
<del> } catch(Exception e) {
<add> } catch (Exception e) {
<ide> System.err.println("Failed to process record.\n" + e.toString());
<ide> }
<ide> }
<ide> if(bulkIndexer!= null) bulkIndexer.close();
<ide>
<ide> System.out.println("done.");
<add> }
<add>
<add> private Iterator<TargetModelJson> createIterator() {
<add> if(repositoryType == RepositoryType.FILESYSTEM_JSON) {
<add> FileSystemTargetRepository repository = new FileSystemTargetRepository(inputPath,
<add> DataFormat.JSON, hashFilename, compressData);
<add> return repository.iterator();
<add> } else {
<add> FilesTargetRepository repository = new FilesTargetRepository(inputPath);
<add> return repository.iterator();
<add> }
<ide> }
<ide>
<ide> private void processMediaFile(TargetModelJson pageModel) throws IOException {
<ide> }
<ide>
<ide> if (!contentType.startsWith("text/html")) {
<add> return;
<add> }
<add>
<add> if (skipRelevant && pageModel.getRelevance().isRelevant()) {
<add> return;
<add> }
<add>
<add> if (skipIrrelevant && !pageModel.getRelevance().isRelevant()) {
<ide> return;
<ide> }
<ide>
<ide> return hs;
<ide> }
<ide>
<add>// public String[] extractImgLinks(TargetModelJson pageModel) {
<add>// try {
<add>// PaginaURL pageParser = new PaginaURL(new Page(pageModel));
<add>// URL[] parsedLinks = pageParser.links();
<add>// HashSet<String> links = new HashSet<>();
<add>// for (URL url : parsedLinks) {
<add>// links.add(url.toString());
<add>// }
<add>// return links.toArray(new String[links.size()]);
<add>// } catch (MalformedURLException e) {
<add>// return new String[0];
<add>// }
<add>// }
<add>
<ide> public String[] extractImgLinks(TargetModelJson pageModel) {
<del> try {
<del> PaginaURL pageParser = new PaginaURL(new Page(pageModel));
<del> URL[] parsedLinks = pageParser.links();
<del> HashSet<String> links = new HashSet<>();
<del> for (URL url : parsedLinks) {
<del> links.add(url.toString());
<add> HashSet<String> links = new HashSet<>();
<add> Document doc = Jsoup.parse(pageModel.getContentAsString());
<add> Elements media = doc.select("[src]");
<add> for (Element src : media) {
<add> if (src.tagName().equals("img")) {
<add> links.add(src.attr("abs:src"));
<ide> }
<del> return links.toArray(new String[links.size()]);
<del> } catch (MalformedURLException e) {
<del> return new String[0];
<del> }
<add> }
<add> return links.toArray(new String[links.size()]);
<ide> }
<ide>
<ide> public void createCDR31DocumentJson(TargetModelJson pageModel) {
<ide>
<ide> List<CDR31MediaObject> mediaObjects = new ArrayList<>();
<del> String[] imgLinks = extractImgLinks(pageModel);
<del> for (String link : imgLinks) {
<del> CDR31MediaObject object = this.mediaObjectCache.get(link);
<del> if (object != null) {
<del> mediaObjects.add(object);
<add> if (!skipUpload) {
<add> String[] imgLinks = extractImgLinks(pageModel);
<add> for (String link : imgLinks) {
<add> CDR31MediaObject object = this.mediaObjectCache.get(link);
<add> if (object != null) {
<add> mediaObjects.add(object);
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 915d66dec58c3183cf5b3db2b0724857e090b557 | 0 | chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq | /**
* 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.activemq.advisory;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerFilter;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.broker.region.MessageReference;
import org.apache.activemq.broker.region.Subscription;
import org.apache.activemq.broker.region.TopicSubscription;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.BrokerInfo;
import org.apache.activemq.command.Command;
import org.apache.activemq.command.ConnectionId;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.DestinationInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageId;
import org.apache.activemq.command.ProducerId;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.security.SecurityContext;
import org.apache.activemq.state.ProducerState;
import org.apache.activemq.usage.Usage;
import org.apache.activemq.util.IdGenerator;
import org.apache.activemq.util.LongSequenceGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This broker filter handles tracking the state of the broker for purposes of
* publishing advisory messages to advisory consumers.
*/
public class AdvisoryBroker extends BrokerFilter {
private static final Logger LOG = LoggerFactory.getLogger(AdvisoryBroker.class);
private static final IdGenerator ID_GENERATOR = new IdGenerator();
protected final ConcurrentHashMap<ConnectionId, ConnectionInfo> connections = new ConcurrentHashMap<ConnectionId, ConnectionInfo>();
protected final ConcurrentHashMap<ConsumerId, ConsumerInfo> consumers = new ConcurrentHashMap<ConsumerId, ConsumerInfo>();
protected final ConcurrentHashMap<ProducerId, ProducerInfo> producers = new ConcurrentHashMap<ProducerId, ProducerInfo>();
protected final ConcurrentHashMap<ActiveMQDestination, DestinationInfo> destinations = new ConcurrentHashMap<ActiveMQDestination, DestinationInfo>();
protected final ConcurrentHashMap<BrokerInfo, ActiveMQMessage> networkBridges = new ConcurrentHashMap<BrokerInfo, ActiveMQMessage>();
protected final ProducerId advisoryProducerId = new ProducerId();
private final LongSequenceGenerator messageIdGenerator = new LongSequenceGenerator();
public AdvisoryBroker(Broker next) {
super(next);
advisoryProducerId.setConnectionId(ID_GENERATOR.generateId());
}
@Override
public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception {
super.addConnection(context, info);
ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
// do not distribute passwords in advisory messages. usernames okay
ConnectionInfo copy = info.copy();
copy.setPassword("");
fireAdvisory(context, topic, copy);
connections.put(copy.getConnectionId(), copy);
}
@Override
public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
Subscription answer = super.addConsumer(context, info);
// Don't advise advisory topics.
if (!AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(info.getDestination());
consumers.put(info.getConsumerId(), info);
fireConsumerAdvisory(context, info.getDestination(), topic, info);
} else {
// We need to replay all the previously collected state objects
// for this newly added consumer.
if (AdvisorySupport.isConnectionAdvisoryTopic(info.getDestination())) {
// Replay the connections.
for (Iterator<ConnectionInfo> iter = connections.values().iterator(); iter.hasNext();) {
ConnectionInfo value = iter.next();
ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
fireAdvisory(context, topic, value, info.getConsumerId());
}
}
// We check here whether the Destination is Temporary Destination specific or not since we
// can avoid sending advisory messages to the consumer if it only wants Temporary Destination
// notifications. If its not just temporary destination related destinations then we have
// to send them all, a composite destination could want both.
if (AdvisorySupport.isTempDestinationAdvisoryTopic(info.getDestination())) {
// Replay the temporary destinations.
for (DestinationInfo destination : destinations.values()) {
if (destination.getDestination().isTemporary()) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination.getDestination());
fireAdvisory(context, topic, destination, info.getConsumerId());
}
}
} else if (AdvisorySupport.isDestinationAdvisoryTopic(info.getDestination())) {
// Replay all the destinations.
for (DestinationInfo destination : destinations.values()) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination.getDestination());
fireAdvisory(context, topic, destination, info.getConsumerId());
}
}
// Replay the producers.
if (AdvisorySupport.isProducerAdvisoryTopic(info.getDestination())) {
for (Iterator<ProducerInfo> iter = producers.values().iterator(); iter.hasNext();) {
ProducerInfo value = iter.next();
ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(value.getDestination());
fireProducerAdvisory(context, value.getDestination(),topic, value, info.getConsumerId());
}
}
// Replay the consumers.
if (AdvisorySupport.isConsumerAdvisoryTopic(info.getDestination())) {
for (Iterator<ConsumerInfo> iter = consumers.values().iterator(); iter.hasNext();) {
ConsumerInfo value = iter.next();
ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(value.getDestination());
fireConsumerAdvisory(context,value.getDestination(), topic, value, info.getConsumerId());
}
}
// Replay network bridges
if (AdvisorySupport.isNetworkBridgeAdvisoryTopic(info.getDestination())) {
for (Iterator<BrokerInfo> iter = networkBridges.keySet().iterator(); iter.hasNext();) {
BrokerInfo key = iter.next();
ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
fireAdvisory(context, topic, key, null, networkBridges.get(key));
}
}
}
return answer;
}
@Override
public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
super.addProducer(context, info);
// Don't advise advisory topics.
if (info.getDestination() != null && !AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(info.getDestination());
fireProducerAdvisory(context, info.getDestination(), topic, info);
producers.put(info.getProducerId(), info);
}
}
@Override
public Destination addDestination(ConnectionContext context, ActiveMQDestination destination,boolean create) throws Exception {
Destination answer = super.addDestination(context, destination,create);
if (!AdvisorySupport.isAdvisoryTopic(destination)) {
DestinationInfo info = new DestinationInfo(context.getConnectionId(), DestinationInfo.ADD_OPERATION_TYPE, destination);
DestinationInfo previous = destinations.putIfAbsent(destination, info);
if( previous==null ) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
fireAdvisory(context, topic, info);
}
}
return answer;
}
@Override
public void addDestinationInfo(ConnectionContext context, DestinationInfo info) throws Exception {
ActiveMQDestination destination = info.getDestination();
next.addDestinationInfo(context, info);
if (!AdvisorySupport.isAdvisoryTopic(destination)) {
DestinationInfo previous = destinations.putIfAbsent(destination, info);
if( previous==null ) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
fireAdvisory(context, topic, info);
}
}
}
@Override
public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception {
super.removeDestination(context, destination, timeout);
DestinationInfo info = destinations.remove(destination);
if (info != null) {
// ensure we don't modify (and loose/overwrite) an in-flight add advisory, so duplicate
info = info.copy();
info.setDestination(destination);
info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE);
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
fireAdvisory(context, topic, info);
ActiveMQTopic[] advisoryDestinations = AdvisorySupport.getAllDestinationAdvisoryTopics(destination);
for(ActiveMQTopic advisoryDestination : advisoryDestinations) {
try {
next.removeDestination(context, advisoryDestination, -1);
} catch (Exception expectedIfDestinationDidNotExistYet) {
}
}
}
}
@Override
public void removeDestinationInfo(ConnectionContext context, DestinationInfo destInfo) throws Exception {
super.removeDestinationInfo(context, destInfo);
DestinationInfo info = destinations.remove(destInfo.getDestination());
if (info != null) {
// ensure we don't modify (and loose/overwrite) an in-flight add advisory, so duplicate
info = info.copy();
info.setDestination(destInfo.getDestination());
info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE);
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destInfo.getDestination());
fireAdvisory(context, topic, info);
ActiveMQTopic[] advisoryDestinations = AdvisorySupport.getAllDestinationAdvisoryTopics(destInfo.getDestination());
for(ActiveMQTopic advisoryDestination : advisoryDestinations) {
try {
next.removeDestination(context, advisoryDestination, -1);
} catch (Exception expectedIfDestinationDidNotExistYet) {
}
}
}
}
@Override
public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
super.removeConnection(context, info, error);
ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
fireAdvisory(context, topic, info.createRemoveCommand());
connections.remove(info.getConnectionId());
}
@Override
public void removeConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
super.removeConsumer(context, info);
// Don't advise advisory topics.
ActiveMQDestination dest = info.getDestination();
if (!AdvisorySupport.isAdvisoryTopic(dest)) {
ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(dest);
consumers.remove(info.getConsumerId());
if (!dest.isTemporary() || destinations.containsKey(dest)) {
fireConsumerAdvisory(context,dest, topic, info.createRemoveCommand());
}
}
}
@Override
public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception {
super.removeProducer(context, info);
// Don't advise advisory topics.
ActiveMQDestination dest = info.getDestination();
if (info.getDestination() != null && !AdvisorySupport.isAdvisoryTopic(dest)) {
ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(dest);
producers.remove(info.getProducerId());
if (!dest.isTemporary() || destinations.contains(dest)) {
fireProducerAdvisory(context, dest,topic, info.createRemoveCommand());
}
}
}
@Override
public void messageExpired(ConnectionContext context, MessageReference messageReference, Subscription subscription) {
super.messageExpired(context, messageReference, subscription);
try {
if(!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getExpiredMessageTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
fireAdvisory(context, topic, payload, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("expired", e);
}
}
@Override
public void messageConsumed(ConnectionContext context, MessageReference messageReference) {
super.messageConsumed(context, messageReference);
try {
if(!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getMessageConsumedAdvisoryTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
fireAdvisory(context, topic,payload);
}
} catch (Exception e) {
handleFireFailure("consumed", e);
}
}
@Override
public void messageDelivered(ConnectionContext context, MessageReference messageReference) {
super.messageDelivered(context, messageReference);
try {
if (!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getMessageDeliveredAdvisoryTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
fireAdvisory(context, topic,payload);
}
} catch (Exception e) {
handleFireFailure("delivered", e);
}
}
@Override
public void messageDiscarded(ConnectionContext context, Subscription sub, MessageReference messageReference) {
super.messageDiscarded(context, sub, messageReference);
try {
if (!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getMessageDiscardedAdvisoryTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
if (sub instanceof TopicSubscription) {
advisoryMessage.setIntProperty(AdvisorySupport.MSG_PROPERTY_DISCARDED_COUNT, ((TopicSubscription)sub).discarded());
}
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, sub.getConsumerInfo().getConsumerId().toString());
fireAdvisory(context, topic, payload, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("discarded", e);
}
}
@Override
public void slowConsumer(ConnectionContext context, Destination destination,Subscription subs) {
super.slowConsumer(context, destination,subs);
try {
if (!AdvisorySupport.isAdvisoryTopic(destination.getActiveMQDestination())) {
ActiveMQTopic topic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination.getActiveMQDestination());
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, subs.getConsumerInfo().getConsumerId().toString());
fireAdvisory(context, topic, subs.getConsumerInfo(), null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("slow consumer", e);
}
}
@Override
public void fastProducer(ConnectionContext context,ProducerInfo producerInfo,ActiveMQDestination destination) {
super.fastProducer(context, producerInfo, destination);
try {
if (!AdvisorySupport.isAdvisoryTopic(destination)) {
ActiveMQTopic topic = AdvisorySupport.getFastProducerAdvisoryTopic(destination);
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_PRODUCER_ID, producerInfo.getProducerId().toString());
fireAdvisory(context, topic, producerInfo, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("fast producer", e);
}
}
@Override
public void isFull(ConnectionContext context, Destination destination, Usage usage) {
super.isFull(context, destination, usage);
if (AdvisorySupport.isAdvisoryTopic(destination.getActiveMQDestination()) == false) {
try {
ActiveMQTopic topic = AdvisorySupport.getFullAdvisoryTopic(destination.getActiveMQDestination());
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_USAGE_NAME, usage.getName());
fireAdvisory(context, topic, null, null, advisoryMessage);
} catch (Exception e) {
handleFireFailure("is full", e);
}
}
}
@Override
public void nowMasterBroker() {
super.nowMasterBroker();
try {
ActiveMQTopic topic = AdvisorySupport.getMasterBrokerAdvisoryTopic();
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
ConnectionContext context = new ConnectionContext();
context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
context.setBroker(getBrokerService().getBroker());
fireAdvisory(context, topic,null,null,advisoryMessage);
} catch (Exception e) {
handleFireFailure("now master broker", e);
}
}
@Override
public void sendToDeadLetterQueue(ConnectionContext context, MessageReference messageReference,
Subscription subscription){
super.sendToDeadLetterQueue(context, messageReference, subscription);
try {
if(!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getMessageDLQdAdvisoryTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
fireAdvisory(context, topic,payload);
}
} catch (Exception e) {
handleFireFailure("add to DLQ", e);
}
}
@Override
public void networkBridgeStarted(BrokerInfo brokerInfo, boolean createdByDuplex, String remoteIp) {
try {
if (brokerInfo != null) {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setBooleanProperty("started", true);
advisoryMessage.setBooleanProperty("createdByDuplex", createdByDuplex);
advisoryMessage.setStringProperty("remoteIp", remoteIp);
networkBridges.putIfAbsent(brokerInfo, advisoryMessage);
ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
ConnectionContext context = new ConnectionContext();
context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
context.setBroker(getBrokerService().getBroker());
fireAdvisory(context, topic, brokerInfo, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("network bridge started", e);
}
}
@Override
public void networkBridgeStopped(BrokerInfo brokerInfo) {
try {
if (brokerInfo != null) {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setBooleanProperty("started", false);
networkBridges.remove(brokerInfo);
ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
ConnectionContext context = new ConnectionContext();
context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
context.setBroker(getBrokerService().getBroker());
fireAdvisory(context, topic, brokerInfo, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("network bridge stopped", e);
}
}
private void handleFireFailure(String message, Throwable cause) {
LOG.warn("Failed to fire " + message + " advisory, reason: " + cause);
if (LOG.isDebugEnabled()) {
LOG.debug(message + " detail", cause);
}
}
protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command) throws Exception {
fireAdvisory(context, topic, command, null);
}
protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
}
protected void fireConsumerAdvisory(ConnectionContext context, ActiveMQDestination consumerDestination,ActiveMQTopic topic, Command command) throws Exception {
fireConsumerAdvisory(context, consumerDestination,topic, command, null);
}
protected void fireConsumerAdvisory(ConnectionContext context, ActiveMQDestination consumerDestination,ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
int count = 0;
Set<Destination>set = getDestinations(consumerDestination);
if (set != null) {
for (Destination dest:set) {
count += dest.getDestinationStatistics().getConsumers().getCount();
}
}
advisoryMessage.setIntProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_COUNT, count);
fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
}
protected void fireProducerAdvisory(ConnectionContext context,ActiveMQDestination producerDestination, ActiveMQTopic topic, Command command) throws Exception {
fireProducerAdvisory(context,producerDestination, topic, command, null);
}
protected void fireProducerAdvisory(ConnectionContext context, ActiveMQDestination producerDestination,ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
int count = 0;
if (producerDestination != null) {
Set<Destination> set = getDestinations(producerDestination);
if (set != null) {
for (Destination dest : set) {
count += dest.getDestinationStatistics().getProducers().getCount();
}
}
}
advisoryMessage.setIntProperty("producerCount", count);
fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
}
protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId, ActiveMQMessage advisoryMessage) throws Exception {
if (getBrokerService().isStarted()) {
//set properties
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_NAME, getBrokerName());
String id = getBrokerId() != null ? getBrokerId().getValue() : "NOT_SET";
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_ID, id);
String url = getBrokerService().getVmConnectorURI().toString();
if (getBrokerService().getDefaultSocketURIString() != null) {
url = getBrokerService().getDefaultSocketURIString();
}
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_URL, url);
//set the data structure
advisoryMessage.setDataStructure(command);
advisoryMessage.setPersistent(false);
advisoryMessage.setType(AdvisorySupport.ADIVSORY_MESSAGE_TYPE);
advisoryMessage.setMessageId(new MessageId(advisoryProducerId, messageIdGenerator.getNextSequenceId()));
advisoryMessage.setTargetConsumerId(targetConsumerId);
advisoryMessage.setDestination(topic);
advisoryMessage.setResponseRequired(false);
advisoryMessage.setProducerId(advisoryProducerId);
boolean originalFlowControl = context.isProducerFlowControl();
final ProducerBrokerExchange producerExchange = new ProducerBrokerExchange();
producerExchange.setConnectionContext(context);
producerExchange.setMutable(true);
producerExchange.setProducerState(new ProducerState(new ProducerInfo()));
try {
context.setProducerFlowControl(false);
next.send(producerExchange, advisoryMessage);
} finally {
context.setProducerFlowControl(originalFlowControl);
}
}
}
public Map<ConnectionId, ConnectionInfo> getAdvisoryConnections() {
return connections;
}
public Map<ConsumerId, ConsumerInfo> getAdvisoryConsumers() {
return consumers;
}
public Map<ProducerId, ProducerInfo> getAdvisoryProducers() {
return producers;
}
public Map<ActiveMQDestination, DestinationInfo> getAdvisoryDestinations() {
return destinations;
}
}
| activemq-broker/src/main/java/org/apache/activemq/advisory/AdvisoryBroker.java | /**
* 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.activemq.advisory;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerFilter;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.broker.region.MessageReference;
import org.apache.activemq.broker.region.Subscription;
import org.apache.activemq.broker.region.TopicSubscription;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.BrokerInfo;
import org.apache.activemq.command.Command;
import org.apache.activemq.command.ConnectionId;
import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.DestinationInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageId;
import org.apache.activemq.command.ProducerId;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.security.SecurityContext;
import org.apache.activemq.state.ProducerState;
import org.apache.activemq.usage.Usage;
import org.apache.activemq.util.IdGenerator;
import org.apache.activemq.util.LongSequenceGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This broker filter handles tracking the state of the broker for purposes of
* publishing advisory messages to advisory consumers.
*/
public class AdvisoryBroker extends BrokerFilter {
private static final Logger LOG = LoggerFactory.getLogger(AdvisoryBroker.class);
private static final IdGenerator ID_GENERATOR = new IdGenerator();
protected final ConcurrentHashMap<ConnectionId, ConnectionInfo> connections = new ConcurrentHashMap<ConnectionId, ConnectionInfo>();
protected final ConcurrentHashMap<ConsumerId, ConsumerInfo> consumers = new ConcurrentHashMap<ConsumerId, ConsumerInfo>();
protected final ConcurrentHashMap<ProducerId, ProducerInfo> producers = new ConcurrentHashMap<ProducerId, ProducerInfo>();
protected final ConcurrentHashMap<ActiveMQDestination, DestinationInfo> destinations = new ConcurrentHashMap<ActiveMQDestination, DestinationInfo>();
protected final ConcurrentHashMap<BrokerInfo, ActiveMQMessage> networkBridges = new ConcurrentHashMap<BrokerInfo, ActiveMQMessage>();
protected final ProducerId advisoryProducerId = new ProducerId();
private final LongSequenceGenerator messageIdGenerator = new LongSequenceGenerator();
public AdvisoryBroker(Broker next) {
super(next);
advisoryProducerId.setConnectionId(ID_GENERATOR.generateId());
}
@Override
public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception {
super.addConnection(context, info);
ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
//do not distribute usernames or passwords in advisory
ConnectionInfo copy = info.copy();
copy.setUserName("");
copy.setPassword("");
fireAdvisory(context, topic, copy);
connections.put(copy.getConnectionId(), copy);
}
@Override
public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
Subscription answer = super.addConsumer(context, info);
// Don't advise advisory topics.
if (!AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(info.getDestination());
consumers.put(info.getConsumerId(), info);
fireConsumerAdvisory(context, info.getDestination(), topic, info);
} else {
// We need to replay all the previously collected state objects
// for this newly added consumer.
if (AdvisorySupport.isConnectionAdvisoryTopic(info.getDestination())) {
// Replay the connections.
for (Iterator<ConnectionInfo> iter = connections.values().iterator(); iter.hasNext();) {
ConnectionInfo value = iter.next();
ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
fireAdvisory(context, topic, value, info.getConsumerId());
}
}
// We check here whether the Destination is Temporary Destination specific or not since we
// can avoid sending advisory messages to the consumer if it only wants Temporary Destination
// notifications. If its not just temporary destination related destinations then we have
// to send them all, a composite destination could want both.
if (AdvisorySupport.isTempDestinationAdvisoryTopic(info.getDestination())) {
// Replay the temporary destinations.
for (DestinationInfo destination : destinations.values()) {
if (destination.getDestination().isTemporary()) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination.getDestination());
fireAdvisory(context, topic, destination, info.getConsumerId());
}
}
} else if (AdvisorySupport.isDestinationAdvisoryTopic(info.getDestination())) {
// Replay all the destinations.
for (DestinationInfo destination : destinations.values()) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination.getDestination());
fireAdvisory(context, topic, destination, info.getConsumerId());
}
}
// Replay the producers.
if (AdvisorySupport.isProducerAdvisoryTopic(info.getDestination())) {
for (Iterator<ProducerInfo> iter = producers.values().iterator(); iter.hasNext();) {
ProducerInfo value = iter.next();
ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(value.getDestination());
fireProducerAdvisory(context, value.getDestination(),topic, value, info.getConsumerId());
}
}
// Replay the consumers.
if (AdvisorySupport.isConsumerAdvisoryTopic(info.getDestination())) {
for (Iterator<ConsumerInfo> iter = consumers.values().iterator(); iter.hasNext();) {
ConsumerInfo value = iter.next();
ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(value.getDestination());
fireConsumerAdvisory(context,value.getDestination(), topic, value, info.getConsumerId());
}
}
// Replay network bridges
if (AdvisorySupport.isNetworkBridgeAdvisoryTopic(info.getDestination())) {
for (Iterator<BrokerInfo> iter = networkBridges.keySet().iterator(); iter.hasNext();) {
BrokerInfo key = iter.next();
ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
fireAdvisory(context, topic, key, null, networkBridges.get(key));
}
}
}
return answer;
}
@Override
public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
super.addProducer(context, info);
// Don't advise advisory topics.
if (info.getDestination() != null && !AdvisorySupport.isAdvisoryTopic(info.getDestination())) {
ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(info.getDestination());
fireProducerAdvisory(context, info.getDestination(), topic, info);
producers.put(info.getProducerId(), info);
}
}
@Override
public Destination addDestination(ConnectionContext context, ActiveMQDestination destination,boolean create) throws Exception {
Destination answer = super.addDestination(context, destination,create);
if (!AdvisorySupport.isAdvisoryTopic(destination)) {
DestinationInfo info = new DestinationInfo(context.getConnectionId(), DestinationInfo.ADD_OPERATION_TYPE, destination);
DestinationInfo previous = destinations.putIfAbsent(destination, info);
if( previous==null ) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
fireAdvisory(context, topic, info);
}
}
return answer;
}
@Override
public void addDestinationInfo(ConnectionContext context, DestinationInfo info) throws Exception {
ActiveMQDestination destination = info.getDestination();
next.addDestinationInfo(context, info);
if (!AdvisorySupport.isAdvisoryTopic(destination)) {
DestinationInfo previous = destinations.putIfAbsent(destination, info);
if( previous==null ) {
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
fireAdvisory(context, topic, info);
}
}
}
@Override
public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception {
super.removeDestination(context, destination, timeout);
DestinationInfo info = destinations.remove(destination);
if (info != null) {
// ensure we don't modify (and loose/overwrite) an in-flight add advisory, so duplicate
info = info.copy();
info.setDestination(destination);
info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE);
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destination);
fireAdvisory(context, topic, info);
ActiveMQTopic[] advisoryDestinations = AdvisorySupport.getAllDestinationAdvisoryTopics(destination);
for(ActiveMQTopic advisoryDestination : advisoryDestinations) {
try {
next.removeDestination(context, advisoryDestination, -1);
} catch (Exception expectedIfDestinationDidNotExistYet) {
}
}
}
}
@Override
public void removeDestinationInfo(ConnectionContext context, DestinationInfo destInfo) throws Exception {
super.removeDestinationInfo(context, destInfo);
DestinationInfo info = destinations.remove(destInfo.getDestination());
if (info != null) {
// ensure we don't modify (and loose/overwrite) an in-flight add advisory, so duplicate
info = info.copy();
info.setDestination(destInfo.getDestination());
info.setOperationType(DestinationInfo.REMOVE_OPERATION_TYPE);
ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(destInfo.getDestination());
fireAdvisory(context, topic, info);
ActiveMQTopic[] advisoryDestinations = AdvisorySupport.getAllDestinationAdvisoryTopics(destInfo.getDestination());
for(ActiveMQTopic advisoryDestination : advisoryDestinations) {
try {
next.removeDestination(context, advisoryDestination, -1);
} catch (Exception expectedIfDestinationDidNotExistYet) {
}
}
}
}
@Override
public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
super.removeConnection(context, info, error);
ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
fireAdvisory(context, topic, info.createRemoveCommand());
connections.remove(info.getConnectionId());
}
@Override
public void removeConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
super.removeConsumer(context, info);
// Don't advise advisory topics.
ActiveMQDestination dest = info.getDestination();
if (!AdvisorySupport.isAdvisoryTopic(dest)) {
ActiveMQTopic topic = AdvisorySupport.getConsumerAdvisoryTopic(dest);
consumers.remove(info.getConsumerId());
if (!dest.isTemporary() || destinations.containsKey(dest)) {
fireConsumerAdvisory(context,dest, topic, info.createRemoveCommand());
}
}
}
@Override
public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception {
super.removeProducer(context, info);
// Don't advise advisory topics.
ActiveMQDestination dest = info.getDestination();
if (info.getDestination() != null && !AdvisorySupport.isAdvisoryTopic(dest)) {
ActiveMQTopic topic = AdvisorySupport.getProducerAdvisoryTopic(dest);
producers.remove(info.getProducerId());
if (!dest.isTemporary() || destinations.contains(dest)) {
fireProducerAdvisory(context, dest,topic, info.createRemoveCommand());
}
}
}
@Override
public void messageExpired(ConnectionContext context, MessageReference messageReference, Subscription subscription) {
super.messageExpired(context, messageReference, subscription);
try {
if(!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getExpiredMessageTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_MESSAGE_ID, payload.getMessageId().toString());
fireAdvisory(context, topic, payload, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("expired", e);
}
}
@Override
public void messageConsumed(ConnectionContext context, MessageReference messageReference) {
super.messageConsumed(context, messageReference);
try {
if(!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getMessageConsumedAdvisoryTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
fireAdvisory(context, topic,payload);
}
} catch (Exception e) {
handleFireFailure("consumed", e);
}
}
@Override
public void messageDelivered(ConnectionContext context, MessageReference messageReference) {
super.messageDelivered(context, messageReference);
try {
if (!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getMessageDeliveredAdvisoryTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
fireAdvisory(context, topic,payload);
}
} catch (Exception e) {
handleFireFailure("delivered", e);
}
}
@Override
public void messageDiscarded(ConnectionContext context, Subscription sub, MessageReference messageReference) {
super.messageDiscarded(context, sub, messageReference);
try {
if (!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getMessageDiscardedAdvisoryTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
if (sub instanceof TopicSubscription) {
advisoryMessage.setIntProperty(AdvisorySupport.MSG_PROPERTY_DISCARDED_COUNT, ((TopicSubscription)sub).discarded());
}
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, sub.getConsumerInfo().getConsumerId().toString());
fireAdvisory(context, topic, payload, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("discarded", e);
}
}
@Override
public void slowConsumer(ConnectionContext context, Destination destination,Subscription subs) {
super.slowConsumer(context, destination,subs);
try {
if (!AdvisorySupport.isAdvisoryTopic(destination.getActiveMQDestination())) {
ActiveMQTopic topic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination.getActiveMQDestination());
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_ID, subs.getConsumerInfo().getConsumerId().toString());
fireAdvisory(context, topic, subs.getConsumerInfo(), null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("slow consumer", e);
}
}
@Override
public void fastProducer(ConnectionContext context,ProducerInfo producerInfo,ActiveMQDestination destination) {
super.fastProducer(context, producerInfo, destination);
try {
if (!AdvisorySupport.isAdvisoryTopic(destination)) {
ActiveMQTopic topic = AdvisorySupport.getFastProducerAdvisoryTopic(destination);
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_PRODUCER_ID, producerInfo.getProducerId().toString());
fireAdvisory(context, topic, producerInfo, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("fast producer", e);
}
}
@Override
public void isFull(ConnectionContext context, Destination destination, Usage usage) {
super.isFull(context, destination, usage);
if (AdvisorySupport.isAdvisoryTopic(destination.getActiveMQDestination()) == false) {
try {
ActiveMQTopic topic = AdvisorySupport.getFullAdvisoryTopic(destination.getActiveMQDestination());
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_USAGE_NAME, usage.getName());
fireAdvisory(context, topic, null, null, advisoryMessage);
} catch (Exception e) {
handleFireFailure("is full", e);
}
}
}
@Override
public void nowMasterBroker() {
super.nowMasterBroker();
try {
ActiveMQTopic topic = AdvisorySupport.getMasterBrokerAdvisoryTopic();
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
ConnectionContext context = new ConnectionContext();
context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
context.setBroker(getBrokerService().getBroker());
fireAdvisory(context, topic,null,null,advisoryMessage);
} catch (Exception e) {
handleFireFailure("now master broker", e);
}
}
@Override
public void sendToDeadLetterQueue(ConnectionContext context, MessageReference messageReference,
Subscription subscription){
super.sendToDeadLetterQueue(context, messageReference, subscription);
try {
if(!messageReference.isAdvisory()) {
ActiveMQTopic topic = AdvisorySupport.getMessageDLQdAdvisoryTopic(messageReference.getMessage().getDestination());
Message payload = messageReference.getMessage().copy();
payload.clearBody();
fireAdvisory(context, topic,payload);
}
} catch (Exception e) {
handleFireFailure("add to DLQ", e);
}
}
@Override
public void networkBridgeStarted(BrokerInfo brokerInfo, boolean createdByDuplex, String remoteIp) {
try {
if (brokerInfo != null) {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setBooleanProperty("started", true);
advisoryMessage.setBooleanProperty("createdByDuplex", createdByDuplex);
advisoryMessage.setStringProperty("remoteIp", remoteIp);
networkBridges.putIfAbsent(brokerInfo, advisoryMessage);
ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
ConnectionContext context = new ConnectionContext();
context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
context.setBroker(getBrokerService().getBroker());
fireAdvisory(context, topic, brokerInfo, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("network bridge started", e);
}
}
@Override
public void networkBridgeStopped(BrokerInfo brokerInfo) {
try {
if (brokerInfo != null) {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
advisoryMessage.setBooleanProperty("started", false);
networkBridges.remove(brokerInfo);
ActiveMQTopic topic = AdvisorySupport.getNetworkBridgeAdvisoryTopic();
ConnectionContext context = new ConnectionContext();
context.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
context.setBroker(getBrokerService().getBroker());
fireAdvisory(context, topic, brokerInfo, null, advisoryMessage);
}
} catch (Exception e) {
handleFireFailure("network bridge stopped", e);
}
}
private void handleFireFailure(String message, Throwable cause) {
LOG.warn("Failed to fire " + message + " advisory, reason: " + cause);
if (LOG.isDebugEnabled()) {
LOG.debug(message + " detail", cause);
}
}
protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command) throws Exception {
fireAdvisory(context, topic, command, null);
}
protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
}
protected void fireConsumerAdvisory(ConnectionContext context, ActiveMQDestination consumerDestination,ActiveMQTopic topic, Command command) throws Exception {
fireConsumerAdvisory(context, consumerDestination,topic, command, null);
}
protected void fireConsumerAdvisory(ConnectionContext context, ActiveMQDestination consumerDestination,ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
int count = 0;
Set<Destination>set = getDestinations(consumerDestination);
if (set != null) {
for (Destination dest:set) {
count += dest.getDestinationStatistics().getConsumers().getCount();
}
}
advisoryMessage.setIntProperty(AdvisorySupport.MSG_PROPERTY_CONSUMER_COUNT, count);
fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
}
protected void fireProducerAdvisory(ConnectionContext context,ActiveMQDestination producerDestination, ActiveMQTopic topic, Command command) throws Exception {
fireProducerAdvisory(context,producerDestination, topic, command, null);
}
protected void fireProducerAdvisory(ConnectionContext context, ActiveMQDestination producerDestination,ActiveMQTopic topic, Command command, ConsumerId targetConsumerId) throws Exception {
ActiveMQMessage advisoryMessage = new ActiveMQMessage();
int count = 0;
if (producerDestination != null) {
Set<Destination> set = getDestinations(producerDestination);
if (set != null) {
for (Destination dest : set) {
count += dest.getDestinationStatistics().getProducers().getCount();
}
}
}
advisoryMessage.setIntProperty("producerCount", count);
fireAdvisory(context, topic, command, targetConsumerId, advisoryMessage);
}
protected void fireAdvisory(ConnectionContext context, ActiveMQTopic topic, Command command, ConsumerId targetConsumerId, ActiveMQMessage advisoryMessage) throws Exception {
if (getBrokerService().isStarted()) {
//set properties
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_NAME, getBrokerName());
String id = getBrokerId() != null ? getBrokerId().getValue() : "NOT_SET";
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_ID, id);
String url = getBrokerService().getVmConnectorURI().toString();
if (getBrokerService().getDefaultSocketURIString() != null) {
url = getBrokerService().getDefaultSocketURIString();
}
advisoryMessage.setStringProperty(AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_URL, url);
//set the data structure
advisoryMessage.setDataStructure(command);
advisoryMessage.setPersistent(false);
advisoryMessage.setType(AdvisorySupport.ADIVSORY_MESSAGE_TYPE);
advisoryMessage.setMessageId(new MessageId(advisoryProducerId, messageIdGenerator.getNextSequenceId()));
advisoryMessage.setTargetConsumerId(targetConsumerId);
advisoryMessage.setDestination(topic);
advisoryMessage.setResponseRequired(false);
advisoryMessage.setProducerId(advisoryProducerId);
boolean originalFlowControl = context.isProducerFlowControl();
final ProducerBrokerExchange producerExchange = new ProducerBrokerExchange();
producerExchange.setConnectionContext(context);
producerExchange.setMutable(true);
producerExchange.setProducerState(new ProducerState(new ProducerInfo()));
try {
context.setProducerFlowControl(false);
next.send(producerExchange, advisoryMessage);
} finally {
context.setProducerFlowControl(originalFlowControl);
}
}
}
public Map<ConnectionId, ConnectionInfo> getAdvisoryConnections() {
return connections;
}
public Map<ConsumerId, ConsumerInfo> getAdvisoryConsumers() {
return consumers;
}
public Map<ProducerId, ProducerInfo> getAdvisoryProducers() {
return producers;
}
public Map<ActiveMQDestination, DestinationInfo> getAdvisoryDestinations() {
return destinations;
}
}
| https://issues.apache.org/jira/browse/AMQ-4198 Include username in ConnectionInfo for ActiveMQ.Advisory.Connection messages
git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@1415631 13f79535-47bb-0310-9956-ffa450edef68
| activemq-broker/src/main/java/org/apache/activemq/advisory/AdvisoryBroker.java | https://issues.apache.org/jira/browse/AMQ-4198 Include username in ConnectionInfo for ActiveMQ.Advisory.Connection messages | <ide><path>ctivemq-broker/src/main/java/org/apache/activemq/advisory/AdvisoryBroker.java
<ide> super.addConnection(context, info);
<ide>
<ide> ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
<del> //do not distribute usernames or passwords in advisory
<add> // do not distribute passwords in advisory messages. usernames okay
<ide> ConnectionInfo copy = info.copy();
<del> copy.setUserName("");
<ide> copy.setPassword("");
<ide> fireAdvisory(context, topic, copy);
<ide> connections.put(copy.getConnectionId(), copy); |
|
JavaScript | mit | 14a15c22ad1ed2f4c38bc26bfc5d3ad003b217ac | 0 | amchung/euglena-mjpegserver | var obj_canvas,
obj_c,
cp_canvas = null;
var canvas
var video_canvas,
vid_c;
var brown_const=0;
var vid_width = 640;
var vid_height = 480;
var n_object = 20;
var m_object = 5;
var canvas;
var context;
function setupD3(){
var canvas = d3.select("#canvasArea").append("canvas")
.attr("width", vid_width)
.attr("height", vid_height);
var context = canvas.node().getContext("2d");
}
function getVideo(){
getVidFrame("http://171.65.102.132:8080/?action=snapshot?t=" + new Date().getTime(), function(image) {
context.clearRect(0, 0, vid_width, vid_height);
context.drawImage(image, 0, 0, vid_width, vid_height);
});
function getVidFrame(path, callback) {
var image = new Image;
image.onload = function() {
callback(image);
compareFrame(image);
};
image.src = path;
}
}
var gameobject = d3.range(n_object).map(function() {
var x = Math.random() * vid_width, y = Math.random() * vid_height;
return {
vx: Math.random() * 2 - 1,
vy: Math.random() * 2 - 1,
path: d3.range(m_object).map(function() { return [x, y]; }),
count: 0
};
});
var w = 640,
h = 480,
n = 20,
m = 12,
degrees = 180 / Math.PI;
var spermatozoa = d3.range(n).map(function() {
var x = Math.random() * w, y = Math.random() * h;
return {
vx: Math.random() * 2 - 1,
vy: Math.random() * 2 - 1,
path: d3.range(m).map(function() { return [x, y]; }),
count: 0
};
});
var svg = d3.select("canvas").append("svg:svg")
.attr("width", w)
.attr("height", h);
var g = svg.selectAll("g")
.data(spermatozoa)
.enter().append("svg:g");
var head = g.append("svg:ellipse")
.attr("rx", 6.5)
.attr("ry", 4);
g.append("svg:path")
.map(function(d) { return d.path.slice(0, 3); })
.attr("class", "mid");
g.append("svg:path")
.map(function(d) { return d.path; })
.attr("class", "tail");
var tail = g.selectAll("path");
d3.timer(function() {
getVideo();
for (var i = -1; ++i < n;) {
var spermatozoon = spermatozoa[i],
path = spermatozoon.path,
dx = spermatozoon.vx,
dy = spermatozoon.vy,
x = path[0][0] += dx,
y = path[0][1] += dy,
speed = Math.sqrt(dx * dx + dy * dy),
count = speed * 10,
k1 = -5 - speed / 3;
// Bounce off the walls.
if (x < 0 || x > w) spermatozoon.vx *= -1;
if (y < 0 || y > h) spermatozoon.vy *= -1;
// Swim!
for (var j = 0; ++j < m;) {
var vx = x - path[j][0],
vy = y - path[j][1],
k2 = Math.sin(((spermatozoon.count += count) + j * 3) / 300) / speed;
path[j][0] = (x += dx / speed * k1) - dy * k2;
path[j][1] = (y += dy / speed * k1) + dx * k2;
speed = Math.sqrt((dx = vx) * dx + (dy = vy) * dy);
}
}
head.attr("transform", function(d) {
return "translate(" + d.path[0] + ")rotate(" + Math.atan2(d.vy, d.vx) * degrees + ")";
});
tail.attr("d", function(d) {
return "M" + d.join("L");
});
});
function game(){
switch(gamephase)
{
case 'pre-game':
// draw intro
break;
case 'game-rest':
vid_c.fillStyle = "#fff";
vid_c.font="14px sans-serif";
vid_c.fillText('New target ...',200,20);
vid_c.fillText('player : ' + username + ' score : ' +score_val ,20,20);
break;
case 'game-action':
vid_c.fillStyle = "#fff";
vid_c.font="14px sans-serif";
vid_c.fillText('Run! Run! Run!',200,20);
vid_c.fillText('player : ' + username + ' score : ' +score_val ,20,20);
break;
case 'gameover':
vid_c.fillStyle = "#fff";
vid_c.font="14px sans-serif";
vid_c.textAlign="start";
vid_c.fillText('player : ' + username + ' score : ' +score_val ,20,20);
vid_c.fillStyle = "rgba(253,172,13,1)";
vid_c.font="40pt sans-serif";
vid_c.textAlign="center";
vid_c.fillText('GAME OVER',vid_width/2,vid_height/2-100);
vid_c.fillStyle = "#fff";
vid_c.font="20pt sans-serif";
vid_c.fillText(username+' scored '+score_val,vid_width/2,vid_height/2);
break;
default:
vid_c.fillStyle = "#fff";
vid_c.font="14px sans-serif";
vid_c.fillText('player : ' + username + ' score : ' +score_val ,20,20);
}
}
var shipX=vid_width/2,
shipY=vid_height/2,
shipRad,
shipL=20,
starX=40,
starY=20;
var gamelevel;
var int_star=-1;
var int_engine=-1;
var engine = false;
var rest = false;
var starTimer;
var enginerTimer;
var gamephase;
var score_val = 0;
var actionTimer;
var hit = new Array();
var unit=30;
function setGameAction(){
actionTimer = window.requestAnimationFrame(actionLoop);
}
function setbackPreGame(){
score_val = 0;
hit = new Array();
gamelevel=1;
shipX = vid_width/2;
shipY = vid_height/2;
gamephase='pre-game';
}
function setGameOver(){
window.cancelAnimationFrame(actionTimer);
actionTimer = undefined;
}
function actionLoop(){
switch(gamephase)
{
case 'rest':
if(rest==false)
{
rest=true;
int_star=gamelevel+6;
getStarLocation(); // get new starX, starY, shipRad
starTimer=window.setInterval(showStar,500);
}
drawStar(shipX,shipY,starX,starY,gamelevel-(int_star-6));
drawShip(shipX,shipY,shipRad);
actionTimer = window.requestAnimationFrame(gameLoop);
break;
case 'engine':
console.log(hit);
if(hit>0)
{
window.clearInterval(engineTimer);
engine=false;
rest=false;
int_star=-1;
int_engine=-1;
gamephase='gameover';
gamelevel=-1;
}
else
{
score_val=score_val+10;
if(engine==false)
{
engine=true;
int_engine=gamelevel+4;
engineTimer=window.setInterval(runEngine,500);
}
}
drawStar(shipX,shipY,starX,starY,gamelevel-(int_star-6));
drawShip(shipX,shipY,shipRad);
break;
}
}
function getStarLocation(){
shipRad=Math.random()*Math.PI*2;
starX=shipX+unit*(Math.cos(shipRad))*gamelevel;
starY=shipY+unit*(Math.sin(shipRad))*gamelevel;
}
function getShipLocation(){
var step = gamelevel-(int_engine-4);
var u = (step > gamelevel - 1) ? 0 : 1;
shipX=shipX+unit*(Math.cos(shipRad))*u;
shipY=shipY+unit*(Math.sin(shipRad))*u;
}
function showStar(){
if(int_star>0)
{
int_star=int_star-1;
}
else
{
window.clearInterval(starTimer);
rest=false;
gamephase='engine';
}
}
function runEngine(){
if(int_engine>0)
{
getShipLocation();
int_engine=int_engine-1;
}
else
{
window.clearInterval(engineTimer);
engine=false;
gamephase='rest';
if(gamelevel<10)
{
gamelevel=gamelevel+1;
}
}
}
function gameOver(){
var msg = {type:'sendscore', user:username, score:score_val};
socket.json.send(msg);
}
/*******************************************************************************
Copyright (C) 2009 Tom Stoeveken
This program is free software;
you can redistribute it and/or modify it under the terms of the
GNU General Public License, version 2.
See the file COPYING for details.
*******************************************************************************/
var img1 = null;
var img2 = null;
var md_canvas = null;
function setupMotionDetection() {
md_canvas = document.getElementById('mdCanvas');
test_canvas = document.getElementById('testCanvas');
md_canvas.width = vid_width;
md_canvas.height = vid_height;
}
/*
compare two images and count the differences
input.: image1 and image2 are Image() objects
input.: threshold specifies by how much the color value of a pixel
must differ before they are regarded to be different
return: number of different pixels
*/
function compare(image1, image2, ptX, ptY, threshold, ObjR) {
var movement = new Array(0,0,0,0);
var md_ctx = md_canvas.getContext("2d");
var width = md_canvas.width/2, height = md_canvas.height/2;
// copy images into canvas element
// these steps scale the images and decodes the image data
md_ctx.drawImage(image1, 0, 0, width, height);
md_ctx.drawImage(image2, width, 0, width, height);
// this makes r,g,b,alpha data of images available
var pixels1 = md_ctx.getImageData(0, 0, width, height);
var pixels2 = md_ctx.getImageData(width, 0, width, height);
// substract picture1 from picture2
// if they differ set color value to max,
// if the difference is below threshold set difference to 0.
for (var x = Math.round((ptX-ObjR)/2); x < Math.round((ptX+ObjR)/2); x++) {
for (var y = Math.round((ptY-ObjR)/2); y < Math.round((ptY+ObjR)/2); y++) {
// each pixel has a red, green, blue and alpha value
// all values are stored in a linear array
var i = x*4 + y*4*pixels1.width;
var ch0 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
var ch1 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
var ch2 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
// count differing pixels
var n = (x<Math.round(ptX/2))?0:1;
var m = (y<Math.round(ptY/2))?0:2;
movement[n+m] += Math.min(1, ch0 + ch1 + ch2);
}
}
return movement;
}
function compareFrame(img1,arrObject) {
// just compare if there are two pictures
if ( img2 != null ) {
var res=[0,0,0,0];
var ObjR=10;
try {
for (var n=0; n<arrMotion.length; n++){
// arrObject [active, position_x, position_y, detection_radius]
res = compare(img1, img2, arrObject[n][1], arrObject[n][2], 10, arrObject[n][3]);
if ((res[0]>400)||(res[1]>400)||(res[2]>400)||(res[3]>400)){
res[0]=0;res[1]=0;res[2]=0;res[3]=0;
}
hit[n]=res[0]+res[1]+res[2]+res[3];
}
}
catch(e) {
// errors
}
}
img2 = img1;
}
| d3-object.js | var obj_canvas,
obj_c,
cp_canvas = null;
var canvas
var video_canvas,
vid_c;
var brown_const=0;
var vid_width = 640;
var vid_height = 480;
var n_object = 20;
var m_object = 5;
var canvas;
var context;
function setupD3(){
var canvas = d3.select("#canvasArea").append("canvas")
.attr("width", vid_width)
.attr("height", vid_height);
var context = canvas.node().getContext("2d");
}
function getVideo(){
getVidFrame("http://171.65.102.132:8080/?action=snapshot?t=" + new Date().getTime(), function(image) {
context.clearRect(0, 0, vid_width, vid_height);
context.drawImage(image, 0, 0, vid_width, vid_height);
});
function getVidFrame(path, callback) {
var image = new Image;
image.onload = function() {
callback(image);
compareFrame(image);
};
image.src = path;
}
}
/*var gameobject = d3.range(n_object).map(function() {
var x = Math.random() * vid_width, y = Math.random() * vid_height;
return {
vx: Math.random() * 2 - 1,
vy: Math.random() * 2 - 1,
path: d3.range(m_object).map(function() { return [x, y]; }),
count: 0
};
});*/
var w = 640,
h = 480,
n = 20,
m = 12,
degrees = 180 / Math.PI;
var spermatozoa = d3.range(n).map(function() {
var x = Math.random() * w, y = Math.random() * h;
return {
vx: Math.random() * 2 - 1,
vy: Math.random() * 2 - 1,
path: d3.range(m).map(function() { return [x, y]; }),
count: 0
};
});
/*var svg = d3.select("canvas").append("svg:svg")
.attr("width", w)
.attr("height", h);
var g = svg.selectAll("g")
.data(spermatozoa)
.enter().append("svg:g");
var head = g.append("svg:ellipse")
.attr("rx", 6.5)
.attr("ry", 4);
g.append("svg:path")
.map(function(d) { return d.path.slice(0, 3); })
.attr("class", "mid");
g.append("svg:path")
.map(function(d) { return d.path; })
.attr("class", "tail");
var tail = g.selectAll("path");*/
/*d3.timer(function() {
getVideo();
for (var i = -1; ++i < n;) {
var spermatozoon = spermatozoa[i],
path = spermatozoon.path,
dx = spermatozoon.vx,
dy = spermatozoon.vy,
x = path[0][0] += dx,
y = path[0][1] += dy,
speed = Math.sqrt(dx * dx + dy * dy),
count = speed * 10,
k1 = -5 - speed / 3;
// Bounce off the walls.
if (x < 0 || x > w) spermatozoon.vx *= -1;
if (y < 0 || y > h) spermatozoon.vy *= -1;
// Swim!
for (var j = 0; ++j < m;) {
var vx = x - path[j][0],
vy = y - path[j][1],
k2 = Math.sin(((spermatozoon.count += count) + j * 3) / 300) / speed;
path[j][0] = (x += dx / speed * k1) - dy * k2;
path[j][1] = (y += dy / speed * k1) + dx * k2;
speed = Math.sqrt((dx = vx) * dx + (dy = vy) * dy);
}
}
head.attr("transform", function(d) {
return "translate(" + d.path[0] + ")rotate(" + Math.atan2(d.vy, d.vx) * degrees + ")";
});
tail.attr("d", function(d) {
return "M" + d.join("L");
});
});*/
function game(){
switch(gamephase)
{
case 'pre-game':
// draw intro
break;
case 'game-rest':
vid_c.fillStyle = "#fff";
vid_c.font="14px sans-serif";
vid_c.fillText('New target ...',200,20);
vid_c.fillText('player : ' + username + ' score : ' +score_val ,20,20);
break;
case 'game-action':
vid_c.fillStyle = "#fff";
vid_c.font="14px sans-serif";
vid_c.fillText('Run! Run! Run!',200,20);
vid_c.fillText('player : ' + username + ' score : ' +score_val ,20,20);
break;
case 'gameover':
vid_c.fillStyle = "#fff";
vid_c.font="14px sans-serif";
vid_c.textAlign="start";
vid_c.fillText('player : ' + username + ' score : ' +score_val ,20,20);
vid_c.fillStyle = "rgba(253,172,13,1)";
vid_c.font="40pt sans-serif";
vid_c.textAlign="center";
vid_c.fillText('GAME OVER',vid_width/2,vid_height/2-100);
vid_c.fillStyle = "#fff";
vid_c.font="20pt sans-serif";
vid_c.fillText(username+' scored '+score_val,vid_width/2,vid_height/2);
break;
default:
vid_c.fillStyle = "#fff";
vid_c.font="14px sans-serif";
vid_c.fillText('player : ' + username + ' score : ' +score_val ,20,20);
}
}
var shipX=vid_width/2,
shipY=vid_height/2,
shipRad,
shipL=20,
starX=40,
starY=20;
var gamelevel;
var int_star=-1;
var int_engine=-1;
var engine = false;
var rest = false;
var starTimer;
var enginerTimer;
var gamephase;
var score_val = 0;
var actionTimer;
var hit = new Array();
var unit=30;
function setGameAction(){
actionTimer = window.requestAnimationFrame(actionLoop);
}
function setbackPreGame(){
score_val = 0;
hit = new Array();
gamelevel=1;
shipX = vid_width/2;
shipY = vid_height/2;
gamephase='pre-game';
}
function setGameOver(){
window.cancelAnimationFrame(actionTimer);
actionTimer = undefined;
}
function actionLoop(){
switch(gamephase)
{
case 'rest':
if(rest==false)
{
rest=true;
int_star=gamelevel+6;
getStarLocation(); // get new starX, starY, shipRad
starTimer=window.setInterval(showStar,500);
}
drawStar(shipX,shipY,starX,starY,gamelevel-(int_star-6));
drawShip(shipX,shipY,shipRad);
actionTimer = window.requestAnimationFrame(gameLoop);
break;
case 'engine':
console.log(hit);
if(hit>0)
{
window.clearInterval(engineTimer);
engine=false;
rest=false;
int_star=-1;
int_engine=-1;
gamephase='gameover';
gamelevel=-1;
}
else
{
score_val=score_val+10;
if(engine==false)
{
engine=true;
int_engine=gamelevel+4;
engineTimer=window.setInterval(runEngine,500);
}
}
drawStar(shipX,shipY,starX,starY,gamelevel-(int_star-6));
drawShip(shipX,shipY,shipRad);
break;
}
}
function getStarLocation(){
shipRad=Math.random()*Math.PI*2;
starX=shipX+unit*(Math.cos(shipRad))*gamelevel;
starY=shipY+unit*(Math.sin(shipRad))*gamelevel;
}
function getShipLocation(){
var step = gamelevel-(int_engine-4);
var u = (step > gamelevel - 1) ? 0 : 1;
shipX=shipX+unit*(Math.cos(shipRad))*u;
shipY=shipY+unit*(Math.sin(shipRad))*u;
}
function showStar(){
if(int_star>0)
{
int_star=int_star-1;
}
else
{
window.clearInterval(starTimer);
rest=false;
gamephase='engine';
}
}
function runEngine(){
if(int_engine>0)
{
getShipLocation();
int_engine=int_engine-1;
}
else
{
window.clearInterval(engineTimer);
engine=false;
gamephase='rest';
if(gamelevel<10)
{
gamelevel=gamelevel+1;
}
}
}
function gameOver(){
var msg = {type:'sendscore', user:username, score:score_val};
socket.json.send(msg);
}
/*******************************************************************************
Copyright (C) 2009 Tom Stoeveken
This program is free software;
you can redistribute it and/or modify it under the terms of the
GNU General Public License, version 2.
See the file COPYING for details.
*******************************************************************************/
var img1 = null;
var img2 = null;
var md_canvas = null;
function setupMotionDetection() {
md_canvas = document.getElementById('mdCanvas');
test_canvas = document.getElementById('testCanvas');
md_canvas.width = vid_width;
md_canvas.height = vid_height;
}
/*
compare two images and count the differences
input.: image1 and image2 are Image() objects
input.: threshold specifies by how much the color value of a pixel
must differ before they are regarded to be different
return: number of different pixels
*/
function compare(image1, image2, ptX, ptY, threshold, ObjR) {
var movement = new Array(0,0,0,0);
var md_ctx = md_canvas.getContext("2d");
var width = md_canvas.width/2, height = md_canvas.height/2;
// copy images into canvas element
// these steps scale the images and decodes the image data
md_ctx.drawImage(image1, 0, 0, width, height);
md_ctx.drawImage(image2, width, 0, width, height);
// this makes r,g,b,alpha data of images available
var pixels1 = md_ctx.getImageData(0, 0, width, height);
var pixels2 = md_ctx.getImageData(width, 0, width, height);
// substract picture1 from picture2
// if they differ set color value to max,
// if the difference is below threshold set difference to 0.
for (var x = Math.round((ptX-ObjR)/2); x < Math.round((ptX+ObjR)/2); x++) {
for (var y = Math.round((ptY-ObjR)/2); y < Math.round((ptY+ObjR)/2); y++) {
// each pixel has a red, green, blue and alpha value
// all values are stored in a linear array
var i = x*4 + y*4*pixels1.width;
var ch0 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
var ch1 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
var ch2 = ((pixels1.data[i] - pixels2.data[i])>threshold)?255:0;
// count differing pixels
var n = (x<Math.round(ptX/2))?0:1;
var m = (y<Math.round(ptY/2))?0:2;
movement[n+m] += Math.min(1, ch0 + ch1 + ch2);
}
}
return movement;
}
function compareFrame(img1,arrObject) {
// just compare if there are two pictures
if ( img2 != null ) {
var res=[0,0,0,0];
var ObjR=10;
try {
for (var n=0; n<arrMotion.length; n++){
// arrObject [active, position_x, position_y, detection_radius]
res = compare(img1, img2, arrObject[n][1], arrObject[n][2], 10, arrObject[n][3]);
if ((res[0]>400)||(res[1]>400)||(res[2]>400)||(res[3]>400)){
res[0]=0;res[1]=0;res[2]=0;res[3]=0;
}
hit[n]=res[0]+res[1]+res[2]+res[3];
}
}
catch(e) {
// errors
}
}
img2 = img1;
}
| playing with d3
| d3-object.js | playing with d3 | <ide><path>3-object.js
<ide> }
<ide> }
<ide>
<del>/*var gameobject = d3.range(n_object).map(function() {
<add>var gameobject = d3.range(n_object).map(function() {
<ide> var x = Math.random() * vid_width, y = Math.random() * vid_height;
<ide> return {
<ide> vx: Math.random() * 2 - 1,
<ide> path: d3.range(m_object).map(function() { return [x, y]; }),
<ide> count: 0
<ide> };
<del>});*/
<add>});
<ide>
<ide>
<ide>
<ide> };
<ide> });
<ide>
<del>/*var svg = d3.select("canvas").append("svg:svg")
<add>var svg = d3.select("canvas").append("svg:svg")
<ide> .attr("width", w)
<ide> .attr("height", h);
<ide>
<ide> .map(function(d) { return d.path; })
<ide> .attr("class", "tail");
<ide>
<del>var tail = g.selectAll("path");*/
<del>
<del>/*d3.timer(function() {
<add>var tail = g.selectAll("path");
<add>
<add>d3.timer(function() {
<ide> getVideo();
<ide> for (var i = -1; ++i < n;) {
<ide> var spermatozoon = spermatozoa[i],
<ide> tail.attr("d", function(d) {
<ide> return "M" + d.join("L");
<ide> });
<del>});*/
<add>});
<ide>
<ide>
<ide> |
|
JavaScript | apache-2.0 | bf12eb2fdadb1b9b4174d34a554aaa40adbdeb85 | 0 | apache/lenya,apache/lenya,apache/lenya,apache/lenya | // create a domain-based "package" to keep the global namespace clean
var org;
if (!org) org = new Object();
if (!org.apache) org.apache = new Object();
if (!org.apache.lenya) org.apache.lenya = new Object();
if (!org.apache.lenya.editors) org.apache.lenya.editors = new Object();
/**
* ObjectData constructor, the interface between generic editor usecases
* and editor modules.
*
* The idea is to use the same data structure for links, images and assets.
* Thus, insertLink, insertImage and insertAsset can all share most of the javascript code.
*
* FIXME: objectData is an exceptionally stupid term. Please fix if you can think of
* something that encompasses "data for to-be-inserted links, images and assets in general".
*
* @param an optional hash map of initial values
*/
org.apache.lenya.editors.ObjectData = function(init) {
if (init) {
for (var i in this) {
if (typeof this[i] == "function") continue; // skip the methods!
//alert("Checking this[" + i + "], init[" + i + "] is '" + init[i] + "'.");
this[i] = init[i];
}
//alert("Created new ObjectData = " + this.toString());
}
}
/**
* href for links, src for assets and images
*/
org.apache.lenya.editors.ObjectData.prototype.url = undefined;
/**
* XHTML title attribute:
*/
org.apache.lenya.editors.ObjectData.prototype.title = undefined;
/**
* element content for links and assets, alt text for images:
*/
org.apache.lenya.editors.ObjectData.prototype.text = undefined;
/**
* width for images
*/
org.apache.lenya.editors.ObjectData.prototype.width = undefined;
/**
* height for images
*/
org.apache.lenya.editors.ObjectData.prototype.height = undefined;
/**
* MIME Type for images and assets.
*/
org.apache.lenya.editors.ObjectData.prototype.type = undefined;
/**
* Utility function to ease debugging. Will dump all fields in
* a human-readable fashion, including their types.
*/
org.apache.lenya.editors.ObjectData.prototype.toString = function() {
var s = "\n";
for (var i in this) {
if (typeof this[i] != "function") {
s += "\t" + i + ": [" + this[i] + "] (" + typeof this[i] + ")\n";
}
}
return s;
}
/**
* set objectData object in editor
*
* This callback must be implemented in the editor window.
* It will be called when the usecase has completed successfully
* and make the obtained data available to your editor.
* Here you must implement the necessary code to either add the
* data to your editor area directly (you may want to use
* org.apache.lenya.editors.generateContentSnippet and
* org.apache.lenya.editors.insertContent as helpers), or
* to fill the values into some editor-specific dialog.
*
* @param objectData a data object as defined by objectDataTemplate
* @param windowName the ID of the usecase window (window.name).
* @see org.apache.lenya.editors.objectDataTemplate
*/
org.apache.lenya.editors.setObjectData = function(objectData, windowName) {
alert("Programming error:\n You must override org.apache.lenya.editors.setObjectData(objectData, windowName)!");
};
/**
* get objectData object from editor
*
* This callback must be implemented in the editor window.
* The usecase will query your editor for an objectData object, which
* it will use to fill form fields with default values (if provided).
* All form fields whose values in objectData are undefined will be
* deactivated, so that your editor can handle them.
*
* Usually, default values are based on selected text or user settings.
*
* @param windowName the ID of the usecase window (window.name).
* @returns an objectData object.
* @see org.apache.lenya.editors.objectDataTemplate
*/
org.apache.lenya.editors.getObjectData = function(windowName) {
alert("Programming error:\n You must override org.apache.lenya.editors.getObjectData(windowName)!");
};
/**
* sets default values of the usecase form
*
* The form field names must correspond to the properties of
* objectDataTemplate.
* Note: if a value in objectData is undefined (as opposed to ""),
* the corresponding form field will be disabled (greyed out).
* Editors should use this to deactivate properties they wish
* to handle themselves.
* @param formName the "name" attribute of the form
* @param objectData
* @see org.apache.lenya.editors.objectDataTemplate
*/
org.apache.lenya.editors.setFormValues = function(formName,objectData) {
var form = document.forms[formName];
for (var i in org.apache.lenya.editors.ObjectData.prototype) {
if (form[i] !== undefined) {
if (objectData[i] !== undefined) {
form[i].value = objectData[i];
} else {
form[i].disabled = true;
form[i].title = "disabled by editor";
}
}
}
}
/**
* reads the values from the usecase form
*
* The form field names must correspond to the properties of
* objectDataTemplate.
* @param formName the "name" attribute of the form
* @returns objectData
*/
org.apache.lenya.editors.getFormValues = function(formName) {
var form = document.forms[formName];
var objectData = new org.apache.lenya.editors.ObjectData();
for (var i in org.apache.lenya.editors.ObjectData.prototype) {
if (form[i] !== undefined) {
objectData[i] = form[i].value;
}
}
return objectData;
}
/**
* handle the submit event of the form
*
* @param formName the "name" attribute of the form
*/
org.apache.lenya.editors.handleFormSubmit = function(formName) {
var objectData = org.apache.lenya.editors.getFormValues(formName);
window.opener.org.apache.lenya.editors.setObjectData(objectData, window.name);
window.close();
}
/**
* handle the load event of the form
*
* @param formName the "name" attribute of the form
*/
org.apache.lenya.editors.handleFormLoad = function(formName) {
var objectData = window.opener.org.apache.lenya.editors.getObjectData(window.name);
org.apache.lenya.editors.setFormValues(formName, objectData);
}
/**
* default attributes for usecase windows (window.open()...)
*/
org.apache.lenya.editors.usecaseWindowOptions =
"toolbar=no,"
+ "scrollbars=yes,"
+ "status=no,"
+ "resizable=yes,"
+ "dependent=yes,"
+ "width=600,"
+ "height=700";
org.apache.lenya.editors.generateUniqueWindowName = function() {
return new String("windowName-" + Math.random().toString().substr(2));
}
/**
* a helper function to open new usecase windows.
*
* If everyone used this, we'd save some maintenance work
* in the long run and can ensure consistent
* behaviour across different editors.
* @param usecase the name of the usecase to invoke, one of
* ("insertLink" | "insertImage" | "insertAsset")
* @param windowName the name of the new window, in case the editor needs
* that info later on.
* @returns the new window object
*/
org.apache.lenya.editors.openUsecaseWindow = function(usecase, windowName) {
var currentBaseURL;
var usecaseWindow;
switch (usecase) {
case "insertLink":
case "insertAsset":
case "insertImage":
currentBaseURL = window.location.href.replace(/\?.*$/,"");
usecaseWindow = window.open(
currentBaseURL + "?lenya.usecase=editors." + usecase,
windowName,
org.apache.lenya.editors.usecaseWindowOptions
);
break;
default:
alert("openUsecaseWindow: Unknown usecase '" + usecase + "'. This is likely a programming error.");
}
return usecaseWindow;
}
/**
* this data structure helps with the insertion of generated tags
*/
org.apache.lenya.editors.ContentSnippet = function(
beforeSelection,
afterSelection,
replaceSelection
) {
this.beforeSelection = beforeSelection,
this.afterSelection = afterSelection,
this.replaceSelection = replaceSelection
}
/**
* the characters to be inserted before the selected text
*/
org.apache.lenya.editors.ContentSnippet.prototype.beforeSelection = "";
/**
* the characters to be inserted after the selected text
*/
org.apache.lenya.editors.ContentSnippet.prototype.afterSelection = "";
/**
* the text to replace the currently selected area (if any)
*/
org.apache.lenya.editors.ContentSnippet.prototype.replaceSelection = undefined;
/**
* @see org.apache.lenya.editors.ObjectData.prototype.toString
*/
org.apache.lenya.editors.ContentSnippet.prototype.toString =
org.apache.lenya.editors.ObjectData.prototype.toString;
/**
* generates a content snippet to be inserted into the editor area
*
* @param usecase the usecase for which the snippet should be generated
* @param objectData an objectData object for the contents
* @param namespace an optional namespace URI (usually http://www.w3.org/1999/xhtml)
* @returns an object of type ContentSnippet
* @see org.apache.lenya.editors.ContentSnippet
*/
org.apache.lenya.editors.generateContentSnippet = function(usecase, objectData, namespace) {
var snippet = new org.apache.lenya.editors.ContentSnippet();
switch (usecase) {
case "insertLink":
snippet.beforeSelection = '<a'
+ (namespace ? ' xmlns="' + namespace + '"' : '')
+ (objectData.url ? ' href="' + objectData.url + '"' : '')
+ (objectData.title ? ' title="' + objectData.title + '"' : '')
+ '>';
snippet.afterSelection = '</a>';
snippet.replaceSelection =
objectData.text ? objectData.text : undefined;
break;
case "insertAsset":
snippet.beforeSelection = '<a'
+ (namespace ? ' xmlns="' + namespace + '"' : '')
+ (objectData.url ? ' href="' + objectData.url + '"' : '')
+ (objectData.title ? ' title="' + objectData.title + '"' : '')
+ ' class="asset">';
snippet.afterSelection = '</a>';
snippet.replaceSelection =
objectData.text ? objectData.text : undefined;
break;
case "insertImage":
snippet.beforeSelection = '<img'
+ (namespace ? ' xmlns="' + namespace + '"' : '')
+ (objectData.url ? ' src="' + objectData.url + '"' : '')
+ (objectData.title ? ' title="' + objectData.title + '"' : '')
+ (objectData.text ? ' alt="' + objectData.text + '"' : '')
+ (objectData.width ? ' width="' + objectData.width + '"' : '')
+ (objectData.height ? ' height="' + objectData.height + '"' : '')
+ '/>';
snippet.afterSelection = "";
snippet.replaceSelection = undefined;
break;
default:
alert("setObjectData: Unknown usecase " + currentUsecase + ". This is likely a programming error.");
return undefined;
}
return snippet;
}
/**
* a cross-browser helper to obtain selected text in form elements
*
* @param formElement a XHTML form element (document.forms[foo].bar)
* In IE, this parameter is disregarded, since IE uses a document-wide
* selection mechanism.
* @returns the selected text or the empty string.
*/
org.apache.lenya.editors.getSelectedText = function(formElement) {
if (formElement.selectionStart !== undefined) {
return formElement.value.substr(
formElement.selectionStart,
formElement.selectionEnd - formElement.selectionStart);
} else
if (document.selection !== undefined) {
return document.selection.createRange().text;
} else {
alert("Sorry, your browser apparently doesn't support text selection via javascript.");
return "";
}
}
/**
* a cross-browser helper to insert data at the selected position in a form field (textarea etc.)
*
* @param formElement a XHTML form element (document.forms[foo].bar)
* @param contentSnippet a org.apache.lenya.editors.ContentSnippet with the text to insert
*
* inspired by http://aktuell.de.selfhtml.org/artikel/javascript/bbcode/
*/
org.apache.lenya.editors.insertContent = function(formElement, snippet) {
alert("snippet: '" + snippet.toString() + "'\n");
// Danger, Will Robinson: you are leaving the w3c sector!
// Selections are not properly standardized yet...
formElement.focus();
// Firefox and friends will support this for textareas etc.
if (formElement.selectionStart !== undefined) {
var begin = formElement.selectionStart;
var end = formElement.selectionEnd;
var content = formElement.value;
var selection = content.substring(begin, end);
// alert("Found selection beginning at [" + begin + "], ending at [" + end + "].");
formElement.value = content.substr(0, begin)
+ snippet.beforeSelection
+ (snippet.replaceSelection ? snippet.replaceSelection : selection)
+ snippet.afterSelection
+ content.substr(end);
// update cursor position:
formElement.selectionStart = begin;
formElement.selectionEnd = begin;
} else
// IE does it thusly:
if (document.selection !== undefined) {
alert("Hey, you are using IE, right? Please get in touch with [email protected] to test this feature!");
var range = document.selection.createRange();
var selection = range.text;
range.text = snippet.beforeSelection
+ (snippet.replaceSelection ? snippet.replaceSelection : selection)
+ snippet.afterSelection;
range.select();
} else {
// for all other browsers, paste the stuff at the end...
alert("Hey, what kind of browser is this? Please get in touch with [email protected] to make this feature work properly for you!");
formElement.value = formElement.value
+ snippet.beforeSelection
+ (snippet.replaceSelection ? snippet.replaceSelection : selection)
+ snippet.afterSelection;
}
}
| src/modules/editors/resources/javascript/org.apache.lenya.editors.js | // create a domain-based "package" to keep the global namespace clean
var org;
if (!org) org = new Object();
if (!org.apache) org.apache = new Object();
if (!org.apache.lenya) org.apache.lenya = new Object();
if (!org.apache.lenya.editors) org.apache.lenya.editors = new Object();
/**
* the interface between generic editor usecases and editor implementations
*
* The idea is to use the same data structure for links, images and assets.
* Thus, insertLink, insertImage and insertAsset can all share most of the javascript code.
*
* FIXME: objectData is an exceptionally stupid term. Please fix if you can think of
* something that encompasses "data for to-be-inserted links, images and assets in general".
*/
/**
* ObjectData constructor.
*
* @param an optional hash map of initial values
*/
org.apache.lenya.editors.ObjectData = function(init) {
if (init) {
for (var i in this) {
if (typeof this[i] == "function") continue;
//alert("Checking this[" + i + "], init[" + i + "] is '" + init[i] + "'.");
this[i] = init[i];
}
//alert("Created new ObjectData = " + this.toString());
}
}
// href for links, src for assets and images:
org.apache.lenya.editors.ObjectData.prototype.url = undefined;
// XHTML title attribute:
org.apache.lenya.editors.ObjectData.prototype.title = undefined;
// element content for links and assets, alt text for images:
org.apache.lenya.editors.ObjectData.prototype.text = undefined;
// width for images
org.apache.lenya.editors.ObjectData.prototype.width = undefined;
// height for images
org.apache.lenya.editors.ObjectData.prototype.height = undefined;
// MIME Type for images and assets.
org.apache.lenya.editors.ObjectData.prototype.type = undefined;
org.apache.lenya.editors.ObjectData.prototype.toString = function() {
var s = "\n";
for (var i in this) {
if (typeof this[i] != "function") {
s += "\t" + i + ": [" + this[i] + "] (" + typeof this[i] + ")\n";
}
}
return s;
}
/**
* set objectData object in editor
*
* This callback must be implemented in the editor window.
* @param objectData a data object as defined by objectDataTemplate
* @param windowName the ID of the usecase window (window.name).
* @see org.apache.lenya.editors.objectDataTemplate
*/
org.apache.lenya.editors.setObjectData = function(objectData, windowName) {
alert("Programming error:\n You must override org.apache.lenya.editors.setObjectData(objectData, windowName)!");
};
/**
* get objectData object from editor
*
* This callback must be implemented in the editor window.
* @param windowName the ID of the usecase window (window.name).
* @returns an objectData object.
* @see org.apache.lenya.editors.objectDataTemplate
*/
org.apache.lenya.editors.getObjectData = function(windowName) {
alert("Programming error:\n You must override org.apache.lenya.editors.getObjectData(windowName)!");
};
/**
* sets default values of the usecase form
*
* The form field names must correspond to the properties of
* objectDataTemplate.
* Note: if a value in objectData is undefined (as opposed to ""),
* the corresponding form field will be disabled (greyed out).
* Editors should use this to deactivate properties they wish
* to handle themselves.
* @param formName the "name" attribute of the form
* @param objectData
* @see org.apache.lenya.editors.objectDataTemplate
*/
org.apache.lenya.editors.setFormValues = function(formName,objectData) {
var form = document.forms[formName];
for (var i in org.apache.lenya.editors.ObjectData.prototype) {
if (form[i] !== undefined) {
if (objectData[i] !== undefined) {
form[i].value = objectData[i];
} else {
form[i].disabled = true;
form[i].title = "disabled by editor";
}
}
}
}
/**
* reads the values from the usecase form
*
* The form field names must correspond to the properties of
* objectDataTemplate.
* @param formName the "name" attribute of the form
* @returns objectData
*/
org.apache.lenya.editors.getFormValues = function(formName) {
var form = document.forms[formName];
var objectData = new org.apache.lenya.editors.ObjectData();
for (var i in org.apache.lenya.editors.ObjectData.prototype) {
if (form[i] !== undefined) {
objectData[i] = form[i].value;
}
}
return objectData;
}
/**
* handle the submit event of the form
*
* @param formName the "name" attribute of the form
*/
org.apache.lenya.editors.handleFormSubmit = function(formName) {
var objectData = org.apache.lenya.editors.getFormValues(formName);
window.opener.org.apache.lenya.editors.setObjectData(objectData, window.name);
window.close();
}
/**
* handle the load event of the form
*
* @param formName the "name" attribute of the form
*/
org.apache.lenya.editors.handleFormLoad = function(formName) {
var objectData = window.opener.org.apache.lenya.editors.getObjectData(window.name);
org.apache.lenya.editors.setFormValues(formName, objectData);
}
/**
* default attributes for usecase windows (window.open()...)
*/
org.apache.lenya.editors.usecaseWindowOptions =
"toolbar=no,"
+ "scrollbars=yes,"
+ "status=no,"
+ "resizable=yes,"
+ "dependent=yes,"
+ "width=600,"
+ "height=700";
org.apache.lenya.editors.generateUniqueWindowName = function() {
return new String("windowName-" + Math.random().toString().substr(2));
}
/**
* a helper function to open new usecase windows.
*
* If everyone used this, we'd save some maintenance work
* in the long run and can ensure consistent
* behaviour across different editors.
* @param usecase the name of the usecase to invoke, one of
* ("insertLink" | "insertImage" | "insertAsset")
* @param windowName the name of the new window, in case the editor needs
* that info later on.
* @returns the new window object
*/
org.apache.lenya.editors.openUsecaseWindow = function(usecase, windowName) {
var currentBaseURL;
var usecaseWindow;
switch (usecase) {
case "insertLink":
case "insertAsset":
case "insertImage":
currentBaseURL = window.location.href.replace(/\?.*$/,"");
usecaseWindow = window.open(
currentBaseURL + "?lenya.usecase=editors." + usecase,
windowName,
org.apache.lenya.editors.usecaseWindowOptions
);
break;
default:
alert("openUsecaseWindow: Unknown usecase '" + usecase + "'. This is likely a programming error.");
}
return usecaseWindow;
}
/**
* this data structure handles insertion of generated tags
*/
org.apache.lenya.editors.contentSnippetTemplate = {
beforeSelection : "", // the characters to be inserted before the selected text
afterSelection : "", // the characters to be inserted after the selected text
replaceSelection : "" // the text to replace the currently selected area (if any)
}
/**
* generates a content snippet to be inserted into the editor area
*
* @param usecase the usecase for which the snippet should be generated
* @param objectData an objectData object for the contents
* @returns an object of type contentSnippetTemplate
* @see org.apache.lenya.editors.contentSnippetTemplate
*/
org.apache.lenya.editors.generateContentSnippet = function(usecase, objectData) {
var snippet = {};
switch (usecase) {
case "insertLink":
snippet.beforeSelection = '<a'
+ (objectData.url ? ' href="' + objectData.url + '"' : '')
+ (objectData.title ? ' title="' + objectData.title + '"' : '')
+ '>';
snippet.afterSelection = '</a>';
snippet.replaceSelection =
objectData.text ? objectData.text : undefined;
break;
case "insertAsset":
snippet.beforeSelection = '<a'
+ (objectData.url ? ' href="' + objectData.url + '"' : '')
+ (objectData.title ? ' title="' + objectData.title + '"' : '')
+ ' class="lenya.asset">';
snippet.afterSelection = '</a>';
snippet.replaceSelection =
objectData.text ? objectData.text : undefined;
break;
case "insertImage":
snippet.beforeSelection = '<img'
+ (objectData.url ? ' src="' + objectData.url + '"' : '')
+ (objectData.title ? ' title="' + objectData.title + '"' : '')
+ (objectData.text ? ' alt="' + objectData.text + '"' : '')
+ '/>';
snippet.afterSelection = undefined;
snippet.replaceSelection = undefined;
break;
default:
alert("setObjectData: Unknown usecase " + currentUsecase + ". This is likely a programming error.");
return undefined;
}
return snippet;
}
/**
* a cross-browser helper to obtain selected text in form elements
*
* @param formElement a XHTML form element (document.forms[foo].bar)
* In IE, this parameter is disregarded, since IE uses a document-wide
* selection mechanism.
* @returns the selected text or the empty string.
*/
org.apache.lenya.editors.getSelectedText = function(formElement) {
if (formElement.selectionStart !== undefined) {
return formElement.value.substr(
formElement.selectionStart,
formElement.selectionEnd - formElement.selectionStart);
} else
if (document.selection !== undefined) {
return document.selection.createRange().text;
} else {
alert("Sorry, your browser apparently doesn't support text selection via javascript.");
return "";
}
}
/**
* a cross-browser helper to insert data at the selected position in a form field (textarea etc.)
*
* @param formElement a XHTML form element (document.forms[foo].bar)
* @param contentSnippet a org.apache.lenya.editors.contentSnippetTemplate with the text to insert
*
* inspired by http://aktuell.de.selfhtml.org/artikel/javascript/bbcode/
*/
org.apache.lenya.editors.insertContent = function(formElement, contentSnippet) {
/* alert("contentSnippet.beforeSelection: '" + contentSnippet.beforeSelection + "'\n"
+ "contentSnippet.afterSelection: '" + contentSnippet.afterSelection + "'\n"
+ "contentSnippet.replaceSelection: '" + contentSnippet.replaceSelection + "'\n"
);*/
// Danger, Will Robinson: you are leaving the w3c sector!
// Selections are not properly standardized yet...
formElement.focus();
// Firefox and friends will support this for textareas etc.
if (formElement.selectionStart !== undefined) {
var begin = formElement.selectionStart;
var end = formElement.selectionEnd;
var content = formElement.value;
var selection = content.substring(begin, end);
// alert("Found selection beginning at [" + begin + "], ending at [" + end + "].");
formElement.value = content.substr(0, begin)
+ (contentSnippet.beforeSelection ? contentSnippet.beforeSelection : "")
+ (contentSnippet.replaceSelection ? contentSnippet.replaceSelection : selection)
+ (contentSnippet.afterSelection ? contentSnippet.afterSelection : "")
+ content.substr(end);
// update cursor position:
formElement.selectionStart = begin;
formElement.selectionEnd = begin;
} else
// IE does it thusly:
if (document.selection !== undefined) {
alert("Hey, you are using IE, right? Please get in touch with [email protected] to test this feature!");
var range = document.selection.createRange();
var selection = range.text;
range.text = (contentSnippet.beforeSelection ? contentSnippet.beforeSelection : "")
+ (contentSnippet.replaceSelection ? contentSnippet.replaceSelection : selection)
+ (contentSnippet.afterSelection ? contentSnippet.afterSelection : "");
range.select();
} else {
// for all other browsers, paste the stuff at the end...
alert("Hey, what kind of browser is this? Please get in touch with [email protected] to make this feature work properly for you!");
formElement.value = formElement.value
+ (contentSnippet.beforeSelection ? contentSnippet.beforeSelection : "")
+ (contentSnippet.replaceSelection ? contentSnippet.replaceSelection : selection)
+ (contentSnippet.afterSelection ? contentSnippet.afterSelection : "");
}
}
| contentSnippet is now also a proper object.
documentation, code formatting
git-svn-id: c334bb69c16d150e1b06e84516f7aa90b3181ca2@559931 13f79535-47bb-0310-9956-ffa450edef68
| src/modules/editors/resources/javascript/org.apache.lenya.editors.js | contentSnippet is now also a proper object. documentation, code formatting | <ide><path>rc/modules/editors/resources/javascript/org.apache.lenya.editors.js
<ide>
<ide>
<ide> /**
<del> * the interface between generic editor usecases and editor implementations
<add> * ObjectData constructor, the interface between generic editor usecases
<add> * and editor modules.
<ide> *
<ide> * The idea is to use the same data structure for links, images and assets.
<ide> * Thus, insertLink, insertImage and insertAsset can all share most of the javascript code.
<ide> *
<ide> * FIXME: objectData is an exceptionally stupid term. Please fix if you can think of
<ide> * something that encompasses "data for to-be-inserted links, images and assets in general".
<del> */
<del>
<del>/**
<del> * ObjectData constructor.
<ide> *
<ide> * @param an optional hash map of initial values
<ide> */
<ide> org.apache.lenya.editors.ObjectData = function(init) {
<ide> if (init) {
<ide> for (var i in this) {
<del> if (typeof this[i] == "function") continue;
<add> if (typeof this[i] == "function") continue; // skip the methods!
<ide> //alert("Checking this[" + i + "], init[" + i + "] is '" + init[i] + "'.");
<ide> this[i] = init[i];
<ide> }
<ide> }
<ide> }
<ide>
<del>// href for links, src for assets and images:
<add>
<add>/**
<add> * href for links, src for assets and images
<add> */
<ide> org.apache.lenya.editors.ObjectData.prototype.url = undefined;
<del>// XHTML title attribute:
<add>
<add>/**
<add> * XHTML title attribute:
<add> */
<ide> org.apache.lenya.editors.ObjectData.prototype.title = undefined;
<del>// element content for links and assets, alt text for images:
<add>
<add>/**
<add> * element content for links and assets, alt text for images:
<add> */
<ide> org.apache.lenya.editors.ObjectData.prototype.text = undefined;
<del>// width for images
<add>
<add>/**
<add> * width for images
<add> */
<ide> org.apache.lenya.editors.ObjectData.prototype.width = undefined;
<del>// height for images
<add>
<add>/**
<add> * height for images
<add> */
<ide> org.apache.lenya.editors.ObjectData.prototype.height = undefined;
<del>// MIME Type for images and assets.
<add>
<add>/**
<add> * MIME Type for images and assets.
<add> */
<ide> org.apache.lenya.editors.ObjectData.prototype.type = undefined;
<ide>
<add>
<add>/**
<add> * Utility function to ease debugging. Will dump all fields in
<add> * a human-readable fashion, including their types.
<add> */
<ide> org.apache.lenya.editors.ObjectData.prototype.toString = function() {
<ide> var s = "\n";
<ide> for (var i in this) {
<ide> * set objectData object in editor
<ide> *
<ide> * This callback must be implemented in the editor window.
<add> * It will be called when the usecase has completed successfully
<add> * and make the obtained data available to your editor.
<add> * Here you must implement the necessary code to either add the
<add> * data to your editor area directly (you may want to use
<add> * org.apache.lenya.editors.generateContentSnippet and
<add> * org.apache.lenya.editors.insertContent as helpers), or
<add> * to fill the values into some editor-specific dialog.
<add> *
<ide> * @param objectData a data object as defined by objectDataTemplate
<ide> * @param windowName the ID of the usecase window (window.name).
<ide> * @see org.apache.lenya.editors.objectDataTemplate
<ide> /**
<ide> * get objectData object from editor
<ide> *
<del> * This callback must be implemented in the editor window.
<add> * This callback must be implemented in the editor window.
<add> * The usecase will query your editor for an objectData object, which
<add> * it will use to fill form fields with default values (if provided).
<add> * All form fields whose values in objectData are undefined will be
<add> * deactivated, so that your editor can handle them.
<add> *
<add> * Usually, default values are based on selected text or user settings.
<add> *
<ide> * @param windowName the ID of the usecase window (window.name).
<ide> * @returns an objectData object.
<ide> * @see org.apache.lenya.editors.objectDataTemplate
<ide> org.apache.lenya.editors.getObjectData = function(windowName) {
<ide> alert("Programming error:\n You must override org.apache.lenya.editors.getObjectData(windowName)!");
<ide> };
<add>
<ide>
<ide> /**
<ide> * sets default values of the usecase form
<ide> return objectData;
<ide> }
<ide>
<add>
<ide> /**
<ide> * handle the submit event of the form
<ide> *
<ide> window.opener.org.apache.lenya.editors.setObjectData(objectData, window.name);
<ide> window.close();
<ide> }
<add>
<ide>
<ide> /**
<ide> * handle the load event of the form
<ide> org.apache.lenya.editors.generateUniqueWindowName = function() {
<ide> return new String("windowName-" + Math.random().toString().substr(2));
<ide> }
<add>
<ide>
<ide> /**
<ide> * a helper function to open new usecase windows.
<ide> return usecaseWindow;
<ide> }
<ide>
<del>/**
<del> * this data structure handles insertion of generated tags
<del> */
<del>org.apache.lenya.editors.contentSnippetTemplate = {
<del> beforeSelection : "", // the characters to be inserted before the selected text
<del> afterSelection : "", // the characters to be inserted after the selected text
<del> replaceSelection : "" // the text to replace the currently selected area (if any)
<del>}
<add>
<add>/**
<add> * this data structure helps with the insertion of generated tags
<add> */
<add>org.apache.lenya.editors.ContentSnippet = function(
<add> beforeSelection,
<add> afterSelection,
<add> replaceSelection
<add>) {
<add> this.beforeSelection = beforeSelection,
<add> this.afterSelection = afterSelection,
<add> this.replaceSelection = replaceSelection
<add>}
<add>
<add>
<add>/**
<add> * the characters to be inserted before the selected text
<add> */
<add>org.apache.lenya.editors.ContentSnippet.prototype.beforeSelection = "";
<add>
<add>/**
<add> * the characters to be inserted after the selected text
<add> */
<add>org.apache.lenya.editors.ContentSnippet.prototype.afterSelection = "";
<add>
<add>/**
<add> * the text to replace the currently selected area (if any)
<add> */
<add>org.apache.lenya.editors.ContentSnippet.prototype.replaceSelection = undefined;
<add>
<add>/**
<add> * @see org.apache.lenya.editors.ObjectData.prototype.toString
<add> */
<add>org.apache.lenya.editors.ContentSnippet.prototype.toString =
<add> org.apache.lenya.editors.ObjectData.prototype.toString;
<add>
<ide>
<ide> /**
<ide> * generates a content snippet to be inserted into the editor area
<ide> *
<ide> * @param usecase the usecase for which the snippet should be generated
<ide> * @param objectData an objectData object for the contents
<del> * @returns an object of type contentSnippetTemplate
<del> * @see org.apache.lenya.editors.contentSnippetTemplate
<del> */
<del>org.apache.lenya.editors.generateContentSnippet = function(usecase, objectData) {
<del> var snippet = {};
<add> * @param namespace an optional namespace URI (usually http://www.w3.org/1999/xhtml)
<add> * @returns an object of type ContentSnippet
<add> * @see org.apache.lenya.editors.ContentSnippet
<add> */
<add>org.apache.lenya.editors.generateContentSnippet = function(usecase, objectData, namespace) {
<add> var snippet = new org.apache.lenya.editors.ContentSnippet();
<ide>
<ide> switch (usecase) {
<ide>
<ide> case "insertLink":
<ide> snippet.beforeSelection = '<a'
<add> + (namespace ? ' xmlns="' + namespace + '"' : '')
<ide> + (objectData.url ? ' href="' + objectData.url + '"' : '')
<ide> + (objectData.title ? ' title="' + objectData.title + '"' : '')
<ide> + '>';
<ide>
<ide> case "insertAsset":
<ide> snippet.beforeSelection = '<a'
<add> + (namespace ? ' xmlns="' + namespace + '"' : '')
<ide> + (objectData.url ? ' href="' + objectData.url + '"' : '')
<ide> + (objectData.title ? ' title="' + objectData.title + '"' : '')
<del> + ' class="lenya.asset">';
<add> + ' class="asset">';
<ide> snippet.afterSelection = '</a>';
<ide> snippet.replaceSelection =
<ide> objectData.text ? objectData.text : undefined;
<ide>
<ide> case "insertImage":
<ide> snippet.beforeSelection = '<img'
<add> + (namespace ? ' xmlns="' + namespace + '"' : '')
<ide> + (objectData.url ? ' src="' + objectData.url + '"' : '')
<ide> + (objectData.title ? ' title="' + objectData.title + '"' : '')
<ide> + (objectData.text ? ' alt="' + objectData.text + '"' : '')
<add> + (objectData.width ? ' width="' + objectData.width + '"' : '')
<add> + (objectData.height ? ' height="' + objectData.height + '"' : '')
<ide> + '/>';
<del> snippet.afterSelection = undefined;
<add> snippet.afterSelection = "";
<ide> snippet.replaceSelection = undefined;
<ide> break;
<ide>
<ide> if (document.selection !== undefined) {
<ide> return document.selection.createRange().text;
<ide> } else {
<del> alert("Sorry, your browser apparently doesn't support text selection via javascript.");
<add> alert("Sorry, your browser apparently doesn't support text selection via javascript.");
<ide> return "";
<ide> }
<ide> }
<ide>
<add>
<ide> /**
<ide> * a cross-browser helper to insert data at the selected position in a form field (textarea etc.)
<ide> *
<ide> * @param formElement a XHTML form element (document.forms[foo].bar)
<del> * @param contentSnippet a org.apache.lenya.editors.contentSnippetTemplate with the text to insert
<add> * @param contentSnippet a org.apache.lenya.editors.ContentSnippet with the text to insert
<ide> *
<ide> * inspired by http://aktuell.de.selfhtml.org/artikel/javascript/bbcode/
<ide> */
<del>org.apache.lenya.editors.insertContent = function(formElement, contentSnippet) {
<del>
<del> /* alert("contentSnippet.beforeSelection: '" + contentSnippet.beforeSelection + "'\n"
<del> + "contentSnippet.afterSelection: '" + contentSnippet.afterSelection + "'\n"
<del> + "contentSnippet.replaceSelection: '" + contentSnippet.replaceSelection + "'\n"
<del> );*/
<add>org.apache.lenya.editors.insertContent = function(formElement, snippet) {
<add>
<add> alert("snippet: '" + snippet.toString() + "'\n");
<ide>
<ide> // Danger, Will Robinson: you are leaving the w3c sector!
<ide> // Selections are not properly standardized yet...
<ide> var selection = content.substring(begin, end);
<ide> // alert("Found selection beginning at [" + begin + "], ending at [" + end + "].");
<ide> formElement.value = content.substr(0, begin)
<del> + (contentSnippet.beforeSelection ? contentSnippet.beforeSelection : "")
<del> + (contentSnippet.replaceSelection ? contentSnippet.replaceSelection : selection)
<del> + (contentSnippet.afterSelection ? contentSnippet.afterSelection : "")
<add> + snippet.beforeSelection
<add> + (snippet.replaceSelection ? snippet.replaceSelection : selection)
<add> + snippet.afterSelection
<ide> + content.substr(end);
<ide> // update cursor position:
<ide> formElement.selectionStart = begin;
<ide> alert("Hey, you are using IE, right? Please get in touch with [email protected] to test this feature!");
<ide> var range = document.selection.createRange();
<ide> var selection = range.text;
<del> range.text = (contentSnippet.beforeSelection ? contentSnippet.beforeSelection : "")
<del> + (contentSnippet.replaceSelection ? contentSnippet.replaceSelection : selection)
<del> + (contentSnippet.afterSelection ? contentSnippet.afterSelection : "");
<add> range.text = snippet.beforeSelection
<add> + (snippet.replaceSelection ? snippet.replaceSelection : selection)
<add> + snippet.afterSelection;
<ide> range.select();
<ide> } else {
<ide> // for all other browsers, paste the stuff at the end...
<ide> alert("Hey, what kind of browser is this? Please get in touch with [email protected] to make this feature work properly for you!");
<ide> formElement.value = formElement.value
<del> + (contentSnippet.beforeSelection ? contentSnippet.beforeSelection : "")
<del> + (contentSnippet.replaceSelection ? contentSnippet.replaceSelection : selection)
<del> + (contentSnippet.afterSelection ? contentSnippet.afterSelection : "");
<del> }
<del>}
<add> + snippet.beforeSelection
<add> + (snippet.replaceSelection ? snippet.replaceSelection : selection)
<add> + snippet.afterSelection;
<add> }
<add>} |
|
JavaScript | mit | 56842235d1172768825fa598098e4317cdbe9534 | 0 | StanleyY/Compiler,StanleyY/Compiler | console.log("Main JS file loaded");
/*
Token Object Structure
{
value: the literal char for the token.
type: the type of token it is. Example: Type, Char, Boolean.
line: the line it was found on.
pos: the position on the above line it was found at.
}
*/
//Globals
OUTPUT = null;
INPUT = null;
INPUT_LINES = null;
TOKENS = [];
RE_TYPE = /^(int|string|boolean)/g;
RE_KEYWORD = /^(if|while|print)/g;
RE_BOOLEAN = /^(true|false)/g;
function init(){
$('#inputTextArea').linedtextarea();
resetPage();
}
function resetPage(){
OUTPUT = $('#outputTextArea');
INPUT = $('#inputTextArea');
INPUT_LINES = INPUT.val().split("\n");
TOKENS = [];
OUTPUT.empty(); // Clear the output text area.
}
function test(){
resetPage();
lexer();
parser();
}
function parser(){
bracesCheck();
}
function lexer(){
checkInvalids();
generateTokens();
}
function bracesCheck(){
var index = 0;
var stack = new Array();
var re_braces = /[\{\(]/g;
for (index = 0; index < TOKENS.length; index++){
current_token = TOKENS[index].value;
if(current_token.match(re_braces) != null) stack.push(current_token);
else if(current_token == "}") {
if(stack.length < 1) raiseFatalError("Unmatched } on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
if(stack.pop() != "{") raiseFatalError("Unexpected } found on Line: " + TOKENS[index].line + ", Position: " + TOKENS[index].pos);
}
else if(current_token == ")") {
if(stack.length < 1) raiseFatalError("Unmatched ) on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
if(stack.pop() != "(") raiseFatalError("Unexpected ) found on Line: " + TOKENS[index].line + ", Position: " + TOKENS[index].pos);
}
}
if(stack.length > 0) raiseFatalError("Unmatched " + stack.pop() + " on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
}
function generateTokens(){
var line = 0;
var pos = 0;
var current_token;
var EOF_found = false;
var string_mode = false;
var re_blocks = /[\{\}\(\)]/g;
var re_digits = /[0-9]/g;
var re_chars = /[a-z]/g;
var re_string = /[ a-z]/g;
while(line < INPUT_LINES.length){
while(pos < INPUT_LINES[line].length){
current_token = INPUT_LINES[line].charAt(pos);
if(string_mode == false){
if (current_token.match(/\s/g)); // Strip whitespace when not in string mode.
else if(current_token.match(re_blocks) != null) generateToken(current_token, "Block", line, pos);
else if(current_token.match(re_digits) != null) generateToken(current_token, "Digit", line, pos);
else if(current_token == "+") generateToken(current_token, "IntOp", line, pos);
else if(current_token == "\"") {
generateToken(current_token, "Quote", line, pos);
string_mode = true;
}
else if (current_token == "=") {
if(INPUT_LINES[line].charAt(pos + 1) == "=") {
generateToken("==", "BoolOp", line, pos);
pos++;
}
else generateToken(current_token, "Assignment", line, pos);
}
else if (current_token == "!") {
if(INPUT_LINES[line].charAt(pos + 1) == "=") {
generateToken("!=", "BoolOp", line, pos);
pos++;
}
else raiseFatalError("Invalid symbol at line: " + line); // This should never be reached due to checkInvalids.
}
else if(current_token.match(re_chars) != null) pos = pos + keywordCheck(current_token, line, pos);
else if(current_token == "$") {generateToken(current_token, "EOF", line, pos); EOF_found = true;}
// If you reaches here, something has gone horribly wrong.
else raiseFatalError("Invalid symbol: " + current_token + " at line " + line);
}
else{ //String Mode
if(current_token.match(re_string) != null) generateToken(current_token, "Char", line, pos);
else if(current_token == "\"") { // Ending Quote
generateToken(current_token, "Quote", line, pos);
string_mode = false;
}
else if(current_token.match(re_string) == null) raiseFatalError("Invalid string on line " + line + ". Only characters and space allowed.");
}
pos++;
}
pos = 0;
line++;
}
if(EOF_found == false) {
raiseWarning("Reached EOF but $ not found. Added and continuing to parse.");
generateToken("$", "EOF", line, pos);
}
console.log(printTokens());
writeOutput("Lexer completed without errors.");
}
function keywordCheck(letter, line, pos){
// keywordCheck returns how far to move the position pointer.
var temp = INPUT_LINES[line].substr(pos);
if(temp.match(RE_TYPE) != null){
if(letter == "b"){
generateToken("boolean", "Type", line, pos);
return 6;
}
else if(letter == "i"){
generateToken("int", "Type", line, pos);
return 2;
}
else if(letter == "s"){
generateToken("string", "Type", line, pos);
return 5;
}
}
else if (temp.match(RE_BOOLEAN) != null){
if(letter == "f"){
generateToken("false", "BoolVal", line, pos);
return 4;
}
else if(letter == "t"){
generateToken("true", "BoolVal", line, pos);
return 3;
}
}
else if (temp.match(RE_KEYWORD) != null){
if(letter == "i"){
generateToken("if", "Keyword", line, pos);
return 1;
}
else if(letter == "p"){
generateToken("print", "Keyword", line, pos);
return 4;
}
else if(letter == "w"){
generateToken("while", "Keyword", line, pos);
return 4;
}
}
generateToken(letter, "Char", line, pos);
return 0;
}
function generateToken(val, given_type, given_line, given_pos){
TOKENS.push({value:val, type:given_type, line:given_line + 1, pos:given_pos + 1});
}
function printTokens(printTypes){
printTypes = printTypes || false; // Hacky way of optional parameter
var output = [];
var index;
for(index = 0; index < TOKENS.length; index++){
if(printTypes) output.push("" + TOKENS[index].value + ", " + TOKENS[index].type);
else output.push(TOKENS[index].value);
}
return output;
}
function checkInvalids(){
var re_invalid = /.*([=]{3,}|(!={2,})|\+{2,}|!(?!=)|[^a-z0-9\+\{\}\(\)"!=$ ]).*/g;
var line = 0;
var invalid_check;
while(line < INPUT_LINES.length){
invalid_check = re_invalid.exec(INPUT_LINES[line]);
if(invalid_check != null) {
console.log(invalid_check);
raiseFatalError("Invalid symbol: " + invalid_check[1] + " found at line: " + (line + 1)
+ " position: " + (re_invalid.lastIndex - invalid_check[1].length));
}
line++;
}
}
function writeOutput(message){
OUTPUT.append(message + "\n");
}
function raiseWarning(message){
message = "Warning: " + message;
writeOutput(message);
}
function raiseFatalError(message){
message = "Fatal Error: " + message;
writeOutput(message);
throw new Error(message);
} | javascripts/main.js | console.log("Main JS file loaded");
/*
Token Object Structure
{
value: the literal char for the token.
type: the type of token it is. Example: Type, Char, Boolean.
line: the line it was found on.
pos: the position on the above line it was found at.
}
*/
//Globals
OUTPUT = null;
INPUT = null;
INPUT_LINES = null;
TOKENS = [];
RE_TYPE = /^(int|string|boolean)/g;
RE_KEYWORD = /^(if|while|print)/g;
RE_BOOLEAN = /^(true|false)/g;
function init(){
$('#inputTextArea').linedtextarea();
resetPage();
}
function resetPage(){
OUTPUT = $('#outputTextArea');
INPUT = $('#inputTextArea');
INPUT_LINES = INPUT.val().split("\n");
TOKENS = [];
OUTPUT.empty(); // Clear the output text area.
}
function test(){
resetPage();
lexer();
parser();
}
function parser(){
bracesCheck();
}
function lexer(){
checkInvalids();
generateTokens();
}
function bracesCheck(){
var index = 0;
var stack = new Array();
var re_braces = /[\{\(]/g;
for (index = 0; index < TOKENS.length; index++){
current_token = TOKENS[index].value;
if(current_token.match(re_braces) != null) stack.push(current_token);
else if(current_token == "}") {
if(stack.length < 1) raiseFatalError("Unmatched } on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
if(stack.pop() != "{") raiseFatalError("Unexpected } found on Line: " + TOKENS[index].line + ", Position: " + TOKENS[index].pos);
}
else if(current_token == ")") {
if(stack.length < 1) raiseFatalError("Unmatched ) on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
if(stack.pop() != "(") raiseFatalError("Unexpected ) found on Line: " + TOKENS[index].line + ", Position: " + TOKENS[index].pos);
}
}
if(stack.length > 0) raiseFatalError("Unmatched " + stack.pop() + " on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
}
function generateTokens(){
var line = 0;
var pos = 0;
var current_token;
var EOF_found = false;
var string_mode = false;
var re_blocks = /[\{\}\(\)]/g;
var re_digits = /[0-9]/g;
var re_chars = /[a-z]/g;
var re_string = /[ a-z]/g;
while(line < INPUT_LINES.length){
while(pos < INPUT_LINES[line].length){
current_token = INPUT_LINES[line].charAt(pos);
if(string_mode == false){
if (current_token.match(/\s/g)); // Strip whitespace when not in string mode.
else if(current_token.match(re_blocks) != null) generateToken(current_token, "Block", line, pos);
else if(current_token.match(re_digits) != null) generateToken(current_token, "Digit", line, pos);
else if(current_token == "+") generateToken(current_token, "IntOp", line, pos);
else if(current_token == "\"") {
generateToken(current_token, "Quote", line, pos);
string_mode = true;
}
else if (current_token == "=") {
if(INPUT_LINES[line].charAt(pos + 1) == "=") {
generateToken("==", "BoolOp", line, pos);
pos++;
}
else generateToken(current_token, "Assignment", line, pos);
}
else if (current_token == "!") {
if(INPUT_LINES[line].charAt(pos + 1) == "=") {
generateToken("!=", "BoolOp", line, pos);
pos++;
}
else raiseFatalError("Invalid symbol at line: " + line); // This should never be reached due to checkInvalids.
}
else if(current_token.match(re_chars) != null) pos = pos + keywordCheck(current_token, line, pos);
else if(current_token == "$") {generateToken(current_token, "EOF", line, pos); EOF_found = true;}
// If you reaches here, something has gone horribly wrong.
else raiseFatalError("Invalid symbol: " + current_token + " at line " + line);
}
else{ //String Mode
if(current_token.match(re_string) != null) generateToken(current_token, "Char", line, pos);
else if(current_token == "\"") { // Ending Quote
generateToken(current_token, "Quote", line, pos);
string_mode = false;
}
else if(current_token.match(re_string) == null) raiseFatalError("Invalid string on line " + line + ". Only characters and space allowed.");
}
pos++;
}
pos = 0;
line++;
}
if(EOF_found == false) {
raiseWarning("Reached EOF but $ not found. Added and continuing to parse.");
generateToken(current_token, "EOF", line, pos);
}
console.log(printTokens());
writeOutput("Lexer completed without errors.");
}
function keywordCheck(letter, line, pos){
// keywordCheck returns how far to move the position pointer.
var temp = INPUT_LINES[line].substr(pos);
if(temp.match(RE_TYPE) != null){
if(letter == "b"){
generateToken("boolean", "Type", line, pos);
return 6;
}
else if(letter == "i"){
generateToken("int", "Type", line, pos);
return 2;
}
else if(letter == "s"){
generateToken("string", "Type", line, pos);
return 5;
}
}
else if (temp.match(RE_BOOLEAN) != null){
if(letter == "f"){
generateToken("false", "BoolVal", line, pos);
return 4;
}
else if(letter == "t"){
generateToken("true", "BoolVal", line, pos);
return 3;
}
}
else if (temp.match(RE_KEYWORD) != null){
if(letter == "i"){
generateToken("if", "Keyword", line, pos);
return 1;
}
else if(letter == "p"){
generateToken("print", "Keyword", line, pos);
return 4;
}
else if(letter == "w"){
generateToken("while", "Keyword", line, pos);
return 4;
}
}
generateToken(letter, "Char", line, pos);
return 0;
}
function generateToken(val, given_type, given_line, given_pos){
TOKENS.push({value:val, type:given_type, line:given_line + 1, pos:given_pos + 1});
}
function printTokens(printTypes){
printTypes = printTypes || false; // Hacky way of optional parameter
var output = [];
var index;
for(index = 0; index < TOKENS.length; index++){
if(printTypes) output.push("" + TOKENS[index].value + ", " + TOKENS[index].type);
else output.push(TOKENS[index].value);
}
return output;
}
function checkInvalids(){
var re_invalid = /.*([=]{3,}|(!={2,})|\+{2,}|!(?!=)|[^a-z0-9\+\{\}\(\)"!=$ ]).*/g;
var line = 0;
var invalid_check;
while(line < INPUT_LINES.length){
invalid_check = re_invalid.exec(INPUT_LINES[line]);
if(invalid_check != null) {
console.log(invalid_check);
raiseFatalError("Invalid symbol: " + invalid_check[1] + " found at line: " + (line + 1)
+ " position: " + (re_invalid.lastIndex - invalid_check[1].length));
}
line++;
}
}
function writeOutput(message){
OUTPUT.append(message + "\n");
}
function raiseWarning(message){
message = "Warning: " + message;
writeOutput(message);
}
function raiseFatalError(message){
message = "Fatal Error: " + message;
writeOutput(message);
throw new Error(message);
} | fixed auto append EOF to appended the actual EOF char
| javascripts/main.js | fixed auto append EOF to appended the actual EOF char | <ide><path>avascripts/main.js
<ide>
<ide> if(EOF_found == false) {
<ide> raiseWarning("Reached EOF but $ not found. Added and continuing to parse.");
<del> generateToken(current_token, "EOF", line, pos);
<add> generateToken("$", "EOF", line, pos);
<ide> }
<ide> console.log(printTokens());
<ide> writeOutput("Lexer completed without errors."); |
|
Java | apache-2.0 | 474950dcefbdcdc54f49b27ce8ae9854302cf9f8 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util;
import com.intellij.openapi.util.ThrowableComputable;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.LongConsumer;
/**
* @author Konstantin Bulenkov
*/
public final class TimeoutUtil {
/**
* @deprecated consider another approach to execute runnable on a background thread
* @see com.intellij.openapi.application.Application#executeOnPooledThread(java.util.concurrent.Callable)
* @see com.intellij.openapi.progress.util.ProgressIndicatorUtils#withTimeout(long, com.intellij.openapi.util.Computable)
* @see com.intellij.util.concurrency.AppExecutorUtil#getAppScheduledExecutorService()
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2020.2")
public static void executeWithTimeout(long timeout, long sleep, @NotNull final Runnable run) {
final long start = System.currentTimeMillis();
final AtomicBoolean done = new AtomicBoolean(false);
final Thread thread = new Thread("Fast Function Thread@" + run.hashCode()) {
@Override
public void run() {
run.run();
done.set(true);
}
};
thread.start();
while (!done.get() && System.currentTimeMillis() - start < timeout) {
try {
//noinspection BusyWait
Thread.sleep(sleep);
} catch (InterruptedException e) {
break;
}
}
if (!thread.isInterrupted()) {
thread.stop();
}
}
/**
* @deprecated consider another approach to execute runnable on a background thread
* @see com.intellij.openapi.application.Application#executeOnPooledThread(java.util.concurrent.Callable)
* @see com.intellij.openapi.progress.util.ProgressIndicatorUtils#withTimeout(long, com.intellij.openapi.util.Computable)
* @see com.intellij.util.concurrency.AppExecutorUtil#getAppScheduledExecutorService()
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2020.2")
public static void executeWithTimeout(long timeout, @NotNull final Runnable run) {
executeWithTimeout(timeout, 50, run);
}
public static void sleep(final long millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException ignored) { }
}
public static long getDurationMillis(long startNanoTime) {
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
}
/**
* @return time of running {@code runnable} in milliseconds
* @see #compute(ThrowableComputable, long, LongConsumer)
* @see #run(ThrowableRunnable, long, LongConsumer)
*/
@ApiStatus.Experimental
public static <E extends Throwable> long measureExecutionTime(@NotNull ThrowableRunnable<E> runnable) throws E {
long startTime = System.nanoTime();
runnable.run();
return getDurationMillis(startTime);
}
/**
* @param runnable a task which execution time is needed to measure
* @param consumer a consumer of a task execution time in milliseconds
*/
@ApiStatus.Experimental
public static <E extends Throwable>
void run(@NotNull ThrowableRunnable<E> runnable, @NotNull LongConsumer consumer) throws E {
run(runnable, Long.MIN_VALUE, consumer);
}
/**
* @param runnable a task which execution time is needed to measure
* @param threshold a minimal value from which duration will be passed to consumer
* @param consumer a consumer of a task execution time in milliseconds
*/
@ApiStatus.Experimental
public static <E extends Throwable>
void run(@NotNull ThrowableRunnable<E> runnable, long threshold, @NotNull LongConsumer consumer) throws E {
long startNanoTime = System.nanoTime();
try {
runnable.run();
}
finally {
long duration = getDurationMillis(startNanoTime);
if (duration >= threshold) consumer.accept(duration);
}
}
/**
* @param computable a task which computation time is needed to measure
* @param consumer a consumer of a task computation time in milliseconds
* @return a result of computation
*/
@ApiStatus.Experimental
public static <T, E extends Throwable>
T compute(@NotNull ThrowableComputable<T, E> computable, @NotNull LongConsumer consumer) throws E {
return compute(computable, Long.MIN_VALUE, consumer);
}
/**
* @param computable a task which computation time is needed to measure
* @param threshold a minimal value from which duration will be passed to consumer
* @param consumer a consumer of a task computation time in milliseconds
* @return a result of computation
*/
@ApiStatus.Experimental
public static <T, E extends Throwable>
T compute(@NotNull ThrowableComputable<T, E> computable, long threshold, @NotNull LongConsumer consumer) throws E {
long startNanoTime = System.nanoTime();
try {
return computable.compute();
}
finally {
long duration = getDurationMillis(startNanoTime);
if (duration >= threshold) consumer.accept(duration);
}
}
}
| platform/util/src/com/intellij/util/TimeoutUtil.java | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Konstantin Bulenkov
*/
public final class TimeoutUtil {
/**
* @deprecated consider another approach to execute runnable on a background thread
* @see com.intellij.openapi.application.Application#executeOnPooledThread(java.util.concurrent.Callable)
* @see com.intellij.openapi.progress.util.ProgressIndicatorUtils#withTimeout(long, com.intellij.openapi.util.Computable)
* @see com.intellij.util.concurrency.AppExecutorUtil#getAppScheduledExecutorService()
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2020.2")
public static void executeWithTimeout(long timeout, long sleep, @NotNull final Runnable run) {
final long start = System.currentTimeMillis();
final AtomicBoolean done = new AtomicBoolean(false);
final Thread thread = new Thread("Fast Function Thread@" + run.hashCode()) {
@Override
public void run() {
run.run();
done.set(true);
}
};
thread.start();
while (!done.get() && System.currentTimeMillis() - start < timeout) {
try {
//noinspection BusyWait
Thread.sleep(sleep);
} catch (InterruptedException e) {
break;
}
}
if (!thread.isInterrupted()) {
thread.stop();
}
}
/**
* @deprecated consider another approach to execute runnable on a background thread
* @see com.intellij.openapi.application.Application#executeOnPooledThread(java.util.concurrent.Callable)
* @see com.intellij.openapi.progress.util.ProgressIndicatorUtils#withTimeout(long, com.intellij.openapi.util.Computable)
* @see com.intellij.util.concurrency.AppExecutorUtil#getAppScheduledExecutorService()
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2020.2")
public static void executeWithTimeout(long timeout, @NotNull final Runnable run) {
executeWithTimeout(timeout, 50, run);
}
public static void sleep(final long millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException ignored) { }
}
public static long getDurationMillis(long startNanoTime) {
return (System.nanoTime() - startNanoTime) / 1000000;
}
/**
* @return time of running {@code runnable} in milliseconds
*/
@ApiStatus.Experimental
public static <E extends Throwable> long measureExecutionTime(@NotNull ThrowableRunnable<E> runnable) throws E {
long startTime = System.nanoTime();
runnable.run();
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
}
}
| Add useful methods to measure execution time
GitOrigin-RevId: 920ce55766c48e0b744480640d3071473a7566e0 | platform/util/src/com/intellij/util/TimeoutUtil.java | Add useful methods to measure execution time | <ide><path>latform/util/src/com/intellij/util/TimeoutUtil.java
<del>// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
<add>// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
<ide> package com.intellij.util;
<ide>
<add>import com.intellij.openapi.util.ThrowableComputable;
<ide> import org.jetbrains.annotations.ApiStatus;
<ide> import org.jetbrains.annotations.NotNull;
<ide>
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<add>import java.util.function.LongConsumer;
<ide>
<ide> /**
<ide> * @author Konstantin Bulenkov
<ide> }
<ide>
<ide> public static long getDurationMillis(long startNanoTime) {
<del> return (System.nanoTime() - startNanoTime) / 1000000;
<add> return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
<ide> }
<ide>
<ide> /**
<ide> * @return time of running {@code runnable} in milliseconds
<add> * @see #compute(ThrowableComputable, long, LongConsumer)
<add> * @see #run(ThrowableRunnable, long, LongConsumer)
<ide> */
<ide> @ApiStatus.Experimental
<ide> public static <E extends Throwable> long measureExecutionTime(@NotNull ThrowableRunnable<E> runnable) throws E {
<ide> long startTime = System.nanoTime();
<ide> runnable.run();
<del> return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
<add> return getDurationMillis(startTime);
<add> }
<add>
<add> /**
<add> * @param runnable a task which execution time is needed to measure
<add> * @param consumer a consumer of a task execution time in milliseconds
<add> */
<add> @ApiStatus.Experimental
<add> public static <E extends Throwable>
<add> void run(@NotNull ThrowableRunnable<E> runnable, @NotNull LongConsumer consumer) throws E {
<add> run(runnable, Long.MIN_VALUE, consumer);
<add> }
<add>
<add> /**
<add> * @param runnable a task which execution time is needed to measure
<add> * @param threshold a minimal value from which duration will be passed to consumer
<add> * @param consumer a consumer of a task execution time in milliseconds
<add> */
<add> @ApiStatus.Experimental
<add> public static <E extends Throwable>
<add> void run(@NotNull ThrowableRunnable<E> runnable, long threshold, @NotNull LongConsumer consumer) throws E {
<add> long startNanoTime = System.nanoTime();
<add> try {
<add> runnable.run();
<add> }
<add> finally {
<add> long duration = getDurationMillis(startNanoTime);
<add> if (duration >= threshold) consumer.accept(duration);
<add> }
<add> }
<add>
<add> /**
<add> * @param computable a task which computation time is needed to measure
<add> * @param consumer a consumer of a task computation time in milliseconds
<add> * @return a result of computation
<add> */
<add> @ApiStatus.Experimental
<add> public static <T, E extends Throwable>
<add> T compute(@NotNull ThrowableComputable<T, E> computable, @NotNull LongConsumer consumer) throws E {
<add> return compute(computable, Long.MIN_VALUE, consumer);
<add> }
<add>
<add> /**
<add> * @param computable a task which computation time is needed to measure
<add> * @param threshold a minimal value from which duration will be passed to consumer
<add> * @param consumer a consumer of a task computation time in milliseconds
<add> * @return a result of computation
<add> */
<add> @ApiStatus.Experimental
<add> public static <T, E extends Throwable>
<add> T compute(@NotNull ThrowableComputable<T, E> computable, long threshold, @NotNull LongConsumer consumer) throws E {
<add> long startNanoTime = System.nanoTime();
<add> try {
<add> return computable.compute();
<add> }
<add> finally {
<add> long duration = getDurationMillis(startNanoTime);
<add> if (duration >= threshold) consumer.accept(duration);
<add> }
<ide> }
<ide> } |
|
JavaScript | mit | 9898af6e3f0451b4cdfb4dec73be97800e0be0ef | 0 | webboilerplate/web-boilerplate,webboilerplate/web-boilerplate | /**
* @license RequireJS domReady 2.0.1 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/requirejs/domReady for details
*/
'use strict';
var isTop, testDiv, scrollIntervalId,
isBrowser = typeof window !== 'undefined' && window.document,
isPageLoaded = !isBrowser,
doc = isBrowser ? document : null,
readyCalls = [];
function runCallbacks(callbacks) {
var i;
for (i = 0; i < callbacks.length; i += 1) {
callbacks[i](doc);
}
}
function callReady() {
var callbacks = readyCalls;
if (isPageLoaded) {
//Call the DOM ready callbacks
if (callbacks.length) {
readyCalls = [];
runCallbacks(callbacks);
}
}
}
/**
* Sets the page as loaded.
*/
function pageLoaded() {
if (!isPageLoaded) {
isPageLoaded = true;
if (scrollIntervalId) {
clearInterval(scrollIntervalId);
}
callReady();
}
}
if (isBrowser) {
if (document.addEventListener) {
//Standards. Hooray! Assumption here that if standards based,
//it knows about DOMContentLoaded.
document.addEventListener('DOMContentLoaded', pageLoaded, false);
window.addEventListener('load', pageLoaded, false);
} else if (window.attachEvent) {
window.attachEvent('onload', pageLoaded);
testDiv = document.createElement('div');
try {
isTop = window.frameElement === null;
} catch (e) {}
//DOMContentLoaded approximation that uses a doScroll, as found by
//Diego Perini: http://javascript.nwbox.com/IEContentLoaded/,
//but modified by other contributors, including jdalton
if (testDiv.doScroll && isTop && window.external) {
scrollIntervalId = setInterval(function() {
try {
testDiv.doScroll();
pageLoaded();
} catch (e) {}
}, 30);
}
}
//Check if document already complete, and if so, just trigger page load
//listeners. Latest webkit browsers also use 'interactive', and
//will fire the onDOMContentLoaded before 'interactive' but not after
//entering 'interactive' or 'complete'. More details:
//http://dev.w3.org/html5/spec/the-end.html#the-end
//http://stackoverflow.com/questions/3665561/document-readystate-of-interactive-vs-ondomcontentloaded
//Hmm, this is more complicated on further use, see 'firing too early'
//bug: https://github.com/requirejs/domReady/issues/1
//so removing the || document.readyState === 'interactive' test.
//There is still a window.onload binding that should get fired if
//DOMContentLoaded is missed.
if (document.readyState === 'complete') {
pageLoaded();
}
}
/** START OF PUBLIC API **/
/**
* Registers a callback for DOM ready. If DOM is already ready, the
* callback is called immediately.
* @param {Function} callback
*/
function domReady(callback) {
if (isPageLoaded) {
callback(doc);
} else {
readyCalls.push(callback);
}
return domReady;
}
domReady.version = '2.0.1';
/**
* Loader Plugin API method
*/
domReady.load = function(name, req, onLoad, config) {
if (config.isBuild) {
onLoad(null);
} else {
domReady(onLoad);
}
};
/** END OF PUBLIC API **/
module.exports = domReady;
| src/assets/js/lib/domready.js | /**
* @license RequireJS domReady 2.0.1 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/requirejs/domReady for details
*/
/*jslint */
/*global require: false, define: false, requirejs: false,
window: false, clearInterval: false, document: false,
self: false, setInterval: false */
'use strict';
var isTop, testDiv, scrollIntervalId,
isBrowser = typeof window !== 'undefined' && window.document,
isPageLoaded = !isBrowser,
doc = isBrowser ? document : null,
readyCalls = [];
function runCallbacks(callbacks) {
var i;
for (i = 0; i < callbacks.length; i += 1) {
callbacks[i](doc);
}
}
function callReady() {
var callbacks = readyCalls;
if (isPageLoaded) {
//Call the DOM ready callbacks
if (callbacks.length) {
readyCalls = [];
runCallbacks(callbacks);
}
}
}
/**
* Sets the page as loaded.
*/
function pageLoaded() {
if (!isPageLoaded) {
isPageLoaded = true;
if (scrollIntervalId) {
clearInterval(scrollIntervalId);
}
callReady();
}
}
if (isBrowser) {
if (document.addEventListener) {
//Standards. Hooray! Assumption here that if standards based,
//it knows about DOMContentLoaded.
document.addEventListener('DOMContentLoaded', pageLoaded, false);
window.addEventListener('load', pageLoaded, false);
} else if (window.attachEvent) {
window.attachEvent('onload', pageLoaded);
testDiv = document.createElement('div');
try {
isTop = window.frameElement === null;
} catch (e) {}
//DOMContentLoaded approximation that uses a doScroll, as found by
//Diego Perini: http://javascript.nwbox.com/IEContentLoaded/,
//but modified by other contributors, including jdalton
if (testDiv.doScroll && isTop && window.external) {
scrollIntervalId = setInterval(function() {
try {
testDiv.doScroll();
pageLoaded();
} catch (e) {}
}, 30);
}
}
//Check if document already complete, and if so, just trigger page load
//listeners. Latest webkit browsers also use 'interactive', and
//will fire the onDOMContentLoaded before 'interactive' but not after
//entering 'interactive' or 'complete'. More details:
//http://dev.w3.org/html5/spec/the-end.html#the-end
//http://stackoverflow.com/questions/3665561/document-readystate-of-interactive-vs-ondomcontentloaded
//Hmm, this is more complicated on further use, see 'firing too early'
//bug: https://github.com/requirejs/domReady/issues/1
//so removing the || document.readyState === 'interactive' test.
//There is still a window.onload binding that should get fired if
//DOMContentLoaded is missed.
if (document.readyState === 'complete') {
pageLoaded();
}
}
/** START OF PUBLIC API **/
/**
* Registers a callback for DOM ready. If DOM is already ready, the
* callback is called immediately.
* @param {Function} callback
*/
function domReady(callback) {
if (isPageLoaded) {
callback(doc);
} else {
readyCalls.push(callback);
}
return domReady;
}
domReady.version = '2.0.1';
/**
* Loader Plugin API method
*/
domReady.load = function(name, req, onLoad, config) {
if (config.isBuild) {
onLoad(null);
} else {
domReady(onLoad);
}
};
/** END OF PUBLIC API **/
module.exports = domReady;
| rm jshint meta from domready
| src/assets/js/lib/domready.js | rm jshint meta from domready | <ide><path>rc/assets/js/lib/domready.js
<ide> * Available via the MIT or new BSD license.
<ide> * see: http://github.com/requirejs/domReady for details
<ide> */
<del>/*jslint */
<del>/*global require: false, define: false, requirejs: false,
<del> window: false, clearInterval: false, document: false,
<del> self: false, setInterval: false */
<ide>
<ide> 'use strict';
<ide> |
|
Java | apache-2.0 | fa6d7e7524489812141cc2d579d9c21429e41de1 | 0 | tejksat/docker-java,docker-java/docker-java,docker-java/docker-java,tejksat/docker-java | package com.github.dockerjava.api.command;
import java.util.List;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.dockerjava.api.model.NetworkSettings;
import com.github.dockerjava.core.RemoteApiVersion;
import javax.annotation.CheckForNull;
@JsonIgnoreProperties(ignoreUnknown = true)
public class InspectExecResponse {
@JsonProperty("ID")
private String id;
@JsonProperty("OpenStdin")
private Boolean openStdin;
@JsonProperty("OpenStderr")
private Boolean openStderr;
@JsonProperty("OpenStdout")
private Boolean openStdout;
@JsonProperty("Running")
private Boolean running;
/**
* @since {@link RemoteApiVersion#VERSION_1_22}
*/
@JsonProperty("CanRemove")
private Boolean canRemove;
@JsonProperty("ExitCode")
private Integer exitCode;
@JsonProperty("ProcessConfig")
private ProcessConfig processConfig;
/**
* @deprecated @since {@link RemoteApiVersion#VERSION_1_22}
*/
@Deprecated
@JsonProperty("Container")
private Container container;
/**
* @since {@link RemoteApiVersion#VERSION_1_22}
*/
@JsonProperty("ContainerID")
private String containerID;
/**
* @since {@link RemoteApiVersion#VERSION_1_22}
*/
@JsonProperty("DetachKeys")
private String detachKeys;
/**
* @since {@link RemoteApiVersion#VERSION_1_25}
*/
@JsonProperty("Pid")
private Integer pid;
public String getId() {
return id;
}
public Boolean isOpenStdin() {
return openStdin;
}
public Boolean isOpenStderr() {
return openStderr;
}
public Boolean isOpenStdout() {
return openStdout;
}
public Boolean isRunning() {
return running;
}
public Integer getExitCode() {
return exitCode;
}
public ProcessConfig getProcessConfig() {
return processConfig;
}
/**
* @see #container
*/
@Deprecated
public Container getContainer() {
return container;
}
/**
* @see #canRemove
*/
@CheckForNull
public Boolean getCanRemove() {
return canRemove;
}
/**
* @see #containerID
*/
@CheckForNull
public String getContainerID() {
return containerID;
}
/**
* @see #detachKeys
*/
@CheckForNull
public String getDetachKeys() {
return detachKeys;
}
/**
* @see #pid
*/
@CheckForNull
public Integer getPid() {
return pid;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class ProcessConfig {
@JsonProperty("arguments")
private List<String> arguments;
@JsonProperty("entrypoint")
private String entryPoint;
@JsonProperty("privileged")
private Boolean privileged;
@JsonProperty("tty")
private Boolean tty;
@JsonProperty("user")
private String user;
public List<String> getArguments() {
return arguments;
}
public String getEntryPoint() {
return entryPoint;
}
public Boolean isPrivileged() {
return privileged;
}
public Boolean isTty() {
return tty;
}
public String getUser() {
return user;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Container {
@JsonProperty("NetworkSettings")
private NetworkSettings networkSettings;
/**
* @since {@link RemoteApiVersion#VERSION_1_21}
*/
public NetworkSettings getNetworkSettings() {
return networkSettings;
}
}
}
| src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java | package com.github.dockerjava.api.command;
import java.util.List;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.dockerjava.api.model.NetworkSettings;
import com.github.dockerjava.core.RemoteApiVersion;
import javax.annotation.CheckForNull;
@JsonIgnoreProperties(ignoreUnknown = true)
public class InspectExecResponse {
@JsonProperty("ID")
private String id;
@JsonProperty("OpenStdin")
private Boolean openStdin;
@JsonProperty("OpenStderr")
private Boolean openStderr;
@JsonProperty("OpenStdout")
private Boolean openStdout;
@JsonProperty("Running")
private Boolean running;
/**
* @since {@link RemoteApiVersion#VERSION_1_22}
*/
@JsonProperty("CanRemove")
private Boolean canRemove;
@JsonProperty("ExitCode")
private Integer exitCode;
@JsonProperty("ProcessConfig")
private ProcessConfig processConfig;
/**
* @deprecated @since {@link RemoteApiVersion#VERSION_1_22}
*/
@Deprecated
@JsonProperty("Container")
private Container container;
/**
* @since {@link RemoteApiVersion#VERSION_1_22}
*/
@JsonProperty("ContainerID")
private String containerID;
/**
* @since {@link RemoteApiVersion#VERSION_1_22}
*/
@JsonProperty("DetachKeys")
private String detachKeys;
public String getId() {
return id;
}
public Boolean isOpenStdin() {
return openStdin;
}
public Boolean isOpenStderr() {
return openStderr;
}
public Boolean isOpenStdout() {
return openStdout;
}
public Boolean isRunning() {
return running;
}
public Integer getExitCode() {
return exitCode;
}
public ProcessConfig getProcessConfig() {
return processConfig;
}
/**
* @see #container
*/
@Deprecated
public Container getContainer() {
return container;
}
/**
* @see #canRemove
*/
@CheckForNull
public Boolean getCanRemove() {
return canRemove;
}
/**
* @see #containerID
*/
@CheckForNull
public String getContainerID() {
return containerID;
}
/**
* @see #detachKeys
*/
@CheckForNull
public String getDetachKeys() {
return detachKeys;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class ProcessConfig {
@JsonProperty("arguments")
private List<String> arguments;
@JsonProperty("entrypoint")
private String entryPoint;
@JsonProperty("privileged")
private Boolean privileged;
@JsonProperty("tty")
private Boolean tty;
@JsonProperty("user")
private String user;
public List<String> getArguments() {
return arguments;
}
public String getEntryPoint() {
return entryPoint;
}
public Boolean isPrivileged() {
return privileged;
}
public Boolean isTty() {
return tty;
}
public String getUser() {
return user;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Container {
@JsonProperty("NetworkSettings")
private NetworkSettings networkSettings;
/**
* @since {@link RemoteApiVersion#VERSION_1_21}
*/
public NetworkSettings getNetworkSettings() {
return networkSettings;
}
}
}
| Add "Pid" field to InspectExecResponse
| GET /exec/(id)/json now returns Pid, which is the system pid for the
| exec’d process.
https://docs.docker.com/engine/api/version-history/#v125-api-changes
| src/main/java/com/github/dockerjava/api/command/InspectExecResponse.java | Add "Pid" field to InspectExecResponse | <ide><path>rc/main/java/com/github/dockerjava/api/command/InspectExecResponse.java
<ide> @JsonProperty("DetachKeys")
<ide> private String detachKeys;
<ide>
<add> /**
<add> * @since {@link RemoteApiVersion#VERSION_1_25}
<add> */
<add> @JsonProperty("Pid")
<add> private Integer pid;
<add>
<ide> public String getId() {
<ide> return id;
<ide> }
<ide> @CheckForNull
<ide> public String getDetachKeys() {
<ide> return detachKeys;
<add> }
<add>
<add> /**
<add> * @see #pid
<add> */
<add> @CheckForNull
<add> public Integer getPid() {
<add> return pid;
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | b865afe131d5a9afdf57b3f9f04f31eb4a7da927 | 0 | eFaps/eFapsApp-Commons | /*
* Copyright 2003 - 2015 The eFaps Team
*
* 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.efaps.esjp.erp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.efaps.admin.datamodel.Attribute;
import org.efaps.admin.datamodel.Dimension;
import org.efaps.admin.datamodel.Dimension.UoM;
import org.efaps.admin.datamodel.Status;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.datamodel.ui.IUIValue;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.admin.program.esjp.Listener;
import org.efaps.admin.ui.AbstractCommand;
import org.efaps.admin.ui.AbstractUserInterfaceObject.TargetMode;
import org.efaps.admin.user.Group;
import org.efaps.admin.user.Role;
import org.efaps.ci.CIAdminUser;
import org.efaps.ci.CIType;
import org.efaps.db.AttributeQuery;
import org.efaps.db.CachedPrintQuery;
import org.efaps.db.Checkin;
import org.efaps.db.Context;
import org.efaps.db.Delete;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.PrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.admin.access.AccessCheck4UI;
import org.efaps.esjp.ci.CIERP;
import org.efaps.esjp.common.AbstractCommon;
import org.efaps.esjp.common.file.FileUtil;
import org.efaps.esjp.common.jasperreport.StandartReport;
import org.efaps.esjp.common.listener.ITypedClass;
import org.efaps.esjp.common.parameter.ParameterUtil;
import org.efaps.esjp.common.uiform.Create;
import org.efaps.esjp.common.uiform.Edit;
import org.efaps.esjp.common.uiform.Field_Base;
import org.efaps.esjp.common.util.InterfaceUtils;
import org.efaps.esjp.common.util.InterfaceUtils_Base.DojoLibs;
import org.efaps.esjp.db.InstanceUtils;
import org.efaps.esjp.erp.listener.IOnAction;
import org.efaps.esjp.erp.listener.IOnCreateDocument;
import org.efaps.esjp.erp.util.ERP;
import org.efaps.util.EFapsException;
import org.efaps.util.cache.CacheReloadException;
import org.jfree.util.Log;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO comment!
*
* @author The eFaps Team
*/
@EFapsUUID("e47df65d-4c5e-423f-b2cc-815c3007b19f")
@EFapsApplication("eFapsApp-Commons")
public abstract class CommonDocument_Base
extends AbstractCommon
implements ITypedClass
{
/**
* Logger for this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(CommonDocument.class);
/**
* {@inheritDoc}
*/
@Override
public CIType getCIType()
throws EFapsException
{
return null;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return empty Return
* @throws EFapsException on error
*/
public Return assignAction(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final AbstractCommand command = (AbstractCommand) _parameter.get(ParameterValues.UIOBJECT);
final Set<Instance> instances = new HashSet<>();
if (InstanceUtils.isValid(_parameter.getInstance()) && _parameter.getInstance().getType().isKindOf(command
.getTargetConnectAttribute().getLink())) {
instances.add(_parameter.getInstance());
} else {
instances.addAll(getSelectedInstances(_parameter));
}
for (final Instance inst : instances) {
Instance instance = null;
if (containsProperty(_parameter, "Select4Instance")) {
final String select4Instance = getProperty(_parameter, "Select4Instance");
final PrintQuery print = new CachedPrintQuery(inst, getRequestKey())
.setLifespanUnit(TimeUnit.SECONDS).setLifespan(30);
print.addSelect(select4Instance);
print.executeWithoutAccessCheck();
final Object obj = print.getSelect(select4Instance);
if (obj instanceof Instance) {
instance = (Instance) obj;
}
} else {
instance = inst;
}
final QueryBuilder queryBldr = new QueryBuilder(command.getTargetCreateType());
queryBldr.addWhereAttrEqValue(command.getTargetConnectAttribute(), instance);
for (final Instance relInst : queryBldr.getQuery().executeWithoutAccessCheck()) {
final PrintQuery print = new PrintQuery(relInst);
print.addAttribute(CIERP.ActionDefinition2DocumentAbstract.FromLinkAbstract,
CIERP.ActionDefinition2DocumentAbstract.ToLinkAbstract,
CIERP.ActionDefinition2DocumentAbstract.Date);
print.executeWithoutAccessCheck();
final Insert insert = new Insert(CIERP.ActionDefinition2DocumentHistorical);
insert.add(CIERP.ActionDefinition2DocumentHistorical.FromLinkAbstract, print.<Long>getAttribute(
CIERP.ActionDefinition2DocumentAbstract.FromLinkAbstract));
insert.add(CIERP.ActionDefinition2DocumentHistorical.ToLinkAbstract, print.<Long>getAttribute(
CIERP.ActionDefinition2DocumentAbstract.ToLinkAbstract));
insert.add(CIERP.ActionDefinition2DocumentHistorical.Date, print.<DateTime>getAttribute(
CIERP.ActionDefinition2DocumentAbstract.Date));
insert.executeWithoutAccessCheck();
new Delete(relInst).execute();
}
if (InstanceUtils.isValid(Instance.get(_parameter.getParameterValue("action")))) {
final Parameter parameter = ParameterUtil.clone(_parameter,
Parameter.ParameterValues.INSTANCE, instance);
final Create create = new Create()
{
@Override
protected void add2basicInsert(final Parameter _parameter,
final Insert _insert)
throws EFapsException
{
super.add2basicInsert(_parameter, _insert);
final Instance actionInst = Instance.get(_parameter.getParameterValue("action"));
if (actionInst.isValid()) {
_insert.add(CIERP.ActionDefinition2ObjectAbstract.FromLinkAbstract, actionInst);
}
}
};
final Instance actionInst = create.basicInsert(parameter);
for (final IOnAction listener : Listener.get().<IOnAction>invoke(IOnAction.class)) {
listener.afterAssign(this, parameter, actionInst);
}
final Map<Status, Status> mapping = getStatusMapping(parameter);
if (!mapping.isEmpty()) {
final PrintQuery print = new PrintQuery(instance);
print.addAttribute(CIERP.DocumentAbstract.StatusAbstract);
print.execute();
final Status status = Status.get(print.<Long>getAttribute(CIERP.DocumentAbstract.StatusAbstract));
if (mapping.containsKey(status)) {
final Update update = new Update(instance);
update.add(CIERP.DocumentAbstract.StatusAbstract, mapping.get(status));
update.execute();
}
}
}
}
return ret;
}
/**
* Validate selected for assign action.
*
* @param _parameter Parameter as passed by the eFaps API
* @return the return
* @throws EFapsException on error
*/
public Return validateSelected4AssignAction(final Parameter _parameter)
throws EFapsException
{
final Return ret = new AccessCheck4UI().check4SelectedOnStatus(_parameter);
if (ret.isEmpty()) {
final List<IWarning> warnings = new ArrayList<>();
warnings.add(new Selected4AssignActionInvalidWarning());
ret.put(ReturnValues.SNIPLETT, WarningUtil.getHtml4Warning(warnings).toString());
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return empty Return
* @throws EFapsException on error
*/
public Return callAction(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
for (final IOnAction listener : Listener.get().<IOnAction>invoke(IOnAction.class)) {
listener.onDocumentUpdate(_parameter, _parameter.getInstance());
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return Return containing access
* @throws EFapsException on error
*/
public Return accessCheck4Action(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Properties properties = ERP.ACTIONDEF.get();
final String key;
if (containsProperty(_parameter, "Key")) {
key = getProperty(_parameter, "Key");
} else {
final Type type = getType4SysConf(_parameter);
if (type != null) {
key = type.getName();
} else {
key = "Default";
}
}
final String accessDef = properties.getProperty(key);
if (accessDef != null) {
String access = getProperty(_parameter, "Access", "NA");
if (access.startsWith("!")) {
access = access.substring(1);
if (!accessDef.equalsIgnoreCase(access)) {
ret.put(ReturnValues.TRUE, true);
}
} else {
if (accessDef.equalsIgnoreCase(access)) {
ret.put(ReturnValues.TRUE, true);
}
}
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return Return containing access
* @throws EFapsException on error
*/
public Return accessCheck4ActionRelation(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final QueryBuilder queryBldr = new QueryBuilder(CIERP.ActionDefinition2DocumentAbstract);
queryBldr.addWhereAttrEqValue(CIERP.ActionDefinition2DocumentAbstract.ToLinkAbstract, _parameter.getInstance());
final InstanceQuery query = queryBldr.getQuery();
if (query.executeWithoutAccessCheck().isEmpty()) {
ret.put(ReturnValues.TRUE, true);
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return scale corrected BigDecimal
* @throws EFapsException on error
*/
public Return setScale4ReadValue(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Object object = _parameter.get(ParameterValues.OTHERS);
if (object != null && object instanceof BigDecimal) {
int scale = 0;
final Object attr = _parameter.get(ParameterValues.CLASS);
if (attr instanceof Attribute) {
final Type type = ((Attribute) attr).getParent();
final String frmtKey = getProperty(_parameter, "Formatter");
final DecimalFormat formatter;
if ("total".equalsIgnoreCase(frmtKey)) {
formatter = NumberFormatter.get().getFrmt4Total(type.getName());
} else if ("discount".equalsIgnoreCase(frmtKey)) {
formatter = NumberFormatter.get().getFrmt4Discount(type.getName());
} else if ("quantity".equalsIgnoreCase(frmtKey)) {
formatter = NumberFormatter.get().getFrmt4Quantity(type.getName());
} else if ("unit".equalsIgnoreCase(frmtKey)) {
formatter = NumberFormatter.get().getFrmt4UnitPrice(type.getName());
} else if (frmtKey != null) {
formatter = NumberFormatter.get().getFrmt4Key(type.getName(), frmtKey);
} else {
formatter = NumberFormatter.get().getFormatter();
}
if (formatter != null) {
final int scaleTmp = ((BigDecimal) object).scale();
if (scaleTmp > formatter.getMaximumFractionDigits()) {
final BigDecimal decTmp = ((BigDecimal) object).stripTrailingZeros();
if (decTmp.scale() < formatter.getMinimumFractionDigits()) {
scale = formatter.getMinimumFractionDigits();
} else if (decTmp.scale() > formatter.getMaximumFractionDigits()) {
scale = formatter.getMaximumFractionDigits();
} else {
scale = decTmp.scale();
}
} else if (scaleTmp < formatter.getMinimumFractionDigits()) {
scale = formatter.getMinimumFractionDigits();
} else {
scale = scaleTmp;
}
}
}
ret.put(ReturnValues.VALUES, ((BigDecimal) object).setScale(scale, BigDecimal.ROUND_HALF_UP));
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return Sales Person Field Value
* @throws EFapsException on error
*/
public Return getSalesPersonFieldValue(final Parameter _parameter)
throws EFapsException
{
final org.efaps.esjp.common.uiform.Field field = new org.efaps.esjp.common.uiform.Field() {
@Override
public DropDownPosition getDropDownPosition(final Parameter _parameter,
final Object _value,
final Object _option)
throws EFapsException
{
final Map<?, ?> props = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
final IUIValue uiValue = (IUIValue) _parameter.get(ParameterValues.UIOBJECT);
final DropDownPosition pos;
if (TargetMode.EDIT.equals(_parameter.get(ParameterValues.ACCESSMODE))) {
final Long persId = (Long) uiValue.getObject();
pos = new DropDownPosition(_value, _option).setSelected(_value.equals(persId));
} else {
if ("true".equalsIgnoreCase((String) props.get("SelectCurrent"))) {
long persId = 0;
try {
persId = Context.getThreadContext().getPerson().getId();
} catch (final EFapsException e) {
// nothing must be done at all
Field_Base.LOG.error("Catched error", e);
}
pos = new DropDownPosition(_value, _option).setSelected(new Long(persId).equals(_value));
} else {
pos = super.getDropDownPosition(_parameter, _value, _option);
}
}
return pos;
}
@Override
protected void add2QueryBuilder4List(final Parameter _parameter,
final QueryBuilder _queryBldr)
throws EFapsException
{
final Map<?, ?> props = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
final String rolesStr = (String) props.get("Roles");
final String groupsStr = (String) props.get("Groups");
if (rolesStr != null && !rolesStr.isEmpty()) {
final String[] roles = rolesStr.split(";");
final List<Long> roleIds = new ArrayList<>();
for (final String role : roles) {
final Role aRole = Role.get(role);
if (aRole != null) {
roleIds.add(aRole.getId());
}
}
if (!roleIds.isEmpty()) {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Person2Role);
queryBldr.addWhereAttrEqValue(CIAdminUser.Person2Role.UserToLink, roleIds.toArray());
_queryBldr.addWhereAttrInQuery(CIAdminUser.Abstract.ID,
queryBldr.getAttributeQuery(CIAdminUser.Person2Role.UserFromLink));
}
}
if (groupsStr != null && !groupsStr.isEmpty()) {
final String[] groups;
boolean and = true;
if (groupsStr.contains("|")) {
groups = groupsStr.split("\\|");
} else {
groups = groupsStr.split(";");
and = false;
}
final List<Long> groupIds = new ArrayList<>();
for (final String group : groups) {
final Group aGroup = Group.get(group);
if (aGroup != null) {
groupIds.add(aGroup.getId());
}
}
if (!groupIds.isEmpty()) {
if (and) {
for (final Long group : groupIds) {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Person2Group);
queryBldr.addWhereAttrEqValue(CIAdminUser.Person2Group.UserToLink, group);
final AttributeQuery attribute = queryBldr
.getAttributeQuery(CIAdminUser.Person2Group.UserFromLink);
_queryBldr.addWhereAttrInQuery(CIAdminUser.Abstract.ID, attribute);
}
} else {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Person2Group);
queryBldr.addWhereAttrEqValue(CIAdminUser.Person2Group.UserToLink, groupIds.toArray());
final AttributeQuery attribute = queryBldr
.getAttributeQuery(CIAdminUser.Person2Group.UserFromLink);
_queryBldr.addWhereAttrInQuery(CIAdminUser.Abstract.ID, attribute);
}
}
}
super.add2QueryBuilder4List(_parameter, _queryBldr);
}
};
return field.getOptionListFieldValue(_parameter);
}
/**
* A Script that removes the table rows,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableRemoveScript(final Parameter _parameter,
final String _tableName)
{
return getTableRemoveScript(_parameter, _tableName, false, false);
}
/**
* A Script that removes the table rows,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _onDomReady add onDomReady script part
* @param _wrapInTags wrap in script tags
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableRemoveScript(final Parameter _parameter,
final String _tableName,
final boolean _onDomReady,
final boolean _wrapInTags)
{
return getTableRemoveScript(_parameter, _tableName, _onDomReady, _wrapInTags, false);
}
/**
* A Script that removes the table rows,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _onDomReady add onDomReady script part
* @param _wrapInTags wrap in script tags
* @param _makeUneditable make the table uneditable
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableRemoveScript(final Parameter _parameter,
final String _tableName,
final boolean _onDomReady,
final boolean _wrapInTags,
final boolean _makeUneditable)
{
final StringBuilder ret = new StringBuilder();
if (_wrapInTags) {
ret.append("<script type=\"text/javascript\">\n");
}
if (_onDomReady) {
ret.append("require([\"dojo/domReady!\"], function(){\n");
}
ret.append("require([\"dojo/_base/lang\",\"dojo/dom\", \"dojo/dom-construct\",")
.append("\"dojo/query\",\"dojo/NodeList-traverse\", \"dojo/NodeList-dom\"],")
.append(" function(lang, dom, domConstruct, query){\n")
.append(" var tN = \"").append(_tableName).append("\";\n")
.append(" for (i = 100;i < 10000; i = i + 100) {\n")
.append(" if( lang.exists(\"eFapsTable\" + i) ){\n")
.append(" var tO = window[\"eFapsTable\" + i];\n")
.append(" if (tO.tableName == tN) {\n")
.append(" var tB = dom.byId(tO.bodyID);\n")
.append(" query(\".eFapsTableRemoveRowCell\", tB).parent().forEach(domConstruct.destroy);\n");
if (_makeUneditable) {
ret.append(" query(\"div\", tB).style(\"display\", \"none\");");
}
ret.append(" }\n")
.append(" } else {\n")
.append(" break;\n")
.append(" }\n")
.append(" }\n")
.append("});");
if (_onDomReady) {
ret.append("});\n");
}
if (_wrapInTags) {
ret.append("</script>\n");
}
return ret;
}
/**
* A Script that deactivates the table by hiding the add and remove buttons,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableDeactivateScript(final Parameter _parameter,
final String _tableName)
{
return getTableDeactivateScript(_parameter, _tableName, false, false);
}
/**
* A Script that deactivates the table by hiding the add and remove buttons,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _onDomReady add onDomReady script part
* @param _wrapInTags wrap in script tags
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableDeactivateScript(final Parameter _parameter,
final String _tableName,
final boolean _onDomReady,
final boolean _wrapInTags)
{
final StringBuilder ret = new StringBuilder();
if (_wrapInTags) {
ret.append("<script type=\"text/javascript\">\n");
}
if (_onDomReady) {
ret.append("require([\"dojo/domReady!\"], function(){\n");
}
ret.append("require([\"dojo/_base/lang\",\"dojo/dom\", \"dojo/query\",\"dojo/NodeList-traverse\", ")
.append("\"dojo/NodeList-dom\"], function(lang, dom, query){\n")
.append(" tableName = \"").append(_tableName).append("\";\n")
.append(" for (i=100;i<10000;i=i+100) {\n")
.append(" if( lang.exists(\"eFapsTable\" + i) ){\n")
.append(" var tO = window[\"eFapsTable\" + i];\n")
.append(" if (tO.tableName == tableName) {\n")
.append(" tableBody = dom.byId(tO.bodyID);\n")
.append(" query(\".eFapsTableRemoveRowCell > *\", tableBody).style({ display:\"none\" });\n")
.append(" query(\"div\", tableBody).at(-1).style(\"display\",\"none\");\n")
.append(" }\n")
.append(" } else {\n")
.append(" break;\n")
.append(" }\n")
.append(" }\n")
.append("});");
if (_onDomReady) {
ret.append("});\n");
}
if (_wrapInTags) {
ret.append("</script>\n");
}
return ret;
}
/**
* A Script adds one new empty Row to the given table.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table the row will be added to
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableAddNewRowScript(final Parameter _parameter,
final String _tableName)
{
return getTableAddNewRowsScript(_parameter, _tableName, null, null);
}
/**
* A Script adds new Rows to the given table and fills it with values.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _values values to be used
* @param _onComplete script to be added on complete
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableAddNewRowsScript(final Parameter _parameter,
final String _tableName,
final Collection<Map<String, Object>> _values,
final StringBuilder _onComplete)
{
return getTableAddNewRowsScript(_parameter, _tableName, _values, _onComplete, false, false, null);
}
/**
* Gets the table add new rows script.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName the table name
* @param _values the values
* @param _onComplete the on complete
* @param _onDomReady the on dom ready
* @param _wrapInTags the wrap in tags
* @param _nonEscapeFields the non escape fields
* @return the table add new rows script
*/
protected StringBuilder getTableAddNewRowsScript(final Parameter _parameter,
final String _tableName,
final Collection<Map<String, Object>> _values,
final StringBuilder _onComplete,
final boolean _onDomReady,
final boolean _wrapInTags,
final Set<String> _nonEscapeFields)
{
return getTableAddNewRowsScript(_parameter, _tableName, _values, _onComplete, _onDomReady, _wrapInTags,
_nonEscapeFields, null);
}
/**
* A Script adds new Rows to the given table and fills it with values.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _values values to be used
* @param _onComplete script to be added on complete
* @param _onDomReady add onDomReady script part
* @param _wrapInTags wrap in script tags
* @param _nonEscapeFields set of fields for which the escape must not apply
* @param _extraParameter the extra parameter
* @return StringBuilder containing the javascript
*/
@SuppressWarnings("checkstyle:ParameterNumber")
protected StringBuilder getTableAddNewRowsScript(final Parameter _parameter,
final String _tableName,
final Collection<Map<String, Object>> _values,
final StringBuilder _onComplete,
final boolean _onDomReady,
final boolean _wrapInTags,
final Set<String> _nonEscapeFields,
final String _extraParameter)
{
final StringBuilder ret = new StringBuilder();
if (_wrapInTags) {
ret.append("<script type=\"text/javascript\">\n");
}
if (_onDomReady) {
ret.append("require([\"dojo/domReady!\"], function(){\n");
}
if (_values == null) {
ret.append(" addNewRows_").append(_tableName).append("(").append(1).append(",function(){\n");
} else {
ret.append(" addNewRows_").append(_tableName).append("(").append(_values.size()).append(",function(){\n")
.append(getSetFieldValuesScript(_parameter, _values, _nonEscapeFields));
}
if (_onComplete != null) {
ret.append(_onComplete);
}
ret.append("\n}, null");
if (_extraParameter != null) {
ret.append(",").append(_extraParameter);
}
ret.append(" );\n");
if (_onDomReady) {
ret.append("\n});\n");
}
if (_wrapInTags) {
ret.append("</script>\n");
}
return ret;
}
/**
* A Script that sets values.
* @param _parameter Parameter as passed by the eFaps API
* @param _values values to be used
* @param _nonEscapeFields set of fields for which the escape must not apply
* @return StringBuilder containing the javascript
*/
protected StringBuilder getSetFieldValuesScript(final Parameter _parameter,
final Collection<Map<String, Object>> _values,
final Set<String> _nonEscapeFields)
{
final StringBuilder ret = new StringBuilder();
int i = 0;
for (final Map<String, Object> values : _values) {
for (final Entry<String, Object> entry : values.entrySet()) {
final String value;
final String label;
if (entry.getValue() instanceof String[] && ((String[]) entry.getValue()).length == 2) {
value = ((String[]) entry.getValue())[0];
label = ((String[]) entry.getValue())[1];
} else {
value = String.valueOf(entry.getValue());
label = null;
}
ret.append(getSetFieldValue(i, entry.getKey(), value, label, _nonEscapeFields == null ? true
: !_nonEscapeFields.contains(entry.getKey()))).append("\n");
}
i++;
}
return ret;
}
/**
* Get a "eFapsSetFieldValue" Javascript line.
* @param _idx index of the field
* @param _fieldName name of the field
* @param _value value
* @return StringBuilder
*/
protected StringBuilder getSetFieldValue(final int _idx,
final String _fieldName,
final String _value)
{
return getSetFieldValue(_idx, _fieldName, _value, null, true);
}
/**
* Get a "eFapsSetFieldValue" Javascript line.
* @param _idx index of the field
* @param _fieldName name of the field
* @param _value value of the field
* @param _label visible value (label) of the field
* @return StringBuilder
*/
protected StringBuilder getSetFieldValue(final int _idx,
final String _fieldName,
final String _value,
final String _label)
{
return getSetFieldValue(_idx, _fieldName, _value, _label, true);
}
/**
* Get a "eFapsSetFieldValue" Javascript line.
* @param _idx index of the field
* @param _fieldName name of the field
* @param _value value
* @param _label shown value
* @param _escape must the value be escaped
* @return StringBuilder
*/
protected StringBuilder getSetFieldValue(final int _idx,
final String _fieldName,
final String _value,
final String _label,
final boolean _escape)
{
final StringBuilder ret = new StringBuilder();
ret.append("eFapsSetFieldValue(").append(_idx).append(",'").append(_fieldName).append("',");
if (_escape) {
ret.append("'").append(StringEscapeUtils.escapeEcmaScript(_value)).append("'");
} else {
ret.append(_value);
}
if (_label != null) {
if (_escape) {
ret.append(",'").append(StringEscapeUtils.escapeEcmaScript(_label)).append("'");
} else {
ret.append(",").append(_label);
}
}
ret.append(");");
return ret;
}
/**
* JavaScript Snipplet that removes from all SELECT with
* <code>fieldname</code> all other options except the one
* identified by the given <code>_idvalue</code>.
* @param _parameter Parameter as passed by the eFaps API
* @param _idvalue value that will be set for the dropdown
* @param _field fieldname
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetDropDownScript(final Parameter _parameter,
final String _field,
final String _idvalue)
throws EFapsException
{
return getSetDropDownScript(_parameter, _field, _idvalue, null);
}
/**
* JavaScript Snipplet that removes from the SELECT with
* <code>fieldname</code> and index <code>_idx</code> (if null from all)
* the other options except the one identified by the given
* <code>_idvalue</code>.
* @param _parameter Parameter as passed by the eFaps API
* @param _idvalue value that will be set for the dropdown
* @param _field fieldname
* @param _idx index
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetDropDownScript(final Parameter _parameter,
final String _field,
final String _idvalue,
final Integer _idx)
throws EFapsException
{
final StringBuilder js = new StringBuilder()
.append("require([\"dojo/query\", \"dojo/dom-construct\",\"dojo/dom-class\"], ")
.append("function(query, domConstruct, domClass) {")
.append("var nl = query(\" select[name='").append(_field).append("']\");");
if (_idx == null) {
js.append("nl.addClass(\"eFapsReadOnly\");")
.append("query(\" select[name='").append(_field).append("'] *\").forEach(function(node){")
.append("if (node.value!='").append(_idvalue).append("') {")
.append("domConstruct.destroy(node);")
.append("}")
.append("});");
} else {
js.append("if (nl[").append(_idx).append("]!=undefined) {")
.append("domClass.add(nl[").append(_idx).append("], \"eFapsReadOnly\");")
.append("query(\"*\", nl[").append(_idx).append("]).forEach(function(node){")
.append("if (node.value!='").append(_idvalue).append("') {")
.append("domConstruct.destroy(node);")
.append("}")
.append("});")
.append("}");
}
js.append("});");
return js;
}
/**
* JavaScript Snipplet that sets all INPUTS or TEXTARES
* with name <code>fieldname</code> to readOnly and assigns class
* eFapsReadOnly.
* @param _parameter Parameter as passed by the eFaps API
* @param _field fieldnames
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetFieldReadOnlyScript(final Parameter _parameter,
final String... _field)
throws EFapsException
{
return getSetFieldReadOnlyScript(_parameter, null, _field);
}
/**
* JavaScript Snipplet that sets INPUTS or TEXTARES
* with name <code>fieldname</code> and Index <code>_idx</code>
* to readOnly and assigns class eFapsReadOnly. If <code>_idx</code> all
* are are set.
* @param _parameter Parameter as passed by the eFaps API
* @param _idx index of the field to be set to readonly
* @param _field fieldnames
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetFieldReadOnlyScript(final Parameter _parameter,
final Integer _idx,
final String... _field)
throws EFapsException
{
return getSetFieldReadOnlyScript(_parameter, _idx, true, _field);
}
/**
* JavaScript Snipplet that sets INPUTS or TEXTARES
* with name <code>fieldname</code> and Index <code>_idx</code>
* to readOnly and assigns class eFapsReadOnly. If <code>_idx</code> all
* are are set.
* @param _parameter Parameter as passed by the eFaps API
* @param _idx index of the field to be set to readonly
* @param _readOnly readonly or not
* @param _field fieldnames
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetFieldReadOnlyScript(final Parameter _parameter,
final Integer _idx,
final boolean _readOnly,
final String... _field)
throws EFapsException
{
final StringBuilder js = new StringBuilder();
for (final String field : _field) {
js.append("var nl = query(\" input[name='").append(field).append("'], textarea[name='")
.append(field).append("']\");");
if (_idx == null) {
js.append("nl.forEach(function(node){")
.append("if (node.type===\"hidden\") {")
.append("var pW = registry.getEnclosingWidget(node);")
.append("if (typeof(pW) !== \"undefined\") {")
.append("if (pW.isInstanceOf(AutoComplete) || pW.isInstanceOf(AutoSuggestion)) {")
.append("pW.set('readOnly', ").append(_readOnly).append(");")
.append("}")
.append("}")
.append("} else {")
.append("node.readOnly =").append(_readOnly).append(";")
.append("}")
.append("});\n");
} else {
js.append("if (nl[").append(_idx).append("]!=undefined) {")
.append("nl[").append(_idx).append("].readOnly =").append(_readOnly).append(";")
.append("}\n");
}
}
if (_readOnly) {
js.append("query(\" input[readonly=''], textarea[readonly='']\").addClass(\"eFapsReadOnly\");");
} else {
js.append("query(\".eFapsReadOnly\").forEach(function(_node) {")
.append("if (!_node.readOnly) {")
.append("domClass.remove(_node, \"eFapsReadOnly\");")
.append("}")
.append("});");
}
return InterfaceUtils.wrapInDojoRequire(_parameter, js, DojoLibs.QUERY, DojoLibs.REGISTRY,
DojoLibs.AUTOCOMP, DojoLibs.AUTOSUGG, DojoLibs.DOMCLASS, DojoLibs.NLDOM);
}
/**
* Get a String Array for UoM Field.
* @param _selected selected id
* @param _dimId id of the Dimension
* @return String for UoM DropDown
* @throws CacheReloadException on error
*/
protected String getUoMFieldStr(final long _selected,
final long _dimId)
throws CacheReloadException
{
final Dimension dim = Dimension.get(_dimId);
final StringBuilder js = new StringBuilder();
js.append("new Array('").append(_selected).append("'");
for (final UoM uom : dim.getUoMs()) {
js.append(",'").append(uom.getId()).append("','").append(uom.getName()).append("'");
}
js.append(")");
return js.toString();
}
/**
* Get a String Array for UoM Field.
* @param _dimId id of the Dimension
* @return String for UoM DropDown
* @throws CacheReloadException on error
*/
protected String getUoMFieldStr(final long _dimId)
throws CacheReloadException
{
final Dimension dim = Dimension.get(_dimId);
return getUoMFieldStr(dim.getBaseUoM().getId(), _dimId);
}
/**
* @param _uoMId id of the UoM
* @return Field String
* @throws CacheReloadException on error
*/
protected String getUoMFieldStrByUoM(final long _uoMId)
throws CacheReloadException
{
return getUoMFieldStr(_uoMId, Dimension.getUoM(_uoMId).getDimId());
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _insert insert to add to
* @param _createdDoc document created
* @throws EFapsException on error
*/
protected void addStatus2DocCreate(final Parameter _parameter,
final Insert _insert,
final CreatedDoc _createdDoc)
throws EFapsException
{
Status status = null;
// first check if set via SystemConfiguration if not set lookup the properties
final Properties properties = ERP.DOCSTATUSCREATE.get();
final Type type = getType4DocCreate(_parameter);
if (type != null) {
final String key = properties.getProperty(type.getName() + ".Status");
if (key != null) {
status = Status.find(type.getStatusAttribute().getLink().getUUID(), key);
}
}
if (status == null) {
final List<Status> statusList = getStatusListFromProperties(_parameter);
if (!statusList.isEmpty()) {
status = statusList.get(0);
}
}
if (status != null) {
_insert.add(getType4DocCreate(_parameter).getStatusAttribute(), status);
}
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _update insert to add to
* @param _editDoc document edited
* @throws EFapsException on error
*/
protected void addStatus2DocEdit(final Parameter _parameter,
final Update _update,
final EditedDoc _editDoc)
throws EFapsException
{
final Type type = _update.getInstance().getType();
if (type.isCheckStatus()) {
final String attrName = type.getStatusAttribute().getName();
final String fieldName = getFieldName4Attribute(_parameter, attrName);
final String statusTmp = _parameter.getParameterValue(fieldName);
final Instance inst = Instance.get(statusTmp);
Status status = null;
if (inst.isValid()) {
status = Status.get(inst.getId());
} else {
if (statusTmp != null && !statusTmp.isEmpty()) {
try {
final Long statusId = Long.valueOf(statusTmp);
status = Status.get(statusId);
} catch (final NumberFormatException e) {
Log.warn("Catched NumberFormatException");
}
}
}
if (status != null) {
_update.add(type.getStatusAttribute(), status);
}
}
}
/**
* Get the type used to create the new Payment Document.
* @param _parameter Parameter as passed by the eFaps API
* @return Type use for the insert
* @throws EFapsException on error
*/
protected Type getType4DocCreate(final Parameter _parameter)
throws EFapsException
{
final AbstractCommand command = (AbstractCommand) _parameter.get(ParameterValues.UIOBJECT);
return command.getTargetCreateType();
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _createdDoc document created
* @return the created file
* @throws EFapsException on error
*/
protected File createReport(final Parameter _parameter,
final CreatedDoc _createdDoc)
throws EFapsException
{
File ret = null;
if ((containsProperty(_parameter, "JasperReport") || containsProperty(_parameter, "JasperKey")
|| containsProperty(_parameter, "JasperConfig"))
&& _createdDoc.getInstance() != null && _createdDoc.getInstance().isValid()) {
try {
final StandartReport report = new StandartReport();
_parameter.put(ParameterValues.INSTANCE, _createdDoc.getInstance());
String name = (String) _createdDoc.getValue(CIERP.DocumentAbstract.Name.name);
if (name == null) {
final PrintQuery print = new PrintQuery(_createdDoc.getInstance());
print.addAttribute(CIERP.DocumentAbstract.Name);
print.execute();
name = print.<String>getAttribute(CIERP.DocumentAbstract.Name);
}
final String fileName = DBProperties.getProperty(_createdDoc.getInstance().getType().getLabelKey(),
"es") + "_" + name;
report.setFileName(fileName);
add2Report(_parameter, _createdDoc, report);
ret = report.getFile(_parameter);
ret = new FileUtil().convertPdf(_parameter, ret, fileName);
if (ret != null) {
final InputStream input = new FileInputStream(ret);
final Checkin checkin = new Checkin(_createdDoc.getInstance());
checkin.execute(fileName + "." + report.getMime(_parameter).getExtension(), input,
((Long) ret.length()).intValue());
}
} catch (final FileNotFoundException e) {
CommonDocument_Base.LOG.error("Catched FileNotFoundException", e);
}
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @return the created file
* @throws EFapsException on error
*/
public Return createReport(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final StandartReport report = new StandartReport();
if (InstanceUtils.isKindOf(_parameter.getInstance(), CIERP.DocumentAbstract)) {
final PrintQuery print = new PrintQuery(_parameter.getInstance());
print.addAttribute(CIERP.DocumentAbstract.Name);
print.execute();
final String name = print.<String>getAttribute(CIERP.DocumentAbstract.Name);
final String fileName = DBProperties.getProperty(_parameter.getInstance().getType().getLabelKey(), "es")
+ "_" + name;
report.setFileName(fileName);
}
add2Report(_parameter, null, report);
File file = report.getFile(_parameter);
if (BooleanUtils.toBoolean(getProperty(_parameter, "Checkin"))) {
try {
file = new FileUtil().convertPdf(_parameter, file, report.getFileName());
if (file != null) {
final InputStream input = new FileInputStream(file);
final Checkin checkin = new Checkin(_parameter.getInstance());
checkin.execute(report.getFileName() + "." + report.getMime(_parameter).getExtension(), input,
((Long) file.length()).intValue());
}
} catch (final FileNotFoundException e) {
CommonDocument_Base.LOG.error("Catched FileNotFoundException", e);
}
}
ret.put(ReturnValues.VALUES, file);
ret.put(ReturnValues.TRUE, true);
return ret;
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _createdDoc document created
* @param _report report
* @throws EFapsException on error
*/
protected void add2Report(final Parameter _parameter,
final CreatedDoc _createdDoc,
final StandartReport _report)
throws EFapsException
{
final String companyName = ERP.COMPANY_NAME.get();
if (companyName != null && !companyName.isEmpty()) {
_report.getJrParameters().put("CompanyName", companyName);
}
final String companyTaxNum = ERP.COMPANY_TAX.get();
if (companyTaxNum != null && !companyTaxNum.isEmpty()) {
_report.getJrParameters().put("CompanyTaxNum", companyTaxNum);
}
final String companyActivity = ERP.COMPANY_ACTIVITY.get();
if (companyActivity != null && !companyActivity.isEmpty()) {
_report.getJrParameters().put("CompanyActivity", companyActivity);
}
final String companyStreet = ERP.COMPANY_STREET.get();
if (companyStreet != null && !companyStreet.isEmpty()) {
_report.getJrParameters().put("CompanyStreet", companyStreet);
}
final String companyRegion = ERP.COMPANY_REGION.get();
if (companyRegion != null && !companyRegion.isEmpty()) {
_report.getJrParameters().put("CompanyRegion", companyRegion);
}
final String companyCity = ERP.COMPANY_CITY.get();
if (companyCity != null && !companyCity.isEmpty()) {
_report.getJrParameters().put("CompanyCity", companyCity);
}
final String companyDistrict = ERP.COMPANY_DISTRICT.get();
if (companyDistrict != null && !companyDistrict.isEmpty()) {
_report.getJrParameters().put("CompanyDistrict", companyDistrict);
}
}
/**
* Method is called in the process of creation of a Document.
* @param _parameter Parameter as passed by the eFaps API
* @param _insert insert to add to
* @param _createdDoc document created
* @throws EFapsException on error
*/
protected void add2DocCreate(final Parameter _parameter,
final Insert _insert,
final CreatedDoc _createdDoc)
throws EFapsException
{
// used by implementation
}
/**
* Method is called in the process of edit of a Document.
* @param _parameter Parameter as passed by the eFaps API
* @param _update update to add to
* @param _editDoc document edited
* @throws EFapsException on error
*/
protected void add2DocEdit(final Parameter _parameter,
final Update _update,
final EditedDoc _editDoc)
throws EFapsException
{
// used by implementation
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _attributeName attributerName the FieldName is wanted for
* @return fieldname
* @throws EFapsException on error
*/
protected String getFieldName4Attribute(final Parameter _parameter,
final String _attributeName)
throws EFapsException
{
return StringUtils.uncapitalize(_attributeName);
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @return new Name
* @throws EFapsException on error
*/
protected String getDocName4Create(final Parameter _parameter)
throws EFapsException
{
//first priority are values from the UserInterface
String ret = _parameter.getParameterValue(getFieldName4Attribute(_parameter, CIERP.DocumentAbstract.Name.name));
if (StringUtils.isEmpty(ret)) {
final Type type = getType4DocCreate(_parameter);
ret = new Naming().fromNumberGenerator(_parameter, type.getName());
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @return type
* @throws EFapsException on error
*/
protected Type getType4SysConf(final Parameter _parameter)
throws EFapsException
{
return CIERP.DocumentAbstract.getType();
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return rate value
* @throws EFapsException on error
*/
protected BigDecimal getRate(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRate(_parameter, _rateInfo, type.getName());
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return formated rate
* @throws EFapsException on error
*/
protected String getRateFrmt(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRateFrmt(_parameter, _rateInfo, type.getName());
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return rate value for UserInterface
* @throws EFapsException on error
*/
protected BigDecimal getRateUI(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRateUI(_parameter, _rateInfo, type.getName());
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return fromatted rate string for UserInterface
* @throws EFapsException on error
*/
protected String getRateUIFrmt(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRateUIFrmt(_parameter, _rateInfo, type.getName());
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return formated rate
* @throws EFapsException on error
*/
protected Object[] getRateObject(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRateObject(_parameter, _rateInfo, type.getName());
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @return new Name
* @throws EFapsException on error
*/
public Return getJavaScript4EditMassiveTable(final Parameter _parameter)
throws EFapsException
{
final Return retVal = new Return();
retVal.put(ReturnValues.SNIPLETT,
getTableDeactivateScript(_parameter, "inventoryTable", true, true).toString());
return retVal;
}
/**
* @param _parameter Parameter as passed from the eFaps API.
* @param _createdDoc CreatedDoc the process must be executed for
* @throws EFapsException on error
*/
public void executeProcess(final Parameter _parameter,
final CreatedDoc _createdDoc)
throws EFapsException
{
final Create create = new Create()
{
@Override
protected void add2ProcessMap(final Parameter _parameter,
final Instance _instance,
final Map<String, Object> _params)
throws EFapsException
{
CommonDocument_Base.this.add2ProcessMap(_parameter, _createdDoc, _params);
}
};
create.executeProcess(_parameter, _createdDoc.getInstance());
}
/**
* Add additional values to the map passed to the process prior to
* execution.
*
* @param _parameter Parameter as passed by the eFasp API
* @param _createdDoc CreatedDoc the process must be executed for
* @param _params Map passed to the Process
* @throws EFapsException on error
*/
protected void add2ProcessMap(final Parameter _parameter,
final CreatedDoc _createdDoc,
final Map<String, Object> _params)
throws EFapsException
{
// to be used by implementation
}
/**
* To start a process on trigger.
* @param _parameter Parameter as passed from the eFaps API.
* @param _instance instance the process must be executed for
* @throws EFapsException on error
*/
public void executeProcess(final Parameter _parameter,
final Instance _instance)
throws EFapsException
{
final Create create = new Create()
{
@Override
protected void add2ProcessMap(final Parameter _parameter,
final Instance _instance,
final Map<String, Object> _params)
throws EFapsException
{
CommonDocument_Base.this.add2ProcessMap(_parameter, _instance, _params);
}
};
create.executeProcess(_parameter, _instance);
}
/**
* Add additional values to the map passed to the process prior to
* execution.
*
* @param _parameter Parameter as passed by the eFasp API
* @param _instance instance the process must be executed for
* @param _params Map passed to the Process
* @throws EFapsException on error
*/
protected void add2ProcessMap(final Parameter _parameter,
final Instance _instance,
final Map<String, Object> _params)
throws EFapsException
{
// to be used by implementation
}
/**
* Add additional values to the map passed to the process prior to
* execution.
*
* @param _parameter Parameter as passed by the eFasp API
* @param _createdDoc CreatedDoc the process must be executed for
* @throws EFapsException on error
*/
public void connect2Object(final Parameter _parameter,
final CreatedDoc _createdDoc)
throws EFapsException
{
final Map<Integer, String> connectTypes = analyseProperty(_parameter, "ConnectType");
if (!connectTypes.isEmpty()) {
final Map<Integer, String> currentLinks = analyseProperty(_parameter, "ConnectCurrentLink");
final Map<Integer, String> foreignLinks = analyseProperty(_parameter, "ConnectForeignLink");
final Map<Integer, String> foreignFields = analyseProperty(_parameter, "ConnectForeignField");
// all must be of the same size
if (connectTypes.size() == currentLinks.size() && foreignLinks.size() == foreignFields.size()
&& connectTypes.size() == foreignLinks.size()) {
for (final Entry<Integer, String> entry: connectTypes.entrySet()) {
final String[] foreigns;
final String foreignField = foreignFields.get(entry.getKey());
if ("CALLINSTANCE".equals(foreignField)) {
foreigns = new String[] { _parameter.getCallInstance().getOid() };
} else {
foreigns = _parameter.getParameterValues(foreignFields.get(entry.getKey()));
}
if (foreigns != null) {
for (final String foreign : foreigns) {
if (!foreign.isEmpty()) {
final String typeStr = entry.getValue();
final Insert insert;
if (isUUID(typeStr)) {
insert = new Insert(UUID.fromString(typeStr));
} else {
insert = new Insert(typeStr);
}
insert.add(currentLinks.get(entry.getKey()), _createdDoc.getInstance());
final Instance inst = Instance.get(foreign);
if (inst.isValid()) {
insert.add(foreignLinks.get(entry.getKey()), inst);
} else {
insert.add(foreignLinks.get(entry.getKey()), foreign);
}
add2connect2Object(_parameter, _createdDoc, insert);
insert.execute();
}
}
}
}
} else {
CommonDocument_Base.LOG.error("The properties must be of the same size!");
}
}
}
/**
* Add additional values to the Update generated by connect definition.
*
* @param _parameter Parameter as passed by the eFasp API
* @param _createdDoc CreatedDoc the process must be executed for
* @param _update update 2 add to
* @throws EFapsException on error
*/
protected void add2connect2Object(final Parameter _parameter,
final CreatedDoc _createdDoc,
final Update _update)
throws EFapsException
{
}
/**
* Update connection 2 object.
*
* @param _parameter the _parameter
* @param _editedDoc the _edited doc
* @throws EFapsException on error
*/
public void updateConnection2Object(final Parameter _parameter,
final EditedDoc _editedDoc)
throws EFapsException
{
final Edit edit = new Edit() {
@Override
protected void add2updateConnection2Object(final Parameter _parameter,
final Update _update)
throws EFapsException
{
super.add2updateConnection2Object(_parameter, _update);
CommonDocument_Base.this.add2updateConnection2Object(_parameter, _editedDoc, _update);
}
};
edit.updateConnection2Object(_parameter, _editedDoc.getInstance());
}
/**
* Add2update connection2 object.
*
* @param _parameter the _parameter
* @param _editedDoc the _edited doc
* @param _update the _update
* @throws EFapsException on error
*/
protected void add2updateConnection2Object(final Parameter _parameter,
final EditedDoc _editedDoc,
final Update _update)
throws EFapsException
{
}
/**
* Method to evaluate the selected row.
*
* @param _parameter paaremter
* @return number of selected row.
*/
public int getSelectedRow(final Parameter _parameter)
{
return InterfaceUtils.getSelectedRow(_parameter);
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return JavaScript to be used for UI
* @throws EFapsException on error
*/
protected CharSequence getJavaScript4Doc(final Parameter _parameter)
throws EFapsException
{
final StringBuilder ret = new StringBuilder();
for (final IOnCreateDocument listener : Listener.get().<IOnCreateDocument>invoke(IOnCreateDocument.class)) {
ret.append(listener.getJavaScript4Doc(this, _parameter));
}
return ret;
}
/**
* Class is used as the return value for the internal Create methods.
*/
public static class CreatedDoc
{
/**
* Instance of the newly created doc.
*/
private Instance instance;
/**
* Positions of the created Document.
*/
private final List<Instance> positions = new ArrayList<>();
/**
* Map can be used to pass values from one method to another.
*/
private final Map<String, Object> values = new HashMap<>();
/**
*
*/
public CreatedDoc()
{
}
/**
* @param _instance Instance of the Document
*/
public CreatedDoc(final Instance _instance)
{
this.instance = _instance;
}
/**
* Getter method for the instance variable {@link #values}.
*
* @return value of instance variable {@link #values}
*/
public Map<String, Object> getValues()
{
return this.values;
}
/**
* @param _key key
* @return value
*/
public Object getValue(final String _key)
{
return this.values.get(_key);
}
/**
* @param _key key
* @param _value value
*/
public void addValue(final String _key,
final Object _value)
{
this.values.put(_key, _value);
}
/**
* Getter method for the instance variable {@link #instance}.
*
* @return value of instance variable {@link #instance}
*/
public Instance getInstance()
{
return this.instance;
}
/**
* Setter method for instance variable {@link #instance}.
*
* @param _instance value for instance variable {@link #instance}
*/
public void setInstance(final Instance _instance)
{
this.instance = _instance;
}
/**
* Getter method for the instance variable {@link #positions}.
*
* @return value of instance variable {@link #positions}
*/
public List<Instance> getPositions()
{
return this.positions;
}
/**
* @param _instance Instance to add
*/
public void addPosition(final Instance _instance)
{
this.positions.add(_instance);
}
}
/**
* Class is used as the return value for the internal Edit methods.
*/
public static class EditedDoc
extends CreatedDoc
{
/**
* @param _instance Instance the document belongs to
*/
public EditedDoc(final Instance _instance)
{
super(_instance);
}
}
/**
* Warning for not enough Stock.
*/
public static class Selected4AssignActionInvalidWarning
extends AbstractWarning
{
/**
* Constructor.
*/
public Selected4AssignActionInvalidWarning()
{
setError(true);
}
}
}
| src/main/efaps/ESJP/org/efaps/esjp/erp/CommonDocument_Base.java | /*
* Copyright 2003 - 2015 The eFaps Team
*
* 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.efaps.esjp.erp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.efaps.admin.datamodel.Attribute;
import org.efaps.admin.datamodel.Dimension;
import org.efaps.admin.datamodel.Dimension.UoM;
import org.efaps.admin.datamodel.Status;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.datamodel.ui.IUIValue;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.admin.program.esjp.Listener;
import org.efaps.admin.ui.AbstractCommand;
import org.efaps.admin.ui.AbstractUserInterfaceObject.TargetMode;
import org.efaps.admin.user.Group;
import org.efaps.admin.user.Role;
import org.efaps.ci.CIAdminUser;
import org.efaps.ci.CIType;
import org.efaps.db.AttributeQuery;
import org.efaps.db.Checkin;
import org.efaps.db.Context;
import org.efaps.db.Delete;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.PrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.admin.access.AccessCheck4UI;
import org.efaps.esjp.ci.CIERP;
import org.efaps.esjp.common.AbstractCommon;
import org.efaps.esjp.common.file.FileUtil;
import org.efaps.esjp.common.jasperreport.StandartReport;
import org.efaps.esjp.common.listener.ITypedClass;
import org.efaps.esjp.common.parameter.ParameterUtil;
import org.efaps.esjp.common.uiform.Create;
import org.efaps.esjp.common.uiform.Edit;
import org.efaps.esjp.common.uiform.Field_Base;
import org.efaps.esjp.common.util.InterfaceUtils;
import org.efaps.esjp.common.util.InterfaceUtils_Base.DojoLibs;
import org.efaps.esjp.db.InstanceUtils;
import org.efaps.esjp.erp.listener.IOnAction;
import org.efaps.esjp.erp.listener.IOnCreateDocument;
import org.efaps.esjp.erp.util.ERP;
import org.efaps.util.EFapsException;
import org.efaps.util.cache.CacheReloadException;
import org.jfree.util.Log;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO comment!
*
* @author The eFaps Team
*/
@EFapsUUID("e47df65d-4c5e-423f-b2cc-815c3007b19f")
@EFapsApplication("eFapsApp-Commons")
public abstract class CommonDocument_Base
extends AbstractCommon
implements ITypedClass
{
/**
* Logger for this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(CommonDocument.class);
/**
* {@inheritDoc}
*/
@Override
public CIType getCIType()
throws EFapsException
{
return null;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return empty Return
* @throws EFapsException on error
*/
public Return assignAction(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final AbstractCommand command = (AbstractCommand) _parameter.get(ParameterValues.UIOBJECT);
final Set<Instance> instances = new HashSet<>();
if (InstanceUtils.isValid(_parameter.getInstance())) {
instances.add(_parameter.getInstance());
} else {
instances.addAll(getSelectedInstances(_parameter));
}
for (final Instance instance : instances) {
final QueryBuilder queryBldr = new QueryBuilder(command.getTargetCreateType());
queryBldr.addWhereAttrEqValue(command.getTargetConnectAttribute(), instance);
for (final Instance relInst : queryBldr.getQuery().executeWithoutAccessCheck()) {
final PrintQuery print = new PrintQuery(relInst);
print.addAttribute(CIERP.ActionDefinition2DocumentAbstract.FromLinkAbstract,
CIERP.ActionDefinition2DocumentAbstract.ToLinkAbstract,
CIERP.ActionDefinition2DocumentAbstract.Date);
print.executeWithoutAccessCheck();
final Insert insert = new Insert(CIERP.ActionDefinition2DocumentHistorical);
insert.add(CIERP.ActionDefinition2DocumentHistorical.FromLinkAbstract, print.<Long>getAttribute(
CIERP.ActionDefinition2DocumentAbstract.FromLinkAbstract));
insert.add(CIERP.ActionDefinition2DocumentHistorical.ToLinkAbstract, print.<Long>getAttribute(
CIERP.ActionDefinition2DocumentAbstract.ToLinkAbstract));
insert.add(CIERP.ActionDefinition2DocumentHistorical.Date, print.<DateTime>getAttribute(
CIERP.ActionDefinition2DocumentAbstract.Date));
insert.executeWithoutAccessCheck();
new Delete(relInst).execute();
}
if (InstanceUtils.isValid(Instance.get(_parameter.getParameterValue("action")))) {
final Parameter parameter = ParameterUtil.clone(_parameter,
Parameter.ParameterValues.INSTANCE, instance);
final Create create = new Create()
{
@Override
protected void add2basicInsert(final Parameter _parameter,
final Insert _insert)
throws EFapsException
{
super.add2basicInsert(_parameter, _insert);
final Instance actionInst = Instance.get(_parameter.getParameterValue("action"));
if (actionInst.isValid()) {
_insert.add(CIERP.ActionDefinition2ObjectAbstract.FromLinkAbstract, actionInst);
}
}
};
final Instance actionInst = create.basicInsert(parameter);
for (final IOnAction listener : Listener.get().<IOnAction>invoke(IOnAction.class)) {
listener.afterAssign(this, parameter, actionInst);
}
final Map<Status, Status> mapping = getStatusMapping(parameter);
if (!mapping.isEmpty()) {
final PrintQuery print = new PrintQuery(instance);
print.addAttribute(CIERP.DocumentAbstract.StatusAbstract);
print.execute();
final Status status = Status.get(print.<Long>getAttribute(CIERP.DocumentAbstract.StatusAbstract));
if (mapping.containsKey(status)) {
final Update update = new Update(instance);
update.add(CIERP.DocumentAbstract.StatusAbstract, mapping.get(status));
update.execute();
}
}
}
}
return ret;
}
/**
* Validate selected for assign action.
*
* @param _parameter Parameter as passed by the eFaps API
* @return the return
* @throws EFapsException on error
*/
public Return validateSelected4AssignAction(final Parameter _parameter)
throws EFapsException
{
final Return ret = new AccessCheck4UI().check4SelectedOnStatus(_parameter);
if (ret.isEmpty()) {
final List<IWarning> warnings = new ArrayList<>();
warnings.add(new Selected4AssignActionInvalidWarning());
ret.put(ReturnValues.SNIPLETT, WarningUtil.getHtml4Warning(warnings).toString());
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return empty Return
* @throws EFapsException on error
*/
public Return callAction(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
for (final IOnAction listener : Listener.get().<IOnAction>invoke(IOnAction.class)) {
listener.onDocumentUpdate(_parameter, _parameter.getInstance());
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return Return containing access
* @throws EFapsException on error
*/
public Return accessCheck4Action(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Properties properties = ERP.ACTIONDEF.get();
final String key;
if (containsProperty(_parameter, "Key")) {
key = getProperty(_parameter, "Key");
} else {
final Type type = getType4SysConf(_parameter);
if (type != null) {
key = type.getName();
} else {
key = "Default";
}
}
final String accessDef = properties.getProperty(key);
if (accessDef != null) {
String access = getProperty(_parameter, "Access", "NA");
if (access.startsWith("!")) {
access = access.substring(1);
if (!accessDef.equalsIgnoreCase(access)) {
ret.put(ReturnValues.TRUE, true);
}
} else {
if (accessDef.equalsIgnoreCase(access)) {
ret.put(ReturnValues.TRUE, true);
}
}
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return Return containing access
* @throws EFapsException on error
*/
public Return accessCheck4ActionRelation(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final QueryBuilder queryBldr = new QueryBuilder(CIERP.ActionDefinition2DocumentAbstract);
queryBldr.addWhereAttrEqValue(CIERP.ActionDefinition2DocumentAbstract.ToLinkAbstract, _parameter.getInstance());
final InstanceQuery query = queryBldr.getQuery();
if (query.executeWithoutAccessCheck().isEmpty()) {
ret.put(ReturnValues.TRUE, true);
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return scale corrected BigDecimal
* @throws EFapsException on error
*/
public Return setScale4ReadValue(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final Object object = _parameter.get(ParameterValues.OTHERS);
if (object != null && object instanceof BigDecimal) {
int scale = 0;
final Object attr = _parameter.get(ParameterValues.CLASS);
if (attr instanceof Attribute) {
final Type type = ((Attribute) attr).getParent();
final String frmtKey = getProperty(_parameter, "Formatter");
final DecimalFormat formatter;
if ("total".equalsIgnoreCase(frmtKey)) {
formatter = NumberFormatter.get().getFrmt4Total(type.getName());
} else if ("discount".equalsIgnoreCase(frmtKey)) {
formatter = NumberFormatter.get().getFrmt4Discount(type.getName());
} else if ("quantity".equalsIgnoreCase(frmtKey)) {
formatter = NumberFormatter.get().getFrmt4Quantity(type.getName());
} else if ("unit".equalsIgnoreCase(frmtKey)) {
formatter = NumberFormatter.get().getFrmt4UnitPrice(type.getName());
} else if (frmtKey != null) {
formatter = NumberFormatter.get().getFrmt4Key(type.getName(), frmtKey);
} else {
formatter = NumberFormatter.get().getFormatter();
}
if (formatter != null) {
final int scaleTmp = ((BigDecimal) object).scale();
if (scaleTmp > formatter.getMaximumFractionDigits()) {
final BigDecimal decTmp = ((BigDecimal) object).stripTrailingZeros();
if (decTmp.scale() < formatter.getMinimumFractionDigits()) {
scale = formatter.getMinimumFractionDigits();
} else if (decTmp.scale() > formatter.getMaximumFractionDigits()) {
scale = formatter.getMaximumFractionDigits();
} else {
scale = decTmp.scale();
}
} else if (scaleTmp < formatter.getMinimumFractionDigits()) {
scale = formatter.getMinimumFractionDigits();
} else {
scale = scaleTmp;
}
}
}
ret.put(ReturnValues.VALUES, ((BigDecimal) object).setScale(scale, BigDecimal.ROUND_HALF_UP));
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return Sales Person Field Value
* @throws EFapsException on error
*/
public Return getSalesPersonFieldValue(final Parameter _parameter)
throws EFapsException
{
final org.efaps.esjp.common.uiform.Field field = new org.efaps.esjp.common.uiform.Field() {
@Override
public DropDownPosition getDropDownPosition(final Parameter _parameter,
final Object _value,
final Object _option)
throws EFapsException
{
final Map<?, ?> props = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
final IUIValue uiValue = (IUIValue) _parameter.get(ParameterValues.UIOBJECT);
final DropDownPosition pos;
if (TargetMode.EDIT.equals(_parameter.get(ParameterValues.ACCESSMODE))) {
final Long persId = (Long) uiValue.getObject();
pos = new DropDownPosition(_value, _option).setSelected(_value.equals(persId));
} else {
if ("true".equalsIgnoreCase((String) props.get("SelectCurrent"))) {
long persId = 0;
try {
persId = Context.getThreadContext().getPerson().getId();
} catch (final EFapsException e) {
// nothing must be done at all
Field_Base.LOG.error("Catched error", e);
}
pos = new DropDownPosition(_value, _option).setSelected(new Long(persId).equals(_value));
} else {
pos = super.getDropDownPosition(_parameter, _value, _option);
}
}
return pos;
}
@Override
protected void add2QueryBuilder4List(final Parameter _parameter,
final QueryBuilder _queryBldr)
throws EFapsException
{
final Map<?, ?> props = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
final String rolesStr = (String) props.get("Roles");
final String groupsStr = (String) props.get("Groups");
if (rolesStr != null && !rolesStr.isEmpty()) {
final String[] roles = rolesStr.split(";");
final List<Long> roleIds = new ArrayList<>();
for (final String role : roles) {
final Role aRole = Role.get(role);
if (aRole != null) {
roleIds.add(aRole.getId());
}
}
if (!roleIds.isEmpty()) {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Person2Role);
queryBldr.addWhereAttrEqValue(CIAdminUser.Person2Role.UserToLink, roleIds.toArray());
_queryBldr.addWhereAttrInQuery(CIAdminUser.Abstract.ID,
queryBldr.getAttributeQuery(CIAdminUser.Person2Role.UserFromLink));
}
}
if (groupsStr != null && !groupsStr.isEmpty()) {
final String[] groups;
boolean and = true;
if (groupsStr.contains("|")) {
groups = groupsStr.split("\\|");
} else {
groups = groupsStr.split(";");
and = false;
}
final List<Long> groupIds = new ArrayList<>();
for (final String group : groups) {
final Group aGroup = Group.get(group);
if (aGroup != null) {
groupIds.add(aGroup.getId());
}
}
if (!groupIds.isEmpty()) {
if (and) {
for (final Long group : groupIds) {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Person2Group);
queryBldr.addWhereAttrEqValue(CIAdminUser.Person2Group.UserToLink, group);
final AttributeQuery attribute = queryBldr
.getAttributeQuery(CIAdminUser.Person2Group.UserFromLink);
_queryBldr.addWhereAttrInQuery(CIAdminUser.Abstract.ID, attribute);
}
} else {
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Person2Group);
queryBldr.addWhereAttrEqValue(CIAdminUser.Person2Group.UserToLink, groupIds.toArray());
final AttributeQuery attribute = queryBldr
.getAttributeQuery(CIAdminUser.Person2Group.UserFromLink);
_queryBldr.addWhereAttrInQuery(CIAdminUser.Abstract.ID, attribute);
}
}
}
super.add2QueryBuilder4List(_parameter, _queryBldr);
}
};
return field.getOptionListFieldValue(_parameter);
}
/**
* A Script that removes the table rows,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableRemoveScript(final Parameter _parameter,
final String _tableName)
{
return getTableRemoveScript(_parameter, _tableName, false, false);
}
/**
* A Script that removes the table rows,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _onDomReady add onDomReady script part
* @param _wrapInTags wrap in script tags
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableRemoveScript(final Parameter _parameter,
final String _tableName,
final boolean _onDomReady,
final boolean _wrapInTags)
{
return getTableRemoveScript(_parameter, _tableName, _onDomReady, _wrapInTags, false);
}
/**
* A Script that removes the table rows,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _onDomReady add onDomReady script part
* @param _wrapInTags wrap in script tags
* @param _makeUneditable make the table uneditable
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableRemoveScript(final Parameter _parameter,
final String _tableName,
final boolean _onDomReady,
final boolean _wrapInTags,
final boolean _makeUneditable)
{
final StringBuilder ret = new StringBuilder();
if (_wrapInTags) {
ret.append("<script type=\"text/javascript\">\n");
}
if (_onDomReady) {
ret.append("require([\"dojo/domReady!\"], function(){\n");
}
ret.append("require([\"dojo/_base/lang\",\"dojo/dom\", \"dojo/dom-construct\",")
.append("\"dojo/query\",\"dojo/NodeList-traverse\", \"dojo/NodeList-dom\"],")
.append(" function(lang, dom, domConstruct, query){\n")
.append(" var tN = \"").append(_tableName).append("\";\n")
.append(" for (i = 100;i < 10000; i = i + 100) {\n")
.append(" if( lang.exists(\"eFapsTable\" + i) ){\n")
.append(" var tO = window[\"eFapsTable\" + i];\n")
.append(" if (tO.tableName == tN) {\n")
.append(" var tB = dom.byId(tO.bodyID);\n")
.append(" query(\".eFapsTableRemoveRowCell\", tB).parent().forEach(domConstruct.destroy);\n");
if (_makeUneditable) {
ret.append(" query(\"div\", tB).style(\"display\", \"none\");");
}
ret.append(" }\n")
.append(" } else {\n")
.append(" break;\n")
.append(" }\n")
.append(" }\n")
.append("});");
if (_onDomReady) {
ret.append("});\n");
}
if (_wrapInTags) {
ret.append("</script>\n");
}
return ret;
}
/**
* A Script that deactivates the table by hiding the add and remove buttons,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableDeactivateScript(final Parameter _parameter,
final String _tableName)
{
return getTableDeactivateScript(_parameter, _tableName, false, false);
}
/**
* A Script that deactivates the table by hiding the add and remove buttons,
* but lives if functional for editing via script etc.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _onDomReady add onDomReady script part
* @param _wrapInTags wrap in script tags
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableDeactivateScript(final Parameter _parameter,
final String _tableName,
final boolean _onDomReady,
final boolean _wrapInTags)
{
final StringBuilder ret = new StringBuilder();
if (_wrapInTags) {
ret.append("<script type=\"text/javascript\">\n");
}
if (_onDomReady) {
ret.append("require([\"dojo/domReady!\"], function(){\n");
}
ret.append("require([\"dojo/_base/lang\",\"dojo/dom\", \"dojo/query\",\"dojo/NodeList-traverse\", ")
.append("\"dojo/NodeList-dom\"], function(lang, dom, query){\n")
.append(" tableName = \"").append(_tableName).append("\";\n")
.append(" for (i=100;i<10000;i=i+100) {\n")
.append(" if( lang.exists(\"eFapsTable\" + i) ){\n")
.append(" var tO = window[\"eFapsTable\" + i];\n")
.append(" if (tO.tableName == tableName) {\n")
.append(" tableBody = dom.byId(tO.bodyID);\n")
.append(" query(\".eFapsTableRemoveRowCell > *\", tableBody).style({ display:\"none\" });\n")
.append(" query(\"div\", tableBody).at(-1).style(\"display\",\"none\");\n")
.append(" }\n")
.append(" } else {\n")
.append(" break;\n")
.append(" }\n")
.append(" }\n")
.append("});");
if (_onDomReady) {
ret.append("});\n");
}
if (_wrapInTags) {
ret.append("</script>\n");
}
return ret;
}
/**
* A Script adds one new empty Row to the given table.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table the row will be added to
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableAddNewRowScript(final Parameter _parameter,
final String _tableName)
{
return getTableAddNewRowsScript(_parameter, _tableName, null, null);
}
/**
* A Script adds new Rows to the given table and fills it with values.
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _values values to be used
* @param _onComplete script to be added on complete
* @return StringBuilder containing the javascript
*/
protected StringBuilder getTableAddNewRowsScript(final Parameter _parameter,
final String _tableName,
final Collection<Map<String, Object>> _values,
final StringBuilder _onComplete)
{
return getTableAddNewRowsScript(_parameter, _tableName, _values, _onComplete, false, false, null);
}
/**
* Gets the table add new rows script.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName the table name
* @param _values the values
* @param _onComplete the on complete
* @param _onDomReady the on dom ready
* @param _wrapInTags the wrap in tags
* @param _nonEscapeFields the non escape fields
* @return the table add new rows script
*/
protected StringBuilder getTableAddNewRowsScript(final Parameter _parameter,
final String _tableName,
final Collection<Map<String, Object>> _values,
final StringBuilder _onComplete,
final boolean _onDomReady,
final boolean _wrapInTags,
final Set<String> _nonEscapeFields)
{
return getTableAddNewRowsScript(_parameter, _tableName, _values, _onComplete, _onDomReady, _wrapInTags,
_nonEscapeFields, null);
}
/**
* A Script adds new Rows to the given table and fills it with values.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _tableName name of the table to be removed
* @param _values values to be used
* @param _onComplete script to be added on complete
* @param _onDomReady add onDomReady script part
* @param _wrapInTags wrap in script tags
* @param _nonEscapeFields set of fields for which the escape must not apply
* @param _extraParameter the extra parameter
* @return StringBuilder containing the javascript
*/
@SuppressWarnings("checkstyle:ParameterNumber")
protected StringBuilder getTableAddNewRowsScript(final Parameter _parameter,
final String _tableName,
final Collection<Map<String, Object>> _values,
final StringBuilder _onComplete,
final boolean _onDomReady,
final boolean _wrapInTags,
final Set<String> _nonEscapeFields,
final String _extraParameter)
{
final StringBuilder ret = new StringBuilder();
if (_wrapInTags) {
ret.append("<script type=\"text/javascript\">\n");
}
if (_onDomReady) {
ret.append("require([\"dojo/domReady!\"], function(){\n");
}
if (_values == null) {
ret.append(" addNewRows_").append(_tableName).append("(").append(1).append(",function(){\n");
} else {
ret.append(" addNewRows_").append(_tableName).append("(").append(_values.size()).append(",function(){\n")
.append(getSetFieldValuesScript(_parameter, _values, _nonEscapeFields));
}
if (_onComplete != null) {
ret.append(_onComplete);
}
ret.append("\n}, null");
if (_extraParameter != null) {
ret.append(",").append(_extraParameter);
}
ret.append(" );\n");
if (_onDomReady) {
ret.append("\n});\n");
}
if (_wrapInTags) {
ret.append("</script>\n");
}
return ret;
}
/**
* A Script that sets values.
* @param _parameter Parameter as passed by the eFaps API
* @param _values values to be used
* @param _nonEscapeFields set of fields for which the escape must not apply
* @return StringBuilder containing the javascript
*/
protected StringBuilder getSetFieldValuesScript(final Parameter _parameter,
final Collection<Map<String, Object>> _values,
final Set<String> _nonEscapeFields)
{
final StringBuilder ret = new StringBuilder();
int i = 0;
for (final Map<String, Object> values : _values) {
for (final Entry<String, Object> entry : values.entrySet()) {
final String value;
final String label;
if (entry.getValue() instanceof String[] && ((String[]) entry.getValue()).length == 2) {
value = ((String[]) entry.getValue())[0];
label = ((String[]) entry.getValue())[1];
} else {
value = String.valueOf(entry.getValue());
label = null;
}
ret.append(getSetFieldValue(i, entry.getKey(), value, label, _nonEscapeFields == null ? true
: !_nonEscapeFields.contains(entry.getKey()))).append("\n");
}
i++;
}
return ret;
}
/**
* Get a "eFapsSetFieldValue" Javascript line.
* @param _idx index of the field
* @param _fieldName name of the field
* @param _value value
* @return StringBuilder
*/
protected StringBuilder getSetFieldValue(final int _idx,
final String _fieldName,
final String _value)
{
return getSetFieldValue(_idx, _fieldName, _value, null, true);
}
/**
* Get a "eFapsSetFieldValue" Javascript line.
* @param _idx index of the field
* @param _fieldName name of the field
* @param _value value of the field
* @param _label visible value (label) of the field
* @return StringBuilder
*/
protected StringBuilder getSetFieldValue(final int _idx,
final String _fieldName,
final String _value,
final String _label)
{
return getSetFieldValue(_idx, _fieldName, _value, _label, true);
}
/**
* Get a "eFapsSetFieldValue" Javascript line.
* @param _idx index of the field
* @param _fieldName name of the field
* @param _value value
* @param _label shown value
* @param _escape must the value be escaped
* @return StringBuilder
*/
protected StringBuilder getSetFieldValue(final int _idx,
final String _fieldName,
final String _value,
final String _label,
final boolean _escape)
{
final StringBuilder ret = new StringBuilder();
ret.append("eFapsSetFieldValue(").append(_idx).append(",'").append(_fieldName).append("',");
if (_escape) {
ret.append("'").append(StringEscapeUtils.escapeEcmaScript(_value)).append("'");
} else {
ret.append(_value);
}
if (_label != null) {
if (_escape) {
ret.append(",'").append(StringEscapeUtils.escapeEcmaScript(_label)).append("'");
} else {
ret.append(",").append(_label);
}
}
ret.append(");");
return ret;
}
/**
* JavaScript Snipplet that removes from all SELECT with
* <code>fieldname</code> all other options except the one
* identified by the given <code>_idvalue</code>.
* @param _parameter Parameter as passed by the eFaps API
* @param _idvalue value that will be set for the dropdown
* @param _field fieldname
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetDropDownScript(final Parameter _parameter,
final String _field,
final String _idvalue)
throws EFapsException
{
return getSetDropDownScript(_parameter, _field, _idvalue, null);
}
/**
* JavaScript Snipplet that removes from the SELECT with
* <code>fieldname</code> and index <code>_idx</code> (if null from all)
* the other options except the one identified by the given
* <code>_idvalue</code>.
* @param _parameter Parameter as passed by the eFaps API
* @param _idvalue value that will be set for the dropdown
* @param _field fieldname
* @param _idx index
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetDropDownScript(final Parameter _parameter,
final String _field,
final String _idvalue,
final Integer _idx)
throws EFapsException
{
final StringBuilder js = new StringBuilder()
.append("require([\"dojo/query\", \"dojo/dom-construct\",\"dojo/dom-class\"], ")
.append("function(query, domConstruct, domClass) {")
.append("var nl = query(\" select[name='").append(_field).append("']\");");
if (_idx == null) {
js.append("nl.addClass(\"eFapsReadOnly\");")
.append("query(\" select[name='").append(_field).append("'] *\").forEach(function(node){")
.append("if (node.value!='").append(_idvalue).append("') {")
.append("domConstruct.destroy(node);")
.append("}")
.append("});");
} else {
js.append("if (nl[").append(_idx).append("]!=undefined) {")
.append("domClass.add(nl[").append(_idx).append("], \"eFapsReadOnly\");")
.append("query(\"*\", nl[").append(_idx).append("]).forEach(function(node){")
.append("if (node.value!='").append(_idvalue).append("') {")
.append("domConstruct.destroy(node);")
.append("}")
.append("});")
.append("}");
}
js.append("});");
return js;
}
/**
* JavaScript Snipplet that sets all INPUTS or TEXTARES
* with name <code>fieldname</code> to readOnly and assigns class
* eFapsReadOnly.
* @param _parameter Parameter as passed by the eFaps API
* @param _field fieldnames
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetFieldReadOnlyScript(final Parameter _parameter,
final String... _field)
throws EFapsException
{
return getSetFieldReadOnlyScript(_parameter, null, _field);
}
/**
* JavaScript Snipplet that sets INPUTS or TEXTARES
* with name <code>fieldname</code> and Index <code>_idx</code>
* to readOnly and assigns class eFapsReadOnly. If <code>_idx</code> all
* are are set.
* @param _parameter Parameter as passed by the eFaps API
* @param _idx index of the field to be set to readonly
* @param _field fieldnames
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetFieldReadOnlyScript(final Parameter _parameter,
final Integer _idx,
final String... _field)
throws EFapsException
{
return getSetFieldReadOnlyScript(_parameter, _idx, true, _field);
}
/**
* JavaScript Snipplet that sets INPUTS or TEXTARES
* with name <code>fieldname</code> and Index <code>_idx</code>
* to readOnly and assigns class eFapsReadOnly. If <code>_idx</code> all
* are are set.
* @param _parameter Parameter as passed by the eFaps API
* @param _idx index of the field to be set to readonly
* @param _readOnly readonly or not
* @param _field fieldnames
* @return JavaScript
* @throws EFapsException on error
*/
public StringBuilder getSetFieldReadOnlyScript(final Parameter _parameter,
final Integer _idx,
final boolean _readOnly,
final String... _field)
throws EFapsException
{
final StringBuilder js = new StringBuilder();
for (final String field : _field) {
js.append("var nl = query(\" input[name='").append(field).append("'], textarea[name='")
.append(field).append("']\");");
if (_idx == null) {
js.append("nl.forEach(function(node){")
.append("if (node.type===\"hidden\") {")
.append("var pW = registry.getEnclosingWidget(node);")
.append("if (typeof(pW) !== \"undefined\") {")
.append("if (pW.isInstanceOf(AutoComplete) || pW.isInstanceOf(AutoSuggestion)) {")
.append("pW.set('readOnly', ").append(_readOnly).append(");")
.append("}")
.append("}")
.append("} else {")
.append("node.readOnly =").append(_readOnly).append(";")
.append("}")
.append("});\n");
} else {
js.append("if (nl[").append(_idx).append("]!=undefined) {")
.append("nl[").append(_idx).append("].readOnly =").append(_readOnly).append(";")
.append("}\n");
}
}
if (_readOnly) {
js.append("query(\" input[readonly=''], textarea[readonly='']\").addClass(\"eFapsReadOnly\");");
} else {
js.append("query(\".eFapsReadOnly\").forEach(function(_node) {")
.append("if (!_node.readOnly) {")
.append("domClass.remove(_node, \"eFapsReadOnly\");")
.append("}")
.append("});");
}
return InterfaceUtils.wrapInDojoRequire(_parameter, js, DojoLibs.QUERY, DojoLibs.REGISTRY,
DojoLibs.AUTOCOMP, DojoLibs.AUTOSUGG, DojoLibs.DOMCLASS, DojoLibs.NLDOM);
}
/**
* Get a String Array for UoM Field.
* @param _selected selected id
* @param _dimId id of the Dimension
* @return String for UoM DropDown
* @throws CacheReloadException on error
*/
protected String getUoMFieldStr(final long _selected,
final long _dimId)
throws CacheReloadException
{
final Dimension dim = Dimension.get(_dimId);
final StringBuilder js = new StringBuilder();
js.append("new Array('").append(_selected).append("'");
for (final UoM uom : dim.getUoMs()) {
js.append(",'").append(uom.getId()).append("','").append(uom.getName()).append("'");
}
js.append(")");
return js.toString();
}
/**
* Get a String Array for UoM Field.
* @param _dimId id of the Dimension
* @return String for UoM DropDown
* @throws CacheReloadException on error
*/
protected String getUoMFieldStr(final long _dimId)
throws CacheReloadException
{
final Dimension dim = Dimension.get(_dimId);
return getUoMFieldStr(dim.getBaseUoM().getId(), _dimId);
}
/**
* @param _uoMId id of the UoM
* @return Field String
* @throws CacheReloadException on error
*/
protected String getUoMFieldStrByUoM(final long _uoMId)
throws CacheReloadException
{
return getUoMFieldStr(_uoMId, Dimension.getUoM(_uoMId).getDimId());
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _insert insert to add to
* @param _createdDoc document created
* @throws EFapsException on error
*/
protected void addStatus2DocCreate(final Parameter _parameter,
final Insert _insert,
final CreatedDoc _createdDoc)
throws EFapsException
{
Status status = null;
// first check if set via SystemConfiguration if not set lookup the properties
final Properties properties = ERP.DOCSTATUSCREATE.get();
final Type type = getType4DocCreate(_parameter);
if (type != null) {
final String key = properties.getProperty(type.getName() + ".Status");
if (key != null) {
status = Status.find(type.getStatusAttribute().getLink().getUUID(), key);
}
}
if (status == null) {
final List<Status> statusList = getStatusListFromProperties(_parameter);
if (!statusList.isEmpty()) {
status = statusList.get(0);
}
}
if (status != null) {
_insert.add(getType4DocCreate(_parameter).getStatusAttribute(), status);
}
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _update insert to add to
* @param _editDoc document edited
* @throws EFapsException on error
*/
protected void addStatus2DocEdit(final Parameter _parameter,
final Update _update,
final EditedDoc _editDoc)
throws EFapsException
{
final Type type = _update.getInstance().getType();
if (type.isCheckStatus()) {
final String attrName = type.getStatusAttribute().getName();
final String fieldName = getFieldName4Attribute(_parameter, attrName);
final String statusTmp = _parameter.getParameterValue(fieldName);
final Instance inst = Instance.get(statusTmp);
Status status = null;
if (inst.isValid()) {
status = Status.get(inst.getId());
} else {
if (statusTmp != null && !statusTmp.isEmpty()) {
try {
final Long statusId = Long.valueOf(statusTmp);
status = Status.get(statusId);
} catch (final NumberFormatException e) {
Log.warn("Catched NumberFormatException");
}
}
}
if (status != null) {
_update.add(type.getStatusAttribute(), status);
}
}
}
/**
* Get the type used to create the new Payment Document.
* @param _parameter Parameter as passed by the eFaps API
* @return Type use for the insert
* @throws EFapsException on error
*/
protected Type getType4DocCreate(final Parameter _parameter)
throws EFapsException
{
final AbstractCommand command = (AbstractCommand) _parameter.get(ParameterValues.UIOBJECT);
return command.getTargetCreateType();
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _createdDoc document created
* @return the created file
* @throws EFapsException on error
*/
protected File createReport(final Parameter _parameter,
final CreatedDoc _createdDoc)
throws EFapsException
{
File ret = null;
if ((containsProperty(_parameter, "JasperReport") || containsProperty(_parameter, "JasperKey")
|| containsProperty(_parameter, "JasperConfig"))
&& _createdDoc.getInstance() != null && _createdDoc.getInstance().isValid()) {
try {
final StandartReport report = new StandartReport();
_parameter.put(ParameterValues.INSTANCE, _createdDoc.getInstance());
String name = (String) _createdDoc.getValue(CIERP.DocumentAbstract.Name.name);
if (name == null) {
final PrintQuery print = new PrintQuery(_createdDoc.getInstance());
print.addAttribute(CIERP.DocumentAbstract.Name);
print.execute();
name = print.<String>getAttribute(CIERP.DocumentAbstract.Name);
}
final String fileName = DBProperties.getProperty(_createdDoc.getInstance().getType().getLabelKey(),
"es") + "_" + name;
report.setFileName(fileName);
add2Report(_parameter, _createdDoc, report);
ret = report.getFile(_parameter);
ret = new FileUtil().convertPdf(_parameter, ret, fileName);
if (ret != null) {
final InputStream input = new FileInputStream(ret);
final Checkin checkin = new Checkin(_createdDoc.getInstance());
checkin.execute(fileName + "." + report.getMime(_parameter).getExtension(), input,
((Long) ret.length()).intValue());
}
} catch (final FileNotFoundException e) {
CommonDocument_Base.LOG.error("Catched FileNotFoundException", e);
}
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @return the created file
* @throws EFapsException on error
*/
public Return createReport(final Parameter _parameter)
throws EFapsException
{
final Return ret = new Return();
final StandartReport report = new StandartReport();
if (InstanceUtils.isKindOf(_parameter.getInstance(), CIERP.DocumentAbstract)) {
final PrintQuery print = new PrintQuery(_parameter.getInstance());
print.addAttribute(CIERP.DocumentAbstract.Name);
print.execute();
final String name = print.<String>getAttribute(CIERP.DocumentAbstract.Name);
final String fileName = DBProperties.getProperty(_parameter.getInstance().getType().getLabelKey(), "es")
+ "_" + name;
report.setFileName(fileName);
}
add2Report(_parameter, null, report);
File file = report.getFile(_parameter);
if (BooleanUtils.toBoolean(getProperty(_parameter, "Checkin"))) {
try {
file = new FileUtil().convertPdf(_parameter, file, report.getFileName());
if (file != null) {
final InputStream input = new FileInputStream(file);
final Checkin checkin = new Checkin(_parameter.getInstance());
checkin.execute(report.getFileName() + "." + report.getMime(_parameter).getExtension(), input,
((Long) file.length()).intValue());
}
} catch (final FileNotFoundException e) {
CommonDocument_Base.LOG.error("Catched FileNotFoundException", e);
}
}
ret.put(ReturnValues.VALUES, file);
ret.put(ReturnValues.TRUE, true);
return ret;
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _createdDoc document created
* @param _report report
* @throws EFapsException on error
*/
protected void add2Report(final Parameter _parameter,
final CreatedDoc _createdDoc,
final StandartReport _report)
throws EFapsException
{
final String companyName = ERP.COMPANY_NAME.get();
if (companyName != null && !companyName.isEmpty()) {
_report.getJrParameters().put("CompanyName", companyName);
}
final String companyTaxNum = ERP.COMPANY_TAX.get();
if (companyTaxNum != null && !companyTaxNum.isEmpty()) {
_report.getJrParameters().put("CompanyTaxNum", companyTaxNum);
}
final String companyActivity = ERP.COMPANY_ACTIVITY.get();
if (companyActivity != null && !companyActivity.isEmpty()) {
_report.getJrParameters().put("CompanyActivity", companyActivity);
}
final String companyStreet = ERP.COMPANY_STREET.get();
if (companyStreet != null && !companyStreet.isEmpty()) {
_report.getJrParameters().put("CompanyStreet", companyStreet);
}
final String companyRegion = ERP.COMPANY_REGION.get();
if (companyRegion != null && !companyRegion.isEmpty()) {
_report.getJrParameters().put("CompanyRegion", companyRegion);
}
final String companyCity = ERP.COMPANY_CITY.get();
if (companyCity != null && !companyCity.isEmpty()) {
_report.getJrParameters().put("CompanyCity", companyCity);
}
final String companyDistrict = ERP.COMPANY_DISTRICT.get();
if (companyDistrict != null && !companyDistrict.isEmpty()) {
_report.getJrParameters().put("CompanyDistrict", companyDistrict);
}
}
/**
* Method is called in the process of creation of a Document.
* @param _parameter Parameter as passed by the eFaps API
* @param _insert insert to add to
* @param _createdDoc document created
* @throws EFapsException on error
*/
protected void add2DocCreate(final Parameter _parameter,
final Insert _insert,
final CreatedDoc _createdDoc)
throws EFapsException
{
// used by implementation
}
/**
* Method is called in the process of edit of a Document.
* @param _parameter Parameter as passed by the eFaps API
* @param _update update to add to
* @param _editDoc document edited
* @throws EFapsException on error
*/
protected void add2DocEdit(final Parameter _parameter,
final Update _update,
final EditedDoc _editDoc)
throws EFapsException
{
// used by implementation
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _attributeName attributerName the FieldName is wanted for
* @return fieldname
* @throws EFapsException on error
*/
protected String getFieldName4Attribute(final Parameter _parameter,
final String _attributeName)
throws EFapsException
{
return StringUtils.uncapitalize(_attributeName);
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @return new Name
* @throws EFapsException on error
*/
protected String getDocName4Create(final Parameter _parameter)
throws EFapsException
{
//first priority are values from the UserInterface
String ret = _parameter.getParameterValue(getFieldName4Attribute(_parameter, CIERP.DocumentAbstract.Name.name));
if (StringUtils.isEmpty(ret)) {
final Type type = getType4DocCreate(_parameter);
ret = new Naming().fromNumberGenerator(_parameter, type.getName());
}
return ret;
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @return type
* @throws EFapsException on error
*/
protected Type getType4SysConf(final Parameter _parameter)
throws EFapsException
{
return CIERP.DocumentAbstract.getType();
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return rate value
* @throws EFapsException on error
*/
protected BigDecimal getRate(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRate(_parameter, _rateInfo, type.getName());
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return formated rate
* @throws EFapsException on error
*/
protected String getRateFrmt(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRateFrmt(_parameter, _rateInfo, type.getName());
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return rate value for UserInterface
* @throws EFapsException on error
*/
protected BigDecimal getRateUI(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRateUI(_parameter, _rateInfo, type.getName());
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return fromatted rate string for UserInterface
* @throws EFapsException on error
*/
protected String getRateUIFrmt(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRateUIFrmt(_parameter, _rateInfo, type.getName());
}
/**
* Get the name for the document on creation.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _rateInfo rateinfo
* @return formated rate
* @throws EFapsException on error
*/
protected Object[] getRateObject(final Parameter _parameter,
final RateInfo _rateInfo)
throws EFapsException
{
final Type type = getType4SysConf(_parameter);
return RateInfo.getRateObject(_parameter, _rateInfo, type.getName());
}
/**
* @param _parameter Parameter as passed by the eFaps API
* @return new Name
* @throws EFapsException on error
*/
public Return getJavaScript4EditMassiveTable(final Parameter _parameter)
throws EFapsException
{
final Return retVal = new Return();
retVal.put(ReturnValues.SNIPLETT,
getTableDeactivateScript(_parameter, "inventoryTable", true, true).toString());
return retVal;
}
/**
* @param _parameter Parameter as passed from the eFaps API.
* @param _createdDoc CreatedDoc the process must be executed for
* @throws EFapsException on error
*/
public void executeProcess(final Parameter _parameter,
final CreatedDoc _createdDoc)
throws EFapsException
{
final Create create = new Create()
{
@Override
protected void add2ProcessMap(final Parameter _parameter,
final Instance _instance,
final Map<String, Object> _params)
throws EFapsException
{
CommonDocument_Base.this.add2ProcessMap(_parameter, _createdDoc, _params);
}
};
create.executeProcess(_parameter, _createdDoc.getInstance());
}
/**
* Add additional values to the map passed to the process prior to
* execution.
*
* @param _parameter Parameter as passed by the eFasp API
* @param _createdDoc CreatedDoc the process must be executed for
* @param _params Map passed to the Process
* @throws EFapsException on error
*/
protected void add2ProcessMap(final Parameter _parameter,
final CreatedDoc _createdDoc,
final Map<String, Object> _params)
throws EFapsException
{
// to be used by implementation
}
/**
* To start a process on trigger.
* @param _parameter Parameter as passed from the eFaps API.
* @param _instance instance the process must be executed for
* @throws EFapsException on error
*/
public void executeProcess(final Parameter _parameter,
final Instance _instance)
throws EFapsException
{
final Create create = new Create()
{
@Override
protected void add2ProcessMap(final Parameter _parameter,
final Instance _instance,
final Map<String, Object> _params)
throws EFapsException
{
CommonDocument_Base.this.add2ProcessMap(_parameter, _instance, _params);
}
};
create.executeProcess(_parameter, _instance);
}
/**
* Add additional values to the map passed to the process prior to
* execution.
*
* @param _parameter Parameter as passed by the eFasp API
* @param _instance instance the process must be executed for
* @param _params Map passed to the Process
* @throws EFapsException on error
*/
protected void add2ProcessMap(final Parameter _parameter,
final Instance _instance,
final Map<String, Object> _params)
throws EFapsException
{
// to be used by implementation
}
/**
* Add additional values to the map passed to the process prior to
* execution.
*
* @param _parameter Parameter as passed by the eFasp API
* @param _createdDoc CreatedDoc the process must be executed for
* @throws EFapsException on error
*/
public void connect2Object(final Parameter _parameter,
final CreatedDoc _createdDoc)
throws EFapsException
{
final Map<Integer, String> connectTypes = analyseProperty(_parameter, "ConnectType");
if (!connectTypes.isEmpty()) {
final Map<Integer, String> currentLinks = analyseProperty(_parameter, "ConnectCurrentLink");
final Map<Integer, String> foreignLinks = analyseProperty(_parameter, "ConnectForeignLink");
final Map<Integer, String> foreignFields = analyseProperty(_parameter, "ConnectForeignField");
// all must be of the same size
if (connectTypes.size() == currentLinks.size() && foreignLinks.size() == foreignFields.size()
&& connectTypes.size() == foreignLinks.size()) {
for (final Entry<Integer, String> entry: connectTypes.entrySet()) {
final String[] foreigns;
final String foreignField = foreignFields.get(entry.getKey());
if ("CALLINSTANCE".equals(foreignField)) {
foreigns = new String[] { _parameter.getCallInstance().getOid() };
} else {
foreigns = _parameter.getParameterValues(foreignFields.get(entry.getKey()));
}
if (foreigns != null) {
for (final String foreign : foreigns) {
if (!foreign.isEmpty()) {
final String typeStr = entry.getValue();
final Insert insert;
if (isUUID(typeStr)) {
insert = new Insert(UUID.fromString(typeStr));
} else {
insert = new Insert(typeStr);
}
insert.add(currentLinks.get(entry.getKey()), _createdDoc.getInstance());
final Instance inst = Instance.get(foreign);
if (inst.isValid()) {
insert.add(foreignLinks.get(entry.getKey()), inst);
} else {
insert.add(foreignLinks.get(entry.getKey()), foreign);
}
add2connect2Object(_parameter, _createdDoc, insert);
insert.execute();
}
}
}
}
} else {
CommonDocument_Base.LOG.error("The properties must be of the same size!");
}
}
}
/**
* Add additional values to the Update generated by connect definition.
*
* @param _parameter Parameter as passed by the eFasp API
* @param _createdDoc CreatedDoc the process must be executed for
* @param _update update 2 add to
* @throws EFapsException on error
*/
protected void add2connect2Object(final Parameter _parameter,
final CreatedDoc _createdDoc,
final Update _update)
throws EFapsException
{
}
/**
* Update connection 2 object.
*
* @param _parameter the _parameter
* @param _editedDoc the _edited doc
* @throws EFapsException on error
*/
public void updateConnection2Object(final Parameter _parameter,
final EditedDoc _editedDoc)
throws EFapsException
{
final Edit edit = new Edit() {
@Override
protected void add2updateConnection2Object(final Parameter _parameter,
final Update _update)
throws EFapsException
{
super.add2updateConnection2Object(_parameter, _update);
CommonDocument_Base.this.add2updateConnection2Object(_parameter, _editedDoc, _update);
}
};
edit.updateConnection2Object(_parameter, _editedDoc.getInstance());
}
/**
* Add2update connection2 object.
*
* @param _parameter the _parameter
* @param _editedDoc the _edited doc
* @param _update the _update
* @throws EFapsException on error
*/
protected void add2updateConnection2Object(final Parameter _parameter,
final EditedDoc _editedDoc,
final Update _update)
throws EFapsException
{
}
/**
* Method to evaluate the selected row.
*
* @param _parameter paaremter
* @return number of selected row.
*/
public int getSelectedRow(final Parameter _parameter)
{
return InterfaceUtils.getSelectedRow(_parameter);
}
/**
* @param _parameter Parameter as passed by the eFasp API
* @return JavaScript to be used for UI
* @throws EFapsException on error
*/
protected CharSequence getJavaScript4Doc(final Parameter _parameter)
throws EFapsException
{
final StringBuilder ret = new StringBuilder();
for (final IOnCreateDocument listener : Listener.get().<IOnCreateDocument>invoke(IOnCreateDocument.class)) {
ret.append(listener.getJavaScript4Doc(this, _parameter));
}
return ret;
}
/**
* Class is used as the return value for the internal Create methods.
*/
public static class CreatedDoc
{
/**
* Instance of the newly created doc.
*/
private Instance instance;
/**
* Positions of the created Document.
*/
private final List<Instance> positions = new ArrayList<>();
/**
* Map can be used to pass values from one method to another.
*/
private final Map<String, Object> values = new HashMap<>();
/**
*
*/
public CreatedDoc()
{
}
/**
* @param _instance Instance of the Document
*/
public CreatedDoc(final Instance _instance)
{
this.instance = _instance;
}
/**
* Getter method for the instance variable {@link #values}.
*
* @return value of instance variable {@link #values}
*/
public Map<String, Object> getValues()
{
return this.values;
}
/**
* @param _key key
* @return value
*/
public Object getValue(final String _key)
{
return this.values.get(_key);
}
/**
* @param _key key
* @param _value value
*/
public void addValue(final String _key,
final Object _value)
{
this.values.put(_key, _value);
}
/**
* Getter method for the instance variable {@link #instance}.
*
* @return value of instance variable {@link #instance}
*/
public Instance getInstance()
{
return this.instance;
}
/**
* Setter method for instance variable {@link #instance}.
*
* @param _instance value for instance variable {@link #instance}
*/
public void setInstance(final Instance _instance)
{
this.instance = _instance;
}
/**
* Getter method for the instance variable {@link #positions}.
*
* @return value of instance variable {@link #positions}
*/
public List<Instance> getPositions()
{
return this.positions;
}
/**
* @param _instance Instance to add
*/
public void addPosition(final Instance _instance)
{
this.positions.add(_instance);
}
}
/**
* Class is used as the return value for the internal Edit methods.
*/
public static class EditedDoc
extends CreatedDoc
{
/**
* @param _instance Instance the document belongs to
*/
public EditedDoc(final Instance _instance)
{
super(_instance);
}
}
/**
* Warning for not enough Stock.
*/
public static class Selected4AssignActionInvalidWarning
extends AbstractWarning
{
/**
* Constructor.
*/
public Selected4AssignActionInvalidWarning()
{
setError(true);
}
}
}
| - Issue eFaps/eFapsApp-Sales#401: Add the assign action massive to the bin for incoming exchange
| src/main/efaps/ESJP/org/efaps/esjp/erp/CommonDocument_Base.java | - Issue eFaps/eFapsApp-Sales#401: Add the assign action massive to the bin for incoming exchange | <ide><path>rc/main/efaps/ESJP/org/efaps/esjp/erp/CommonDocument_Base.java
<ide> import java.util.Properties;
<ide> import java.util.Set;
<ide> import java.util.UUID;
<add>import java.util.concurrent.TimeUnit;
<ide>
<ide> import org.apache.commons.lang3.BooleanUtils;
<ide> import org.apache.commons.lang3.StringEscapeUtils;
<ide> import org.efaps.ci.CIAdminUser;
<ide> import org.efaps.ci.CIType;
<ide> import org.efaps.db.AttributeQuery;
<add>import org.efaps.db.CachedPrintQuery;
<ide> import org.efaps.db.Checkin;
<ide> import org.efaps.db.Context;
<ide> import org.efaps.db.Delete;
<ide> {
<ide> final Return ret = new Return();
<ide> final AbstractCommand command = (AbstractCommand) _parameter.get(ParameterValues.UIOBJECT);
<add>
<ide> final Set<Instance> instances = new HashSet<>();
<del> if (InstanceUtils.isValid(_parameter.getInstance())) {
<add> if (InstanceUtils.isValid(_parameter.getInstance()) && _parameter.getInstance().getType().isKindOf(command
<add> .getTargetConnectAttribute().getLink())) {
<ide> instances.add(_parameter.getInstance());
<ide> } else {
<ide> instances.addAll(getSelectedInstances(_parameter));
<ide> }
<del> for (final Instance instance : instances) {
<add> for (final Instance inst : instances) {
<add> Instance instance = null;
<add> if (containsProperty(_parameter, "Select4Instance")) {
<add> final String select4Instance = getProperty(_parameter, "Select4Instance");
<add> final PrintQuery print = new CachedPrintQuery(inst, getRequestKey())
<add> .setLifespanUnit(TimeUnit.SECONDS).setLifespan(30);
<add> print.addSelect(select4Instance);
<add> print.executeWithoutAccessCheck();
<add> final Object obj = print.getSelect(select4Instance);
<add> if (obj instanceof Instance) {
<add> instance = (Instance) obj;
<add> }
<add> } else {
<add> instance = inst;
<add> }
<add>
<ide> final QueryBuilder queryBldr = new QueryBuilder(command.getTargetCreateType());
<ide> queryBldr.addWhereAttrEqValue(command.getTargetConnectAttribute(), instance);
<ide> for (final Instance relInst : queryBldr.getQuery().executeWithoutAccessCheck()) { |
|
Java | apache-2.0 | 3edf134f4eb4983115ba15b6079675fe9d75a45a | 0 | Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services | package org.sagebionetworks.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
/**
* @author deflaux
*
*/
public class HttpClientHelper {
/**
* Download the content to a file or stream if it is larger than this length
*/
public static final int MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH = 1024 * 1024;
private static final int DEFAULT_CONNECT_TIMEOUT_MSEC = 500;
private static final int DEFAULT_SOCKET_TIMEOUT_MSEC = 20000;
// Note: Having this 'password' in plaintext is OK because (1) it's a well
// known default for key stores,
// and (2) the keystore (below) contains only public certificates.
private static final String DEFAULT_JAVA_KEYSTORE_PW = "changeit";
private static final String KEYSTORE_NAME = "HttpClientHelperPublicCertsOnly.jks";
/**
* Create a new HTTP client connection factory.
*
* @param verifySSLCertificates
* @return the HTTP client connection factory
*/
public static HttpClient createNewClient(boolean verifySSLCertificates) {
try {
SSLContext ctx = null;
X509HostnameVerifier hostNameVarifier = null;
// Should certificates be checked.
if (verifySSLCertificates) {
ctx = createSecureSSLContext();
hostNameVarifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
} else {
// This will allow any certificate.
ctx = createEasySSLContext();
hostNameVarifier = new AcceptAnyHostName();
}
SchemeSocketFactory ssf = new SSLSocketFactory(ctx,
hostNameVarifier);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, ssf));
// schemeRegistry.register(new Scheme("https", 8443, ssf));
// TODO its unclear how to set a default for the timeout in
// milliseconds
// used when retrieving an
// instance of ManagedClientConnection from the
// ClientConnectionManager
// since parameters are now deprecated for connection managers.
ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(
schemeRegistry);
HttpParams clientParams = new BasicHttpParams();
clientParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
DEFAULT_CONNECT_TIMEOUT_MSEC);
clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT,
DEFAULT_SOCKET_TIMEOUT_MSEC);
return new DefaultHttpClient(connectionManager, clientParams);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (CertificateException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* The resulting SSLContext will validate
*
* @return the SSLContext with validation
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws CertificateException
* @throws IOException
* @throws KeyManagementException
*/
public static SSLContext createSecureSSLContext()
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException, KeyManagementException {
// from
// http://www.coderanch.com/t/372437/java/java/javax-net-ssl-keyStore-system
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keystoreStream = HttpClientHelper.class.getClassLoader()
.getResourceAsStream(KEYSTORE_NAME);
keystore.load(keystoreStream, DEFAULT_JAVA_KEYSTORE_PW.toCharArray());
trustManagerFactory.init(keystore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext ctx = SSLContext.getInstance("TLS"); // was SSL
ctx.init(null, trustManagers, null);
return ctx;
}
/**
* The resulting SSLContext will allow any certificate.
*
* @return the SSLContext that will allow any certificate
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws CertificateException
* @throws IOException
* @throws KeyManagementException
*/
public static SSLContext createEasySSLContext()
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException, KeyManagementException {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null,
new TrustManager[] { new AcceptAnyCertificatManager() }, null);
return sslcontext;
}
/**
* A trust manager that accepts all certificates.
*
* @author jmhill
*
*/
private static class AcceptAnyCertificatManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Oh, I am easy!
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Oh, I am easy!
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
/**
* Accepts any host name.
*
* @author jmhill
*
*/
private static class AcceptAnyHostName implements X509HostnameVerifier {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void verify(String host, X509Certificate cert)
throws SSLException {
// TODO Auto-generated method stub
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts)
throws SSLException {
// TODO Auto-generated method stub
}
}
/**
* Get the Connection timeout on the passed client
*
* @param client
* @param milliseconds
*/
public static void setGlobalConnectionTimeout(HttpClient client,
int milliseconds) {
client.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, milliseconds);
}
/**
* Set the socket timeout (SO_TIMEOUT) in milliseconds, which is the timeout
* for waiting for data or, put differently, a maximum period inactivity
* between two consecutive data packets). A timeout value of zero is
* interpreted as an infinite timeout. This will change the configuration
* for all requests.
*
* @param client
*
* @param milliseconds
*/
public static void setGlobalSocketTimeout(HttpClient client,
int milliseconds) {
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
milliseconds);
}
/**
* Perform a request using the provided Client.
*
* @param client
* @param requestUrl
* @param requestMethod
* @param requestContent
* @param requestHeaders
* @return the response object
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static HttpResponse performRequest(HttpClient client,
String requestUrl, String requestMethod, String requestContent,
Map<String, String> requestHeaders) throws ClientProtocolException,
IOException, HttpClientHelperException {
HttpEntity requestEntity = null;
if (null != requestContent) {
requestEntity = new StringEntity(requestContent);
}
return performEntityRequest(client, requestUrl, requestMethod,
requestEntity, requestHeaders);
}
/**
* Perform a request using the provided Client.
*
* @param client
* @param requestUrl
* @param requestMethod
* @param requestEntity
* @param requestHeaders
* @return the response object
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static HttpResponse performEntityRequest(HttpClient client,
String requestUrl, String requestMethod, HttpEntity requestEntity,
Map<String, String> requestHeaders) throws ClientProtocolException,
IOException, HttpClientHelperException {
HttpRequestBase request = null;
if (requestMethod.equals("GET")) {
request = new HttpGet(requestUrl);
} else if (requestMethod.equals("POST")) {
request = new HttpPost(requestUrl);
if (null != requestEntity) {
((HttpEntityEnclosingRequestBase) request)
.setEntity(requestEntity);
}
} else if (requestMethod.equals("PUT")) {
request = new HttpPut(requestUrl);
if (null != requestEntity) {
((HttpEntityEnclosingRequestBase) request)
.setEntity(requestEntity);
}
} else if (requestMethod.equals("DELETE")) {
request = new HttpDelete(requestUrl);
}
if (null != requestHeaders) {
for (Entry<String, String> header : requestHeaders.entrySet()) {
request.setHeader(header.getKey(), header.getValue());
}
}
HttpResponse response = client.execute(request);
if (300 <= response.getStatusLine().getStatusCode()) {
StringBuilder verboseMessage = new StringBuilder(
"FAILURE: Got HTTP status "
+ response.getStatusLine().getStatusCode()
+ " for " + requestUrl);
// TODO this potentially prints out headers such as sessionToken to
// our logs, consider whether this is a good idea
if ((null != requestHeaders) && (0 < requestHeaders.size())) {
verboseMessage.append("\nHeaders: ");
for (Entry<String, String> entry : requestHeaders.entrySet()) {
verboseMessage.append("\n\t" + entry.getKey() + ": "
+ entry.getValue());
}
}
if (null != requestEntity) {
verboseMessage.append("\nRequest Content: " + requestEntity);
}
String responseBody = (null != response.getEntity()) ? EntityUtils
.toString(response.getEntity()) : null;
verboseMessage.append("\nResponse Content: " + responseBody);
throw new HttpClientHelperException(verboseMessage.toString(),
response);
}
return response;
}
/**
* Get content as a string using the provided HttpClient.
*
* @param client
* @param requestUrl
* @return the content returned in a string
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static String getContent(final HttpClient client,
final String requestUrl) throws ClientProtocolException,
IOException, HttpClientHelperException {
String responseContent = null;
HttpResponse response = HttpClientHelper.performRequest(client,
requestUrl, "GET", null, null);
HttpEntity entity = response.getEntity();
if (null != entity) {
if (MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH < entity
.getContentLength()) {
throw new HttpClientHelperException("Requested content("
+ requestUrl + ") is too large("
+ entity.getContentLength()
+ "), download it to a file instead", response);
}
responseContent = EntityUtils.toString(entity);
}
return responseContent;
}
/**
* Get content as a file using the provided HttpClient
*
* @param client
* @param requestUrl
* @param file
* if null a temp file will be created
* @return the file
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static File getContent(final HttpClient client,
final String requestUrl, File file) throws ClientProtocolException,
IOException, HttpClientHelperException {
if (null == file) {
file = File.createTempFile(HttpClientHelper.class.getName(), "tmp");
}
HttpResponse response = HttpClientHelper.performRequest(client,
requestUrl, "GET", null, null);
HttpEntity fileEntity = response.getEntity();
if (null != fileEntity) {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileEntity.writeTo(fileOutputStream);
fileOutputStream.close();
}
return file;
}
/**
* Post content provided as a string using the provided HttpClient.
*
* @param client
* @param requestUrl
* @param requestContent
* @param requestHeaders
* @return the content returned in a string
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static String postContent(final HttpClient client,
final String requestUrl, final String requestContent,
Map<String, String> requestHeaders) throws ClientProtocolException,
IOException, HttpClientHelperException {
String responseContent = null;
HttpResponse response = HttpClientHelper.performRequest(client,
requestUrl, "POST", requestContent, requestHeaders);
HttpEntity entity = response.getEntity();
if (null != entity) {
if (MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH < entity
.getContentLength()) {
throw new HttpClientHelperException("Requested content("
+ requestUrl + ") is too large("
+ entity.getContentLength()
+ "), download it to a file instead", response);
}
responseContent = EntityUtils.toString(entity);
}
return responseContent;
}
/**
* Post content provided as an InputStream using the provided HttpClient.
*
* @param client
* @param requestUrl
* @param stream
* @param length
* @param requestHeaders
* @return the response, if any
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static String postStream(final HttpClient client,
final String requestUrl, final InputStream stream,
final long length, Map<String, String> requestHeaders)
throws ClientProtocolException, IOException,
HttpClientHelperException {
String responseContent = null;
InputStreamEntity requestEntity = new InputStreamEntity(stream, length);
HttpResponse response = HttpClientHelper.performEntityRequest(client,
requestUrl, "POST", requestEntity, requestHeaders);
HttpEntity entity = response.getEntity();
if (null != entity) {
if (MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH < entity
.getContentLength()) {
throw new HttpClientHelperException("Requested content("
+ requestUrl + ") is too large("
+ entity.getContentLength()
+ "), download it to a file instead", response);
}
responseContent = EntityUtils.toString(entity);
}
return responseContent;
}
/**
* Put content provided as an InputStream using the provided HttpClient.
*
* @param client
* @param requestUrl
* @param stream
* @param length
* @param requestHeaders
* @return the response, if any
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static String putStream(final HttpClient client,
final String requestUrl, final InputStream stream,
final long length, Map<String, String> requestHeaders)
throws ClientProtocolException, IOException,
HttpClientHelperException {
String responseContent = null;
InputStreamEntity requestEntity = new InputStreamEntity(stream, length);
HttpResponse response = HttpClientHelper.performEntityRequest(client,
requestUrl, "PUT", requestEntity, requestHeaders);
HttpEntity entity = response.getEntity();
if (null != entity) {
if (MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH < entity
.getContentLength()) {
throw new HttpClientHelperException("Requested content("
+ requestUrl + ") is too large("
+ entity.getContentLength()
+ "), download it to a file instead", response);
}
responseContent = EntityUtils.toString(entity);
}
return responseContent;
}
/**
* Download to a file using the provided client. Deprecated: use getContent
* instead
*
* @param client
* @param requestUrl
* @param filepath
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
@Deprecated
public static void downloadFile(final HttpClient client,
final String requestUrl, final String filepath)
throws ClientProtocolException, IOException,
HttpClientHelperException {
HttpResponse response = HttpClientHelper.performRequest(client,
requestUrl, "GET", null, null);
HttpEntity fileEntity = response.getEntity();
if (null != fileEntity) {
FileOutputStream fileOutputStream = new FileOutputStream(filepath);
fileEntity.writeTo(fileOutputStream);
fileOutputStream.close();
}
}
/**
* Upload a file using the provided client. This is currently hardcoded to
* do a PUT and pretty specific to S3. Deprecated: use putStream instead.
*
* @param client
* @param requestUrl
* @param filepath
* @param contentType
* @param requestHeaders
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
@Deprecated
public static void uploadFile(final HttpClient client,
final String requestUrl, final String filepath,
final String contentType, Map<String, String> requestHeaders)
throws ClientProtocolException, IOException,
HttpClientHelperException {
HttpPut put = new HttpPut(requestUrl);
FileEntity fileEntity = new FileEntity(new File(filepath), contentType);
put.setEntity(fileEntity);
if (null != requestHeaders) {
for (Entry<String, String> header : requestHeaders.entrySet()) {
put.addHeader(header.getKey(), header.getValue());
}
}
HttpResponse response = client.execute(put);
if (300 <= response.getStatusLine().getStatusCode()) {
String errorMessage = "Request(" + requestUrl + ") failed: "
+ response.getStatusLine().getReasonPhrase();
HttpEntity responseEntity = response.getEntity();
if (null != responseEntity) {
errorMessage += EntityUtils.toString(responseEntity);
}
throw new HttpClientHelperException(errorMessage, response);
}
}
}
| lib/communicationUtilities/src/main/java/org/sagebionetworks/utils/HttpClientHelper.java | package org.sagebionetworks.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
/**
* @author deflaux
*
*/
public class HttpClientHelper {
/**
* Download the content to a file or stream if it is larger than this length
*/
public static final int MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH = 1024 * 1024;
private static final int DEFAULT_CONNECT_TIMEOUT_MSEC = 500;
private static final int DEFAULT_SOCKET_TIMEOUT_MSEC = 2000;
// Note: Having this 'password' in plaintext is OK because (1) it's a well
// known default for key stores,
// and (2) the keystore (below) contains only public certificates.
private static final String DEFAULT_JAVA_KEYSTORE_PW = "changeit";
private static final String KEYSTORE_NAME = "HttpClientHelperPublicCertsOnly.jks";
/**
* Create a new HTTP client connection factory.
*
* @param verifySSLCertificates
* @return the HTTP client connection factory
*/
public static HttpClient createNewClient(boolean verifySSLCertificates) {
try {
SSLContext ctx = null;
X509HostnameVerifier hostNameVarifier = null;
// Should certificates be checked.
if (verifySSLCertificates) {
ctx = createSecureSSLContext();
hostNameVarifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
} else {
// This will allow any certificate.
ctx = createEasySSLContext();
hostNameVarifier = new AcceptAnyHostName();
}
SchemeSocketFactory ssf = new SSLSocketFactory(ctx,
hostNameVarifier);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, ssf));
// schemeRegistry.register(new Scheme("https", 8443, ssf));
// TODO its unclear how to set a default for the timeout in
// milliseconds
// used when retrieving an
// instance of ManagedClientConnection from the
// ClientConnectionManager
// since parameters are now deprecated for connection managers.
ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(
schemeRegistry);
HttpParams clientParams = new BasicHttpParams();
clientParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
DEFAULT_CONNECT_TIMEOUT_MSEC);
clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT,
DEFAULT_SOCKET_TIMEOUT_MSEC);
return new DefaultHttpClient(connectionManager, clientParams);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (CertificateException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* The resulting SSLContext will validate
*
* @return the SSLContext with validation
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws CertificateException
* @throws IOException
* @throws KeyManagementException
*/
public static SSLContext createSecureSSLContext()
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException, KeyManagementException {
// from
// http://www.coderanch.com/t/372437/java/java/javax-net-ssl-keyStore-system
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keystoreStream = HttpClientHelper.class.getClassLoader()
.getResourceAsStream(KEYSTORE_NAME);
keystore.load(keystoreStream, DEFAULT_JAVA_KEYSTORE_PW.toCharArray());
trustManagerFactory.init(keystore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext ctx = SSLContext.getInstance("TLS"); // was SSL
ctx.init(null, trustManagers, null);
return ctx;
}
/**
* The resulting SSLContext will allow any certificate.
*
* @return the SSLContext that will allow any certificate
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws CertificateException
* @throws IOException
* @throws KeyManagementException
*/
public static SSLContext createEasySSLContext()
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException, KeyManagementException {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null,
new TrustManager[] { new AcceptAnyCertificatManager() }, null);
return sslcontext;
}
/**
* A trust manager that accepts all certificates.
*
* @author jmhill
*
*/
private static class AcceptAnyCertificatManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Oh, I am easy!
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Oh, I am easy!
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
/**
* Accepts any host name.
*
* @author jmhill
*
*/
private static class AcceptAnyHostName implements X509HostnameVerifier {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void verify(String host, X509Certificate cert)
throws SSLException {
// TODO Auto-generated method stub
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts)
throws SSLException {
// TODO Auto-generated method stub
}
}
/**
* Get the Connection timeout on the passed client
*
* @param client
* @param milliseconds
*/
public static void setGlobalConnectionTimeout(HttpClient client,
int milliseconds) {
client.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, milliseconds);
}
/**
* Set the socket timeout (SO_TIMEOUT) in milliseconds, which is the timeout
* for waiting for data or, put differently, a maximum period inactivity
* between two consecutive data packets). A timeout value of zero is
* interpreted as an infinite timeout. This will change the configuration
* for all requests.
*
* @param client
*
* @param milliseconds
*/
public static void setGlobalSocketTimeout(HttpClient client,
int milliseconds) {
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
milliseconds);
}
/**
* Perform a request using the provided Client.
*
* @param client
* @param requestUrl
* @param requestMethod
* @param requestContent
* @param requestHeaders
* @return the response object
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static HttpResponse performRequest(HttpClient client,
String requestUrl, String requestMethod, String requestContent,
Map<String, String> requestHeaders) throws ClientProtocolException,
IOException, HttpClientHelperException {
HttpEntity requestEntity = null;
if (null != requestContent) {
requestEntity = new StringEntity(requestContent);
}
return performEntityRequest(client, requestUrl, requestMethod,
requestEntity, requestHeaders);
}
/**
* Perform a request using the provided Client.
*
* @param client
* @param requestUrl
* @param requestMethod
* @param requestEntity
* @param requestHeaders
* @return the response object
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static HttpResponse performEntityRequest(HttpClient client,
String requestUrl, String requestMethod, HttpEntity requestEntity,
Map<String, String> requestHeaders) throws ClientProtocolException,
IOException, HttpClientHelperException {
HttpRequestBase request = null;
if (requestMethod.equals("GET")) {
request = new HttpGet(requestUrl);
} else if (requestMethod.equals("POST")) {
request = new HttpPost(requestUrl);
if (null != requestEntity) {
((HttpEntityEnclosingRequestBase) request)
.setEntity(requestEntity);
}
} else if (requestMethod.equals("PUT")) {
request = new HttpPut(requestUrl);
if (null != requestEntity) {
((HttpEntityEnclosingRequestBase) request)
.setEntity(requestEntity);
}
} else if (requestMethod.equals("DELETE")) {
request = new HttpDelete(requestUrl);
}
if (null != requestHeaders) {
for (Entry<String, String> header : requestHeaders.entrySet()) {
request.setHeader(header.getKey(), header.getValue());
}
}
HttpResponse response = client.execute(request);
if (300 <= response.getStatusLine().getStatusCode()) {
StringBuilder verboseMessage = new StringBuilder(
"FAILURE: Got HTTP status "
+ response.getStatusLine().getStatusCode()
+ " for " + requestUrl);
// TODO this potentially prints out headers such as sessionToken to
// our logs, consider whether this is a good idea
if ((null != requestHeaders) && (0 < requestHeaders.size())) {
verboseMessage.append("\nHeaders: ");
for (Entry<String, String> entry : requestHeaders.entrySet()) {
verboseMessage.append("\n\t" + entry.getKey() + ": "
+ entry.getValue());
}
}
if (null != requestEntity) {
verboseMessage.append("\nRequest Content: " + requestEntity);
}
String responseBody = (null != response.getEntity()) ? EntityUtils
.toString(response.getEntity()) : null;
verboseMessage.append("\nResponse Content: " + responseBody);
throw new HttpClientHelperException(verboseMessage.toString(),
response);
}
return response;
}
/**
* Get content as a string using the provided HttpClient.
*
* @param client
* @param requestUrl
* @return the content returned in a string
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static String getContent(final HttpClient client,
final String requestUrl) throws ClientProtocolException,
IOException, HttpClientHelperException {
String responseContent = null;
HttpResponse response = HttpClientHelper.performRequest(client,
requestUrl, "GET", null, null);
HttpEntity entity = response.getEntity();
if (null != entity) {
if (MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH < entity
.getContentLength()) {
throw new HttpClientHelperException("Requested content("
+ requestUrl + ") is too large("
+ entity.getContentLength()
+ "), download it to a file instead", response);
}
responseContent = EntityUtils.toString(entity);
}
return responseContent;
}
/**
* Get content as a file using the provided HttpClient
*
* @param client
* @param requestUrl
* @param file
* if null a temp file will be created
* @return the file
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static File getContent(final HttpClient client,
final String requestUrl, File file) throws ClientProtocolException,
IOException, HttpClientHelperException {
if (null == file) {
file = File.createTempFile(HttpClientHelper.class.getName(), "tmp");
}
HttpResponse response = HttpClientHelper.performRequest(client,
requestUrl, "GET", null, null);
HttpEntity fileEntity = response.getEntity();
if (null != fileEntity) {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileEntity.writeTo(fileOutputStream);
fileOutputStream.close();
}
return file;
}
/**
* Post content provided as a string using the provided HttpClient.
*
* @param client
* @param requestUrl
* @param requestContent
* @param requestHeaders
* @return the content returned in a string
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static String postContent(final HttpClient client,
final String requestUrl, final String requestContent,
Map<String, String> requestHeaders) throws ClientProtocolException,
IOException, HttpClientHelperException {
String responseContent = null;
HttpResponse response = HttpClientHelper.performRequest(client,
requestUrl, "POST", requestContent, requestHeaders);
HttpEntity entity = response.getEntity();
if (null != entity) {
if (MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH < entity
.getContentLength()) {
throw new HttpClientHelperException("Requested content("
+ requestUrl + ") is too large("
+ entity.getContentLength()
+ "), download it to a file instead", response);
}
responseContent = EntityUtils.toString(entity);
}
return responseContent;
}
/**
* Post content provided as an InputStream using the provided HttpClient.
*
* @param client
* @param requestUrl
* @param stream
* @param length
* @param requestHeaders
* @return the response, if any
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static String postStream(final HttpClient client,
final String requestUrl, final InputStream stream,
final long length, Map<String, String> requestHeaders)
throws ClientProtocolException, IOException,
HttpClientHelperException {
String responseContent = null;
InputStreamEntity requestEntity = new InputStreamEntity(stream, length);
HttpResponse response = HttpClientHelper.performEntityRequest(client,
requestUrl, "POST", requestEntity, requestHeaders);
HttpEntity entity = response.getEntity();
if (null != entity) {
if (MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH < entity
.getContentLength()) {
throw new HttpClientHelperException("Requested content("
+ requestUrl + ") is too large("
+ entity.getContentLength()
+ "), download it to a file instead", response);
}
responseContent = EntityUtils.toString(entity);
}
return responseContent;
}
/**
* Put content provided as an InputStream using the provided HttpClient.
*
* @param client
* @param requestUrl
* @param stream
* @param length
* @param requestHeaders
* @return the response, if any
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
public static String putStream(final HttpClient client,
final String requestUrl, final InputStream stream,
final long length, Map<String, String> requestHeaders)
throws ClientProtocolException, IOException,
HttpClientHelperException {
String responseContent = null;
InputStreamEntity requestEntity = new InputStreamEntity(stream, length);
HttpResponse response = HttpClientHelper.performEntityRequest(client,
requestUrl, "PUT", requestEntity, requestHeaders);
HttpEntity entity = response.getEntity();
if (null != entity) {
if (MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH < entity
.getContentLength()) {
throw new HttpClientHelperException("Requested content("
+ requestUrl + ") is too large("
+ entity.getContentLength()
+ "), download it to a file instead", response);
}
responseContent = EntityUtils.toString(entity);
}
return responseContent;
}
/**
* Download to a file using the provided client. Deprecated: use getContent
* instead
*
* @param client
* @param requestUrl
* @param filepath
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
@Deprecated
public static void downloadFile(final HttpClient client,
final String requestUrl, final String filepath)
throws ClientProtocolException, IOException,
HttpClientHelperException {
HttpResponse response = HttpClientHelper.performRequest(client,
requestUrl, "GET", null, null);
HttpEntity fileEntity = response.getEntity();
if (null != fileEntity) {
FileOutputStream fileOutputStream = new FileOutputStream(filepath);
fileEntity.writeTo(fileOutputStream);
fileOutputStream.close();
}
}
/**
* Upload a file using the provided client. This is currently hardcoded to
* do a PUT and pretty specific to S3. Deprecated: use putStream instead.
*
* @param client
* @param requestUrl
* @param filepath
* @param contentType
* @param requestHeaders
* @throws ClientProtocolException
* @throws IOException
* @throws HttpClientHelperException
*/
@Deprecated
public static void uploadFile(final HttpClient client,
final String requestUrl, final String filepath,
final String contentType, Map<String, String> requestHeaders)
throws ClientProtocolException, IOException,
HttpClientHelperException {
HttpPut put = new HttpPut(requestUrl);
FileEntity fileEntity = new FileEntity(new File(filepath), contentType);
put.setEntity(fileEntity);
if (null != requestHeaders) {
for (Entry<String, String> header : requestHeaders.entrySet()) {
put.addHeader(header.getKey(), header.getValue());
}
}
HttpResponse response = client.execute(put);
if (300 <= response.getStatusLine().getStatusCode()) {
String errorMessage = "Request(" + requestUrl + ") failed: "
+ response.getStatusLine().getReasonPhrase();
HttpEntity responseEntity = response.getEntity();
if (null != responseEntity) {
errorMessage += EntityUtils.toString(responseEntity);
}
throw new HttpClientHelperException(errorMessage, response);
}
}
}
| Change hardcoded default to 20s.
| lib/communicationUtilities/src/main/java/org/sagebionetworks/utils/HttpClientHelper.java | Change hardcoded default to 20s. | <ide><path>ib/communicationUtilities/src/main/java/org/sagebionetworks/utils/HttpClientHelper.java
<ide> public static final int MAX_ALLOWED_DOWNLOAD_TO_STRING_LENGTH = 1024 * 1024;
<ide>
<ide> private static final int DEFAULT_CONNECT_TIMEOUT_MSEC = 500;
<del> private static final int DEFAULT_SOCKET_TIMEOUT_MSEC = 2000;
<add> private static final int DEFAULT_SOCKET_TIMEOUT_MSEC = 20000;
<ide>
<ide> // Note: Having this 'password' in plaintext is OK because (1) it's a well
<ide> // known default for key stores, |
|
Java | mit | c2538895645668ec8b42c3f4eb0080f4a3b0932e | 0 | Team4761/2016-Robot-Code | package org.robockets.stronghold.robot.highgoalshooter;
import org.robockets.stronghold.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* Align the robot horizontally with the target.
*/
public class HorizontalAlign extends Command {
NetworkTable table;
boolean continuous;
/**
* * @param continuos If it should stop when on target.
*/
public HorizontalAlign(boolean continuous) {
requires(Robot.shooter);
this.continuous = continuous;
}
protected void initialize() {
table = NetworkTable.getTable("vision");
}
protected void execute() {
double pixelError = table.getNumber("horiz_offset", 0);
SmartDashboard.putNumber("factorz", SmartDashboard.getNumber("factorz", 0.02));
double factor = SmartDashboard.getNumber("factorz", 0.02); // Or something.
SmartDashboard.putNumber("Setpoint delta", factor * pixelError);
if (table.getNumber("heartbeat", 0) == 1) {
Robot.shooter.setTurnTableAngle(Robot.shooter.turnTableSource.pidGet() + (factor * pixelError));
table.putNumber("heartbeat", 1);
}
}
protected boolean isFinished() {
if (continuous) return Robot.shooter.turnTablePidController.onTarget();
return false;
}
protected void end() {
}
protected void interrupted() {
end();
}
}
| src/org/robockets/stronghold/robot/highgoalshooter/HorizontalAlign.java | package org.robockets.stronghold.robot.highgoalshooter;
import org.robockets.stronghold.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* Align the robot horizontally with the target.
*/
public class HorizontalAlign extends Command {
NetworkTable table;
boolean continuous;
/**
* * @param continuos If it should stop when on target.
*/
public HorizontalAlign(boolean continuous) {
requires(Robot.shooter);
this.continuous = continuous;
}
protected void initialize() {
table = NetworkTable.getTable("vision");
}
protected void execute() {
double pixelError = table.getNumber("horiz_offset", 0);
SmartDashboard.putNumber("factorz", SmartDashboard.getNumber("factorz", 0.02));
double factor = SmartDashboard.getNumber("factorz", 0.02); // Or something.
SmartDashboard.putNumber("Setpoint delta", factor * pixelError);
if (table.getBoolean("heartbeat", false)) {
Robot.shooter.setTurnTableAngle(Robot.shooter.turnTableSource.pidGet() + (factor * pixelError));
table.putBoolean("heartbeat", false);
}
}
protected boolean isFinished() {
if (continuous) return Robot.shooter.turnTablePidController.onTarget();
return false;
}
protected void end() {
}
protected void interrupted() {
end();
}
}
| Make heartbeat work with numbers.
Simon did not anticipate writing booleans to NetworkTables. Hence he is a bum
and is forcing me to use the numbers 0 and 1 the equivalent of false and true.
:frown:
| src/org/robockets/stronghold/robot/highgoalshooter/HorizontalAlign.java | Make heartbeat work with numbers. | <ide><path>rc/org/robockets/stronghold/robot/highgoalshooter/HorizontalAlign.java
<ide> double factor = SmartDashboard.getNumber("factorz", 0.02); // Or something.
<ide>
<ide> SmartDashboard.putNumber("Setpoint delta", factor * pixelError);
<del> if (table.getBoolean("heartbeat", false)) {
<add> if (table.getNumber("heartbeat", 0) == 1) {
<ide> Robot.shooter.setTurnTableAngle(Robot.shooter.turnTableSource.pidGet() + (factor * pixelError));
<del> table.putBoolean("heartbeat", false);
<add> table.putNumber("heartbeat", 1);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 7f8dbea204674ff53d53148d14367e286b406a41 | 0 | joshelser/accumulo,adamjshook/accumulo,mjwall/accumulo,milleruntime/accumulo,dhutchis/accumulo,dhutchis/accumulo,apache/accumulo,ivakegg/accumulo,mjwall/accumulo,phrocker/accumulo-1,adamjshook/accumulo,ctubbsii/accumulo,phrocker/accumulo,keith-turner/accumulo,lstav/accumulo,apache/accumulo,dhutchis/accumulo,wjsl/jaredcumulo,phrocker/accumulo,ivakegg/accumulo,phrocker/accumulo,ctubbsii/accumulo,wjsl/jaredcumulo,milleruntime/accumulo,lstav/accumulo,phrocker/accumulo,wjsl/jaredcumulo,phrocker/accumulo,joshelser/accumulo,apache/accumulo,mikewalch/accumulo,apache/accumulo,joshelser/accumulo,ivakegg/accumulo,ivakegg/accumulo,apache/accumulo,joshelser/accumulo,phrocker/accumulo,phrocker/accumulo,phrocker/accumulo-1,milleruntime/accumulo,keith-turner/accumulo,adamjshook/accumulo,mikewalch/accumulo,milleruntime/accumulo,ctubbsii/accumulo,mjwall/accumulo,mikewalch/accumulo,phrocker/accumulo-1,mjwall/accumulo,apache/accumulo,mikewalch/accumulo,keith-turner/accumulo,mikewalch/accumulo,apache/accumulo,milleruntime/accumulo,lstav/accumulo,dhutchis/accumulo,mikewalch/accumulo,keith-turner/accumulo,milleruntime/accumulo,ivakegg/accumulo,mikewalch/accumulo,lstav/accumulo,wjsl/jaredcumulo,wjsl/jaredcumulo,milleruntime/accumulo,joshelser/accumulo,mjwall/accumulo,ctubbsii/accumulo,adamjshook/accumulo,keith-turner/accumulo,adamjshook/accumulo,lstav/accumulo,phrocker/accumulo-1,adamjshook/accumulo,phrocker/accumulo-1,wjsl/jaredcumulo,phrocker/accumulo-1,mjwall/accumulo,adamjshook/accumulo,ctubbsii/accumulo,dhutchis/accumulo,keith-turner/accumulo,ivakegg/accumulo,adamjshook/accumulo,phrocker/accumulo-1,phrocker/accumulo,joshelser/accumulo,joshelser/accumulo,keith-turner/accumulo,joshelser/accumulo,dhutchis/accumulo,ivakegg/accumulo,ctubbsii/accumulo,phrocker/accumulo,ctubbsii/accumulo,dhutchis/accumulo,lstav/accumulo,wjsl/jaredcumulo,wjsl/jaredcumulo,lstav/accumulo,adamjshook/accumulo,dhutchis/accumulo,mikewalch/accumulo,mjwall/accumulo,dhutchis/accumulo | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.server.tabletserver;
import static org.apache.accumulo.server.problems.ProblemType.TABLET_LOAD;
import java.io.File;
import java.io.IOException;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.impl.TabletType;
import org.apache.accumulo.core.client.impl.Translator;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.constraints.Violations;
import org.apache.accumulo.core.constraints.Constraint.Environment;
import org.apache.accumulo.core.data.Column;
import org.apache.accumulo.core.data.ConstraintViolationSummary;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.data.thrift.InitialMultiScan;
import org.apache.accumulo.core.data.thrift.InitialScan;
import org.apache.accumulo.core.data.thrift.IterInfo;
import org.apache.accumulo.core.data.thrift.MapFileInfo;
import org.apache.accumulo.core.data.thrift.MultiScanResult;
import org.apache.accumulo.core.data.thrift.ScanResult;
import org.apache.accumulo.core.data.thrift.TColumn;
import org.apache.accumulo.core.data.thrift.TKey;
import org.apache.accumulo.core.data.thrift.TKeyExtent;
import org.apache.accumulo.core.data.thrift.TKeyValue;
import org.apache.accumulo.core.data.thrift.TMutation;
import org.apache.accumulo.core.data.thrift.TRange;
import org.apache.accumulo.core.data.thrift.UpdateErrors;
import org.apache.accumulo.core.file.FileUtil;
import org.apache.accumulo.core.iterators.IterationInterruptedException;
import org.apache.accumulo.core.master.MasterNotRunningException;
import org.apache.accumulo.core.master.thrift.Compacting;
import org.apache.accumulo.core.master.thrift.MasterClientService;
import org.apache.accumulo.core.master.thrift.TableInfo;
import org.apache.accumulo.core.master.thrift.TabletLoadState;
import org.apache.accumulo.core.master.thrift.TabletServerStatus;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.SystemPermission;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.core.security.thrift.AuthInfo;
import org.apache.accumulo.core.security.thrift.SecurityErrorCode;
import org.apache.accumulo.core.security.thrift.ThriftSecurityException;
import org.apache.accumulo.core.tabletserver.thrift.ActiveScan;
import org.apache.accumulo.core.tabletserver.thrift.ConstraintViolationException;
import org.apache.accumulo.core.tabletserver.thrift.NoSuchScanIDException;
import org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException;
import org.apache.accumulo.core.tabletserver.thrift.ScanState;
import org.apache.accumulo.core.tabletserver.thrift.ScanType;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.tabletserver.thrift.TabletStats;
import org.apache.accumulo.core.util.AddressUtil;
import org.apache.accumulo.core.util.ByteBufferUtil;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.core.util.ColumnFQ;
import org.apache.accumulo.core.util.Daemon;
import org.apache.accumulo.core.util.LoggingRunnable;
import org.apache.accumulo.core.util.ServerServices;
import org.apache.accumulo.core.util.Stat;
import org.apache.accumulo.core.util.ThriftUtil;
import org.apache.accumulo.core.util.UtilWaitThread;
import org.apache.accumulo.core.util.ServerServices.Service;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.core.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.server.Accumulo;
import org.apache.accumulo.server.ServerConstants;
import org.apache.accumulo.server.client.ClientServiceHandler;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.conf.ServerConfiguration;
import org.apache.accumulo.server.master.state.Assignment;
import org.apache.accumulo.server.master.state.DistributedStoreException;
import org.apache.accumulo.server.master.state.TServerInstance;
import org.apache.accumulo.server.master.state.TabletLocationState;
import org.apache.accumulo.server.master.state.TabletStateStore;
import org.apache.accumulo.server.metrics.AbstractMetricsImpl;
import org.apache.accumulo.server.problems.ProblemReport;
import org.apache.accumulo.server.problems.ProblemReports;
import org.apache.accumulo.server.security.Authenticator;
import org.apache.accumulo.server.security.SecurityConstants;
import org.apache.accumulo.server.security.ZKAuthenticator;
import org.apache.accumulo.server.tabletserver.Tablet.CommitSession;
import org.apache.accumulo.server.tabletserver.Tablet.KVEntry;
import org.apache.accumulo.server.tabletserver.Tablet.LookupResult;
import org.apache.accumulo.server.tabletserver.Tablet.MajorCompactionReason;
import org.apache.accumulo.server.tabletserver.Tablet.ScanBatch;
import org.apache.accumulo.server.tabletserver.Tablet.Scanner;
import org.apache.accumulo.server.tabletserver.Tablet.SplitInfo;
import org.apache.accumulo.server.tabletserver.Tablet.TConstraintViolationException;
import org.apache.accumulo.server.tabletserver.Tablet.TabletClosedException;
import org.apache.accumulo.server.tabletserver.TabletServerResourceManager.TabletResourceManager;
import org.apache.accumulo.server.tabletserver.TabletStatsKeeper.Operation;
import org.apache.accumulo.server.tabletserver.log.LoggerStrategy;
import org.apache.accumulo.server.tabletserver.log.MutationReceiver;
import org.apache.accumulo.server.tabletserver.log.RemoteLogger;
import org.apache.accumulo.server.tabletserver.log.RoundRobinLoggerStrategy;
import org.apache.accumulo.server.tabletserver.log.TabletServerLogger;
import org.apache.accumulo.server.tabletserver.mastermessage.MasterMessage;
import org.apache.accumulo.server.tabletserver.mastermessage.SplitReportMessage;
import org.apache.accumulo.server.tabletserver.mastermessage.TabletStatusMessage;
import org.apache.accumulo.server.tabletserver.metrics.TabletServerMBean;
import org.apache.accumulo.server.tabletserver.metrics.TabletServerMinCMetrics;
import org.apache.accumulo.server.tabletserver.metrics.TabletServerScanMetrics;
import org.apache.accumulo.server.tabletserver.metrics.TabletServerUpdateMetrics;
import org.apache.accumulo.server.trace.TraceFileSystem;
import org.apache.accumulo.server.util.FileSystemMonitor;
import org.apache.accumulo.server.util.Halt;
import org.apache.accumulo.server.util.MapCounter;
import org.apache.accumulo.server.util.MetadataTable;
import org.apache.accumulo.server.util.TServerUtils;
import org.apache.accumulo.server.util.MetadataTable.LogEntry;
import org.apache.accumulo.server.util.TServerUtils.ServerPort;
import org.apache.accumulo.server.util.time.RelativeTime;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.server.zookeeper.IZooReaderWriter;
import org.apache.accumulo.server.zookeeper.TransactionWatcher;
import org.apache.accumulo.server.zookeeper.ZooCache;
import org.apache.accumulo.server.zookeeper.ZooLock;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.accumulo.server.zookeeper.ZooLock.LockLossReason;
import org.apache.accumulo.server.zookeeper.ZooLock.LockWatcher;
import org.apache.accumulo.start.Platform;
import org.apache.accumulo.start.classloader.AccumuloClassLoader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.server.TServer;
import org.apache.zookeeper.KeeperException;
import cloudtrace.instrument.Span;
import cloudtrace.instrument.Trace;
import cloudtrace.instrument.thrift.TraceWrap;
import cloudtrace.thrift.TInfo;
enum ScanRunState {
QUEUED, RUNNING, FINISHED
}
public class TabletServer extends AbstractMetricsImpl implements org.apache.accumulo.server.tabletserver.metrics.TabletServerMBean {
private static final Logger log = Logger.getLogger(TabletServer.class);
private static HashMap<String,Long> prevGcTime = new HashMap<String,Long>();
private static long lastMemorySize = 0;
private static long gcTimeIncreasedCount;
private static AtomicLong scanCount = new AtomicLong();
private static final Class<? extends LoggerStrategy> DEFAULT_LOGGER_STRATEGY = RoundRobinLoggerStrategy.class;
private static final long MAX_TIME_TO_WAIT_FOR_SCAN_RESULT_MILLIS = 1000;
private TabletServerLogger logger;
private LoggerStrategy loggerStrategy;
protected TabletServerMinCMetrics mincMetrics = new TabletServerMinCMetrics();
public TabletServer() {
super();
SimpleTimer.getInstance().schedule(new TimerTask() {
@Override
public void run() {
synchronized (onlineTablets) {
long now = System.currentTimeMillis();
for (Tablet tablet : onlineTablets.values())
try {
tablet.updateRates(now);
} catch (Exception ex) {
log.error(ex, ex);
}
}
}
}, 5000, 5000);
}
private synchronized static void logGCInfo() {
List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans();
Runtime rt = Runtime.getRuntime();
StringBuilder sb = new StringBuilder("gc");
boolean sawChange = false;
long maxIncreaseInCollectionTime = 0;
for (GarbageCollectorMXBean gcBean : gcmBeans) {
Long prevTime = prevGcTime.get(gcBean.getName());
long pt = 0;
if (prevTime != null) {
pt = prevTime;
}
long time = gcBean.getCollectionTime();
if (time - pt != 0) {
sawChange = true;
}
long increaseInCollectionTime = time - pt;
sb.append(String.format(" %s=%,.2f(+%,.2f) secs", gcBean.getName(), time / 1000.0, increaseInCollectionTime / 1000.0));
maxIncreaseInCollectionTime = Math.max(increaseInCollectionTime, maxIncreaseInCollectionTime);
prevGcTime.put(gcBean.getName(), time);
}
long mem = rt.freeMemory();
if (maxIncreaseInCollectionTime == 0) {
gcTimeIncreasedCount = 0;
} else {
gcTimeIncreasedCount++;
if (gcTimeIncreasedCount > 3 && mem < rt.totalMemory() * 0.05) {
log.warn("Running low on memory");
gcTimeIncreasedCount = 0;
}
}
if (mem > lastMemorySize) {
sawChange = true;
}
String sign = "+";
if (mem - lastMemorySize <= 0) {
sign = "";
}
sb.append(String.format(" freemem=%,d(%s%,d) totalmem=%,d", mem, sign, (mem - lastMemorySize), rt.totalMemory()));
if (sawChange) {
log.debug(sb.toString());
}
final long keepAliveTimeout = ServerConfiguration.getSystemConfiguration().getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT);
if (maxIncreaseInCollectionTime > keepAliveTimeout) {
Halt.halt("Garbage collection may be interfering with lock keep-alive. Halting.", -1);
}
lastMemorySize = mem;
}
private TabletStatsKeeper statsKeeper;
private static class Session {
long lastAccessTime;
long startTime;
String user;
String client = TServerUtils.clientAddress.get();
public boolean reserved;
public void cleanup() {}
}
private static class SessionManager {
SecureRandom random;
Map<Long,Session> sessions;
SessionManager() {
random = new SecureRandom();
sessions = new HashMap<Long,Session>();
final long maxIdle = ServerConfiguration.getSystemConfiguration().getTimeInMillis(Property.TSERV_SESSION_MAXIDLE);
TimerTask r = new TimerTask() {
public void run() {
sweep(maxIdle);
}
};
SimpleTimer.getInstance().schedule(r, 0, Math.max(maxIdle / 2, 1000));
}
synchronized long createSession(Session session, boolean reserve) {
long sid = random.nextLong();
while (sessions.containsKey(sid)) {
sid = random.nextLong();
}
sessions.put(sid, session);
session.reserved = reserve;
session.startTime = session.lastAccessTime = System.currentTimeMillis();
return sid;
}
/**
* while a session is reserved, it cannot be canceled or removed
*
* @param sessionId
*/
synchronized Session reserveSession(long sessionId) {
Session session = sessions.get(sessionId);
if (session != null) {
if (session.reserved)
throw new IllegalStateException();
session.reserved = true;
}
return session;
}
synchronized void unreserveSession(Session session) {
if (!session.reserved)
throw new IllegalStateException();
session.reserved = false;
session.lastAccessTime = System.currentTimeMillis();
}
synchronized void unreserveSession(long sessionId) {
Session session = getSession(sessionId);
if (session != null)
unreserveSession(session);
}
synchronized Session getSession(long sessionId) {
Session session = sessions.get(sessionId);
if (session != null)
session.lastAccessTime = System.currentTimeMillis();
return session;
}
Session removeSession(long sessionId) {
Session session = null;
synchronized (this) {
session = sessions.remove(sessionId);
}
// do clean up out side of lock..
if (session != null)
session.cleanup();
return session;
}
private void sweep(long maxIdle) {
ArrayList<Session> sessionsToCleanup = new ArrayList<Session>();
synchronized (this) {
Iterator<Session> iter = sessions.values().iterator();
while (iter.hasNext()) {
Session session = iter.next();
long idleTime = System.currentTimeMillis() - session.lastAccessTime;
if (idleTime > maxIdle && !session.reserved) {
iter.remove();
sessionsToCleanup.add(session);
}
}
}
// do clean up outside of lock
for (Session session : sessionsToCleanup) {
session.cleanup();
}
}
synchronized void removeIfNotAccessed(final long sessionId, long delay) {
Session session = sessions.get(sessionId);
if (session != null) {
final long removeTime = session.lastAccessTime;
TimerTask r = new TimerTask() {
public void run() {
Session sessionToCleanup = null;
synchronized (SessionManager.this) {
Session session2 = sessions.get(sessionId);
if (session2 != null && session2.lastAccessTime == removeTime && !session2.reserved) {
sessions.remove(sessionId);
sessionToCleanup = session2;
}
}
// call clean up outside of lock
if (sessionToCleanup != null)
sessionToCleanup.cleanup();
}
};
SimpleTimer.getInstance().schedule(r, delay);
}
}
public synchronized Map<String,MapCounter<ScanRunState>> getActiveScansPerTable() {
Map<String,MapCounter<ScanRunState>> counts = new HashMap<String,MapCounter<ScanRunState>>();
for (Entry<Long,Session> entry : sessions.entrySet()) {
Session session = entry.getValue();
@SuppressWarnings("rawtypes")
ScanTask nbt = null;
String tableID = null;
if (session instanceof ScanSession) {
ScanSession ss = (ScanSession) session;
nbt = ss.nextBatchTask;
tableID = ss.extent.getTableId().toString();
} else if (session instanceof MultiScanSession) {
MultiScanSession mss = (MultiScanSession) session;
nbt = mss.lookupTask;
tableID = mss.threadPoolExtent.getTableId().toString();
}
if (nbt == null)
continue;
ScanRunState srs = nbt.getScanRunState();
if (nbt == null || srs == ScanRunState.FINISHED)
continue;
MapCounter<ScanRunState> stateCounts = counts.get(tableID);
if (stateCounts == null) {
stateCounts = new MapCounter<ScanRunState>();
counts.put(tableID, stateCounts);
}
stateCounts.increment(srs, 1);
}
return counts;
}
public synchronized List<ActiveScan> getActiveScans() {
ArrayList<ActiveScan> activeScans = new ArrayList<ActiveScan>();
long ct = System.currentTimeMillis();
for (Entry<Long,Session> entry : sessions.entrySet()) {
Session session = entry.getValue();
if (session instanceof ScanSession) {
ScanSession ss = (ScanSession) session;
ScanState state = ScanState.RUNNING;
ScanTask<ScanBatch> nbt = ss.nextBatchTask;
if (nbt == null) {
state = ScanState.IDLE;
} else {
switch (nbt.getScanRunState()) {
case QUEUED:
state = ScanState.QUEUED;
break;
case FINISHED:
state = ScanState.IDLE;
break;
}
}
activeScans.add(new ActiveScan(ss.client, ss.user, ss.extent.getTableId().toString(), ct - ss.startTime, ct - ss.lastAccessTime, ScanType.SINGLE,
state, ss.extent.toThrift(), Translator.translate(ss.columnSet, Translator.CT), ss.ssiList, ss.ssio));
} else if (session instanceof MultiScanSession) {
MultiScanSession mss = (MultiScanSession) session;
ScanState state = ScanState.RUNNING;
ScanTask<MultiScanResult> nbt = mss.lookupTask;
if (nbt == null) {
state = ScanState.IDLE;
} else {
switch (nbt.getScanRunState()) {
case QUEUED:
state = ScanState.QUEUED;
break;
case FINISHED:
state = ScanState.IDLE;
break;
}
}
activeScans.add(new ActiveScan(mss.client, mss.user, mss.threadPoolExtent.getTableId().toString(), ct - mss.startTime, ct - mss.lastAccessTime,
ScanType.BATCH, state, mss.threadPoolExtent.toThrift(), Translator.translate(mss.columnSet, Translator.CT), mss.ssiList, mss.ssio));
}
}
return activeScans;
}
}
static class TservConstraintEnv implements Environment {
private AuthInfo credentials;
private Authenticator authenticator;
private Authorizations auths;
private KeyExtent ke;
TservConstraintEnv(Authenticator authenticator, AuthInfo credentials) {
this.authenticator = authenticator;
this.credentials = credentials;
}
void setExtent(KeyExtent ke) {
this.ke = ke;
}
@Override
public KeyExtent getExtent() {
return ke;
}
@Override
public String getUser() {
return credentials.user;
}
@Override
public Authorizations getAuthorizations() {
if (auths == null)
try {
this.auths = authenticator.getUserAuthorizations(credentials, getUser());
} catch (AccumuloSecurityException e) {
throw new RuntimeException(e);
}
return auths;
}
}
private abstract class ScanTask<T> implements RunnableFuture<T> {
protected AtomicBoolean interruptFlag;
protected ArrayBlockingQueue<Object> resultQueue;
protected AtomicInteger state;
protected AtomicReference<ScanRunState> runState;
private static final int INITIAL = 1;
private static final int ADDED = 2;
private static final int CANCELED = 3;
ScanTask() {
interruptFlag = new AtomicBoolean(false);
runState = new AtomicReference<ScanRunState>(ScanRunState.QUEUED);
state = new AtomicInteger(INITIAL);
resultQueue = new ArrayBlockingQueue<Object>(1);
}
protected void addResult(Object o) {
if (state.compareAndSet(INITIAL, ADDED))
resultQueue.add(o);
else if (state.get() == ADDED)
throw new IllegalStateException("Tried to add more than one result");
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (!mayInterruptIfRunning)
throw new IllegalArgumentException("Cancel will always attempt to interupt running next batch task");
if (state.get() == CANCELED)
return true;
if (state.compareAndSet(INITIAL, CANCELED)) {
interruptFlag.set(true);
resultQueue = null;
return true;
}
return false;
}
@Override
public T get() throws InterruptedException, ExecutionException {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
ArrayBlockingQueue<Object> localRQ = resultQueue;
if (state.get() == CANCELED)
throw new CancellationException();
if (localRQ == null && state.get() == ADDED)
throw new IllegalStateException("Tried to get result twice");
Object r = localRQ.poll(timeout, unit);
// could have been canceled while waiting
if (state.get() == CANCELED) {
if (r != null)
throw new IllegalStateException("Nothing should have been added when in canceled state");
throw new CancellationException();
}
if (r == null)
throw new TimeoutException();
// make this method stop working now that something is being
// returned
resultQueue = null;
if (r instanceof Throwable)
throw new ExecutionException((Throwable) r);
return (T) r;
}
@Override
public boolean isCancelled() {
return state.get() == CANCELED;
}
@Override
public boolean isDone() {
return runState.get().equals(ScanRunState.FINISHED);
}
public ScanRunState getScanRunState() {
return runState.get();
}
}
private static class UpdateSession extends Session {
public Tablet currentTablet;
public MapCounter<Tablet> successfulCommits = new MapCounter<Tablet>();
Map<KeyExtent,Long> failures = new HashMap<KeyExtent,Long>();
List<KeyExtent> authFailures = new ArrayList<KeyExtent>();
public Violations violations;
public AuthInfo credentials;
public long totalUpdates = 0;
public long flushTime = 0;
Stat prepareTimes = new Stat();
Stat walogTimes = new Stat();
Stat commitTimes = new Stat();
Stat authTimes = new Stat();
public Map<Tablet,List<Mutation>> queuedMutations = new HashMap<Tablet,List<Mutation>>();
public long queuedMutationSize = 0;
TservConstraintEnv cenv = null;
}
private static class ScanSession extends Session {
public KeyExtent extent;
public HashSet<Column> columnSet;
public List<IterInfo> ssiList;
public Map<String,Map<String,String>> ssio;
public long entriesReturned = 0;
public Stat nbTimes = new Stat();
public long batchCount = 0;
public volatile ScanTask<ScanBatch> nextBatchTask;
public AtomicBoolean interruptFlag;
public Scanner scanner;
@Override
public void cleanup() {
try {
if (nextBatchTask != null)
nextBatchTask.cancel(true);
} finally {
if (scanner != null)
scanner.close();
}
}
}
private static class MultiScanSession extends Session {
HashSet<Column> columnSet;
Map<KeyExtent,List<Range>> queries;
public List<IterInfo> ssiList;
public Map<String,Map<String,String>> ssio;
public Authorizations auths;
// stats
int numRanges;
int numTablets;
int numEntries;
long totalLookupTime;
public volatile ScanTask<MultiScanResult> lookupTask;
public KeyExtent threadPoolExtent;
@Override
public void cleanup() {
if (lookupTask != null)
lookupTask.cancel(true);
}
}
/**
* This little class keeps track of writes in progress and allows readers to wait for writes that started before the read. It assumes that the operation ids
* are monotonically increasing.
*
*/
static class WriteTracker {
private static AtomicLong operationCounter = new AtomicLong(1);
private Map<TabletType,TreeSet<Long>> inProgressWrites = new EnumMap<TabletType,TreeSet<Long>>(TabletType.class);
WriteTracker() {
for (TabletType ttype : TabletType.values()) {
inProgressWrites.put(ttype, new TreeSet<Long>());
}
}
synchronized long startWrite(TabletType ttype) {
long operationId = operationCounter.getAndIncrement();
inProgressWrites.get(ttype).add(operationId);
return operationId;
}
synchronized void finishWrite(long operationId) {
if (operationId == -1)
return;
boolean removed = false;
for (TabletType ttype : TabletType.values()) {
removed = inProgressWrites.get(ttype).remove(operationId);
if (removed)
break;
}
if (!removed) {
throw new IllegalArgumentException("Attempted to finish write not in progress, operationId " + operationId);
}
this.notifyAll();
}
synchronized void waitForWrites(TabletType ttype) {
long operationId = operationCounter.getAndIncrement();
while (inProgressWrites.get(ttype).floor(operationId) != null) {
try {
this.wait();
} catch (InterruptedException e) {
log.error(e, e);
}
}
}
public long startWrite(Set<Tablet> keySet) {
if (keySet.size() == 0)
return -1;
ArrayList<KeyExtent> extents = new ArrayList<KeyExtent>(keySet.size());
for (Tablet tablet : keySet)
extents.add(tablet.getExtent());
return startWrite(TabletType.type(extents));
}
}
TransactionWatcher watcher = new TransactionWatcher();
private class ThriftClientHandler extends ClientServiceHandler implements TabletClientService.Iface {
SessionManager sessionManager;
AccumuloConfiguration acuConf = ServerConfiguration.getSystemConfiguration();
TabletServerUpdateMetrics updateMetrics = new TabletServerUpdateMetrics();
TabletServerScanMetrics scanMetrics = new TabletServerScanMetrics();
WriteTracker writeTracker = new WriteTracker();
ThriftClientHandler() {
super(watcher);
log.debug(ThriftClientHandler.class.getName() + " created");
sessionManager = new SessionManager();
// Register the metrics MBean
try {
updateMetrics.register();
scanMetrics.register();
} catch (Exception e) {
log.error("Exception registering MBean with MBean Server", e);
}
}
@Override
public List<TKeyExtent> bulkImport(TInfo tinfo, AuthInfo credentials, long tid, Map<TKeyExtent,Map<String,MapFileInfo>> files, boolean setTime)
throws ThriftSecurityException {
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
ArrayList<TKeyExtent> failures = new ArrayList<TKeyExtent>();
for (Entry<TKeyExtent,Map<String,MapFileInfo>> entry : files.entrySet()) {
TKeyExtent tke = entry.getKey();
Map<String,MapFileInfo> fileMap = entry.getValue();
Tablet importTablet = onlineTablets.get(new KeyExtent(tke));
if (importTablet == null) {
failures.add(tke);
} else {
try {
importTablet.importMapFiles(tid, fileMap, setTime);
} catch (IOException ioe) {
log.info("file not imported: " + ioe.getMessage());
failures.add(tke);
}
}
}
return failures;
}
private class NextBatchTask extends ScanTask<ScanBatch> {
private long scanID;
NextBatchTask(long scanID, AtomicBoolean interruptFlag) {
this.scanID = scanID;
this.interruptFlag = interruptFlag;
if (interruptFlag.get())
cancel(true);
}
@Override
public void run() {
ScanSession scanSession = (ScanSession) sessionManager.getSession(scanID);
try {
runState.set(ScanRunState.RUNNING);
if (isCancelled() || scanSession == null)
return;
Tablet tablet = onlineTablets.get(scanSession.extent);
if (tablet == null) {
addResult(new org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException(scanSession.extent.toThrift()));
return;
}
long t1 = System.currentTimeMillis();
ScanBatch batch = scanSession.scanner.read();
long t2 = System.currentTimeMillis();
scanSession.nbTimes.addStat(t2 - t1);
// there should only be one thing on the queue at a time, so
// it should be ok to call add()
// instead of put()... if add() fails because queue is at
// capacity it means there is code
// problem somewhere
addResult(batch);
} catch (TabletClosedException e) {
addResult(new org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException(scanSession.extent.toThrift()));
} catch (IterationInterruptedException iie) {
if (!isCancelled()) {
log.warn("Iteration interrupted, when scan not cancelled", iie);
addResult(iie);
}
} catch (TooManyFilesException tmfe) {
addResult(tmfe);
} catch (Throwable e) {
log.warn("exception while scanning tablet " + scanSession.extent, e);
addResult(e);
} finally {
runState.set(ScanRunState.FINISHED);
}
}
}
private class LookupTask extends ScanTask<MultiScanResult> {
private long scanID;
LookupTask(long scanID) {
this.scanID = scanID;
}
@Override
public void run() {
MultiScanSession session = (MultiScanSession) sessionManager.getSession(scanID);
try {
runState.set(ScanRunState.RUNNING);
if (isCancelled() || session == null)
return;
long maxResultsSize = acuConf.getMemoryInBytes(Property.TABLE_SCAN_MAXMEM);
long bytesAdded = 0;
long maxScanTime = 4000;
long startTime = System.currentTimeMillis();
ArrayList<KVEntry> results = new ArrayList<KVEntry>();
Map<KeyExtent,List<Range>> failures = new HashMap<KeyExtent,List<Range>>();
ArrayList<KeyExtent> fullScans = new ArrayList<KeyExtent>();
KeyExtent partScan = null;
Key partNextKey = null;
boolean partNextKeyInclusive = false;
Iterator<Entry<KeyExtent,List<Range>>> iter = session.queries.entrySet().iterator();
// check the time so that the read ahead thread is not
// monopolized
while (iter.hasNext() && bytesAdded < maxResultsSize && (System.currentTimeMillis() - startTime) < maxScanTime) {
Entry<KeyExtent,List<Range>> entry = iter.next();
iter.remove();
// check that tablet server is serving requested tablet
Tablet tablet = onlineTablets.get(entry.getKey());
if (tablet == null) {
failures.put(entry.getKey(), entry.getValue());
continue;
}
LookupResult lookupResult;
try {
// do the following check to avoid a race condition
// between setting false below and the task being
// canceled
if (isCancelled())
interruptFlag.set(true);
lookupResult = tablet.lookup(entry.getValue(), session.columnSet, session.auths, results, maxResultsSize - bytesAdded, session.ssiList,
session.ssio, interruptFlag);
// if the tablet was closed it it possible that the
// interrupt flag was set.... do not want it set for
// the next
// lookup
interruptFlag.set(false);
} catch (IOException e) {
log.warn("lookup failed for tablet " + entry.getKey(), e);
throw new RuntimeException(e);
}
bytesAdded += lookupResult.bytesAdded;
if (lookupResult.unfinishedRanges.size() > 0) {
if (lookupResult.closed) {
failures.put(entry.getKey(), lookupResult.unfinishedRanges);
} else {
session.queries.put(entry.getKey(), lookupResult.unfinishedRanges);
partScan = entry.getKey();
partNextKey = lookupResult.unfinishedRanges.get(0).getStartKey();
partNextKeyInclusive = lookupResult.unfinishedRanges.get(0).isStartKeyInclusive();
}
} else {
fullScans.add(entry.getKey());
}
}
long finishTime = System.currentTimeMillis();
session.totalLookupTime += (finishTime - startTime);
session.numEntries += results.size();
// convert everything to thrift before adding result
List<TKeyValue> retResults = new ArrayList<TKeyValue>();
for (KVEntry entry : results)
retResults.add(new TKeyValue(entry.key.toThrift(), ByteBuffer.wrap(entry.value)));
Map<TKeyExtent,List<TRange>> retFailures = Translator.translate(failures, Translator.KET, new Translator.ListTranslator<Range,TRange>(Translator.RT));
List<TKeyExtent> retFullScans = Translator.translate(fullScans, Translator.KET);
TKeyExtent retPartScan = null;
TKey retPartNextKey = null;
if (partScan != null) {
retPartScan = partScan.toThrift();
retPartNextKey = partNextKey.toThrift();
}
// add results to queue
addResult(new MultiScanResult(retResults, retFailures, retFullScans, retPartScan, retPartNextKey, partNextKeyInclusive, session.queries.size() != 0));
} catch (IterationInterruptedException iie) {
if (!isCancelled()) {
log.warn("Iteration interrupted, when scan not cancelled", iie);
addResult(iie);
}
} catch (Throwable e) {
log.warn("exception while doing multi-scan ", e);
addResult(e);
} finally {
runState.set(ScanRunState.FINISHED);
}
}
}
@Override
public InitialScan startScan(TInfo tinfo, AuthInfo credentials, TKeyExtent textent, TRange range, List<TColumn> columns, int batchSize,
List<IterInfo> ssiList, Map<String,Map<String,String>> ssio, List<ByteBuffer> authorizations, boolean waitForWrites, boolean isolated)
throws NotServingTabletException, ThriftSecurityException, org.apache.accumulo.core.tabletserver.thrift.TooManyFilesException {
Authorizations userauths = null;
try {
if (!authenticator.hasTablePermission(credentials, credentials.user, new String(textent.getTable()), TablePermission.READ))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
userauths = authenticator.getUserAuthorizations(credentials, credentials.user);
for (ByteBuffer auth : authorizations)
if (!userauths.contains(ByteBufferUtil.toBytes(auth)))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.BAD_AUTHORIZATIONS);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
scanCount.addAndGet(1);
KeyExtent extent = new KeyExtent(textent);
// wait for any writes that are in flight.. this done to ensure
// consistency across client restarts... assume a client writes
// to accumulo and dies while waiting for a confirmation from
// accumulo... the client process restarts and tries to read
// data from accumulo making the assumption that it will get
// any writes previously made... however if the server side thread
// processing the write from the dead client is still in progress,
// the restarted client may not see the write unless we wait here.
// this behavior is very important when the client is reading the
// !METADATA table
if (waitForWrites)
writeTracker.waitForWrites(TabletType.type(extent));
Tablet tablet = onlineTablets.get(extent);
if (tablet == null)
throw new NotServingTabletException(textent);
ScanSession scanSession = new ScanSession();
scanSession.user = credentials.user;
scanSession.extent = new KeyExtent(extent);
scanSession.columnSet = new HashSet<Column>();
scanSession.ssiList = ssiList;
scanSession.ssio = ssio;
scanSession.interruptFlag = new AtomicBoolean();
for (TColumn tcolumn : columns) {
scanSession.columnSet.add(new Column(tcolumn));
}
scanSession.scanner = tablet.createScanner(new Range(range), batchSize, scanSession.columnSet, new Authorizations(authorizations), ssiList, ssio,
isolated, scanSession.interruptFlag);
long sid = sessionManager.createSession(scanSession, true);
ScanResult scanResult;
try {
scanResult = continueScan(tinfo, sid, scanSession);
} catch (NoSuchScanIDException e) {
log.error("The impossible happened", e);
throw new RuntimeException();
} finally {
sessionManager.unreserveSession(sid);
}
return new InitialScan(sid, scanResult);
}
@Override
public ScanResult continueScan(TInfo tinfo, long scanID) throws NoSuchScanIDException, NotServingTabletException,
org.apache.accumulo.core.tabletserver.thrift.TooManyFilesException {
ScanSession scanSession = (ScanSession) sessionManager.reserveSession(scanID);
if (scanSession == null) {
throw new NoSuchScanIDException();
}
try {
return continueScan(tinfo, scanID, scanSession);
} finally {
sessionManager.unreserveSession(scanSession);
}
}
private ScanResult continueScan(TInfo tinfo, long scanID, ScanSession scanSession) throws NoSuchScanIDException, NotServingTabletException,
org.apache.accumulo.core.tabletserver.thrift.TooManyFilesException {
if (scanSession.nextBatchTask == null) {
scanSession.nextBatchTask = new NextBatchTask(scanID, scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, scanSession.nextBatchTask);
}
ScanBatch bresult;
try {
bresult = scanSession.nextBatchTask.get(MAX_TIME_TO_WAIT_FOR_SCAN_RESULT_MILLIS, TimeUnit.MILLISECONDS);
scanSession.nextBatchTask = null;
} catch (ExecutionException e) {
sessionManager.removeSession(scanID);
if (e.getCause() instanceof NotServingTabletException)
throw (NotServingTabletException) e.getCause();
else if (e.getCause() instanceof TooManyFilesException)
throw new org.apache.accumulo.core.tabletserver.thrift.TooManyFilesException(scanSession.extent.toThrift());
else
throw new RuntimeException(e);
} catch (CancellationException ce) {
sessionManager.removeSession(scanID);
Tablet tablet = onlineTablets.get(scanSession.extent);
if (tablet == null || tablet.isClosed())
throw new NotServingTabletException(scanSession.extent.toThrift());
else
throw new NoSuchScanIDException();
} catch (TimeoutException e) {
List<TKeyValue> param = Collections.emptyList();
long timeout = acuConf.getTimeInMillis(Property.TSERV_CLIENT_TIMEOUT);
sessionManager.removeIfNotAccessed(scanID, timeout);
return new ScanResult(param, true);
} catch (Throwable t) {
sessionManager.removeSession(scanID);
log.warn("Failed to get next batch", t);
throw new RuntimeException(t);
}
ScanResult scanResult = new ScanResult(Key.compress(bresult.results), bresult.more);
scanSession.entriesReturned += scanResult.results.size();
scanSession.batchCount++;
if (scanResult.more && scanSession.batchCount > 3) {
// start reading next batch while current batch is transmitted
// to client
scanSession.nextBatchTask = new NextBatchTask(scanID, scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, scanSession.nextBatchTask);
}
if (!scanResult.more)
closeScan(tinfo, scanID);
return scanResult;
}
@Override
public void closeScan(TInfo tinfo, long scanID) {
ScanSession ss = (ScanSession) sessionManager.removeSession(scanID);
if (ss != null) {
long t2 = System.currentTimeMillis();
log.debug(String.format("ScanSess tid %s %s %,d entries in %.2f secs, nbTimes = [%s] ", TServerUtils.clientAddress.get(), ss.extent.getTableId()
.toString(), ss.entriesReturned, (t2 - ss.startTime) / 1000.0, ss.nbTimes.toString()));
if (scanMetrics.isEnabled()) {
scanMetrics.add(TabletServerScanMetrics.scan, t2 - ss.startTime);
scanMetrics.add(TabletServerScanMetrics.resultSize, ss.entriesReturned);
}
}
}
@Override
public InitialMultiScan startMultiScan(TInfo tinfo, AuthInfo credentials, Map<TKeyExtent,List<TRange>> tbatch, List<TColumn> tcolumns,
List<IterInfo> ssiList, Map<String,Map<String,String>> ssio, List<ByteBuffer> authorizations, boolean waitForWrites) throws ThriftSecurityException {
// find all of the tables that need to be scanned
HashSet<String> tables = new HashSet<String>();
for (TKeyExtent keyExtent : tbatch.keySet()) {
tables.add(new String(keyExtent.getTable()));
}
// check if user has permission to the tables
Authorizations userauths = null;
try {
for (String table : tables)
if (!authenticator.hasTablePermission(credentials, credentials.user, table, TablePermission.READ))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
userauths = authenticator.getUserAuthorizations(credentials, credentials.user);
for (ByteBuffer auth : authorizations)
if (!userauths.contains(ByteBufferUtil.toBytes(auth)))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.BAD_AUTHORIZATIONS);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
KeyExtent threadPoolExtent = null;
Map<KeyExtent,List<Range>> batch = Translator.translate(tbatch, Translator.TKET, new Translator.ListTranslator<TRange,Range>(Translator.TRT));
for (KeyExtent keyExtent : batch.keySet()) {
if (threadPoolExtent == null) {
threadPoolExtent = keyExtent;
} else if (keyExtent.equals(Constants.ROOT_TABLET_EXTENT)) {
throw new IllegalArgumentException("Cannot batch query root tablet with other tablets " + threadPoolExtent + " " + keyExtent);
} else if (keyExtent.getTableId().toString().equals(Constants.METADATA_TABLE_ID)
&& !threadPoolExtent.getTableId().toString().equals(Constants.METADATA_TABLE_ID)) {
throw new IllegalArgumentException("Cannot batch query !METADATA and non !METADATA tablets " + threadPoolExtent + " " + keyExtent);
}
}
if (waitForWrites)
writeTracker.waitForWrites(TabletType.type(batch.keySet()));
MultiScanSession mss = new MultiScanSession();
mss.user = credentials.user;
mss.queries = batch;
mss.columnSet = new HashSet<Column>(tcolumns.size());
mss.ssiList = ssiList;
mss.ssio = ssio;
mss.auths = new Authorizations(authorizations);
mss.numTablets = batch.size();
for (List<Range> ranges : batch.values()) {
mss.numRanges += ranges.size();
}
for (TColumn tcolumn : tcolumns)
mss.columnSet.add(new Column(tcolumn));
mss.threadPoolExtent = threadPoolExtent;
long sid = sessionManager.createSession(mss, true);
MultiScanResult result;
try {
result = continueMultiScan(tinfo, sid, mss);
} catch (NoSuchScanIDException e) {
log.error("the impossible happened", e);
throw new RuntimeException("the impossible happened", e);
} finally {
sessionManager.unreserveSession(sid);
}
scanCount.addAndGet(batch.size());
return new InitialMultiScan(sid, result);
}
@Override
public MultiScanResult continueMultiScan(TInfo tinfo, long scanID) throws NoSuchScanIDException {
MultiScanSession session = (MultiScanSession) sessionManager.reserveSession(scanID);
if (session == null) {
throw new NoSuchScanIDException();
}
try {
return continueMultiScan(tinfo, scanID, session);
} finally {
sessionManager.unreserveSession(session);
}
}
private MultiScanResult continueMultiScan(TInfo tinfo, long scanID, MultiScanSession session) throws NoSuchScanIDException {
if (session.lookupTask == null) {
session.lookupTask = new LookupTask(scanID);
resourceManager.executeReadAhead(session.threadPoolExtent, session.lookupTask);
}
try {
MultiScanResult scanResult = session.lookupTask.get(MAX_TIME_TO_WAIT_FOR_SCAN_RESULT_MILLIS, TimeUnit.MILLISECONDS);
session.lookupTask = null;
return scanResult;
} catch (TimeoutException e1) {
long timeout = acuConf.getTimeInMillis(Property.TSERV_CLIENT_TIMEOUT);
sessionManager.removeIfNotAccessed(scanID, timeout);
List<TKeyValue> results = Collections.emptyList();
Map<TKeyExtent,List<TRange>> failures = Collections.emptyMap();
List<TKeyExtent> fullScans = Collections.emptyList();
return new MultiScanResult(results, failures, fullScans, null, null, false, true);
} catch (Throwable t) {
sessionManager.removeSession(scanID);
log.warn("Failed to get multiscan result", t);
throw new RuntimeException(t);
}
}
@Override
public void closeMultiScan(TInfo tinfo, long scanID) throws NoSuchScanIDException {
MultiScanSession session = (MultiScanSession) sessionManager.removeSession(scanID);
if (session == null) {
throw new NoSuchScanIDException();
}
long t2 = System.currentTimeMillis();
log.debug(String.format("MultiScanSess %s %,d entries in %.2f secs (lookup_time:%.2f secs tablets:%,d ranges:%,d) ", TServerUtils.clientAddress.get(),
session.numEntries, (t2 - session.startTime) / 1000.0, session.totalLookupTime / 1000.0, session.numTablets, session.numRanges));
}
@Override
public long startUpdate(TInfo tinfo, AuthInfo credentials) throws ThriftSecurityException {
// Make sure user is real
try {
if (!authenticator.authenticateUser(credentials, credentials.user, credentials.password)) {
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.permissionErrors, 0);
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS);
}
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
UpdateSession us = new UpdateSession();
us.violations = new Violations();
us.credentials = credentials;
us.cenv = new TservConstraintEnv(authenticator, credentials);
long sid = sessionManager.createSession(us, false);
return sid;
}
private void setUpdateTablet(UpdateSession us, KeyExtent keyExtent) {
long t1 = System.currentTimeMillis();
try {
// if user has no permission to write to this table, add it to
// the failures list
boolean sameTable = us.currentTablet != null && (us.currentTablet.getExtent().getTableId().equals(keyExtent.getTableId()));
if (sameTable
|| authenticator.hasTablePermission(SecurityConstants.getSystemCredentials(), us.credentials.user, keyExtent.getTableId().toString(),
TablePermission.WRITE)) {
long t2 = System.currentTimeMillis();
us.authTimes.addStat(t2 - t1);
us.currentTablet = onlineTablets.get(keyExtent);
if (us.currentTablet != null) {
us.queuedMutations.put(us.currentTablet, new ArrayList<Mutation>());
} else {
// not serving tablet, so report all mutations as
// failures
us.failures.put(keyExtent, 0l);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.unknownTabletErrors, 0);
}
} else {
log.warn("Denying access to table " + keyExtent.getTableId() + " for user " + us.credentials.user);
long t2 = System.currentTimeMillis();
us.authTimes.addStat(t2 - t1);
us.currentTablet = null;
us.authFailures.add(keyExtent);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.permissionErrors, 0);
return;
}
} catch (AccumuloSecurityException e) {
log.error("Denying permission to check user " + us.credentials.user + " with user " + e.getUser(), e);
long t2 = System.currentTimeMillis();
us.authTimes.addStat(t2 - t1);
us.currentTablet = null;
us.authFailures.add(keyExtent);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.permissionErrors, 0);
return;
}
}
@Override
public void applyUpdates(TInfo tinfo, long updateID, TKeyExtent tkeyExtent, List<TMutation> tmutations) {
UpdateSession us = (UpdateSession) sessionManager.reserveSession(updateID);
if (us == null) {
throw new RuntimeException("No Such SessionID");
}
try {
KeyExtent keyExtent = new KeyExtent(tkeyExtent);
if (us.currentTablet == null || !us.currentTablet.getExtent().equals(keyExtent))
setUpdateTablet(us, keyExtent);
if (us.currentTablet != null) {
List<Mutation> mutations = us.queuedMutations.get(us.currentTablet);
for (TMutation tmutation : tmutations) {
Mutation mutation = new Mutation(tmutation);
mutations.add(mutation);
us.queuedMutationSize += mutation.numBytes();
}
if (us.queuedMutationSize > ServerConfiguration.getSystemConfiguration().getMemoryInBytes(Property.TSERV_MUTATION_QUEUE_MAX))
flush(us);
}
} finally {
sessionManager.unreserveSession(us);
}
}
private void flush(UpdateSession us) {
int mutationCount = 0;
Map<CommitSession,List<Mutation>> sendables = new HashMap<CommitSession,List<Mutation>>();
Throwable error = null;
long pt1 = System.currentTimeMillis();
boolean containsMetadataTablet = false;
for (Tablet tablet : us.queuedMutations.keySet())
if (tablet.getExtent().getTableId().toString().equals(Constants.METADATA_TABLE_ID))
containsMetadataTablet = true;
if (!containsMetadataTablet && us.queuedMutations.size() > 0)
TabletServer.this.resourceManager.waitUntilCommitsAreEnabled();
Span prep = Trace.start("prep");
for (Entry<Tablet,? extends List<Mutation>> entry : us.queuedMutations.entrySet()) {
Tablet tablet = entry.getKey();
List<Mutation> mutations = entry.getValue();
if (mutations.size() > 0) {
try {
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.mutationArraySize, mutations.size());
CommitSession commitSession = tablet.prepareMutationsForCommit(us.cenv, mutations);
if (commitSession == null) {
if (us.currentTablet == tablet) {
us.currentTablet = null;
}
us.failures.put(tablet.getExtent(), us.successfulCommits.get(tablet));
} else {
sendables.put(commitSession, mutations);
mutationCount += mutations.size();
}
} catch (TConstraintViolationException e) {
us.violations.add(e.getViolations());
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.constraintViolations, 0);
if (e.getNonViolators().size() > 0) {
// only log and commit mutations if there were some
// that did not
// violate constraints... this is what
// prepareMutationsForCommit()
// expects
sendables.put(e.getCommitSession(), e.getNonViolators());
}
mutationCount += mutations.size();
} catch (HoldTimeoutException t) {
error = t;
log.debug("Giving up on mutations due to a long memory hold time");
break;
} catch (Throwable t) {
error = t;
log.error("Unexpected error preparing for commit", error);
break;
}
}
}
prep.stop();
Span wal = Trace.start("wal");
long pt2 = System.currentTimeMillis();
long avgPrepareTime = (long) ((pt2 - pt1) / (double) us.queuedMutations.size());
us.prepareTimes.addStat(pt2 - pt1);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.commitPrep, (avgPrepareTime));
if (error != null) {
for (Entry<CommitSession,List<Mutation>> e : sendables.entrySet()) {
e.getKey().abortCommit(e.getValue());
}
throw new RuntimeException(error);
}
try {
while (true) {
try {
long t1 = System.currentTimeMillis();
logger.logManyTablets(sendables);
long t2 = System.currentTimeMillis();
us.walogTimes.addStat(t2 - t1);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.waLogWriteTime, (t2 - t1));
break;
} catch (IOException ex) {
log.warn("logging mutations failed, retrying");
} catch (Throwable t) {
log.error("Unknown exception logging mutations, counts for mutations in flight not decremented!", t);
throw new RuntimeException(t);
}
}
wal.stop();
Span commit = Trace.start("commit");
long t1 = System.currentTimeMillis();
for (Entry<CommitSession,? extends List<Mutation>> entry : sendables.entrySet()) {
CommitSession commitSession = entry.getKey();
List<Mutation> mutations = entry.getValue();
commitSession.commit(mutations);
Tablet tablet = commitSession.getTablet();
if (tablet == us.currentTablet) {
// because constraint violations may filter out some
// mutations, for proper
// accounting with the client code, need to increment
// the count based
// on the original number of mutations from the client
// NOT the filtered number
us.successfulCommits.increment(tablet, us.queuedMutations.get(tablet).size());
}
}
long t2 = System.currentTimeMillis();
long avgCommitTime = (long) ((t2 - t1) / (double) sendables.size());
us.flushTime += (t2 - pt1);
us.commitTimes.addStat(t2 - t1);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.commitTime, avgCommitTime);
commit.stop();
} finally {
us.queuedMutations.clear();
if (us.currentTablet != null) {
us.queuedMutations.put(us.currentTablet, new ArrayList<Mutation>());
}
us.queuedMutationSize = 0;
}
us.totalUpdates += mutationCount;
}
@Override
public UpdateErrors closeUpdate(TInfo tinfo, long updateID) throws NoSuchScanIDException {
UpdateSession us = (UpdateSession) sessionManager.removeSession(updateID);
if (us == null) {
throw new NoSuchScanIDException();
}
// clients may or may not see data from an update session while
// it is in progress, however when the update session is closed
// want to ensure that reads wait for the write to finish
long opid = writeTracker.startWrite(us.queuedMutations.keySet());
try {
flush(us);
} finally {
writeTracker.finishWrite(opid);
}
log.debug(String.format("UpSess %s %,d in %.3fs, at=[%s] ft=%.3fs(pt=%.3fs lt=%.3fs ct=%.3fs)", TServerUtils.clientAddress.get(), us.totalUpdates,
(System.currentTimeMillis() - us.startTime) / 1000.0, us.authTimes.toString(), us.flushTime / 1000.0, us.prepareTimes.getSum() / 1000.0,
us.walogTimes.getSum() / 1000.0, us.commitTimes.getSum() / 1000.0));
if (us.failures.size() > 0) {
Entry<KeyExtent,Long> first = us.failures.entrySet().iterator().next();
log.debug(String.format("Failures: %d, first extent %s successful commits: %d", us.failures.size(), first.getKey().toString(), first.getValue()));
}
List<ConstraintViolationSummary> violations = us.violations.asList();
if (violations.size() > 0) {
ConstraintViolationSummary first = us.violations.asList().iterator().next();
log.debug(String.format("Violations: %d, first %s occurs %d", violations.size(), first.violationDescription, first.numberOfViolatingMutations));
}
if (us.authFailures.size() > 0) {
KeyExtent first = us.authFailures.iterator().next();
log.debug(String.format("Authentication Failures: %d, first %s", us.authFailures.size(), first.toString()));
}
return new UpdateErrors(Translator.translate(us.failures, Translator.KET), Translator.translate(violations, Translator.CVST), Translator.translate(
us.authFailures, Translator.KET));
}
@Override
public void update(TInfo tinfo, AuthInfo credentials, TKeyExtent tkeyExtent, TMutation tmutation) throws NotServingTabletException,
ConstraintViolationException, ThriftSecurityException {
try {
if (!authenticator.hasTablePermission(credentials, credentials.user, new String(tkeyExtent.getTable()), TablePermission.WRITE))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
KeyExtent keyExtent = new KeyExtent(tkeyExtent);
Tablet tablet = onlineTablets.get(new KeyExtent(keyExtent));
if (tablet == null) {
throw new NotServingTabletException(tkeyExtent);
}
if (!keyExtent.getTableId().toString().equals(Constants.METADATA_TABLE_ID))
TabletServer.this.resourceManager.waitUntilCommitsAreEnabled();
long opid = writeTracker.startWrite(TabletType.type(keyExtent));
try {
Mutation mutation = new Mutation(tmutation);
List<Mutation> mutations = Collections.singletonList(mutation);
Span prep = Trace.start("prep");
CommitSession cs = tablet.prepareMutationsForCommit(new TservConstraintEnv(authenticator, credentials), mutations);
prep.stop();
if (cs == null) {
throw new NotServingTabletException(tkeyExtent);
}
while (true) {
try {
Span wal = Trace.start("wal");
logger.log(cs, cs.getWALogSeq(), mutation);
wal.stop();
break;
} catch (IOException ex) {
log.warn(ex, ex);
}
}
Span commit = Trace.start("commit");
cs.commit(mutations);
commit.stop();
} catch (TConstraintViolationException e) {
throw new ConstraintViolationException(Translator.translate(e.getViolations().asList(), Translator.CVST));
} finally {
writeTracker.finishWrite(opid);
}
}
@Override
public void splitTablet(TInfo tinfo, AuthInfo credentials, TKeyExtent tkeyExtent, ByteBuffer splitPoint) throws NotServingTabletException,
ThriftSecurityException {
String tableId = new String(ByteBufferUtil.toBytes(tkeyExtent.table));
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_TABLE)
&& !authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM)
&& !authenticator.hasTablePermission(credentials, credentials.user, tableId, TablePermission.ALTER_TABLE))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
KeyExtent keyExtent = new KeyExtent(tkeyExtent);
Tablet tablet = onlineTablets.get(keyExtent);
if (tablet == null) {
throw new NotServingTabletException(tkeyExtent);
}
if (keyExtent.getEndRow() == null || !keyExtent.getEndRow().equals(ByteBufferUtil.toText(splitPoint))) {
try {
if (TabletServer.this.splitTablet(tablet, ByteBufferUtil.toBytes(splitPoint)) == null) {
throw new NotServingTabletException(tkeyExtent);
}
} catch (IOException e) {
log.warn("Failed to split " + keyExtent, e);
throw new RuntimeException(e);
}
}
}
@Override
public TabletServerStatus getTabletServerStatus(TInfo tinfo, AuthInfo credentials) throws ThriftSecurityException, TException {
return getStats(sessionManager.getActiveScansPerTable());
}
@Override
public List<TabletStats> getTabletStats(TInfo tinfo, AuthInfo credentials, String tableId) throws ThriftSecurityException, TException {
TreeMap<KeyExtent,Tablet> onlineTabletsCopy;
synchronized (onlineTablets) {
onlineTabletsCopy = new TreeMap<KeyExtent,Tablet>(onlineTablets);
}
List<TabletStats> result = new ArrayList<TabletStats>();
Text text = new Text(tableId);
KeyExtent start = new KeyExtent(text, new Text(), null);
for (Entry<KeyExtent,Tablet> entry : onlineTabletsCopy.tailMap(start).entrySet()) {
KeyExtent ke = entry.getKey();
if (ke.getTableId().compareTo(text) == 0) {
Tablet tablet = entry.getValue();
TabletStats stats = tablet.timer.getTabletStats();
stats.extent = ke.toThrift();
stats.ingestRate = tablet.ingestRate();
stats.queryRate = tablet.queryRate();
stats.splitCreationTime = tablet.getSplitCreationTime();
stats.numEntries = tablet.getNumEntries();
result.add(stats);
}
}
return result;
}
private ZooCache masterLockCache = new ZooCache();
private void checkPermission(AuthInfo credentials, String lock, boolean requiresSystemPermission, final String request) throws ThriftSecurityException {
if (requiresSystemPermission) {
boolean fatal = false;
try {
log.debug("Got " + request + " message from user: " + credentials.user);
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM)) {
log.warn("Got " + request + " message from user: " + credentials.user);
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
}
} catch (AccumuloSecurityException e) {
log.warn("Got " + request + " message from unauthenticatable user: " + e.getUser());
if (e.getUser().equals(SecurityConstants.SYSTEM_USERNAME)) {
log.fatal("Got message from a service with a mismatched configuration. Please ensure a compatible configuration.", e);
fatal = true;
}
throw e.asThriftException();
} finally {
if (fatal) {
Halt.halt(1, new Runnable() {
public void run() {
logGCInfo();
}
});
}
}
}
if (tabletServerLock == null || !tabletServerLock.wasLockAcquired()) {
log.warn("Got " + request + " message from master before lock acquired, ignoring...");
throw new RuntimeException("Lock not acquired");
}
if (tabletServerLock != null && tabletServerLock.wasLockAcquired() && !tabletServerLock.isLocked()) {
Halt.halt(1, new Runnable() {
public void run() {
log.info("Tablet server no longer holds lock during checkPermission() : " + request + ", exiting");
logGCInfo();
}
});
}
ZooUtil.LockID lid = new ZooUtil.LockID(ZooUtil.getRoot(HdfsZooInstance.getInstance()) + Constants.ZMASTER_LOCK, lock);
try {
if (!ZooLock.isLockHeld(masterLockCache, lid)) {
// maybe the cache is out of date and a new master holds the
// lock?
masterLockCache.clear();
if (!ZooLock.isLockHeld(masterLockCache, lid)) {
log.warn("Got " + request + " message from a master that does not hold the current lock " + lock);
throw new RuntimeException("bad master lock");
}
}
} catch (Exception e) {
throw new RuntimeException("bad master lock", e);
}
}
@Override
public void loadTablet(TInfo tinfo, AuthInfo credentials, String lock, final TKeyExtent textent) {
try {
checkPermission(credentials, lock, true, "loadTablet");
} catch (ThriftSecurityException e) {
log.error(e, e);
throw new RuntimeException(e);
}
final KeyExtent extent = new KeyExtent(textent);
synchronized (unopenedTablets) {
synchronized (openingTablets) {
synchronized (onlineTablets) {
// checking if this exact tablet is in any of the sets
// below is not a strong enough check
// when splits and fix splits occurring
Set<KeyExtent> unopenedOverlapping = KeyExtent.findOverlapping(extent, unopenedTablets);
Set<KeyExtent> openingOverlapping = KeyExtent.findOverlapping(extent, openingTablets);
Set<KeyExtent> onlineOverlapping = KeyExtent.findOverlapping(extent, onlineTablets);
Set<KeyExtent> all = new HashSet<KeyExtent>();
all.addAll(unopenedOverlapping);
all.addAll(openingOverlapping);
all.addAll(onlineOverlapping);
if (!all.isEmpty()) {
if (all.size() != 1 || !all.contains(extent)) {
log.error("Tablet " + extent + " overlaps previously assigned " + unopenedOverlapping + " " + openingOverlapping + " " + onlineOverlapping);
}
return;
}
unopenedTablets.add(extent);
}
}
}
// add the assignment job to the appropriate queue
log.info("Loading tablet " + extent);
final Runnable ah = new LoggingRunnable(log, new AssignmentHandler(extent));
// Root tablet assignment must take place immediately
if (extent.compareTo(Constants.ROOT_TABLET_EXTENT) == 0) {
new Thread("Root Tablet Assignment") {
public void run() {
ah.run();
if (onlineTablets.containsKey(extent)) {
log.info("Root tablet loaded: " + extent);
} else {
log.info("Root tablet failed to load");
}
}
}.start();
} else {
if (extent.getTableId().compareTo(new Text(Constants.METADATA_TABLE_ID)) == 0) {
resourceManager.addMetaDataAssignment(ah);
} else {
resourceManager.addAssignment(ah);
}
}
}
@Override
public void unloadTablet(TInfo tinfo, AuthInfo credentials, String lock, TKeyExtent textent, boolean save) {
try {
checkPermission(credentials, lock, true, "unloadTablet");
} catch (ThriftSecurityException e) {
log.error(e, e);
throw new RuntimeException(e);
}
KeyExtent extent = new KeyExtent(textent);
resourceManager.addMigration(extent, new LoggingRunnable(log, new UnloadTabletHandler(extent, save)));
}
@Override
public void flush(TInfo tinfo, AuthInfo credentials, String lock, String tableId, ByteBuffer startRow, ByteBuffer endRow) {
try {
checkPermission(credentials, lock, true, "flush");
} catch (ThriftSecurityException e) {
log.error(e, e);
throw new RuntimeException(e);
}
ArrayList<Tablet> tabletsToFlush = new ArrayList<Tablet>();
KeyExtent ke = new KeyExtent(new Text(tableId), ByteBufferUtil.toText(endRow), ByteBufferUtil.toText(startRow));
synchronized (onlineTablets) {
for (Tablet tablet : onlineTablets.values())
if (ke.overlaps(tablet.getExtent()))
tabletsToFlush.add(tablet);
}
Long flushID = null;
for (Tablet tablet : tabletsToFlush) {
if (flushID == null) {
// read the flush id once from zookeeper instead of reading
// it for each tablet
flushID = tablet.getFlushID();
}
tablet.flush(flushID);
}
}
@Override
public void flushTablet(TInfo tinfo, AuthInfo credentials, String lock, TKeyExtent textent) throws TException {
try {
checkPermission(credentials, lock, true, "flushTablet");
} catch (ThriftSecurityException e) {
log.error(e, e);
throw new RuntimeException(e);
}
Tablet tablet = onlineTablets.get(new KeyExtent(textent));
if (tablet != null) {
log.info("Flushing " + tablet.getExtent());
tablet.flush(tablet.getFlushID());
}
}
@Override
public void halt(TInfo tinfo, AuthInfo credentials, String lock) throws ThriftSecurityException {
checkPermission(credentials, lock, true, "halt");
Halt.halt(0, new Runnable() {
public void run() {
log.info("Master requested tablet server halt");
logGCInfo();
serverStopRequested = true;
try {
tabletServerLock.unlock();
} catch (Exception e) {
log.error(e, e);
}
}
});
}
@Override
public void fastHalt(TInfo info, AuthInfo credentials, String lock) {
try {
halt(info, credentials, lock);
} catch (Exception e) {
log.warn("Error halting", e);
}
}
@Override
public TabletStats getHistoricalStats(TInfo tinfo, AuthInfo credentials) throws ThriftSecurityException, TException {
return statsKeeper.getTabletStats();
}
@Override
public void useLoggers(TInfo tinfo, AuthInfo credentials, Set<String> loggers) throws TException {
loggerStrategy.preferLoggers(loggers);
}
@Override
public List<ActiveScan> getActiveScans(TInfo tinfo, AuthInfo credentials) throws ThriftSecurityException, TException {
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
return sessionManager.getActiveScans();
}
@Override
public void chop(TInfo tinfo, AuthInfo credentials, String lock, TKeyExtent textent) throws TException {
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (Exception e) {
throw new RuntimeException(e);
}
KeyExtent ke = new KeyExtent(textent);
Tablet tablet = onlineTablets.get(ke);
if (tablet != null) {
tablet.chopFiles();
}
}
@Override
public void compact(TInfo tinfo, AuthInfo credentials, String lock, String tableId, ByteBuffer startRow, ByteBuffer endRow) throws TException {
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (Exception e) {
throw new RuntimeException(e);
}
KeyExtent ke = new KeyExtent(new Text(tableId), ByteBufferUtil.toText(endRow), ByteBufferUtil.toText(startRow));
ArrayList<Tablet> tabletsToCompact = new ArrayList<Tablet>();
synchronized (onlineTablets) {
for (Tablet tablet : onlineTablets.values())
if (ke.overlaps(tablet.getExtent()))
tabletsToCompact.add(tablet);
}
Long compactionId = null;
for (Tablet tablet : tabletsToCompact) {
// all for the same table id, so only need to read
// compaction id once
if (compactionId == null)
compactionId = tablet.getCompactionID();
tablet.compactAll(compactionId);
}
}
}
private class SplitRunner implements Runnable {
private Tablet tablet;
public SplitRunner(Tablet tablet) {
this.tablet = tablet;
}
@Override
public void run() {
if (majorCompactorDisabled) {
// this will make split task that were queued when shutdown was
// initiated exit
return;
}
splitTablet(tablet);
}
}
boolean isMajorCompactionDisabled() {
return majorCompactorDisabled;
}
private class MajorCompactor implements Runnable {
private AccumuloConfiguration acuConf = ServerConfiguration.getSystemConfiguration();
public void run() {
while (!majorCompactorDisabled) {
try {
UtilWaitThread.sleep(acuConf.getTimeInMillis(Property.TSERV_MAJC_DELAY));
TreeMap<KeyExtent,Tablet> copyOnlineTablets = new TreeMap<KeyExtent,Tablet>();
synchronized (onlineTablets) {
copyOnlineTablets.putAll(onlineTablets); // avoid
// concurrent
// modification
}
int numMajorCompactionsInProgress = 0;
Iterator<Entry<KeyExtent,Tablet>> iter = copyOnlineTablets.entrySet().iterator();
while (iter.hasNext() && !majorCompactorDisabled) { // bail
// early
// now
// if
// we're
// shutting
// down
Entry<KeyExtent,Tablet> entry = iter.next();
Tablet tablet = entry.getValue();
// if we need to split AND compact, we need a good way
// to decide what to do
if (tablet.needsSplit()) {
resourceManager.executeSplit(tablet.getExtent(), new LoggingRunnable(log, new SplitRunner(tablet)));
continue;
}
int maxLogEntriesPerTablet = ServerConfiguration.getTableConfiguration(tablet.getExtent().getTableId().toString()).getCount(
Property.TABLE_MINC_LOGS_MAX);
if (tablet.getLogCount() >= maxLogEntriesPerTablet) {
log.debug("Initiating minor compaction for " + tablet.getExtent() + " because it has " + tablet.getLogCount() + " write ahead logs");
tablet.initiateMinorCompaction();
}
synchronized (tablet) {
if (tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL) || tablet.majorCompactionQueued() || tablet.majorCompactionRunning()) {
numMajorCompactionsInProgress++;
continue;
}
}
}
int idleCompactionsToStart = Math.max(1, acuConf.getCount(Property.TSERV_MAJC_MAXCONCURRENT) / 2);
if (numMajorCompactionsInProgress < idleCompactionsToStart) {
// system is not major compacting, can schedule some
// idle compactions
iter = copyOnlineTablets.entrySet().iterator();
while (iter.hasNext() && !majorCompactorDisabled && numMajorCompactionsInProgress < idleCompactionsToStart) {
Entry<KeyExtent,Tablet> entry = iter.next();
Tablet tablet = entry.getValue();
if (tablet.initiateMajorCompaction(MajorCompactionReason.IDLE)) {
numMajorCompactionsInProgress++;
}
}
}
} catch (Throwable t) {
log.error("Unexpected exception in " + Thread.currentThread().getName(), t);
UtilWaitThread.sleep(1000);
}
}
}
}
private void splitTablet(Tablet tablet) {
try {
TreeMap<KeyExtent,SplitInfo> tabletInfo = splitTablet(tablet, null);
if (tabletInfo == null) {
// either split or compact not both
// were not able to split... so see if a major compaction is
// needed
tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL);
}
} catch (IOException e) {
statsKeeper.updateTime(Operation.SPLIT, 0, 0, true);
log.error("split failed: " + e.getMessage() + " for tablet " + tablet.getExtent(), e);
} catch (Exception e) {
statsKeeper.updateTime(Operation.SPLIT, 0, 0, true);
log.error("Unknown error on split: " + e, e);
}
}
private TreeMap<KeyExtent,SplitInfo> splitTablet(Tablet tablet, byte[] splitPoint) throws IOException {
long t1 = System.currentTimeMillis();
TreeMap<KeyExtent,SplitInfo> tabletInfo = tablet.split(splitPoint);
if (tabletInfo == null) {
return null;
}
log.info("Starting split: " + tablet.getExtent());
statsKeeper.incrementStatusSplit();
long start = System.currentTimeMillis();
Tablet[] newTablets = new Tablet[2];
Entry<KeyExtent,SplitInfo> first = tabletInfo.firstEntry();
newTablets[0] = new Tablet(TabletServer.this, new Text(first.getValue().dir), first.getKey(), resourceManager.createTabletResourceManager(),
first.getValue().datafiles, first.getValue().time, first.getValue().initFlushID, first.getValue().initCompactID);
Entry<KeyExtent,SplitInfo> last = tabletInfo.lastEntry();
newTablets[1] = new Tablet(TabletServer.this, new Text(last.getValue().dir), last.getKey(), resourceManager.createTabletResourceManager(),
last.getValue().datafiles, last.getValue().time, last.getValue().initFlushID, last.getValue().initCompactID);
// roll tablet stats over into tablet server's statsKeeper object as
// historical data
statsKeeper.saveMinorTimes(tablet.timer);
statsKeeper.saveMajorTimes(tablet.timer);
// lose the reference to the old tablet and open two new ones
synchronized (onlineTablets) {
onlineTablets.remove(tablet.getExtent());
onlineTablets.put(newTablets[0].getExtent(), newTablets[0]);
onlineTablets.put(newTablets[1].getExtent(), newTablets[1]);
}
// tell the master
enqueueMasterMessage(new SplitReportMessage(tablet.getExtent(), newTablets[0].getExtent(), new Text("/" + newTablets[0].getLocation().getName()),
newTablets[1].getExtent(), new Text("/" + newTablets[1].getLocation().getName())));
statsKeeper.updateTime(Operation.SPLIT, start, 0, false);
long t2 = System.currentTimeMillis();
log.info("Tablet split: " + tablet.getExtent() + " size0 " + newTablets[0].estimateTabletSize() + " size1 " + newTablets[1].estimateTabletSize() + " time "
+ (t2 - t1) + "ms");
return tabletInfo;
}
public long lastPingTime = System.currentTimeMillis();
public Socket currentMaster;
// a queue to hold messages that are to be sent back to the master
private BlockingDeque<MasterMessage> masterMessages = new LinkedBlockingDeque<MasterMessage>();
// add a message for the main thread to send back to the master
void enqueueMasterMessage(MasterMessage m) {
masterMessages.addLast(m);
}
private class UnloadTabletHandler implements Runnable {
private KeyExtent extent;
private boolean saveState;
public UnloadTabletHandler(KeyExtent extent, boolean saveState) {
this.extent = extent;
this.saveState = saveState;
}
public void run() {
Tablet t = null;
synchronized (unopenedTablets) {
if (unopenedTablets.contains(extent)) {
unopenedTablets.remove(extent);
// enqueueMasterMessage(new TabletUnloadedMessage(extent));
return;
}
}
synchronized (openingTablets) {
while (openingTablets.contains(extent)) {
try {
openingTablets.wait();
} catch (InterruptedException e) {}
}
}
synchronized (onlineTablets) {
if (onlineTablets.containsKey(extent)) {
t = onlineTablets.get(extent);
}
}
if (t == null) {
// Tablet has probably been recently unloaded: repeated master
// unload request is crossing the successful unloaded message
log.info("told to unload tablet that was not being served " + extent);
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.UNLOAD_FAILURE_NOT_SERVING, extent));
return;
}
try {
t.close(saveState);
} catch (Throwable e) {
if ((t.isClosing() || t.isClosed()) && e instanceof IllegalStateException) {
log.debug("Failed to unload tablet " + extent + "... it was alread closing or closed : " + e.getMessage());
} else {
log.error("Failed to close tablet " + extent + "... Aborting migration", e);
}
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.UNLOAD_ERROR, extent));
return;
}
// stop serving tablet - client will get not serving tablet
// exceptions
onlineTablets.remove(extent);
try {
TServerInstance instance = new TServerInstance(clientAddress, getLock().getSessionId());
TabletLocationState tls = new TabletLocationState(extent, null, instance, null, null, false);
log.debug("Unassigning " + tls);
TabletStateStore.unassign(tls);
} catch (DistributedStoreException ex) {
log.warn("Unable to update storage", ex);
} catch (KeeperException e) {
log.warn("Unable determine our zookeeper session information", e);
} catch (InterruptedException e) {
log.warn("Interrupted while getting our zookeeper session information", e);
}
// tell the master how it went
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.UNLOADED, extent));
// roll tablet stats over into tablet server's statsKeeper object as
// historical data
statsKeeper.saveMinorTimes(t.timer);
statsKeeper.saveMajorTimes(t.timer);
log.info("unloaded " + extent);
}
}
private class AssignmentHandler implements Runnable {
private KeyExtent extent;
private int retryAttempt = 0;
public AssignmentHandler(KeyExtent extent) {
this.extent = extent;
}
public AssignmentHandler(KeyExtent extent, int retryAttempt) {
this(extent);
this.retryAttempt = retryAttempt;
}
public void run() {
log.info(clientAddress + ": got assignment from master: " + extent);
final boolean isMetaDataTablet = extent.getTableId().toString().compareTo(Constants.METADATA_TABLE_ID) == 0;
synchronized (unopenedTablets) {
synchronized (openingTablets) {
synchronized (onlineTablets) {
// nothing should be moving between sets, do a sanity
// check
Set<KeyExtent> unopenedOverlapping = KeyExtent.findOverlapping(extent, unopenedTablets);
Set<KeyExtent> openingOverlapping = KeyExtent.findOverlapping(extent, openingTablets);
Set<KeyExtent> onlineOverlapping = KeyExtent.findOverlapping(extent, onlineTablets);
if (openingOverlapping.contains(extent) || onlineOverlapping.contains(extent))
return;
if (!unopenedTablets.contains(extent) || unopenedOverlapping.size() != 1 || openingOverlapping.size() > 0 || onlineOverlapping.size() > 0) {
throw new IllegalStateException("overlaps assigned " + extent + " " + !unopenedTablets.contains(extent) + " " + unopenedOverlapping + " "
+ openingOverlapping + " " + onlineOverlapping);
}
}
unopenedTablets.remove(extent);
openingTablets.add(extent);
}
}
log.debug("Loading extent: " + extent);
// check Metadata table before accepting assignment
SortedMap<KeyExtent,Text> tabletsInRange = null;
SortedMap<Key,Value> tabletsKeyValues = new TreeMap<Key,Value>();
try {
tabletsInRange = verifyTabletInformation(extent, TabletServer.this.getTabletSession(), tabletsKeyValues, getClientAddressString(), getLock());
} catch (Exception e) {
synchronized (openingTablets) {
openingTablets.remove(extent);
openingTablets.notifyAll();
}
log.warn("Failed to verify tablet " + extent, e);
throw new RuntimeException(e);
}
if (tabletsInRange == null) {
log.info("Reporting tablet " + extent + " assignment failure: unable to verify Tablet Information");
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.LOAD_FAILURE, extent));
synchronized (openingTablets) {
openingTablets.remove(extent);
openingTablets.notifyAll();
}
return;
}
// If extent given is not the one to be opened, update
if (tabletsInRange.size() != 1 || !tabletsInRange.containsKey(extent)) {
tabletsKeyValues.clear();
synchronized (openingTablets) {
openingTablets.remove(extent);
openingTablets.notifyAll();
for (KeyExtent e : tabletsInRange.keySet())
openingTablets.add(e);
}
} else {
// remove any metadata entries for the previous tablet
Iterator<Key> iter = tabletsKeyValues.keySet().iterator();
Text row = extent.getMetadataEntry();
while (iter.hasNext()) {
Key key = iter.next();
if (!key.getRow().equals(row)) {
iter.remove();
}
}
}
if (tabletsInRange.size() > 1) {
log.debug("Master didn't know " + extent + " was split, letting it know about " + tabletsInRange.keySet());
enqueueMasterMessage(new SplitReportMessage(extent, tabletsInRange));
}
// create the tablet object
for (Entry<KeyExtent,Text> entry : tabletsInRange.entrySet()) {
Tablet tablet = null;
boolean successful = false;
final KeyExtent extentToOpen = entry.getKey();
Text locationToOpen = entry.getValue();
if (onlineTablets.containsKey(extentToOpen)) {
// know this was from fixing a split, because initial check
// would have caught original extent
log.warn("Something is screwy! Already serving tablet " + extentToOpen + " derived from fixing split. Original extent = " + extent);
synchronized (openingTablets) {
openingTablets.remove(extentToOpen);
openingTablets.notifyAll();
}
continue;
}
try {
TabletResourceManager trm = resourceManager.createTabletResourceManager();
// this opens the tablet file and fills in the endKey in the
// extent
tablet = new Tablet(TabletServer.this, locationToOpen, extentToOpen, trm, tabletsKeyValues);
if (!tablet.initiateMinorCompaction() && tablet.getNumEntriesInMemory() > 0) {
log.warn("Minor compaction after recovery fails for " + extentToOpen);
// it is important to wait for minc in the case that the
// minor compaction finish
// event did not make it to the logs (the file will be
// in !METADATA, preventing replay of compacted data)...
// but do not want a majc to wipe the file out from
// !METADATA and then have another process failure...
// this could cause duplicate data to replay
tablet.waitForMinC();
}
synchronized (openingTablets) {
synchronized (onlineTablets) {
openingTablets.remove(extentToOpen);
onlineTablets.put(extentToOpen, tablet);
openingTablets.notifyAll();
}
}
tablet = null; // release this reference
successful = true;
} catch (Throwable e) {
log.warn("exception trying to assign tablet " + extentToOpen + " " + locationToOpen, e);
if (e.getMessage() != null)
log.warn(e.getMessage());
String table = extent.getTableId().toString();
ProblemReports.getInstance().report(new ProblemReport(table, TABLET_LOAD, extentToOpen.getUUID().toString(), getClientAddressString(), e));
}
if (!successful) {
synchronized (unopenedTablets) {
synchronized (openingTablets) {
openingTablets.remove(extentToOpen);
unopenedTablets.add(extentToOpen);
openingTablets.notifyAll();
}
}
log.warn("failed to open tablet " + extentToOpen + " reporting failure to master");
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.LOAD_FAILURE, extentToOpen));
long reschedule = Math.min((1l << Math.min(32, retryAttempt)) * 1000, 10 * 60 * 1000l);
log.warn(String.format("rescheduling tablet load in %.2f seconds", reschedule / 1000.));
SimpleTimer.getInstance().schedule(new TimerTask() {
@Override
public void run() {
log.info("adding tablet " + extent + " back to the assignment pool (retry " + retryAttempt + ")");
AssignmentHandler handler = new AssignmentHandler(extentToOpen, retryAttempt + 1);
if (isMetaDataTablet) {
if (Constants.ROOT_TABLET_EXTENT.equals(extent)) {
new Thread(new LoggingRunnable(log, handler), "Root tablet assignment retry").start();
} else {
resourceManager.addMetaDataAssignment(handler);
}
} else {
resourceManager.addAssignment(handler);
}
}
}, reschedule);
} else {
try {
Assignment assignment = new Assignment(extentToOpen, getTabletSession());
TabletStateStore.setLocation(assignment);
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.LOADED, extentToOpen));
} catch (DistributedStoreException ex) {
log.warn("Unable to update storage", ex);
}
}
}
}
}
private FileSystem fs;
private Configuration conf;
private ZooCache cache;
private SortedMap<KeyExtent,Tablet> onlineTablets = Collections.synchronizedSortedMap(new TreeMap<KeyExtent,Tablet>());
private SortedSet<KeyExtent> unopenedTablets = Collections.synchronizedSortedSet(new TreeSet<KeyExtent>());
private SortedSet<KeyExtent> openingTablets = Collections.synchronizedSortedSet(new TreeSet<KeyExtent>());
private Thread majorCompactorThread;
// used for stopping the server and MasterListener thread
private volatile boolean serverStopRequested = false;
private InetSocketAddress clientAddress;
private TabletServerResourceManager resourceManager;
private Authenticator authenticator;
private volatile boolean majorCompactorDisabled = false;
private volatile boolean shutdownComplete = false;
private ZooLock tabletServerLock;
private TServer server;
private static final String METRICS_PREFIX = "tserver";
private static ObjectName OBJECT_NAME = null;
public TabletStatsKeeper getStatsKeeper() {
return statsKeeper;
}
public Set<String> getLoggers() throws TException, MasterNotRunningException, ThriftSecurityException {
Set<String> allLoggers = new HashSet<String>();
String dir = ZooUtil.getRoot(HdfsZooInstance.getInstance()) + Constants.ZLOGGERS;
for (String child : cache.getChildren(dir)) {
allLoggers.add(new String(cache.get(dir + "/" + child)));
}
if (allLoggers.isEmpty()) {
log.warn("there are no loggers registered in zookeeper");
return allLoggers;
}
Set<String> result = loggerStrategy.getLoggers(Collections.unmodifiableSet(allLoggers));
Set<String> bogus = new HashSet<String>(result);
bogus.removeAll(allLoggers);
if (!bogus.isEmpty())
log.warn("logger strategy is returning loggers that are not candidates");
result.removeAll(bogus);
if (result.isEmpty())
log.warn("strategy returned no useful loggers");
return result;
}
public void addLoggersToMetadata(List<RemoteLogger> logs, KeyExtent extent, int id) {
log.info("Adding " + logs.size() + " logs for extent " + extent + " as alias " + id);
List<MetadataTable.LogEntry> entries = new ArrayList<MetadataTable.LogEntry>();
long now = RelativeTime.currentTimeMillis();
List<String> logSet = new ArrayList<String>();
for (RemoteLogger log : logs)
logSet.add(log.toString());
for (RemoteLogger log : logs) {
MetadataTable.LogEntry entry = new MetadataTable.LogEntry();
entry.extent = extent;
entry.tabletId = id;
entry.timestamp = now;
entry.server = log.getLogger();
entry.filename = log.getFileName();
entry.logSet = logSet;
entries.add(entry);
}
MetadataTable.addLogEntries(SecurityConstants.getSystemCredentials(), entries, getLock());
}
private int startServer(Property portHint, TProcessor processor, String threadName) throws UnknownHostException {
ServerPort sp = TServerUtils.startServer(portHint, processor, this.getClass().getSimpleName(), threadName, Property.TSERV_PORTSEARCH,
Property.TSERV_MINTHREADS, Property.TSERV_THREADCHECK);
this.server = sp.server;
return sp.port;
}
private String getMasterAddress() {
try {
List<String> locations = HdfsZooInstance.getInstance().getMasterLocations();
if (locations.size() == 0)
return null;
return locations.get(0);
} catch (Exception e) {
log.warn("Failed to obtain master host " + e);
}
return null;
}
// Connect to the master for posting asynchronous results
private MasterClientService.Iface masterConnection(String address) {
try {
if (address == null) {
return null;
}
MasterClientService.Iface client = ThriftUtil.getClient(new MasterClientService.Client.Factory(), address, Property.MASTER_CLIENTPORT,
Property.GENERAL_RPC_TIMEOUT, ServerConfiguration.getSystemConfiguration());
// log.info("Listener API to master has been opened");
return client;
} catch (Exception e) {
log.warn("Issue with masterConnection (" + address + ") " + e, e);
}
return null;
}
private void returnMasterConnection(MasterClientService.Iface client) {
ThriftUtil.returnClient(client);
}
private int startTabletClientService() throws UnknownHostException {
// start listening for client connection last
TabletClientService.Iface tch = TraceWrap.service(new ThriftClientHandler());
TabletClientService.Processor processor = new TabletClientService.Processor(tch);
int port = startServer(Property.TSERV_CLIENTPORT, processor, "Thrift Client Server");
log.info("port = " + port);
return port;
}
ZooLock getLock() {
return tabletServerLock;
}
private void announceExistence() {
IZooReaderWriter zoo = ZooReaderWriter.getInstance();
try {
String zPath = ZooUtil.getRoot(HdfsZooInstance.getInstance()) + Constants.ZTSERVERS + "/" + getClientAddressString();
zoo.putPersistentData(zPath, new byte[] {}, NodeExistsPolicy.SKIP);
tabletServerLock = new ZooLock(zPath);
LockWatcher lw = new LockWatcher() {
@Override
public void lostLock(final LockLossReason reason) {
Halt.halt(0, new Runnable() {
public void run() {
if (!serverStopRequested)
log.fatal("Lost tablet server lock (reason = " + reason + "), exiting.");
logGCInfo();
}
});
}
};
byte[] lockContent = new ServerServices(getClientAddressString(), Service.TSERV_CLIENT).toString().getBytes();
for (int i = 0; i < 120 / 5; i++) {
zoo.putPersistentData(zPath, new byte[0], NodeExistsPolicy.SKIP);
if (tabletServerLock.tryLock(lw, lockContent)) {
log.debug("Obtained tablet server lock " + tabletServerLock.getLockPath());
return;
}
log.info("Waiting for tablet server lock");
UtilWaitThread.sleep(5000);
}
String msg = "Too many retries, exiting.";
log.info(msg);
throw new RuntimeException(msg);
} catch (Exception e) {
log.info("Could not obtain tablet server lock, exiting.", e);
throw new RuntimeException(e);
}
}
// main loop listens for client requests
public void run() {
int clientPort = 0;
try {
clientPort = startTabletClientService();
} catch (UnknownHostException e1) {
log.error("Unable to start tablet client service", e1);
UtilWaitThread.sleep(1000);
}
if (clientPort == 0) {
throw new RuntimeException("Failed to start the tablet client service");
}
clientAddress = new InetSocketAddress(clientAddress.getAddress(), clientPort);
announceExistence();
try {
OBJECT_NAME = new ObjectName("accumulo.server.metrics:service=TServerInfo,name=TabletServerMBean,instance=" + Thread.currentThread().getName());
// Do this because interface not in same package.
StandardMBean mbean = new StandardMBean(this, TabletServerMBean.class, false);
this.register(mbean);
mincMetrics.register();
} catch (Exception e) {
log.error("Error registering with JMX", e);
}
String masterHost;
while (!serverStopRequested) {
// send all of the pending messages
try {
MasterMessage mm = null;
MasterClientService.Iface iface = null;
try {
// wait until a message is ready to send, or a sever stop
// was requested
while (mm == null && !serverStopRequested) {
mm = masterMessages.poll(1000, TimeUnit.MILLISECONDS);
}
// have a message to send to the master, so grab a
// connection
masterHost = getMasterAddress();
iface = masterConnection(masterHost);
TServiceClient client = (TServiceClient) iface;
// if while loop does not execute at all and mm != null,
// then
// finally block should place mm back on queue
while (!serverStopRequested && mm != null && client != null && client.getOutputProtocol() != null
&& client.getOutputProtocol().getTransport() != null && client.getOutputProtocol().getTransport().isOpen()) {
try {
mm.send(SecurityConstants.getSystemCredentials(), getClientAddressString(), iface);
mm = null;
} catch (TException ex) {
log.warn("Error sending message: queuing message again");
masterMessages.putFirst(mm);
mm = null;
throw ex;
}
// if any messages are immediately available grab em and
// send them
mm = masterMessages.poll();
}
} finally {
if (mm != null) {
masterMessages.putFirst(mm);
}
returnMasterConnection(iface);
UtilWaitThread.sleep(1000);
}
} catch (InterruptedException e) {
log.info("Interrupt Exception received, shutting down");
serverStopRequested = true;
} catch (Exception e) {
// may have lost connection with master
// loop back to the beginning and wait for a new one
// this way we survive master failures
log.error(getClientAddressString() + ": TServerInfo: Exception. Master down?", e);
}
}
// wait for shutdown
// if the main thread exits oldServer the master listener, the JVM will
// kill the
// other threads and finalize objects. We want the shutdown that is
// running
// in the master listener thread to complete oldServer this happens.
// consider making other threads daemon threads so that objects don't
// get prematurely finalized
synchronized (this) {
while (shutdownComplete == false) {
try {
this.wait(1000);
} catch (InterruptedException e) {
log.error(e.toString());
}
}
}
log.debug("Stopping Thrift Servers");
TServerUtils.stopTServer(server);
try {
log.debug("Closing filesystem");
fs.close();
} catch (IOException e) {
log.warn("Failed to close filesystem : " + e.getMessage(), e);
}
logGCInfo();
log.info("TServerInfo: stop requested. exiting ... ");
try {
tabletServerLock.unlock();
} catch (Exception e) {
log.warn("Failed to release tablet server lock", e);
}
}
private long totalMinorCompactions;
public static SortedMap<KeyExtent,Text> verifyTabletInformation(KeyExtent extent, TServerInstance instance, SortedMap<Key,Value> tabletsKeyValues,
String clientAddress, ZooLock lock) throws AccumuloSecurityException {
for (int tries = 0; tries < 3; tries++) {
try {
log.debug("verifying extent " + extent);
if (extent.equals(Constants.ROOT_TABLET_EXTENT)) {
TreeMap<KeyExtent,Text> set = new TreeMap<KeyExtent,Text>();
set.put(extent, new Text(Constants.ZROOT_TABLET));
return set;
}
List<ColumnFQ> columnsToFetch = Arrays.asList(new ColumnFQ[] {Constants.METADATA_DIRECTORY_COLUMN, Constants.METADATA_PREV_ROW_COLUMN,
Constants.METADATA_SPLIT_RATIO_COLUMN, Constants.METADATA_OLD_PREV_ROW_COLUMN, Constants.METADATA_TIME_COLUMN});
if (tabletsKeyValues == null) {
tabletsKeyValues = new TreeMap<Key,Value>();
}
MetadataTable.getTabletAndPrevTabletKeyValues(tabletsKeyValues, extent, null, SecurityConstants.getSystemCredentials());
SortedMap<Text,SortedMap<ColumnFQ,Value>> tabletEntries;
tabletEntries = MetadataTable.getTabletEntries(tabletsKeyValues, columnsToFetch);
if (tabletEntries.size() == 0) {
log.warn("Failed to find any metadata entries for " + extent);
return null;
}
// ensure lst key in map is same as extent that was passed in
if (!tabletEntries.lastKey().equals(extent.getMetadataEntry())) {
log.warn("Failed to find metadata entry for " + extent + " found " + tabletEntries.lastKey());
return null;
}
TServerInstance future = null;
Text metadataEntry = extent.getMetadataEntry();
for (Entry<Key,Value> entry : tabletsKeyValues.entrySet()) {
Key key = entry.getKey();
if (!metadataEntry.equals(key.getRow()))
continue;
Text cf = key.getColumnFamily();
if (cf.equals(Constants.METADATA_FUTURE_LOCATION_COLUMN_FAMILY)) {
future = new TServerInstance(entry.getValue(), key.getColumnQualifier());
} else if (cf.equals(Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY)) {
log.error("Tablet seems to be already assigned to " + new TServerInstance(entry.getValue(), key.getColumnQualifier()));
return null;
}
}
if (future == null) {
log.warn("The master has not assigned " + extent + " to " + instance);
return null;
}
if (!instance.equals(future)) {
log.warn("Table " + extent + " has been assigned to " + future + " which is not " + instance);
return null;
}
// look for incomplete splits
int splitsFixed = 0;
for (Entry<Text,SortedMap<ColumnFQ,Value>> entry : tabletEntries.entrySet()) {
if (extent.getPrevEndRow() != null) {
Text prevRowMetadataEntry = new Text(KeyExtent.getMetadataEntry(extent.getTableId(), extent.getPrevEndRow()));
if (entry.getKey().compareTo(prevRowMetadataEntry) <= 0) {
continue;
}
}
if (entry.getValue().containsKey(Constants.METADATA_OLD_PREV_ROW_COLUMN)) {
KeyExtent fixedke = MetadataTable.fixSplit(entry.getKey(), entry.getValue(), instance, SecurityConstants.getSystemCredentials(), lock);
if (fixedke != null) {
if (fixedke.getPrevEndRow() == null || fixedke.getPrevEndRow().compareTo(extent.getPrevEndRow()) < 0) {
extent = new KeyExtent(extent);
extent.setPrevEndRow(fixedke.getPrevEndRow());
}
splitsFixed++;
}
}
}
if (splitsFixed > 0) {
// reread and reverify metadata entries now that metadata
// entries were fixed
tabletsKeyValues.clear();
return verifyTabletInformation(extent, instance, null, clientAddress, lock);
}
SortedMap<KeyExtent,Text> children = new TreeMap<KeyExtent,Text>();
for (Entry<Text,SortedMap<ColumnFQ,Value>> entry : tabletEntries.entrySet()) {
if (extent.getPrevEndRow() != null) {
Text prevRowMetadataEntry = new Text(KeyExtent.getMetadataEntry(extent.getTableId(), extent.getPrevEndRow()));
if (entry.getKey().compareTo(prevRowMetadataEntry) <= 0) {
continue;
}
}
Value prevEndRowIBW = entry.getValue().get(Constants.METADATA_PREV_ROW_COLUMN);
if (prevEndRowIBW == null) {
log.warn("Metadata entry does not have prev row (" + entry.getKey() + ")");
return null;
}
Value dirIBW = entry.getValue().get(Constants.METADATA_DIRECTORY_COLUMN);
if (dirIBW == null) {
log.warn("Metadata entry does not have directory (" + entry.getKey() + ")");
return null;
}
Text dir = new Text(dirIBW.get());
KeyExtent child = new KeyExtent(entry.getKey(), prevEndRowIBW);
children.put(child, dir);
}
if (!MetadataTable.isContiguousRange(extent, new TreeSet<KeyExtent>(children.keySet()))) {
log.warn("For extent " + extent + " metadata entries " + children + " do not form a contiguous range.");
return null;
}
return children;
} catch (AccumuloException e) {
log.error("error verifying metadata information. retrying ...");
log.error(e.toString());
UtilWaitThread.sleep(1000);
} catch (AccumuloSecurityException e) {
// if it's a security exception, retrying won't work either.
log.error(e.toString());
throw e;
}
}
// default is to accept
return null;
}
public String getClientAddressString() {
if (clientAddress == null)
return null;
return AddressUtil.toString(clientAddress);
}
TServerInstance getTabletSession() {
String address = getClientAddressString();
if (address == null)
return null;
try {
return new TServerInstance(address, tabletServerLock.getSessionId());
} catch (Exception ex) {
log.warn("Unable to read session from tablet server lock" + ex);
return null;
}
}
public void config(String[] args) throws UnknownHostException {
InetAddress local = Accumulo.getLocalAddress(args);
try {
Accumulo.init("tserver");
log.info("Tablet server starting on " + local.getHostAddress());
conf = CachedConfiguration.getInstance();
fs = TraceFileSystem.wrap(FileUtil.getFileSystem(conf, ServerConfiguration.getSiteConfiguration()));
authenticator = ZKAuthenticator.getInstance();
if (args.length > 0)
conf.set("tabletserver.hostname", args[0]);
Accumulo.enableTracing(local.getHostAddress(), "tserver");
} catch (IOException e) {
log.fatal("couldn't get a reference to the filesystem. quitting");
throw new RuntimeException(e);
}
clientAddress = new InetSocketAddress(local, 0);
logger = new TabletServerLogger(this, ServerConfiguration.getSystemConfiguration().getMemoryInBytes(Property.TSERV_WALOG_MAX_SIZE));
if (ServerConfiguration.getSystemConfiguration().getBoolean(Property.TSERV_LOCK_MEMORY)) {
String path = "lib/native/mlock/" + System.mapLibraryName("MLock-" + Platform.getPlatform());
path = new File(path).getAbsolutePath();
try {
System.load(path);
log.info("Trying to lock memory pages to RAM");
if (MLock.lockMemoryPages() < 0)
log.error("Failed to lock memory pages to RAM");
else
log.info("Memory pages are now locked into RAM");
} catch (Throwable t) {
log.error("Failed to load native library for locking pages to RAM " + path + " (" + t + ")", t);
}
}
FileSystemMonitor.start(Property.TSERV_MONITOR_FS);
TimerTask gcDebugTask = new TimerTask() {
@Override
public void run() {
logGCInfo();
}
};
SimpleTimer.getInstance().schedule(gcDebugTask, 0, 1000);
this.resourceManager = new TabletServerResourceManager(conf, fs);
lastPingTime = System.currentTimeMillis();
currentMaster = null;
statsKeeper = new TabletStatsKeeper();
// start major compactor
majorCompactorThread = new Daemon(new LoggingRunnable(log, new MajorCompactor()));
majorCompactorThread.setName("Split/MajC initiator");
majorCompactorThread.start();
String className = ServerConfiguration.getSystemConfiguration().get(Property.TSERV_LOGGER_STRATEGY);
Class<? extends LoggerStrategy> klass = DEFAULT_LOGGER_STRATEGY;
try {
klass = AccumuloClassLoader.loadClass(className, LoggerStrategy.class);
} catch (Exception ex) {
log.warn("Unable to load class " + className + " for logger strategy, using " + klass.getName(), ex);
}
try {
Constructor<? extends LoggerStrategy> constructor = klass.getConstructor(TabletServer.class);
loggerStrategy = constructor.newInstance(this);
} catch (Exception ex) {
log.warn("Unable to create object of type " + klass.getName() + " using " + DEFAULT_LOGGER_STRATEGY.getName());
}
if (loggerStrategy == null) {
try {
loggerStrategy = DEFAULT_LOGGER_STRATEGY.getConstructor(TabletServer.class).newInstance(this);
} catch (Exception ex) {
log.fatal("Programmer error: cannot create a logger strategy.");
throw new RuntimeException(ex);
}
}
cache = new ZooCache();
}
public TabletServerStatus getStats(Map<String,MapCounter<ScanRunState>> scanCounts) {
TabletServerStatus result = new TabletServerStatus();
Map<KeyExtent,Tablet> onlineTabletsCopy;
synchronized (this.onlineTablets) {
onlineTabletsCopy = new HashMap<KeyExtent,Tablet>(this.onlineTablets);
}
Map<String,TableInfo> tables = new HashMap<String,TableInfo>();
for (Entry<KeyExtent,Tablet> entry : onlineTabletsCopy.entrySet()) {
String tableId = entry.getKey().getTableId().toString();
TableInfo table = tables.get(tableId);
if (table == null) {
table = new TableInfo();
table.minor = new Compacting();
table.major = new Compacting();
tables.put(tableId, table);
}
Tablet tablet = entry.getValue();
long recs = tablet.getNumEntries();
table.tablets++;
table.onlineTablets++;
table.recs += recs;
table.queryRate += tablet.queryRate();
table.queryByteRate += tablet.queryByteRate();
table.ingestRate += tablet.ingestRate();
table.ingestByteRate += tablet.ingestByteRate();
long recsInMemory = tablet.getNumEntriesInMemory();
table.recsInMemory += recsInMemory;
if (tablet.minorCompactionRunning())
table.minor.running++;
if (tablet.minorCompactionQueued())
table.minor.queued++;
if (tablet.majorCompactionRunning())
table.major.running++;
if (tablet.majorCompactionQueued())
table.major.queued++;
}
for (Entry<String,MapCounter<ScanRunState>> entry : scanCounts.entrySet()) {
TableInfo table = tables.get(entry.getKey());
if (table == null) {
table = new TableInfo();
tables.put(entry.getKey(), table);
}
if (table.scans == null)
table.scans = new Compacting();
table.scans.queued += entry.getValue().get(ScanRunState.QUEUED);
table.scans.running += entry.getValue().get(ScanRunState.RUNNING);
}
ArrayList<KeyExtent> offlineTabletsCopy = new ArrayList<KeyExtent>();
synchronized (this.unopenedTablets) {
synchronized (this.openingTablets) {
offlineTabletsCopy.addAll(this.unopenedTablets);
offlineTabletsCopy.addAll(this.openingTablets);
}
}
for (KeyExtent extent : offlineTabletsCopy) {
String tableId = extent.getTableId().toString();
TableInfo table = tables.get(tableId);
if (table == null) {
table = new TableInfo();
tables.put(tableId, table);
}
table.tablets++;
}
result.lastContact = RelativeTime.currentTimeMillis();
result.tableMap = tables;
result.osLoad = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
result.name = getClientAddressString();
result.holdTime = resourceManager.holdTime();
result.lookups = scanCount.get();
result.loggers = new HashSet<String>();
result.indexCacheHits = resourceManager.getIndexCache().getStats().getHitCount();
result.indexCacheRequest = resourceManager.getIndexCache().getStats().getRequestCount();
result.dataCacheHits = resourceManager.getDataCache().getStats().getHitCount();
result.dataCacheRequest = resourceManager.getDataCache().getStats().getRequestCount();
logger.getLoggers(result.loggers);
return result;
}
public static void main(String[] args) throws IOException {
TabletServer server = new TabletServer();
server.config(args);
server.run();
}
public void minorCompactionFinished(CommitSession tablet, String newDatafile, int walogSeq) throws IOException {
totalMinorCompactions++;
logger.minorCompactionFinished(tablet, newDatafile, walogSeq);
}
public void minorCompactionStarted(CommitSession tablet, int lastUpdateSequence, String newMapfileLocation) throws IOException {
logger.minorCompactionStarted(tablet, lastUpdateSequence, newMapfileLocation);
}
public void recover(Tablet tablet, List<LogEntry> logEntries, Set<String> tabletFiles, MutationReceiver mutationReceiver) throws IOException {
List<String> recoveryLogs = new ArrayList<String>();
List<LogEntry> sorted = new ArrayList<LogEntry>(logEntries);
Collections.sort(sorted, new Comparator<LogEntry>() {
@Override
public int compare(LogEntry e1, LogEntry e2) {
return (int) (e1.timestamp - e2.timestamp);
}
});
for (LogEntry entry : sorted) {
String recovery = null;
for (String log : entry.logSet) {
String[] parts = log.split("/"); // "host:port/filename"
log = ServerConstants.getRecoveryDir() + "/" + parts[1] + ".recovered";
Path finished = new Path(log + "/finished");
TabletServer.log.info("Looking for " + finished);
if (fs.exists(finished)) {
recovery = log;
break;
}
}
if (recovery == null)
throw new IOException("Unable to find recovery files for extent " + tablet.getExtent() + " logEntry: " + entry);
recoveryLogs.add(recovery);
}
logger.recover(tablet, recoveryLogs, tabletFiles, mutationReceiver);
}
private final AtomicInteger logIdGenerator = new AtomicInteger();
public int createLogId(KeyExtent tablet) {
String table = tablet.getTableId().toString();
AccumuloConfiguration acuTableConf = ServerConfiguration.getTableConfiguration(table);
if (acuTableConf.getBoolean(Property.TABLE_WALOG_ENABLED)) {
return logIdGenerator.incrementAndGet();
}
return -1;
}
// / JMX methods
@Override
public long getEntries() {
if (this.isEnabled()) {
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.getNumEntries();
}
return result;
}
return 0;
}
@Override
public long getEntriesInMemory() {
if (this.isEnabled()) {
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.getNumEntriesInMemory();
}
return result;
}
return 0;
}
@Override
public long getIngest() {
if (this.isEnabled()) {
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.getNumEntriesInMemory();
}
return result;
}
return 0;
}
@Override
public int getMajorCompactions() {
if (this.isEnabled()) {
int result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
if (tablet.majorCompactionRunning())
result++;
}
return result;
}
return 0;
}
@Override
public int getMajorCompactionsQueued() {
if (this.isEnabled()) {
int result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
if (tablet.majorCompactionQueued())
result++;
}
return result;
}
return 0;
}
@Override
public int getMinorCompactions() {
if (this.isEnabled()) {
int result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
if (tablet.minorCompactionRunning())
result++;
}
return result;
}
return 0;
}
@Override
public int getMinorCompactionsQueued() {
if (this.isEnabled()) {
int result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
if (tablet.minorCompactionQueued())
result++;
}
return result;
}
return 0;
}
@Override
public int getOnlineCount() {
if (this.isEnabled())
return onlineTablets.size();
return 0;
}
@Override
public int getOpeningCount() {
if (this.isEnabled())
return openingTablets.size();
return 0;
}
@Override
public long getQueries() {
if (this.isEnabled()) {
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.totalQueries();
}
return result;
}
return 0;
}
@Override
public int getUnopenedCount() {
if (this.isEnabled())
return unopenedTablets.size();
return 0;
}
@Override
public String getName() {
if (this.isEnabled())
return getClientAddressString();
return "";
}
@Override
public long getTotalMinorCompactions() {
if (this.isEnabled())
return totalMinorCompactions;
return 0;
}
@Override
public double getHoldTime() {
if (this.isEnabled())
return this.resourceManager.holdTime() / 1000.;
return 0;
}
@Override
public double getAverageFilesPerTablet() {
if (this.isEnabled()) {
int count = 0;
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.getDatafiles().size();
count++;
}
if (count == 0)
return 0;
return result / (double) count;
}
return 0;
}
protected ObjectName getObjectName() {
return OBJECT_NAME;
}
protected String getMetricsPrefix() {
return METRICS_PREFIX;
}
}
| src/server/src/main/java/org/apache/accumulo/server/tabletserver/TabletServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.server.tabletserver;
import static org.apache.accumulo.server.problems.ProblemType.TABLET_LOAD;
import java.io.File;
import java.io.IOException;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.impl.TabletType;
import org.apache.accumulo.core.client.impl.Translator;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.constraints.Violations;
import org.apache.accumulo.core.constraints.Constraint.Environment;
import org.apache.accumulo.core.data.Column;
import org.apache.accumulo.core.data.ConstraintViolationSummary;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.data.thrift.InitialMultiScan;
import org.apache.accumulo.core.data.thrift.InitialScan;
import org.apache.accumulo.core.data.thrift.IterInfo;
import org.apache.accumulo.core.data.thrift.MapFileInfo;
import org.apache.accumulo.core.data.thrift.MultiScanResult;
import org.apache.accumulo.core.data.thrift.ScanResult;
import org.apache.accumulo.core.data.thrift.TColumn;
import org.apache.accumulo.core.data.thrift.TKey;
import org.apache.accumulo.core.data.thrift.TKeyExtent;
import org.apache.accumulo.core.data.thrift.TKeyValue;
import org.apache.accumulo.core.data.thrift.TMutation;
import org.apache.accumulo.core.data.thrift.TRange;
import org.apache.accumulo.core.data.thrift.UpdateErrors;
import org.apache.accumulo.core.file.FileUtil;
import org.apache.accumulo.core.iterators.IterationInterruptedException;
import org.apache.accumulo.core.master.MasterNotRunningException;
import org.apache.accumulo.core.master.thrift.Compacting;
import org.apache.accumulo.core.master.thrift.MasterClientService;
import org.apache.accumulo.core.master.thrift.TableInfo;
import org.apache.accumulo.core.master.thrift.TabletLoadState;
import org.apache.accumulo.core.master.thrift.TabletServerStatus;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.SystemPermission;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.core.security.thrift.AuthInfo;
import org.apache.accumulo.core.security.thrift.SecurityErrorCode;
import org.apache.accumulo.core.security.thrift.ThriftSecurityException;
import org.apache.accumulo.core.tabletserver.thrift.ActiveScan;
import org.apache.accumulo.core.tabletserver.thrift.ConstraintViolationException;
import org.apache.accumulo.core.tabletserver.thrift.NoSuchScanIDException;
import org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException;
import org.apache.accumulo.core.tabletserver.thrift.ScanState;
import org.apache.accumulo.core.tabletserver.thrift.ScanType;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.tabletserver.thrift.TabletStats;
import org.apache.accumulo.core.util.AddressUtil;
import org.apache.accumulo.core.util.ByteBufferUtil;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.core.util.ColumnFQ;
import org.apache.accumulo.core.util.Daemon;
import org.apache.accumulo.core.util.LoggingRunnable;
import org.apache.accumulo.core.util.ServerServices;
import org.apache.accumulo.core.util.Stat;
import org.apache.accumulo.core.util.ThriftUtil;
import org.apache.accumulo.core.util.UtilWaitThread;
import org.apache.accumulo.core.util.ServerServices.Service;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.core.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.server.Accumulo;
import org.apache.accumulo.server.ServerConstants;
import org.apache.accumulo.server.client.ClientServiceHandler;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.conf.ServerConfiguration;
import org.apache.accumulo.server.master.state.Assignment;
import org.apache.accumulo.server.master.state.DistributedStoreException;
import org.apache.accumulo.server.master.state.TServerInstance;
import org.apache.accumulo.server.master.state.TabletLocationState;
import org.apache.accumulo.server.master.state.TabletStateStore;
import org.apache.accumulo.server.metrics.AbstractMetricsImpl;
import org.apache.accumulo.server.problems.ProblemReport;
import org.apache.accumulo.server.problems.ProblemReports;
import org.apache.accumulo.server.security.Authenticator;
import org.apache.accumulo.server.security.SecurityConstants;
import org.apache.accumulo.server.security.ZKAuthenticator;
import org.apache.accumulo.server.tabletserver.Tablet.CommitSession;
import org.apache.accumulo.server.tabletserver.Tablet.KVEntry;
import org.apache.accumulo.server.tabletserver.Tablet.LookupResult;
import org.apache.accumulo.server.tabletserver.Tablet.MajorCompactionReason;
import org.apache.accumulo.server.tabletserver.Tablet.ScanBatch;
import org.apache.accumulo.server.tabletserver.Tablet.Scanner;
import org.apache.accumulo.server.tabletserver.Tablet.SplitInfo;
import org.apache.accumulo.server.tabletserver.Tablet.TConstraintViolationException;
import org.apache.accumulo.server.tabletserver.Tablet.TabletClosedException;
import org.apache.accumulo.server.tabletserver.TabletServerResourceManager.TabletResourceManager;
import org.apache.accumulo.server.tabletserver.TabletStatsKeeper.Operation;
import org.apache.accumulo.server.tabletserver.log.LoggerStrategy;
import org.apache.accumulo.server.tabletserver.log.MutationReceiver;
import org.apache.accumulo.server.tabletserver.log.RemoteLogger;
import org.apache.accumulo.server.tabletserver.log.RoundRobinLoggerStrategy;
import org.apache.accumulo.server.tabletserver.log.TabletServerLogger;
import org.apache.accumulo.server.tabletserver.mastermessage.MasterMessage;
import org.apache.accumulo.server.tabletserver.mastermessage.SplitReportMessage;
import org.apache.accumulo.server.tabletserver.mastermessage.TabletStatusMessage;
import org.apache.accumulo.server.tabletserver.metrics.TabletServerMBean;
import org.apache.accumulo.server.tabletserver.metrics.TabletServerMinCMetrics;
import org.apache.accumulo.server.tabletserver.metrics.TabletServerScanMetrics;
import org.apache.accumulo.server.tabletserver.metrics.TabletServerUpdateMetrics;
import org.apache.accumulo.server.trace.TraceFileSystem;
import org.apache.accumulo.server.util.FileSystemMonitor;
import org.apache.accumulo.server.util.Halt;
import org.apache.accumulo.server.util.MapCounter;
import org.apache.accumulo.server.util.MetadataTable;
import org.apache.accumulo.server.util.TServerUtils;
import org.apache.accumulo.server.util.MetadataTable.LogEntry;
import org.apache.accumulo.server.util.TServerUtils.ServerPort;
import org.apache.accumulo.server.util.time.RelativeTime;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.server.zookeeper.IZooReaderWriter;
import org.apache.accumulo.server.zookeeper.TransactionWatcher;
import org.apache.accumulo.server.zookeeper.ZooCache;
import org.apache.accumulo.server.zookeeper.ZooLock;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.accumulo.server.zookeeper.ZooLock.LockLossReason;
import org.apache.accumulo.server.zookeeper.ZooLock.LockWatcher;
import org.apache.accumulo.start.Platform;
import org.apache.accumulo.start.classloader.AccumuloClassLoader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.server.TServer;
import org.apache.zookeeper.KeeperException;
import cloudtrace.instrument.Span;
import cloudtrace.instrument.Trace;
import cloudtrace.instrument.thrift.TraceWrap;
import cloudtrace.thrift.TInfo;
enum ScanRunState {
QUEUED, RUNNING, FINISHED
}
public class TabletServer extends AbstractMetricsImpl implements TabletServerMBean {
private static final Logger log = Logger.getLogger(TabletServer.class);
private static HashMap<String,Long> prevGcTime = new HashMap<String,Long>();
private static long lastMemorySize = 0;
private static long gcTimeIncreasedCount;
private static AtomicLong scanCount = new AtomicLong();
private static final Class<? extends LoggerStrategy> DEFAULT_LOGGER_STRATEGY = RoundRobinLoggerStrategy.class;
private static final long MAX_TIME_TO_WAIT_FOR_SCAN_RESULT_MILLIS = 1000;
private TabletServerLogger logger;
private LoggerStrategy loggerStrategy;
protected TabletServerMinCMetrics mincMetrics = new TabletServerMinCMetrics();
public TabletServer() {
super();
SimpleTimer.getInstance().schedule(new TimerTask() {
@Override
public void run() {
synchronized (onlineTablets) {
long now = System.currentTimeMillis();
for (Tablet tablet : onlineTablets.values())
try {
tablet.updateRates(now);
} catch (Exception ex) {
log.error(ex, ex);
}
}
}
}, 5000, 5000);
}
private synchronized static void logGCInfo() {
List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans();
Runtime rt = Runtime.getRuntime();
StringBuilder sb = new StringBuilder("gc");
boolean sawChange = false;
long maxIncreaseInCollectionTime = 0;
for (GarbageCollectorMXBean gcBean : gcmBeans) {
Long prevTime = prevGcTime.get(gcBean.getName());
long pt = 0;
if (prevTime != null) {
pt = prevTime;
}
long time = gcBean.getCollectionTime();
if (time - pt != 0) {
sawChange = true;
}
long increaseInCollectionTime = time - pt;
sb.append(String.format(" %s=%,.2f(+%,.2f) secs", gcBean.getName(), time / 1000.0, increaseInCollectionTime / 1000.0));
maxIncreaseInCollectionTime = Math.max(increaseInCollectionTime, maxIncreaseInCollectionTime);
prevGcTime.put(gcBean.getName(), time);
}
long mem = rt.freeMemory();
if (maxIncreaseInCollectionTime == 0) {
gcTimeIncreasedCount = 0;
} else {
gcTimeIncreasedCount++;
if (gcTimeIncreasedCount > 3 && mem < rt.totalMemory() * 0.05) {
log.warn("Running low on memory");
gcTimeIncreasedCount = 0;
}
}
if (mem > lastMemorySize) {
sawChange = true;
}
String sign = "+";
if (mem - lastMemorySize <= 0) {
sign = "";
}
sb.append(String.format(" freemem=%,d(%s%,d) totalmem=%,d", mem, sign, (mem - lastMemorySize), rt.totalMemory()));
if (sawChange) {
log.debug(sb.toString());
}
final long keepAliveTimeout = ServerConfiguration.getSystemConfiguration().getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT);
if (maxIncreaseInCollectionTime > keepAliveTimeout) {
Halt.halt("Garbage collection may be interfering with lock keep-alive. Halting.", -1);
}
lastMemorySize = mem;
}
private TabletStatsKeeper statsKeeper;
private static class Session {
long lastAccessTime;
long startTime;
String user;
String client = TServerUtils.clientAddress.get();
public boolean reserved;
public void cleanup() {}
}
private static class SessionManager {
SecureRandom random;
Map<Long,Session> sessions;
SessionManager() {
random = new SecureRandom();
sessions = new HashMap<Long,Session>();
final long maxIdle = ServerConfiguration.getSystemConfiguration().getTimeInMillis(Property.TSERV_SESSION_MAXIDLE);
TimerTask r = new TimerTask() {
public void run() {
sweep(maxIdle);
}
};
SimpleTimer.getInstance().schedule(r, 0, Math.max(maxIdle / 2, 1000));
}
synchronized long createSession(Session session, boolean reserve) {
long sid = random.nextLong();
while (sessions.containsKey(sid)) {
sid = random.nextLong();
}
sessions.put(sid, session);
session.reserved = reserve;
session.startTime = session.lastAccessTime = System.currentTimeMillis();
return sid;
}
/**
* while a session is reserved, it cannot be canceled or removed
*
* @param sessionId
*/
synchronized Session reserveSession(long sessionId) {
Session session = sessions.get(sessionId);
if (session != null) {
if (session.reserved)
throw new IllegalStateException();
session.reserved = true;
}
return session;
}
synchronized void unreserveSession(Session session) {
if (!session.reserved)
throw new IllegalStateException();
session.reserved = false;
session.lastAccessTime = System.currentTimeMillis();
}
synchronized void unreserveSession(long sessionId) {
Session session = getSession(sessionId);
if (session != null)
unreserveSession(session);
}
synchronized Session getSession(long sessionId) {
Session session = sessions.get(sessionId);
if (session != null)
session.lastAccessTime = System.currentTimeMillis();
return session;
}
Session removeSession(long sessionId) {
Session session = null;
synchronized (this) {
session = sessions.remove(sessionId);
}
// do clean up out side of lock..
if (session != null)
session.cleanup();
return session;
}
private void sweep(long maxIdle) {
ArrayList<Session> sessionsToCleanup = new ArrayList<Session>();
synchronized (this) {
Iterator<Session> iter = sessions.values().iterator();
while (iter.hasNext()) {
Session session = iter.next();
long idleTime = System.currentTimeMillis() - session.lastAccessTime;
if (idleTime > maxIdle && !session.reserved) {
iter.remove();
sessionsToCleanup.add(session);
}
}
}
// do clean up outside of lock
for (Session session : sessionsToCleanup) {
session.cleanup();
}
}
synchronized void removeIfNotAccessed(final long sessionId, long delay) {
Session session = sessions.get(sessionId);
if (session != null) {
final long removeTime = session.lastAccessTime;
TimerTask r = new TimerTask() {
public void run() {
Session sessionToCleanup = null;
synchronized (SessionManager.this) {
Session session2 = sessions.get(sessionId);
if (session2 != null && session2.lastAccessTime == removeTime && !session2.reserved) {
sessions.remove(sessionId);
sessionToCleanup = session2;
}
}
// call clean up outside of lock
if (sessionToCleanup != null)
sessionToCleanup.cleanup();
}
};
SimpleTimer.getInstance().schedule(r, delay);
}
}
public synchronized Map<String,MapCounter<ScanRunState>> getActiveScansPerTable() {
Map<String,MapCounter<ScanRunState>> counts = new HashMap<String,MapCounter<ScanRunState>>();
for (Entry<Long,Session> entry : sessions.entrySet()) {
Session session = entry.getValue();
@SuppressWarnings("rawtypes")
ScanTask nbt = null;
String tableID = null;
if (session instanceof ScanSession) {
ScanSession ss = (ScanSession) session;
nbt = ss.nextBatchTask;
tableID = ss.extent.getTableId().toString();
} else if (session instanceof MultiScanSession) {
MultiScanSession mss = (MultiScanSession) session;
nbt = mss.lookupTask;
tableID = mss.threadPoolExtent.getTableId().toString();
}
if (nbt == null)
continue;
ScanRunState srs = nbt.getScanRunState();
if (nbt == null || srs == ScanRunState.FINISHED)
continue;
MapCounter<ScanRunState> stateCounts = counts.get(tableID);
if (stateCounts == null) {
stateCounts = new MapCounter<ScanRunState>();
counts.put(tableID, stateCounts);
}
stateCounts.increment(srs, 1);
}
return counts;
}
public synchronized List<ActiveScan> getActiveScans() {
ArrayList<ActiveScan> activeScans = new ArrayList<ActiveScan>();
long ct = System.currentTimeMillis();
for (Entry<Long,Session> entry : sessions.entrySet()) {
Session session = entry.getValue();
if (session instanceof ScanSession) {
ScanSession ss = (ScanSession) session;
ScanState state = ScanState.RUNNING;
ScanTask<ScanBatch> nbt = ss.nextBatchTask;
if (nbt == null) {
state = ScanState.IDLE;
} else {
switch (nbt.getScanRunState()) {
case QUEUED:
state = ScanState.QUEUED;
break;
case FINISHED:
state = ScanState.IDLE;
break;
}
}
activeScans.add(new ActiveScan(ss.client, ss.user, ss.extent.getTableId().toString(), ct - ss.startTime, ct - ss.lastAccessTime, ScanType.SINGLE,
state, ss.extent.toThrift(), Translator.translate(ss.columnSet, Translator.CT), ss.ssiList, ss.ssio));
} else if (session instanceof MultiScanSession) {
MultiScanSession mss = (MultiScanSession) session;
ScanState state = ScanState.RUNNING;
ScanTask<MultiScanResult> nbt = mss.lookupTask;
if (nbt == null) {
state = ScanState.IDLE;
} else {
switch (nbt.getScanRunState()) {
case QUEUED:
state = ScanState.QUEUED;
break;
case FINISHED:
state = ScanState.IDLE;
break;
}
}
activeScans.add(new ActiveScan(mss.client, mss.user, mss.threadPoolExtent.getTableId().toString(), ct - mss.startTime, ct - mss.lastAccessTime,
ScanType.BATCH, state, mss.threadPoolExtent.toThrift(), Translator.translate(mss.columnSet, Translator.CT), mss.ssiList, mss.ssio));
}
}
return activeScans;
}
}
static class TservConstraintEnv implements Environment {
private AuthInfo credentials;
private Authenticator authenticator;
private Authorizations auths;
private KeyExtent ke;
TservConstraintEnv(Authenticator authenticator, AuthInfo credentials) {
this.authenticator = authenticator;
this.credentials = credentials;
}
void setExtent(KeyExtent ke) {
this.ke = ke;
}
@Override
public KeyExtent getExtent() {
return ke;
}
@Override
public String getUser() {
return credentials.user;
}
@Override
public Authorizations getAuthorizations() {
if (auths == null)
try {
this.auths = authenticator.getUserAuthorizations(credentials, getUser());
} catch (AccumuloSecurityException e) {
throw new RuntimeException(e);
}
return auths;
}
}
private abstract class ScanTask<T> implements RunnableFuture<T> {
protected AtomicBoolean interruptFlag;
protected ArrayBlockingQueue<Object> resultQueue;
protected AtomicInteger state;
protected AtomicReference<ScanRunState> runState;
private static final int INITIAL = 1;
private static final int ADDED = 2;
private static final int CANCELED = 3;
ScanTask() {
interruptFlag = new AtomicBoolean(false);
runState = new AtomicReference<ScanRunState>(ScanRunState.QUEUED);
state = new AtomicInteger(INITIAL);
resultQueue = new ArrayBlockingQueue<Object>(1);
}
protected void addResult(Object o) {
if (state.compareAndSet(INITIAL, ADDED))
resultQueue.add(o);
else if (state.get() == ADDED)
throw new IllegalStateException("Tried to add more than one result");
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (!mayInterruptIfRunning)
throw new IllegalArgumentException("Cancel will always attempt to interupt running next batch task");
if (state.get() == CANCELED)
return true;
if (state.compareAndSet(INITIAL, CANCELED)) {
interruptFlag.set(true);
resultQueue = null;
return true;
}
return false;
}
@Override
public T get() throws InterruptedException, ExecutionException {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
ArrayBlockingQueue<Object> localRQ = resultQueue;
if (state.get() == CANCELED)
throw new CancellationException();
if (localRQ == null && state.get() == ADDED)
throw new IllegalStateException("Tried to get result twice");
Object r = localRQ.poll(timeout, unit);
// could have been canceled while waiting
if (state.get() == CANCELED) {
if (r != null)
throw new IllegalStateException("Nothing should have been added when in canceled state");
throw new CancellationException();
}
if (r == null)
throw new TimeoutException();
// make this method stop working now that something is being
// returned
resultQueue = null;
if (r instanceof Throwable)
throw new ExecutionException((Throwable) r);
return (T) r;
}
@Override
public boolean isCancelled() {
return state.get() == CANCELED;
}
@Override
public boolean isDone() {
return runState.get().equals(ScanRunState.FINISHED);
}
public ScanRunState getScanRunState() {
return runState.get();
}
}
private static class UpdateSession extends Session {
public Tablet currentTablet;
public MapCounter<Tablet> successfulCommits = new MapCounter<Tablet>();
Map<KeyExtent,Long> failures = new HashMap<KeyExtent,Long>();
List<KeyExtent> authFailures = new ArrayList<KeyExtent>();
public Violations violations;
public AuthInfo credentials;
public long totalUpdates = 0;
public long flushTime = 0;
Stat prepareTimes = new Stat();
Stat walogTimes = new Stat();
Stat commitTimes = new Stat();
Stat authTimes = new Stat();
public Map<Tablet,List<Mutation>> queuedMutations = new HashMap<Tablet,List<Mutation>>();
public long queuedMutationSize = 0;
TservConstraintEnv cenv = null;
}
private static class ScanSession extends Session {
public KeyExtent extent;
public HashSet<Column> columnSet;
public List<IterInfo> ssiList;
public Map<String,Map<String,String>> ssio;
public long entriesReturned = 0;
public Stat nbTimes = new Stat();
public long batchCount = 0;
public volatile ScanTask<ScanBatch> nextBatchTask;
public AtomicBoolean interruptFlag;
public Scanner scanner;
@Override
public void cleanup() {
try {
if (nextBatchTask != null)
nextBatchTask.cancel(true);
} finally {
if (scanner != null)
scanner.close();
}
}
}
private static class MultiScanSession extends Session {
HashSet<Column> columnSet;
Map<KeyExtent,List<Range>> queries;
public List<IterInfo> ssiList;
public Map<String,Map<String,String>> ssio;
public Authorizations auths;
// stats
int numRanges;
int numTablets;
int numEntries;
long totalLookupTime;
public volatile ScanTask<MultiScanResult> lookupTask;
public KeyExtent threadPoolExtent;
@Override
public void cleanup() {
if (lookupTask != null)
lookupTask.cancel(true);
}
}
/**
* This little class keeps track of writes in progress and allows readers to wait for writes that started before the read. It assumes that the operation ids
* are monotonically increasing.
*
*/
static class WriteTracker {
private static AtomicLong operationCounter = new AtomicLong(1);
private Map<TabletType,TreeSet<Long>> inProgressWrites = new EnumMap<TabletType,TreeSet<Long>>(TabletType.class);
WriteTracker() {
for (TabletType ttype : TabletType.values()) {
inProgressWrites.put(ttype, new TreeSet<Long>());
}
}
synchronized long startWrite(TabletType ttype) {
long operationId = operationCounter.getAndIncrement();
inProgressWrites.get(ttype).add(operationId);
return operationId;
}
synchronized void finishWrite(long operationId) {
if (operationId == -1)
return;
boolean removed = false;
for (TabletType ttype : TabletType.values()) {
removed = inProgressWrites.get(ttype).remove(operationId);
if (removed)
break;
}
if (!removed) {
throw new IllegalArgumentException("Attempted to finish write not in progress, operationId " + operationId);
}
this.notifyAll();
}
synchronized void waitForWrites(TabletType ttype) {
long operationId = operationCounter.getAndIncrement();
while (inProgressWrites.get(ttype).floor(operationId) != null) {
try {
this.wait();
} catch (InterruptedException e) {
log.error(e, e);
}
}
}
public long startWrite(Set<Tablet> keySet) {
if (keySet.size() == 0)
return -1;
ArrayList<KeyExtent> extents = new ArrayList<KeyExtent>(keySet.size());
for (Tablet tablet : keySet)
extents.add(tablet.getExtent());
return startWrite(TabletType.type(extents));
}
}
TransactionWatcher watcher = new TransactionWatcher();
private class ThriftClientHandler extends ClientServiceHandler implements TabletClientService.Iface {
SessionManager sessionManager;
AccumuloConfiguration acuConf = ServerConfiguration.getSystemConfiguration();
TabletServerUpdateMetrics updateMetrics = new TabletServerUpdateMetrics();
TabletServerScanMetrics scanMetrics = new TabletServerScanMetrics();
WriteTracker writeTracker = new WriteTracker();
ThriftClientHandler() {
super(watcher);
log.debug(ThriftClientHandler.class.getName() + " created");
sessionManager = new SessionManager();
// Register the metrics MBean
try {
updateMetrics.register();
scanMetrics.register();
} catch (Exception e) {
log.error("Exception registering MBean with MBean Server", e);
}
}
@Override
public List<TKeyExtent> bulkImport(TInfo tinfo, AuthInfo credentials, long tid, Map<TKeyExtent,Map<String,MapFileInfo>> files, boolean setTime)
throws ThriftSecurityException {
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
ArrayList<TKeyExtent> failures = new ArrayList<TKeyExtent>();
for (Entry<TKeyExtent,Map<String,MapFileInfo>> entry : files.entrySet()) {
TKeyExtent tke = entry.getKey();
Map<String,MapFileInfo> fileMap = entry.getValue();
Tablet importTablet = onlineTablets.get(new KeyExtent(tke));
if (importTablet == null) {
failures.add(tke);
} else {
try {
importTablet.importMapFiles(tid, fileMap, setTime);
} catch (IOException ioe) {
log.info("file not imported: " + ioe.getMessage());
failures.add(tke);
}
}
}
return failures;
}
private class NextBatchTask extends ScanTask<ScanBatch> {
private long scanID;
NextBatchTask(long scanID, AtomicBoolean interruptFlag) {
this.scanID = scanID;
this.interruptFlag = interruptFlag;
if (interruptFlag.get())
cancel(true);
}
@Override
public void run() {
ScanSession scanSession = (ScanSession) sessionManager.getSession(scanID);
try {
runState.set(ScanRunState.RUNNING);
if (isCancelled() || scanSession == null)
return;
Tablet tablet = onlineTablets.get(scanSession.extent);
if (tablet == null) {
addResult(new org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException(scanSession.extent.toThrift()));
return;
}
long t1 = System.currentTimeMillis();
ScanBatch batch = scanSession.scanner.read();
long t2 = System.currentTimeMillis();
scanSession.nbTimes.addStat(t2 - t1);
// there should only be one thing on the queue at a time, so
// it should be ok to call add()
// instead of put()... if add() fails because queue is at
// capacity it means there is code
// problem somewhere
addResult(batch);
} catch (TabletClosedException e) {
addResult(new org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException(scanSession.extent.toThrift()));
} catch (IterationInterruptedException iie) {
if (!isCancelled()) {
log.warn("Iteration interrupted, when scan not cancelled", iie);
addResult(iie);
}
} catch (TooManyFilesException tmfe) {
addResult(tmfe);
} catch (Throwable e) {
log.warn("exception while scanning tablet " + scanSession.extent, e);
addResult(e);
} finally {
runState.set(ScanRunState.FINISHED);
}
}
}
private class LookupTask extends ScanTask<MultiScanResult> {
private long scanID;
LookupTask(long scanID) {
this.scanID = scanID;
}
@Override
public void run() {
MultiScanSession session = (MultiScanSession) sessionManager.getSession(scanID);
try {
runState.set(ScanRunState.RUNNING);
if (isCancelled() || session == null)
return;
long maxResultsSize = acuConf.getMemoryInBytes(Property.TABLE_SCAN_MAXMEM);
long bytesAdded = 0;
long maxScanTime = 4000;
long startTime = System.currentTimeMillis();
ArrayList<KVEntry> results = new ArrayList<KVEntry>();
Map<KeyExtent,List<Range>> failures = new HashMap<KeyExtent,List<Range>>();
ArrayList<KeyExtent> fullScans = new ArrayList<KeyExtent>();
KeyExtent partScan = null;
Key partNextKey = null;
boolean partNextKeyInclusive = false;
Iterator<Entry<KeyExtent,List<Range>>> iter = session.queries.entrySet().iterator();
// check the time so that the read ahead thread is not
// monopolized
while (iter.hasNext() && bytesAdded < maxResultsSize && (System.currentTimeMillis() - startTime) < maxScanTime) {
Entry<KeyExtent,List<Range>> entry = iter.next();
iter.remove();
// check that tablet server is serving requested tablet
Tablet tablet = onlineTablets.get(entry.getKey());
if (tablet == null) {
failures.put(entry.getKey(), entry.getValue());
continue;
}
LookupResult lookupResult;
try {
// do the following check to avoid a race condition
// between setting false below and the task being
// canceled
if (isCancelled())
interruptFlag.set(true);
lookupResult = tablet.lookup(entry.getValue(), session.columnSet, session.auths, results, maxResultsSize - bytesAdded, session.ssiList,
session.ssio, interruptFlag);
// if the tablet was closed it it possible that the
// interrupt flag was set.... do not want it set for
// the next
// lookup
interruptFlag.set(false);
} catch (IOException e) {
log.warn("lookup failed for tablet " + entry.getKey(), e);
throw new RuntimeException(e);
}
bytesAdded += lookupResult.bytesAdded;
if (lookupResult.unfinishedRanges.size() > 0) {
if (lookupResult.closed) {
failures.put(entry.getKey(), lookupResult.unfinishedRanges);
} else {
session.queries.put(entry.getKey(), lookupResult.unfinishedRanges);
partScan = entry.getKey();
partNextKey = lookupResult.unfinishedRanges.get(0).getStartKey();
partNextKeyInclusive = lookupResult.unfinishedRanges.get(0).isStartKeyInclusive();
}
} else {
fullScans.add(entry.getKey());
}
}
long finishTime = System.currentTimeMillis();
session.totalLookupTime += (finishTime - startTime);
session.numEntries += results.size();
// convert everything to thrift before adding result
List<TKeyValue> retResults = new ArrayList<TKeyValue>();
for (KVEntry entry : results)
retResults.add(new TKeyValue(entry.key.toThrift(), ByteBuffer.wrap(entry.value)));
Map<TKeyExtent,List<TRange>> retFailures = Translator.translate(failures, Translator.KET, new Translator.ListTranslator<Range,TRange>(Translator.RT));
List<TKeyExtent> retFullScans = Translator.translate(fullScans, Translator.KET);
TKeyExtent retPartScan = null;
TKey retPartNextKey = null;
if (partScan != null) {
retPartScan = partScan.toThrift();
retPartNextKey = partNextKey.toThrift();
}
// add results to queue
addResult(new MultiScanResult(retResults, retFailures, retFullScans, retPartScan, retPartNextKey, partNextKeyInclusive, session.queries.size() != 0));
} catch (IterationInterruptedException iie) {
if (!isCancelled()) {
log.warn("Iteration interrupted, when scan not cancelled", iie);
addResult(iie);
}
} catch (Throwable e) {
log.warn("exception while doing multi-scan ", e);
addResult(e);
} finally {
runState.set(ScanRunState.FINISHED);
}
}
}
@Override
public InitialScan startScan(TInfo tinfo, AuthInfo credentials, TKeyExtent textent, TRange range, List<TColumn> columns, int batchSize,
List<IterInfo> ssiList, Map<String,Map<String,String>> ssio, List<ByteBuffer> authorizations, boolean waitForWrites, boolean isolated)
throws NotServingTabletException, ThriftSecurityException, org.apache.accumulo.core.tabletserver.thrift.TooManyFilesException {
Authorizations userauths = null;
try {
if (!authenticator.hasTablePermission(credentials, credentials.user, new String(textent.getTable()), TablePermission.READ))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
userauths = authenticator.getUserAuthorizations(credentials, credentials.user);
for (ByteBuffer auth : authorizations)
if (!userauths.contains(ByteBufferUtil.toBytes(auth)))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.BAD_AUTHORIZATIONS);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
scanCount.addAndGet(1);
KeyExtent extent = new KeyExtent(textent);
// wait for any writes that are in flight.. this done to ensure
// consistency across client restarts... assume a client writes
// to accumulo and dies while waiting for a confirmation from
// accumulo... the client process restarts and tries to read
// data from accumulo making the assumption that it will get
// any writes previously made... however if the server side thread
// processing the write from the dead client is still in progress,
// the restarted client may not see the write unless we wait here.
// this behavior is very important when the client is reading the
// !METADATA table
if (waitForWrites)
writeTracker.waitForWrites(TabletType.type(extent));
Tablet tablet = onlineTablets.get(extent);
if (tablet == null)
throw new NotServingTabletException(textent);
ScanSession scanSession = new ScanSession();
scanSession.user = credentials.user;
scanSession.extent = new KeyExtent(extent);
scanSession.columnSet = new HashSet<Column>();
scanSession.ssiList = ssiList;
scanSession.ssio = ssio;
scanSession.interruptFlag = new AtomicBoolean();
for (TColumn tcolumn : columns) {
scanSession.columnSet.add(new Column(tcolumn));
}
scanSession.scanner = tablet.createScanner(new Range(range), batchSize, scanSession.columnSet, new Authorizations(authorizations), ssiList, ssio,
isolated, scanSession.interruptFlag);
long sid = sessionManager.createSession(scanSession, true);
ScanResult scanResult;
try {
scanResult = continueScan(tinfo, sid, scanSession);
} catch (NoSuchScanIDException e) {
log.error("The impossible happened", e);
throw new RuntimeException();
} finally {
sessionManager.unreserveSession(sid);
}
return new InitialScan(sid, scanResult);
}
@Override
public ScanResult continueScan(TInfo tinfo, long scanID) throws NoSuchScanIDException, NotServingTabletException,
org.apache.accumulo.core.tabletserver.thrift.TooManyFilesException {
ScanSession scanSession = (ScanSession) sessionManager.reserveSession(scanID);
if (scanSession == null) {
throw new NoSuchScanIDException();
}
try {
return continueScan(tinfo, scanID, scanSession);
} finally {
sessionManager.unreserveSession(scanSession);
}
}
private ScanResult continueScan(TInfo tinfo, long scanID, ScanSession scanSession) throws NoSuchScanIDException, NotServingTabletException,
org.apache.accumulo.core.tabletserver.thrift.TooManyFilesException {
if (scanSession.nextBatchTask == null) {
scanSession.nextBatchTask = new NextBatchTask(scanID, scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, scanSession.nextBatchTask);
}
ScanBatch bresult;
try {
bresult = scanSession.nextBatchTask.get(MAX_TIME_TO_WAIT_FOR_SCAN_RESULT_MILLIS, TimeUnit.MILLISECONDS);
scanSession.nextBatchTask = null;
} catch (ExecutionException e) {
sessionManager.removeSession(scanID);
if (e.getCause() instanceof NotServingTabletException)
throw (NotServingTabletException) e.getCause();
else if (e.getCause() instanceof TooManyFilesException)
throw new org.apache.accumulo.core.tabletserver.thrift.TooManyFilesException(scanSession.extent.toThrift());
else
throw new RuntimeException(e);
} catch (CancellationException ce) {
sessionManager.removeSession(scanID);
Tablet tablet = onlineTablets.get(scanSession.extent);
if (tablet == null || tablet.isClosed())
throw new NotServingTabletException(scanSession.extent.toThrift());
else
throw new NoSuchScanIDException();
} catch (TimeoutException e) {
List<TKeyValue> param = Collections.emptyList();
long timeout = acuConf.getTimeInMillis(Property.TSERV_CLIENT_TIMEOUT);
sessionManager.removeIfNotAccessed(scanID, timeout);
return new ScanResult(param, true);
} catch (Throwable t) {
sessionManager.removeSession(scanID);
log.warn("Failed to get next batch", t);
throw new RuntimeException(t);
}
ScanResult scanResult = new ScanResult(Key.compress(bresult.results), bresult.more);
scanSession.entriesReturned += scanResult.results.size();
scanSession.batchCount++;
if (scanResult.more && scanSession.batchCount > 3) {
// start reading next batch while current batch is transmitted
// to client
scanSession.nextBatchTask = new NextBatchTask(scanID, scanSession.interruptFlag);
resourceManager.executeReadAhead(scanSession.extent, scanSession.nextBatchTask);
}
if (!scanResult.more)
closeScan(tinfo, scanID);
return scanResult;
}
@Override
public void closeScan(TInfo tinfo, long scanID) {
ScanSession ss = (ScanSession) sessionManager.removeSession(scanID);
if (ss != null) {
long t2 = System.currentTimeMillis();
log.debug(String.format("ScanSess tid %s %s %,d entries in %.2f secs, nbTimes = [%s] ", TServerUtils.clientAddress.get(), ss.extent.getTableId()
.toString(), ss.entriesReturned, (t2 - ss.startTime) / 1000.0, ss.nbTimes.toString()));
if (scanMetrics.isEnabled()) {
scanMetrics.add(TabletServerScanMetrics.scan, t2 - ss.startTime);
scanMetrics.add(TabletServerScanMetrics.resultSize, ss.entriesReturned);
}
}
}
@Override
public InitialMultiScan startMultiScan(TInfo tinfo, AuthInfo credentials, Map<TKeyExtent,List<TRange>> tbatch, List<TColumn> tcolumns,
List<IterInfo> ssiList, Map<String,Map<String,String>> ssio, List<ByteBuffer> authorizations, boolean waitForWrites) throws ThriftSecurityException {
// find all of the tables that need to be scanned
HashSet<String> tables = new HashSet<String>();
for (TKeyExtent keyExtent : tbatch.keySet()) {
tables.add(new String(keyExtent.getTable()));
}
// check if user has permission to the tables
Authorizations userauths = null;
try {
for (String table : tables)
if (!authenticator.hasTablePermission(credentials, credentials.user, table, TablePermission.READ))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
userauths = authenticator.getUserAuthorizations(credentials, credentials.user);
for (ByteBuffer auth : authorizations)
if (!userauths.contains(ByteBufferUtil.toBytes(auth)))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.BAD_AUTHORIZATIONS);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
KeyExtent threadPoolExtent = null;
Map<KeyExtent,List<Range>> batch = Translator.translate(tbatch, Translator.TKET, new Translator.ListTranslator<TRange,Range>(Translator.TRT));
for (KeyExtent keyExtent : batch.keySet()) {
if (threadPoolExtent == null) {
threadPoolExtent = keyExtent;
} else if (keyExtent.equals(Constants.ROOT_TABLET_EXTENT)) {
throw new IllegalArgumentException("Cannot batch query root tablet with other tablets " + threadPoolExtent + " " + keyExtent);
} else if (keyExtent.getTableId().toString().equals(Constants.METADATA_TABLE_ID)
&& !threadPoolExtent.getTableId().toString().equals(Constants.METADATA_TABLE_ID)) {
throw new IllegalArgumentException("Cannot batch query !METADATA and non !METADATA tablets " + threadPoolExtent + " " + keyExtent);
}
}
if (waitForWrites)
writeTracker.waitForWrites(TabletType.type(batch.keySet()));
MultiScanSession mss = new MultiScanSession();
mss.user = credentials.user;
mss.queries = batch;
mss.columnSet = new HashSet<Column>(tcolumns.size());
mss.ssiList = ssiList;
mss.ssio = ssio;
mss.auths = new Authorizations(authorizations);
mss.numTablets = batch.size();
for (List<Range> ranges : batch.values()) {
mss.numRanges += ranges.size();
}
for (TColumn tcolumn : tcolumns)
mss.columnSet.add(new Column(tcolumn));
mss.threadPoolExtent = threadPoolExtent;
long sid = sessionManager.createSession(mss, true);
MultiScanResult result;
try {
result = continueMultiScan(tinfo, sid, mss);
} catch (NoSuchScanIDException e) {
log.error("the impossible happened", e);
throw new RuntimeException("the impossible happened", e);
} finally {
sessionManager.unreserveSession(sid);
}
scanCount.addAndGet(batch.size());
return new InitialMultiScan(sid, result);
}
@Override
public MultiScanResult continueMultiScan(TInfo tinfo, long scanID) throws NoSuchScanIDException {
MultiScanSession session = (MultiScanSession) sessionManager.reserveSession(scanID);
if (session == null) {
throw new NoSuchScanIDException();
}
try {
return continueMultiScan(tinfo, scanID, session);
} finally {
sessionManager.unreserveSession(session);
}
}
private MultiScanResult continueMultiScan(TInfo tinfo, long scanID, MultiScanSession session) throws NoSuchScanIDException {
if (session.lookupTask == null) {
session.lookupTask = new LookupTask(scanID);
resourceManager.executeReadAhead(session.threadPoolExtent, session.lookupTask);
}
try {
MultiScanResult scanResult = session.lookupTask.get(MAX_TIME_TO_WAIT_FOR_SCAN_RESULT_MILLIS, TimeUnit.MILLISECONDS);
session.lookupTask = null;
return scanResult;
} catch (TimeoutException e1) {
long timeout = acuConf.getTimeInMillis(Property.TSERV_CLIENT_TIMEOUT);
sessionManager.removeIfNotAccessed(scanID, timeout);
List<TKeyValue> results = Collections.emptyList();
Map<TKeyExtent,List<TRange>> failures = Collections.emptyMap();
List<TKeyExtent> fullScans = Collections.emptyList();
return new MultiScanResult(results, failures, fullScans, null, null, false, true);
} catch (Throwable t) {
sessionManager.removeSession(scanID);
log.warn("Failed to get multiscan result", t);
throw new RuntimeException(t);
}
}
@Override
public void closeMultiScan(TInfo tinfo, long scanID) throws NoSuchScanIDException {
MultiScanSession session = (MultiScanSession) sessionManager.removeSession(scanID);
if (session == null) {
throw new NoSuchScanIDException();
}
long t2 = System.currentTimeMillis();
log.debug(String.format("MultiScanSess %s %,d entries in %.2f secs (lookup_time:%.2f secs tablets:%,d ranges:%,d) ", TServerUtils.clientAddress.get(),
session.numEntries, (t2 - session.startTime) / 1000.0, session.totalLookupTime / 1000.0, session.numTablets, session.numRanges));
}
@Override
public long startUpdate(TInfo tinfo, AuthInfo credentials) throws ThriftSecurityException {
// Make sure user is real
try {
if (!authenticator.authenticateUser(credentials, credentials.user, credentials.password)) {
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.permissionErrors, 0);
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS);
}
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
UpdateSession us = new UpdateSession();
us.violations = new Violations();
us.credentials = credentials;
us.cenv = new TservConstraintEnv(authenticator, credentials);
long sid = sessionManager.createSession(us, false);
return sid;
}
private void setUpdateTablet(UpdateSession us, KeyExtent keyExtent) {
long t1 = System.currentTimeMillis();
try {
// if user has no permission to write to this table, add it to
// the failures list
boolean sameTable = us.currentTablet != null && (us.currentTablet.getExtent().getTableId().equals(keyExtent.getTableId()));
if (sameTable
|| authenticator.hasTablePermission(SecurityConstants.getSystemCredentials(), us.credentials.user, keyExtent.getTableId().toString(),
TablePermission.WRITE)) {
long t2 = System.currentTimeMillis();
us.authTimes.addStat(t2 - t1);
us.currentTablet = onlineTablets.get(keyExtent);
if (us.currentTablet != null) {
us.queuedMutations.put(us.currentTablet, new ArrayList<Mutation>());
} else {
// not serving tablet, so report all mutations as
// failures
us.failures.put(keyExtent, 0l);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.unknownTabletErrors, 0);
}
} else {
log.warn("Denying access to table " + keyExtent.getTableId() + " for user " + us.credentials.user);
long t2 = System.currentTimeMillis();
us.authTimes.addStat(t2 - t1);
us.currentTablet = null;
us.authFailures.add(keyExtent);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.permissionErrors, 0);
return;
}
} catch (AccumuloSecurityException e) {
log.error("Denying permission to check user " + us.credentials.user + " with user " + e.getUser(), e);
long t2 = System.currentTimeMillis();
us.authTimes.addStat(t2 - t1);
us.currentTablet = null;
us.authFailures.add(keyExtent);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.permissionErrors, 0);
return;
}
}
@Override
public void applyUpdates(TInfo tinfo, long updateID, TKeyExtent tkeyExtent, List<TMutation> tmutations) {
UpdateSession us = (UpdateSession) sessionManager.reserveSession(updateID);
if (us == null) {
throw new RuntimeException("No Such SessionID");
}
try {
KeyExtent keyExtent = new KeyExtent(tkeyExtent);
if (us.currentTablet == null || !us.currentTablet.getExtent().equals(keyExtent))
setUpdateTablet(us, keyExtent);
if (us.currentTablet != null) {
List<Mutation> mutations = us.queuedMutations.get(us.currentTablet);
for (TMutation tmutation : tmutations) {
Mutation mutation = new Mutation(tmutation);
mutations.add(mutation);
us.queuedMutationSize += mutation.numBytes();
}
if (us.queuedMutationSize > ServerConfiguration.getSystemConfiguration().getMemoryInBytes(Property.TSERV_MUTATION_QUEUE_MAX))
flush(us);
}
} finally {
sessionManager.unreserveSession(us);
}
}
private void flush(UpdateSession us) {
int mutationCount = 0;
Map<CommitSession,List<Mutation>> sendables = new HashMap<CommitSession,List<Mutation>>();
Throwable error = null;
long pt1 = System.currentTimeMillis();
boolean containsMetadataTablet = false;
for (Tablet tablet : us.queuedMutations.keySet())
if (tablet.getExtent().getTableId().toString().equals(Constants.METADATA_TABLE_ID))
containsMetadataTablet = true;
if (!containsMetadataTablet && us.queuedMutations.size() > 0)
TabletServer.this.resourceManager.waitUntilCommitsAreEnabled();
Span prep = Trace.start("prep");
for (Entry<Tablet,? extends List<Mutation>> entry : us.queuedMutations.entrySet()) {
Tablet tablet = entry.getKey();
List<Mutation> mutations = entry.getValue();
if (mutations.size() > 0) {
try {
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.mutationArraySize, mutations.size());
CommitSession commitSession = tablet.prepareMutationsForCommit(us.cenv, mutations);
if (commitSession == null) {
if (us.currentTablet == tablet) {
us.currentTablet = null;
}
us.failures.put(tablet.getExtent(), us.successfulCommits.get(tablet));
} else {
sendables.put(commitSession, mutations);
mutationCount += mutations.size();
}
} catch (TConstraintViolationException e) {
us.violations.add(e.getViolations());
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.constraintViolations, 0);
if (e.getNonViolators().size() > 0) {
// only log and commit mutations if there were some
// that did not
// violate constraints... this is what
// prepareMutationsForCommit()
// expects
sendables.put(e.getCommitSession(), e.getNonViolators());
}
mutationCount += mutations.size();
} catch (HoldTimeoutException t) {
error = t;
log.debug("Giving up on mutations due to a long memory hold time");
break;
} catch (Throwable t) {
error = t;
log.error("Unexpected error preparing for commit", error);
break;
}
}
}
prep.stop();
Span wal = Trace.start("wal");
long pt2 = System.currentTimeMillis();
long avgPrepareTime = (long) ((pt2 - pt1) / (double) us.queuedMutations.size());
us.prepareTimes.addStat(pt2 - pt1);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.commitPrep, (avgPrepareTime));
if (error != null) {
for (Entry<CommitSession,List<Mutation>> e : sendables.entrySet()) {
e.getKey().abortCommit(e.getValue());
}
throw new RuntimeException(error);
}
try {
while (true) {
try {
long t1 = System.currentTimeMillis();
logger.logManyTablets(sendables);
long t2 = System.currentTimeMillis();
us.walogTimes.addStat(t2 - t1);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.waLogWriteTime, (t2 - t1));
break;
} catch (IOException ex) {
log.warn("logging mutations failed, retrying");
} catch (Throwable t) {
log.error("Unknown exception logging mutations, counts for mutations in flight not decremented!", t);
throw new RuntimeException(t);
}
}
wal.stop();
Span commit = Trace.start("commit");
long t1 = System.currentTimeMillis();
for (Entry<CommitSession,? extends List<Mutation>> entry : sendables.entrySet()) {
CommitSession commitSession = entry.getKey();
List<Mutation> mutations = entry.getValue();
commitSession.commit(mutations);
Tablet tablet = commitSession.getTablet();
if (tablet == us.currentTablet) {
// because constraint violations may filter out some
// mutations, for proper
// accounting with the client code, need to increment
// the count based
// on the original number of mutations from the client
// NOT the filtered number
us.successfulCommits.increment(tablet, us.queuedMutations.get(tablet).size());
}
}
long t2 = System.currentTimeMillis();
long avgCommitTime = (long) ((t2 - t1) / (double) sendables.size());
us.flushTime += (t2 - pt1);
us.commitTimes.addStat(t2 - t1);
if (updateMetrics.isEnabled())
updateMetrics.add(TabletServerUpdateMetrics.commitTime, avgCommitTime);
commit.stop();
} finally {
us.queuedMutations.clear();
if (us.currentTablet != null) {
us.queuedMutations.put(us.currentTablet, new ArrayList<Mutation>());
}
us.queuedMutationSize = 0;
}
us.totalUpdates += mutationCount;
}
@Override
public UpdateErrors closeUpdate(TInfo tinfo, long updateID) throws NoSuchScanIDException {
UpdateSession us = (UpdateSession) sessionManager.removeSession(updateID);
if (us == null) {
throw new NoSuchScanIDException();
}
// clients may or may not see data from an update session while
// it is in progress, however when the update session is closed
// want to ensure that reads wait for the write to finish
long opid = writeTracker.startWrite(us.queuedMutations.keySet());
try {
flush(us);
} finally {
writeTracker.finishWrite(opid);
}
log.debug(String.format("UpSess %s %,d in %.3fs, at=[%s] ft=%.3fs(pt=%.3fs lt=%.3fs ct=%.3fs)", TServerUtils.clientAddress.get(), us.totalUpdates,
(System.currentTimeMillis() - us.startTime) / 1000.0, us.authTimes.toString(), us.flushTime / 1000.0, us.prepareTimes.getSum() / 1000.0,
us.walogTimes.getSum() / 1000.0, us.commitTimes.getSum() / 1000.0));
if (us.failures.size() > 0) {
Entry<KeyExtent,Long> first = us.failures.entrySet().iterator().next();
log.debug(String.format("Failures: %d, first extent %s successful commits: %d", us.failures.size(), first.getKey().toString(), first.getValue()));
}
List<ConstraintViolationSummary> violations = us.violations.asList();
if (violations.size() > 0) {
ConstraintViolationSummary first = us.violations.asList().iterator().next();
log.debug(String.format("Violations: %d, first %s occurs %d", violations.size(), first.violationDescription, first.numberOfViolatingMutations));
}
if (us.authFailures.size() > 0) {
KeyExtent first = us.authFailures.iterator().next();
log.debug(String.format("Authentication Failures: %d, first %s", us.authFailures.size(), first.toString()));
}
return new UpdateErrors(Translator.translate(us.failures, Translator.KET), Translator.translate(violations, Translator.CVST), Translator.translate(
us.authFailures, Translator.KET));
}
@Override
public void update(TInfo tinfo, AuthInfo credentials, TKeyExtent tkeyExtent, TMutation tmutation) throws NotServingTabletException,
ConstraintViolationException, ThriftSecurityException {
try {
if (!authenticator.hasTablePermission(credentials, credentials.user, new String(tkeyExtent.getTable()), TablePermission.WRITE))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
KeyExtent keyExtent = new KeyExtent(tkeyExtent);
Tablet tablet = onlineTablets.get(new KeyExtent(keyExtent));
if (tablet == null) {
throw new NotServingTabletException(tkeyExtent);
}
if (!keyExtent.getTableId().toString().equals(Constants.METADATA_TABLE_ID))
TabletServer.this.resourceManager.waitUntilCommitsAreEnabled();
long opid = writeTracker.startWrite(TabletType.type(keyExtent));
try {
Mutation mutation = new Mutation(tmutation);
List<Mutation> mutations = Collections.singletonList(mutation);
Span prep = Trace.start("prep");
CommitSession cs = tablet.prepareMutationsForCommit(new TservConstraintEnv(authenticator, credentials), mutations);
prep.stop();
if (cs == null) {
throw new NotServingTabletException(tkeyExtent);
}
while (true) {
try {
Span wal = Trace.start("wal");
logger.log(cs, cs.getWALogSeq(), mutation);
wal.stop();
break;
} catch (IOException ex) {
log.warn(ex, ex);
}
}
Span commit = Trace.start("commit");
cs.commit(mutations);
commit.stop();
} catch (TConstraintViolationException e) {
throw new ConstraintViolationException(Translator.translate(e.getViolations().asList(), Translator.CVST));
} finally {
writeTracker.finishWrite(opid);
}
}
@Override
public void splitTablet(TInfo tinfo, AuthInfo credentials, TKeyExtent tkeyExtent, ByteBuffer splitPoint) throws NotServingTabletException,
ThriftSecurityException {
String tableId = new String(ByteBufferUtil.toBytes(tkeyExtent.table));
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_TABLE)
&& !authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM)
&& !authenticator.hasTablePermission(credentials, credentials.user, tableId, TablePermission.ALTER_TABLE))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
KeyExtent keyExtent = new KeyExtent(tkeyExtent);
Tablet tablet = onlineTablets.get(keyExtent);
if (tablet == null) {
throw new NotServingTabletException(tkeyExtent);
}
if (keyExtent.getEndRow() == null || !keyExtent.getEndRow().equals(ByteBufferUtil.toText(splitPoint))) {
try {
if (TabletServer.this.splitTablet(tablet, ByteBufferUtil.toBytes(splitPoint)) == null) {
throw new NotServingTabletException(tkeyExtent);
}
} catch (IOException e) {
log.warn("Failed to split " + keyExtent, e);
throw new RuntimeException(e);
}
}
}
@Override
public TabletServerStatus getTabletServerStatus(TInfo tinfo, AuthInfo credentials) throws ThriftSecurityException, TException {
return getStats(sessionManager.getActiveScansPerTable());
}
@Override
public List<TabletStats> getTabletStats(TInfo tinfo, AuthInfo credentials, String tableId) throws ThriftSecurityException, TException {
TreeMap<KeyExtent,Tablet> onlineTabletsCopy;
synchronized (onlineTablets) {
onlineTabletsCopy = new TreeMap<KeyExtent,Tablet>(onlineTablets);
}
List<TabletStats> result = new ArrayList<TabletStats>();
Text text = new Text(tableId);
KeyExtent start = new KeyExtent(text, new Text(), null);
for (Entry<KeyExtent,Tablet> entry : onlineTabletsCopy.tailMap(start).entrySet()) {
KeyExtent ke = entry.getKey();
if (ke.getTableId().compareTo(text) == 0) {
Tablet tablet = entry.getValue();
TabletStats stats = tablet.timer.getTabletStats();
stats.extent = ke.toThrift();
stats.ingestRate = tablet.ingestRate();
stats.queryRate = tablet.queryRate();
stats.splitCreationTime = tablet.getSplitCreationTime();
stats.numEntries = tablet.getNumEntries();
result.add(stats);
}
}
return result;
}
private ZooCache masterLockCache = new ZooCache();
private void checkPermission(AuthInfo credentials, String lock, boolean requiresSystemPermission, final String request) throws ThriftSecurityException {
if (requiresSystemPermission) {
boolean fatal = false;
try {
log.debug("Got " + request + " message from user: " + credentials.user);
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM)) {
log.warn("Got " + request + " message from user: " + credentials.user);
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
}
} catch (AccumuloSecurityException e) {
log.warn("Got " + request + " message from unauthenticatable user: " + e.getUser());
if (e.getUser().equals(SecurityConstants.SYSTEM_USERNAME)) {
log.fatal("Got message from a service with a mismatched configuration. Please ensure a compatible configuration.", e);
fatal = true;
}
throw e.asThriftException();
} finally {
if (fatal) {
Halt.halt(1, new Runnable() {
public void run() {
logGCInfo();
}
});
}
}
}
if (tabletServerLock == null || !tabletServerLock.wasLockAcquired()) {
log.warn("Got " + request + " message from master before lock acquired, ignoring...");
throw new RuntimeException("Lock not acquired");
}
if (tabletServerLock != null && tabletServerLock.wasLockAcquired() && !tabletServerLock.isLocked()) {
Halt.halt(1, new Runnable() {
public void run() {
log.info("Tablet server no longer holds lock during checkPermission() : " + request + ", exiting");
logGCInfo();
}
});
}
ZooUtil.LockID lid = new ZooUtil.LockID(ZooUtil.getRoot(HdfsZooInstance.getInstance()) + Constants.ZMASTER_LOCK, lock);
try {
if (!ZooLock.isLockHeld(masterLockCache, lid)) {
// maybe the cache is out of date and a new master holds the
// lock?
masterLockCache.clear();
if (!ZooLock.isLockHeld(masterLockCache, lid)) {
log.warn("Got " + request + " message from a master that does not hold the current lock " + lock);
throw new RuntimeException("bad master lock");
}
}
} catch (Exception e) {
throw new RuntimeException("bad master lock", e);
}
}
@Override
public void loadTablet(TInfo tinfo, AuthInfo credentials, String lock, final TKeyExtent textent) {
try {
checkPermission(credentials, lock, true, "loadTablet");
} catch (ThriftSecurityException e) {
log.error(e, e);
throw new RuntimeException(e);
}
final KeyExtent extent = new KeyExtent(textent);
synchronized (unopenedTablets) {
synchronized (openingTablets) {
synchronized (onlineTablets) {
// checking if this exact tablet is in any of the sets
// below is not a strong enough check
// when splits and fix splits occurring
Set<KeyExtent> unopenedOverlapping = KeyExtent.findOverlapping(extent, unopenedTablets);
Set<KeyExtent> openingOverlapping = KeyExtent.findOverlapping(extent, openingTablets);
Set<KeyExtent> onlineOverlapping = KeyExtent.findOverlapping(extent, onlineTablets);
Set<KeyExtent> all = new HashSet<KeyExtent>();
all.addAll(unopenedOverlapping);
all.addAll(openingOverlapping);
all.addAll(onlineOverlapping);
if (!all.isEmpty()) {
if (all.size() != 1 || !all.contains(extent)) {
log.error("Tablet " + extent + " overlaps previously assigned " + unopenedOverlapping + " " + openingOverlapping + " " + onlineOverlapping);
}
return;
}
unopenedTablets.add(extent);
}
}
}
// add the assignment job to the appropriate queue
log.info("Loading tablet " + extent);
final Runnable ah = new LoggingRunnable(log, new AssignmentHandler(extent));
// Root tablet assignment must take place immediately
if (extent.compareTo(Constants.ROOT_TABLET_EXTENT) == 0) {
new Thread("Root Tablet Assignment") {
public void run() {
ah.run();
if (onlineTablets.containsKey(extent)) {
log.info("Root tablet loaded: " + extent);
} else {
log.info("Root tablet failed to load");
}
}
}.start();
} else {
if (extent.getTableId().compareTo(new Text(Constants.METADATA_TABLE_ID)) == 0) {
resourceManager.addMetaDataAssignment(ah);
} else {
resourceManager.addAssignment(ah);
}
}
}
@Override
public void unloadTablet(TInfo tinfo, AuthInfo credentials, String lock, TKeyExtent textent, boolean save) {
try {
checkPermission(credentials, lock, true, "unloadTablet");
} catch (ThriftSecurityException e) {
log.error(e, e);
throw new RuntimeException(e);
}
KeyExtent extent = new KeyExtent(textent);
resourceManager.addMigration(extent, new LoggingRunnable(log, new UnloadTabletHandler(extent, save)));
}
@Override
public void flush(TInfo tinfo, AuthInfo credentials, String lock, String tableId, ByteBuffer startRow, ByteBuffer endRow) {
try {
checkPermission(credentials, lock, true, "flush");
} catch (ThriftSecurityException e) {
log.error(e, e);
throw new RuntimeException(e);
}
ArrayList<Tablet> tabletsToFlush = new ArrayList<Tablet>();
KeyExtent ke = new KeyExtent(new Text(tableId), ByteBufferUtil.toText(endRow), ByteBufferUtil.toText(startRow));
synchronized (onlineTablets) {
for (Tablet tablet : onlineTablets.values())
if (ke.overlaps(tablet.getExtent()))
tabletsToFlush.add(tablet);
}
Long flushID = null;
for (Tablet tablet : tabletsToFlush) {
if (flushID == null) {
// read the flush id once from zookeeper instead of reading
// it for each tablet
flushID = tablet.getFlushID();
}
tablet.flush(flushID);
}
}
@Override
public void flushTablet(TInfo tinfo, AuthInfo credentials, String lock, TKeyExtent textent) throws TException {
try {
checkPermission(credentials, lock, true, "flushTablet");
} catch (ThriftSecurityException e) {
log.error(e, e);
throw new RuntimeException(e);
}
Tablet tablet = onlineTablets.get(new KeyExtent(textent));
if (tablet != null) {
log.info("Flushing " + tablet.getExtent());
tablet.flush(tablet.getFlushID());
}
}
@Override
public void halt(TInfo tinfo, AuthInfo credentials, String lock) throws ThriftSecurityException {
checkPermission(credentials, lock, true, "halt");
Halt.halt(0, new Runnable() {
public void run() {
log.info("Master requested tablet server halt");
logGCInfo();
serverStopRequested = true;
try {
tabletServerLock.unlock();
} catch (Exception e) {
log.error(e, e);
}
}
});
}
@Override
public void fastHalt(TInfo info, AuthInfo credentials, String lock) {
try {
halt(info, credentials, lock);
} catch (Exception e) {
log.warn("Error halting", e);
}
}
@Override
public TabletStats getHistoricalStats(TInfo tinfo, AuthInfo credentials) throws ThriftSecurityException, TException {
return statsKeeper.getTabletStats();
}
@Override
public void useLoggers(TInfo tinfo, AuthInfo credentials, Set<String> loggers) throws TException {
loggerStrategy.preferLoggers(loggers);
}
@Override
public List<ActiveScan> getActiveScans(TInfo tinfo, AuthInfo credentials) throws ThriftSecurityException, TException {
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (AccumuloSecurityException e) {
throw e.asThriftException();
}
return sessionManager.getActiveScans();
}
@Override
public void chop(TInfo tinfo, AuthInfo credentials, String lock, TKeyExtent textent) throws TException {
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (Exception e) {
throw new RuntimeException(e);
}
KeyExtent ke = new KeyExtent(textent);
Tablet tablet = onlineTablets.get(ke);
if (tablet != null) {
tablet.chopFiles();
}
}
@Override
public void compact(TInfo tinfo, AuthInfo credentials, String lock, String tableId, ByteBuffer startRow, ByteBuffer endRow) throws TException {
try {
if (!authenticator.hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM))
throw new ThriftSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED);
} catch (Exception e) {
throw new RuntimeException(e);
}
KeyExtent ke = new KeyExtent(new Text(tableId), ByteBufferUtil.toText(endRow), ByteBufferUtil.toText(startRow));
ArrayList<Tablet> tabletsToCompact = new ArrayList<Tablet>();
synchronized (onlineTablets) {
for (Tablet tablet : onlineTablets.values())
if (ke.overlaps(tablet.getExtent()))
tabletsToCompact.add(tablet);
}
Long compactionId = null;
for (Tablet tablet : tabletsToCompact) {
// all for the same table id, so only need to read
// compaction id once
if (compactionId == null)
compactionId = tablet.getCompactionID();
tablet.compactAll(compactionId);
}
}
}
private class SplitRunner implements Runnable {
private Tablet tablet;
public SplitRunner(Tablet tablet) {
this.tablet = tablet;
}
@Override
public void run() {
if (majorCompactorDisabled) {
// this will make split task that were queued when shutdown was
// initiated exit
return;
}
splitTablet(tablet);
}
}
boolean isMajorCompactionDisabled() {
return majorCompactorDisabled;
}
private class MajorCompactor implements Runnable {
private AccumuloConfiguration acuConf = ServerConfiguration.getSystemConfiguration();
public void run() {
while (!majorCompactorDisabled) {
try {
UtilWaitThread.sleep(acuConf.getTimeInMillis(Property.TSERV_MAJC_DELAY));
TreeMap<KeyExtent,Tablet> copyOnlineTablets = new TreeMap<KeyExtent,Tablet>();
synchronized (onlineTablets) {
copyOnlineTablets.putAll(onlineTablets); // avoid
// concurrent
// modification
}
int numMajorCompactionsInProgress = 0;
Iterator<Entry<KeyExtent,Tablet>> iter = copyOnlineTablets.entrySet().iterator();
while (iter.hasNext() && !majorCompactorDisabled) { // bail
// early
// now
// if
// we're
// shutting
// down
Entry<KeyExtent,Tablet> entry = iter.next();
Tablet tablet = entry.getValue();
// if we need to split AND compact, we need a good way
// to decide what to do
if (tablet.needsSplit()) {
resourceManager.executeSplit(tablet.getExtent(), new LoggingRunnable(log, new SplitRunner(tablet)));
continue;
}
int maxLogEntriesPerTablet = ServerConfiguration.getTableConfiguration(tablet.getExtent().getTableId().toString()).getCount(
Property.TABLE_MINC_LOGS_MAX);
if (tablet.getLogCount() >= maxLogEntriesPerTablet) {
log.debug("Initiating minor compaction for " + tablet.getExtent() + " because it has " + tablet.getLogCount() + " write ahead logs");
tablet.initiateMinorCompaction();
}
synchronized (tablet) {
if (tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL) || tablet.majorCompactionQueued() || tablet.majorCompactionRunning()) {
numMajorCompactionsInProgress++;
continue;
}
}
}
int idleCompactionsToStart = Math.max(1, acuConf.getCount(Property.TSERV_MAJC_MAXCONCURRENT) / 2);
if (numMajorCompactionsInProgress < idleCompactionsToStart) {
// system is not major compacting, can schedule some
// idle compactions
iter = copyOnlineTablets.entrySet().iterator();
while (iter.hasNext() && !majorCompactorDisabled && numMajorCompactionsInProgress < idleCompactionsToStart) {
Entry<KeyExtent,Tablet> entry = iter.next();
Tablet tablet = entry.getValue();
if (tablet.initiateMajorCompaction(MajorCompactionReason.IDLE)) {
numMajorCompactionsInProgress++;
}
}
}
} catch (Throwable t) {
log.error("Unexpected exception in " + Thread.currentThread().getName(), t);
UtilWaitThread.sleep(1000);
}
}
}
}
private void splitTablet(Tablet tablet) {
try {
TreeMap<KeyExtent,SplitInfo> tabletInfo = splitTablet(tablet, null);
if (tabletInfo == null) {
// either split or compact not both
// were not able to split... so see if a major compaction is
// needed
tablet.initiateMajorCompaction(MajorCompactionReason.NORMAL);
}
} catch (IOException e) {
statsKeeper.updateTime(Operation.SPLIT, 0, 0, true);
log.error("split failed: " + e.getMessage() + " for tablet " + tablet.getExtent(), e);
} catch (Exception e) {
statsKeeper.updateTime(Operation.SPLIT, 0, 0, true);
log.error("Unknown error on split: " + e, e);
}
}
private TreeMap<KeyExtent,SplitInfo> splitTablet(Tablet tablet, byte[] splitPoint) throws IOException {
long t1 = System.currentTimeMillis();
TreeMap<KeyExtent,SplitInfo> tabletInfo = tablet.split(splitPoint);
if (tabletInfo == null) {
return null;
}
log.info("Starting split: " + tablet.getExtent());
statsKeeper.incrementStatusSplit();
long start = System.currentTimeMillis();
Tablet[] newTablets = new Tablet[2];
Entry<KeyExtent,SplitInfo> first = tabletInfo.firstEntry();
newTablets[0] = new Tablet(TabletServer.this, new Text(first.getValue().dir), first.getKey(), resourceManager.createTabletResourceManager(),
first.getValue().datafiles, first.getValue().time, first.getValue().initFlushID, first.getValue().initCompactID);
Entry<KeyExtent,SplitInfo> last = tabletInfo.lastEntry();
newTablets[1] = new Tablet(TabletServer.this, new Text(last.getValue().dir), last.getKey(), resourceManager.createTabletResourceManager(),
last.getValue().datafiles, last.getValue().time, last.getValue().initFlushID, last.getValue().initCompactID);
// roll tablet stats over into tablet server's statsKeeper object as
// historical data
statsKeeper.saveMinorTimes(tablet.timer);
statsKeeper.saveMajorTimes(tablet.timer);
// lose the reference to the old tablet and open two new ones
synchronized (onlineTablets) {
onlineTablets.remove(tablet.getExtent());
onlineTablets.put(newTablets[0].getExtent(), newTablets[0]);
onlineTablets.put(newTablets[1].getExtent(), newTablets[1]);
}
// tell the master
enqueueMasterMessage(new SplitReportMessage(tablet.getExtent(), newTablets[0].getExtent(), new Text("/" + newTablets[0].getLocation().getName()),
newTablets[1].getExtent(), new Text("/" + newTablets[1].getLocation().getName())));
statsKeeper.updateTime(Operation.SPLIT, start, 0, false);
long t2 = System.currentTimeMillis();
log.info("Tablet split: " + tablet.getExtent() + " size0 " + newTablets[0].estimateTabletSize() + " size1 " + newTablets[1].estimateTabletSize() + " time "
+ (t2 - t1) + "ms");
return tabletInfo;
}
public long lastPingTime = System.currentTimeMillis();
public Socket currentMaster;
// a queue to hold messages that are to be sent back to the master
private BlockingDeque<MasterMessage> masterMessages = new LinkedBlockingDeque<MasterMessage>();
// add a message for the main thread to send back to the master
void enqueueMasterMessage(MasterMessage m) {
masterMessages.addLast(m);
}
private class UnloadTabletHandler implements Runnable {
private KeyExtent extent;
private boolean saveState;
public UnloadTabletHandler(KeyExtent extent, boolean saveState) {
this.extent = extent;
this.saveState = saveState;
}
public void run() {
Tablet t = null;
synchronized (unopenedTablets) {
if (unopenedTablets.contains(extent)) {
unopenedTablets.remove(extent);
// enqueueMasterMessage(new TabletUnloadedMessage(extent));
return;
}
}
synchronized (openingTablets) {
while (openingTablets.contains(extent)) {
try {
openingTablets.wait();
} catch (InterruptedException e) {}
}
}
synchronized (onlineTablets) {
if (onlineTablets.containsKey(extent)) {
t = onlineTablets.get(extent);
}
}
if (t == null) {
// Tablet has probably been recently unloaded: repeated master
// unload request is crossing the successful unloaded message
log.info("told to unload tablet that was not being served " + extent);
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.UNLOAD_FAILURE_NOT_SERVING, extent));
return;
}
try {
t.close(saveState);
} catch (Throwable e) {
if ((t.isClosing() || t.isClosed()) && e instanceof IllegalStateException) {
log.debug("Failed to unload tablet " + extent + "... it was alread closing or closed : " + e.getMessage());
} else {
log.error("Failed to close tablet " + extent + "... Aborting migration", e);
}
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.UNLOAD_ERROR, extent));
return;
}
// stop serving tablet - client will get not serving tablet
// exceptions
onlineTablets.remove(extent);
try {
TServerInstance instance = new TServerInstance(clientAddress, getLock().getSessionId());
TabletLocationState tls = new TabletLocationState(extent, null, instance, null, null, false);
log.debug("Unassigning " + tls);
TabletStateStore.unassign(tls);
} catch (DistributedStoreException ex) {
log.warn("Unable to update storage", ex);
} catch (KeeperException e) {
log.warn("Unable determine our zookeeper session information", e);
} catch (InterruptedException e) {
log.warn("Interrupted while getting our zookeeper session information", e);
}
// tell the master how it went
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.UNLOADED, extent));
// roll tablet stats over into tablet server's statsKeeper object as
// historical data
statsKeeper.saveMinorTimes(t.timer);
statsKeeper.saveMajorTimes(t.timer);
log.info("unloaded " + extent);
}
}
private class AssignmentHandler implements Runnable {
private KeyExtent extent;
private int retryAttempt = 0;
public AssignmentHandler(KeyExtent extent) {
this.extent = extent;
}
public AssignmentHandler(KeyExtent extent, int retryAttempt) {
this(extent);
this.retryAttempt = retryAttempt;
}
public void run() {
log.info(clientAddress + ": got assignment from master: " + extent);
final boolean isMetaDataTablet = extent.getTableId().toString().compareTo(Constants.METADATA_TABLE_ID) == 0;
synchronized (unopenedTablets) {
synchronized (openingTablets) {
synchronized (onlineTablets) {
// nothing should be moving between sets, do a sanity
// check
Set<KeyExtent> unopenedOverlapping = KeyExtent.findOverlapping(extent, unopenedTablets);
Set<KeyExtent> openingOverlapping = KeyExtent.findOverlapping(extent, openingTablets);
Set<KeyExtent> onlineOverlapping = KeyExtent.findOverlapping(extent, onlineTablets);
if (openingOverlapping.contains(extent) || onlineOverlapping.contains(extent))
return;
if (!unopenedTablets.contains(extent) || unopenedOverlapping.size() != 1 || openingOverlapping.size() > 0 || onlineOverlapping.size() > 0) {
throw new IllegalStateException("overlaps assigned " + extent + " " + !unopenedTablets.contains(extent) + " " + unopenedOverlapping + " "
+ openingOverlapping + " " + onlineOverlapping);
}
}
unopenedTablets.remove(extent);
openingTablets.add(extent);
}
}
log.debug("Loading extent: " + extent);
// check Metadata table before accepting assignment
SortedMap<KeyExtent,Text> tabletsInRange = null;
SortedMap<Key,Value> tabletsKeyValues = new TreeMap<Key,Value>();
try {
tabletsInRange = verifyTabletInformation(extent, TabletServer.this.getTabletSession(), tabletsKeyValues, getClientAddressString(), getLock());
} catch (Exception e) {
synchronized (openingTablets) {
openingTablets.remove(extent);
openingTablets.notifyAll();
}
log.warn("Failed to verify tablet " + extent, e);
throw new RuntimeException(e);
}
if (tabletsInRange == null) {
log.info("Reporting tablet " + extent + " assignment failure: unable to verify Tablet Information");
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.LOAD_FAILURE, extent));
synchronized (openingTablets) {
openingTablets.remove(extent);
openingTablets.notifyAll();
}
return;
}
// If extent given is not the one to be opened, update
if (tabletsInRange.size() != 1 || !tabletsInRange.containsKey(extent)) {
tabletsKeyValues.clear();
synchronized (openingTablets) {
openingTablets.remove(extent);
openingTablets.notifyAll();
for (KeyExtent e : tabletsInRange.keySet())
openingTablets.add(e);
}
} else {
// remove any metadata entries for the previous tablet
Iterator<Key> iter = tabletsKeyValues.keySet().iterator();
Text row = extent.getMetadataEntry();
while (iter.hasNext()) {
Key key = iter.next();
if (!key.getRow().equals(row)) {
iter.remove();
}
}
}
if (tabletsInRange.size() > 1) {
log.debug("Master didn't know " + extent + " was split, letting it know about " + tabletsInRange.keySet());
enqueueMasterMessage(new SplitReportMessage(extent, tabletsInRange));
}
// create the tablet object
for (Entry<KeyExtent,Text> entry : tabletsInRange.entrySet()) {
Tablet tablet = null;
boolean successful = false;
final KeyExtent extentToOpen = entry.getKey();
Text locationToOpen = entry.getValue();
if (onlineTablets.containsKey(extentToOpen)) {
// know this was from fixing a split, because initial check
// would have caught original extent
log.warn("Something is screwy! Already serving tablet " + extentToOpen + " derived from fixing split. Original extent = " + extent);
synchronized (openingTablets) {
openingTablets.remove(extentToOpen);
openingTablets.notifyAll();
}
continue;
}
try {
TabletResourceManager trm = resourceManager.createTabletResourceManager();
// this opens the tablet file and fills in the endKey in the
// extent
tablet = new Tablet(TabletServer.this, locationToOpen, extentToOpen, trm, tabletsKeyValues);
if (!tablet.initiateMinorCompaction() && tablet.getNumEntriesInMemory() > 0) {
log.warn("Minor compaction after recovery fails for " + extentToOpen);
// it is important to wait for minc in the case that the
// minor compaction finish
// event did not make it to the logs (the file will be
// in !METADATA, preventing replay of compacted data)...
// but do not want a majc to wipe the file out from
// !METADATA and then have another process failure...
// this could cause duplicate data to replay
tablet.waitForMinC();
}
synchronized (openingTablets) {
synchronized (onlineTablets) {
openingTablets.remove(extentToOpen);
onlineTablets.put(extentToOpen, tablet);
openingTablets.notifyAll();
}
}
tablet = null; // release this reference
successful = true;
} catch (Throwable e) {
log.warn("exception trying to assign tablet " + extentToOpen + " " + locationToOpen, e);
if (e.getMessage() != null)
log.warn(e.getMessage());
String table = extent.getTableId().toString();
ProblemReports.getInstance().report(new ProblemReport(table, TABLET_LOAD, extentToOpen.getUUID().toString(), getClientAddressString(), e));
}
if (!successful) {
synchronized (unopenedTablets) {
synchronized (openingTablets) {
openingTablets.remove(extentToOpen);
unopenedTablets.add(extentToOpen);
openingTablets.notifyAll();
}
}
log.warn("failed to open tablet " + extentToOpen + " reporting failure to master");
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.LOAD_FAILURE, extentToOpen));
long reschedule = Math.min((1l << Math.min(32, retryAttempt)) * 1000, 10 * 60 * 1000l);
log.warn(String.format("rescheduling tablet load in %.2f seconds", reschedule / 1000.));
SimpleTimer.getInstance().schedule(new TimerTask() {
@Override
public void run() {
log.info("adding tablet " + extent + " back to the assignment pool (retry " + retryAttempt + ")");
AssignmentHandler handler = new AssignmentHandler(extentToOpen, retryAttempt + 1);
if (isMetaDataTablet) {
if (Constants.ROOT_TABLET_EXTENT.equals(extent)) {
new Thread(new LoggingRunnable(log, handler), "Root tablet assignment retry").start();
} else {
resourceManager.addMetaDataAssignment(handler);
}
} else {
resourceManager.addAssignment(handler);
}
}
}, reschedule);
} else {
try {
Assignment assignment = new Assignment(extentToOpen, getTabletSession());
TabletStateStore.setLocation(assignment);
enqueueMasterMessage(new TabletStatusMessage(TabletLoadState.LOADED, extentToOpen));
} catch (DistributedStoreException ex) {
log.warn("Unable to update storage", ex);
}
}
}
}
}
private FileSystem fs;
private Configuration conf;
private ZooCache cache;
private SortedMap<KeyExtent,Tablet> onlineTablets = Collections.synchronizedSortedMap(new TreeMap<KeyExtent,Tablet>());
private SortedSet<KeyExtent> unopenedTablets = Collections.synchronizedSortedSet(new TreeSet<KeyExtent>());
private SortedSet<KeyExtent> openingTablets = Collections.synchronizedSortedSet(new TreeSet<KeyExtent>());
private Thread majorCompactorThread;
// used for stopping the server and MasterListener thread
private volatile boolean serverStopRequested = false;
private InetSocketAddress clientAddress;
private TabletServerResourceManager resourceManager;
private Authenticator authenticator;
private volatile boolean majorCompactorDisabled = false;
private volatile boolean shutdownComplete = false;
private ZooLock tabletServerLock;
private TServer server;
private static final String METRICS_PREFIX = "tserver";
private static ObjectName OBJECT_NAME = null;
public TabletStatsKeeper getStatsKeeper() {
return statsKeeper;
}
public Set<String> getLoggers() throws TException, MasterNotRunningException, ThriftSecurityException {
Set<String> allLoggers = new HashSet<String>();
String dir = ZooUtil.getRoot(HdfsZooInstance.getInstance()) + Constants.ZLOGGERS;
for (String child : cache.getChildren(dir)) {
allLoggers.add(new String(cache.get(dir + "/" + child)));
}
if (allLoggers.isEmpty()) {
log.warn("there are no loggers registered in zookeeper");
return allLoggers;
}
Set<String> result = loggerStrategy.getLoggers(Collections.unmodifiableSet(allLoggers));
Set<String> bogus = new HashSet<String>(result);
bogus.removeAll(allLoggers);
if (!bogus.isEmpty())
log.warn("logger strategy is returning loggers that are not candidates");
result.removeAll(bogus);
if (result.isEmpty())
log.warn("strategy returned no useful loggers");
return result;
}
public void addLoggersToMetadata(List<RemoteLogger> logs, KeyExtent extent, int id) {
log.info("Adding " + logs.size() + " logs for extent " + extent + " as alias " + id);
List<MetadataTable.LogEntry> entries = new ArrayList<MetadataTable.LogEntry>();
long now = RelativeTime.currentTimeMillis();
List<String> logSet = new ArrayList<String>();
for (RemoteLogger log : logs)
logSet.add(log.toString());
for (RemoteLogger log : logs) {
MetadataTable.LogEntry entry = new MetadataTable.LogEntry();
entry.extent = extent;
entry.tabletId = id;
entry.timestamp = now;
entry.server = log.getLogger();
entry.filename = log.getFileName();
entry.logSet = logSet;
entries.add(entry);
}
MetadataTable.addLogEntries(SecurityConstants.getSystemCredentials(), entries, getLock());
}
private int startServer(Property portHint, TProcessor processor, String threadName) throws UnknownHostException {
ServerPort sp = TServerUtils.startServer(portHint, processor, this.getClass().getSimpleName(), threadName, Property.TSERV_PORTSEARCH,
Property.TSERV_MINTHREADS, Property.TSERV_THREADCHECK);
this.server = sp.server;
return sp.port;
}
private String getMasterAddress() {
try {
List<String> locations = HdfsZooInstance.getInstance().getMasterLocations();
if (locations.size() == 0)
return null;
return locations.get(0);
} catch (Exception e) {
log.warn("Failed to obtain master host " + e);
}
return null;
}
// Connect to the master for posting asynchronous results
private MasterClientService.Iface masterConnection(String address) {
try {
if (address == null) {
return null;
}
MasterClientService.Iface client = ThriftUtil.getClient(new MasterClientService.Client.Factory(), address, Property.MASTER_CLIENTPORT,
Property.GENERAL_RPC_TIMEOUT, ServerConfiguration.getSystemConfiguration());
// log.info("Listener API to master has been opened");
return client;
} catch (Exception e) {
log.warn("Issue with masterConnection (" + address + ") " + e, e);
}
return null;
}
private void returnMasterConnection(MasterClientService.Iface client) {
ThriftUtil.returnClient(client);
}
private int startTabletClientService() throws UnknownHostException {
// start listening for client connection last
TabletClientService.Iface tch = TraceWrap.service(new ThriftClientHandler());
TabletClientService.Processor processor = new TabletClientService.Processor(tch);
int port = startServer(Property.TSERV_CLIENTPORT, processor, "Thrift Client Server");
log.info("port = " + port);
return port;
}
ZooLock getLock() {
return tabletServerLock;
}
private void announceExistence() {
IZooReaderWriter zoo = ZooReaderWriter.getInstance();
try {
String zPath = ZooUtil.getRoot(HdfsZooInstance.getInstance()) + Constants.ZTSERVERS + "/" + getClientAddressString();
zoo.putPersistentData(zPath, new byte[] {}, NodeExistsPolicy.SKIP);
tabletServerLock = new ZooLock(zPath);
LockWatcher lw = new LockWatcher() {
@Override
public void lostLock(final LockLossReason reason) {
Halt.halt(0, new Runnable() {
public void run() {
if (!serverStopRequested)
log.fatal("Lost tablet server lock (reason = " + reason + "), exiting.");
logGCInfo();
}
});
}
};
byte[] lockContent = new ServerServices(getClientAddressString(), Service.TSERV_CLIENT).toString().getBytes();
for (int i = 0; i < 120 / 5; i++) {
zoo.putPersistentData(zPath, new byte[0], NodeExistsPolicy.SKIP);
if (tabletServerLock.tryLock(lw, lockContent)) {
log.debug("Obtained tablet server lock " + tabletServerLock.getLockPath());
return;
}
log.info("Waiting for tablet server lock");
UtilWaitThread.sleep(5000);
}
String msg = "Too many retries, exiting.";
log.info(msg);
throw new RuntimeException(msg);
} catch (Exception e) {
log.info("Could not obtain tablet server lock, exiting.", e);
throw new RuntimeException(e);
}
}
// main loop listens for client requests
public void run() {
int clientPort = 0;
try {
clientPort = startTabletClientService();
} catch (UnknownHostException e1) {
log.error("Unable to start tablet client service", e1);
UtilWaitThread.sleep(1000);
}
if (clientPort == 0) {
throw new RuntimeException("Failed to start the tablet client service");
}
clientAddress = new InetSocketAddress(clientAddress.getAddress(), clientPort);
announceExistence();
try {
OBJECT_NAME = new ObjectName("accumulo.server.metrics:service=TServerInfo,name=TabletServerMBean,instance=" + Thread.currentThread().getName());
// Do this because interface not in same package.
StandardMBean mbean = new StandardMBean(this, TabletServerMBean.class, false);
this.register(mbean);
mincMetrics.register();
} catch (Exception e) {
log.error("Error registering with JMX", e);
}
String masterHost;
while (!serverStopRequested) {
// send all of the pending messages
try {
MasterMessage mm = null;
MasterClientService.Iface iface = null;
try {
// wait until a message is ready to send, or a sever stop
// was requested
while (mm == null && !serverStopRequested) {
mm = masterMessages.poll(1000, TimeUnit.MILLISECONDS);
}
// have a message to send to the master, so grab a
// connection
masterHost = getMasterAddress();
iface = masterConnection(masterHost);
TServiceClient client = (TServiceClient) iface;
// if while loop does not execute at all and mm != null,
// then
// finally block should place mm back on queue
while (!serverStopRequested && mm != null && client != null && client.getOutputProtocol() != null
&& client.getOutputProtocol().getTransport() != null && client.getOutputProtocol().getTransport().isOpen()) {
try {
mm.send(SecurityConstants.getSystemCredentials(), getClientAddressString(), iface);
mm = null;
} catch (TException ex) {
log.warn("Error sending message: queuing message again");
masterMessages.putFirst(mm);
mm = null;
throw ex;
}
// if any messages are immediately available grab em and
// send them
mm = masterMessages.poll();
}
} finally {
if (mm != null) {
masterMessages.putFirst(mm);
}
returnMasterConnection(iface);
UtilWaitThread.sleep(1000);
}
} catch (InterruptedException e) {
log.info("Interrupt Exception received, shutting down");
serverStopRequested = true;
} catch (Exception e) {
// may have lost connection with master
// loop back to the beginning and wait for a new one
// this way we survive master failures
log.error(getClientAddressString() + ": TServerInfo: Exception. Master down?", e);
}
}
// wait for shutdown
// if the main thread exits oldServer the master listener, the JVM will
// kill the
// other threads and finalize objects. We want the shutdown that is
// running
// in the master listener thread to complete oldServer this happens.
// consider making other threads daemon threads so that objects don't
// get prematurely finalized
synchronized (this) {
while (shutdownComplete == false) {
try {
this.wait(1000);
} catch (InterruptedException e) {
log.error(e.toString());
}
}
}
log.debug("Stopping Thrift Servers");
TServerUtils.stopTServer(server);
try {
log.debug("Closing filesystem");
fs.close();
} catch (IOException e) {
log.warn("Failed to close filesystem : " + e.getMessage(), e);
}
logGCInfo();
log.info("TServerInfo: stop requested. exiting ... ");
try {
tabletServerLock.unlock();
} catch (Exception e) {
log.warn("Failed to release tablet server lock", e);
}
}
private long totalMinorCompactions;
public static SortedMap<KeyExtent,Text> verifyTabletInformation(KeyExtent extent, TServerInstance instance, SortedMap<Key,Value> tabletsKeyValues,
String clientAddress, ZooLock lock) throws AccumuloSecurityException {
for (int tries = 0; tries < 3; tries++) {
try {
log.debug("verifying extent " + extent);
if (extent.equals(Constants.ROOT_TABLET_EXTENT)) {
TreeMap<KeyExtent,Text> set = new TreeMap<KeyExtent,Text>();
set.put(extent, new Text(Constants.ZROOT_TABLET));
return set;
}
List<ColumnFQ> columnsToFetch = Arrays.asList(new ColumnFQ[] {Constants.METADATA_DIRECTORY_COLUMN, Constants.METADATA_PREV_ROW_COLUMN,
Constants.METADATA_SPLIT_RATIO_COLUMN, Constants.METADATA_OLD_PREV_ROW_COLUMN, Constants.METADATA_TIME_COLUMN});
if (tabletsKeyValues == null) {
tabletsKeyValues = new TreeMap<Key,Value>();
}
MetadataTable.getTabletAndPrevTabletKeyValues(tabletsKeyValues, extent, null, SecurityConstants.getSystemCredentials());
SortedMap<Text,SortedMap<ColumnFQ,Value>> tabletEntries;
tabletEntries = MetadataTable.getTabletEntries(tabletsKeyValues, columnsToFetch);
if (tabletEntries.size() == 0) {
log.warn("Failed to find any metadata entries for " + extent);
return null;
}
// ensure lst key in map is same as extent that was passed in
if (!tabletEntries.lastKey().equals(extent.getMetadataEntry())) {
log.warn("Failed to find metadata entry for " + extent + " found " + tabletEntries.lastKey());
return null;
}
TServerInstance future = null;
Text metadataEntry = extent.getMetadataEntry();
for (Entry<Key,Value> entry : tabletsKeyValues.entrySet()) {
Key key = entry.getKey();
if (!metadataEntry.equals(key.getRow()))
continue;
Text cf = key.getColumnFamily();
if (cf.equals(Constants.METADATA_FUTURE_LOCATION_COLUMN_FAMILY)) {
future = new TServerInstance(entry.getValue(), key.getColumnQualifier());
} else if (cf.equals(Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY)) {
log.error("Tablet seems to be already assigned to " + new TServerInstance(entry.getValue(), key.getColumnQualifier()));
return null;
}
}
if (future == null) {
log.warn("The master has not assigned " + extent + " to " + instance);
return null;
}
if (!instance.equals(future)) {
log.warn("Table " + extent + " has been assigned to " + future + " which is not " + instance);
return null;
}
// look for incomplete splits
int splitsFixed = 0;
for (Entry<Text,SortedMap<ColumnFQ,Value>> entry : tabletEntries.entrySet()) {
if (extent.getPrevEndRow() != null) {
Text prevRowMetadataEntry = new Text(KeyExtent.getMetadataEntry(extent.getTableId(), extent.getPrevEndRow()));
if (entry.getKey().compareTo(prevRowMetadataEntry) <= 0) {
continue;
}
}
if (entry.getValue().containsKey(Constants.METADATA_OLD_PREV_ROW_COLUMN)) {
KeyExtent fixedke = MetadataTable.fixSplit(entry.getKey(), entry.getValue(), instance, SecurityConstants.getSystemCredentials(), lock);
if (fixedke != null) {
if (fixedke.getPrevEndRow() == null || fixedke.getPrevEndRow().compareTo(extent.getPrevEndRow()) < 0) {
extent = new KeyExtent(extent);
extent.setPrevEndRow(fixedke.getPrevEndRow());
}
splitsFixed++;
}
}
}
if (splitsFixed > 0) {
// reread and reverify metadata entries now that metadata
// entries were fixed
tabletsKeyValues.clear();
return verifyTabletInformation(extent, instance, null, clientAddress, lock);
}
SortedMap<KeyExtent,Text> children = new TreeMap<KeyExtent,Text>();
for (Entry<Text,SortedMap<ColumnFQ,Value>> entry : tabletEntries.entrySet()) {
if (extent.getPrevEndRow() != null) {
Text prevRowMetadataEntry = new Text(KeyExtent.getMetadataEntry(extent.getTableId(), extent.getPrevEndRow()));
if (entry.getKey().compareTo(prevRowMetadataEntry) <= 0) {
continue;
}
}
Value prevEndRowIBW = entry.getValue().get(Constants.METADATA_PREV_ROW_COLUMN);
if (prevEndRowIBW == null) {
log.warn("Metadata entry does not have prev row (" + entry.getKey() + ")");
return null;
}
Value dirIBW = entry.getValue().get(Constants.METADATA_DIRECTORY_COLUMN);
if (dirIBW == null) {
log.warn("Metadata entry does not have directory (" + entry.getKey() + ")");
return null;
}
Text dir = new Text(dirIBW.get());
KeyExtent child = new KeyExtent(entry.getKey(), prevEndRowIBW);
children.put(child, dir);
}
if (!MetadataTable.isContiguousRange(extent, new TreeSet<KeyExtent>(children.keySet()))) {
log.warn("For extent " + extent + " metadata entries " + children + " do not form a contiguous range.");
return null;
}
return children;
} catch (AccumuloException e) {
log.error("error verifying metadata information. retrying ...");
log.error(e.toString());
UtilWaitThread.sleep(1000);
} catch (AccumuloSecurityException e) {
// if it's a security exception, retrying won't work either.
log.error(e.toString());
throw e;
}
}
// default is to accept
return null;
}
public String getClientAddressString() {
if (clientAddress == null)
return null;
return AddressUtil.toString(clientAddress);
}
TServerInstance getTabletSession() {
String address = getClientAddressString();
if (address == null)
return null;
try {
return new TServerInstance(address, tabletServerLock.getSessionId());
} catch (Exception ex) {
log.warn("Unable to read session from tablet server lock" + ex);
return null;
}
}
public void config(String[] args) throws UnknownHostException {
InetAddress local = Accumulo.getLocalAddress(args);
try {
Accumulo.init("tserver");
log.info("Tablet server starting on " + local.getHostAddress());
conf = CachedConfiguration.getInstance();
fs = TraceFileSystem.wrap(FileUtil.getFileSystem(conf, ServerConfiguration.getSiteConfiguration()));
authenticator = ZKAuthenticator.getInstance();
if (args.length > 0)
conf.set("tabletserver.hostname", args[0]);
Accumulo.enableTracing(local.getHostAddress(), "tserver");
} catch (IOException e) {
log.fatal("couldn't get a reference to the filesystem. quitting");
throw new RuntimeException(e);
}
clientAddress = new InetSocketAddress(local, 0);
logger = new TabletServerLogger(this, ServerConfiguration.getSystemConfiguration().getMemoryInBytes(Property.TSERV_WALOG_MAX_SIZE));
if (ServerConfiguration.getSystemConfiguration().getBoolean(Property.TSERV_LOCK_MEMORY)) {
String path = "lib/native/mlock/" + System.mapLibraryName("MLock-" + Platform.getPlatform());
path = new File(path).getAbsolutePath();
try {
System.load(path);
log.info("Trying to lock memory pages to RAM");
if (MLock.lockMemoryPages() < 0)
log.error("Failed to lock memory pages to RAM");
else
log.info("Memory pages are now locked into RAM");
} catch (Throwable t) {
log.error("Failed to load native library for locking pages to RAM " + path + " (" + t + ")", t);
}
}
FileSystemMonitor.start(Property.TSERV_MONITOR_FS);
TimerTask gcDebugTask = new TimerTask() {
@Override
public void run() {
logGCInfo();
}
};
SimpleTimer.getInstance().schedule(gcDebugTask, 0, 1000);
this.resourceManager = new TabletServerResourceManager(conf, fs);
lastPingTime = System.currentTimeMillis();
currentMaster = null;
statsKeeper = new TabletStatsKeeper();
// start major compactor
majorCompactorThread = new Daemon(new LoggingRunnable(log, new MajorCompactor()));
majorCompactorThread.setName("Split/MajC initiator");
majorCompactorThread.start();
String className = ServerConfiguration.getSystemConfiguration().get(Property.TSERV_LOGGER_STRATEGY);
Class<? extends LoggerStrategy> klass = DEFAULT_LOGGER_STRATEGY;
try {
klass = AccumuloClassLoader.loadClass(className, LoggerStrategy.class);
} catch (Exception ex) {
log.warn("Unable to load class " + className + " for logger strategy, using " + klass.getName(), ex);
}
try {
Constructor<? extends LoggerStrategy> constructor = klass.getConstructor(TabletServer.class);
loggerStrategy = constructor.newInstance(this);
} catch (Exception ex) {
log.warn("Unable to create object of type " + klass.getName() + " using " + DEFAULT_LOGGER_STRATEGY.getName());
}
if (loggerStrategy == null) {
try {
loggerStrategy = DEFAULT_LOGGER_STRATEGY.getConstructor(TabletServer.class).newInstance(this);
} catch (Exception ex) {
log.fatal("Programmer error: cannot create a logger strategy.");
throw new RuntimeException(ex);
}
}
cache = new ZooCache();
}
public TabletServerStatus getStats(Map<String,MapCounter<ScanRunState>> scanCounts) {
TabletServerStatus result = new TabletServerStatus();
Map<KeyExtent,Tablet> onlineTabletsCopy;
synchronized (this.onlineTablets) {
onlineTabletsCopy = new HashMap<KeyExtent,Tablet>(this.onlineTablets);
}
Map<String,TableInfo> tables = new HashMap<String,TableInfo>();
for (Entry<KeyExtent,Tablet> entry : onlineTabletsCopy.entrySet()) {
String tableId = entry.getKey().getTableId().toString();
TableInfo table = tables.get(tableId);
if (table == null) {
table = new TableInfo();
table.minor = new Compacting();
table.major = new Compacting();
tables.put(tableId, table);
}
Tablet tablet = entry.getValue();
long recs = tablet.getNumEntries();
table.tablets++;
table.onlineTablets++;
table.recs += recs;
table.queryRate += tablet.queryRate();
table.queryByteRate += tablet.queryByteRate();
table.ingestRate += tablet.ingestRate();
table.ingestByteRate += tablet.ingestByteRate();
long recsInMemory = tablet.getNumEntriesInMemory();
table.recsInMemory += recsInMemory;
if (tablet.minorCompactionRunning())
table.minor.running++;
if (tablet.minorCompactionQueued())
table.minor.queued++;
if (tablet.majorCompactionRunning())
table.major.running++;
if (tablet.majorCompactionQueued())
table.major.queued++;
}
for (Entry<String,MapCounter<ScanRunState>> entry : scanCounts.entrySet()) {
TableInfo table = tables.get(entry.getKey());
if (table == null) {
table = new TableInfo();
tables.put(entry.getKey(), table);
}
if (table.scans == null)
table.scans = new Compacting();
table.scans.queued += entry.getValue().get(ScanRunState.QUEUED);
table.scans.running += entry.getValue().get(ScanRunState.RUNNING);
}
ArrayList<KeyExtent> offlineTabletsCopy = new ArrayList<KeyExtent>();
synchronized (this.unopenedTablets) {
synchronized (this.openingTablets) {
offlineTabletsCopy.addAll(this.unopenedTablets);
offlineTabletsCopy.addAll(this.openingTablets);
}
}
for (KeyExtent extent : offlineTabletsCopy) {
String tableId = extent.getTableId().toString();
TableInfo table = tables.get(tableId);
if (table == null) {
table = new TableInfo();
tables.put(tableId, table);
}
table.tablets++;
}
result.lastContact = RelativeTime.currentTimeMillis();
result.tableMap = tables;
result.osLoad = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
result.name = getClientAddressString();
result.holdTime = resourceManager.holdTime();
result.lookups = scanCount.get();
result.loggers = new HashSet<String>();
result.indexCacheHits = resourceManager.getIndexCache().getStats().getHitCount();
result.indexCacheRequest = resourceManager.getIndexCache().getStats().getRequestCount();
result.dataCacheHits = resourceManager.getDataCache().getStats().getHitCount();
result.dataCacheRequest = resourceManager.getDataCache().getStats().getRequestCount();
logger.getLoggers(result.loggers);
return result;
}
public static void main(String[] args) throws IOException {
TabletServer server = new TabletServer();
server.config(args);
server.run();
}
public void minorCompactionFinished(CommitSession tablet, String newDatafile, int walogSeq) throws IOException {
totalMinorCompactions++;
logger.minorCompactionFinished(tablet, newDatafile, walogSeq);
}
public void minorCompactionStarted(CommitSession tablet, int lastUpdateSequence, String newMapfileLocation) throws IOException {
logger.minorCompactionStarted(tablet, lastUpdateSequence, newMapfileLocation);
}
public void recover(Tablet tablet, List<LogEntry> logEntries, Set<String> tabletFiles, MutationReceiver mutationReceiver) throws IOException {
List<String> recoveryLogs = new ArrayList<String>();
List<LogEntry> sorted = new ArrayList<LogEntry>(logEntries);
Collections.sort(sorted, new Comparator<LogEntry>() {
@Override
public int compare(LogEntry e1, LogEntry e2) {
return (int) (e1.timestamp - e2.timestamp);
}
});
for (LogEntry entry : sorted) {
String recovery = null;
for (String log : entry.logSet) {
String[] parts = log.split("/"); // "host:port/filename"
log = ServerConstants.getRecoveryDir() + "/" + parts[1] + ".recovered";
Path finished = new Path(log + "/finished");
TabletServer.log.info("Looking for " + finished);
if (fs.exists(finished)) {
recovery = log;
break;
}
}
if (recovery == null)
throw new IOException("Unable to find recovery files for extent " + tablet.getExtent() + " logEntry: " + entry);
recoveryLogs.add(recovery);
}
logger.recover(tablet, recoveryLogs, tabletFiles, mutationReceiver);
}
private final AtomicInteger logIdGenerator = new AtomicInteger();
public int createLogId(KeyExtent tablet) {
String table = tablet.getTableId().toString();
AccumuloConfiguration acuTableConf = ServerConfiguration.getTableConfiguration(table);
if (acuTableConf.getBoolean(Property.TABLE_WALOG_ENABLED)) {
return logIdGenerator.incrementAndGet();
}
return -1;
}
// / JMX methods
@Override
public long getEntries() {
if (this.isEnabled()) {
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.getNumEntries();
}
return result;
}
return 0;
}
@Override
public long getEntriesInMemory() {
if (this.isEnabled()) {
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.getNumEntriesInMemory();
}
return result;
}
return 0;
}
@Override
public long getIngest() {
if (this.isEnabled()) {
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.getNumEntriesInMemory();
}
return result;
}
return 0;
}
@Override
public int getMajorCompactions() {
if (this.isEnabled()) {
int result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
if (tablet.majorCompactionRunning())
result++;
}
return result;
}
return 0;
}
@Override
public int getMajorCompactionsQueued() {
if (this.isEnabled()) {
int result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
if (tablet.majorCompactionQueued())
result++;
}
return result;
}
return 0;
}
@Override
public int getMinorCompactions() {
if (this.isEnabled()) {
int result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
if (tablet.minorCompactionRunning())
result++;
}
return result;
}
return 0;
}
@Override
public int getMinorCompactionsQueued() {
if (this.isEnabled()) {
int result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
if (tablet.minorCompactionQueued())
result++;
}
return result;
}
return 0;
}
@Override
public int getOnlineCount() {
if (this.isEnabled())
return onlineTablets.size();
return 0;
}
@Override
public int getOpeningCount() {
if (this.isEnabled())
return openingTablets.size();
return 0;
}
@Override
public long getQueries() {
if (this.isEnabled()) {
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.totalQueries();
}
return result;
}
return 0;
}
@Override
public int getUnopenedCount() {
if (this.isEnabled())
return unopenedTablets.size();
return 0;
}
@Override
public String getName() {
if (this.isEnabled())
return getClientAddressString();
return "";
}
@Override
public long getTotalMinorCompactions() {
if (this.isEnabled())
return totalMinorCompactions;
return 0;
}
@Override
public double getHoldTime() {
if (this.isEnabled())
return this.resourceManager.holdTime() / 1000.;
return 0;
}
@Override
public double getAverageFilesPerTablet() {
if (this.isEnabled()) {
int count = 0;
long result = 0;
for (Tablet tablet : Collections.unmodifiableCollection(onlineTablets.values())) {
result += tablet.getDatafiles().size();
count++;
}
if (count == 0)
return 0;
return result / (double) count;
}
return 0;
}
protected ObjectName getObjectName() {
return OBJECT_NAME;
}
protected String getMetricsPrefix() {
return METRICS_PREFIX;
}
}
| ACCUMULO-88: help the compiler find the TabletServerMBean interface
git-svn-id: ee25ee0bfe882ec55abc48667331b454c011093e@1195477 13f79535-47bb-0310-9956-ffa450edef68
| src/server/src/main/java/org/apache/accumulo/server/tabletserver/TabletServer.java | ACCUMULO-88: help the compiler find the TabletServerMBean interface | <ide><path>rc/server/src/main/java/org/apache/accumulo/server/tabletserver/TabletServer.java
<ide> QUEUED, RUNNING, FINISHED
<ide> }
<ide>
<del>public class TabletServer extends AbstractMetricsImpl implements TabletServerMBean {
<add>public class TabletServer extends AbstractMetricsImpl implements org.apache.accumulo.server.tabletserver.metrics.TabletServerMBean {
<ide> private static final Logger log = Logger.getLogger(TabletServer.class);
<ide>
<ide> private static HashMap<String,Long> prevGcTime = new HashMap<String,Long>(); |
|
JavaScript | mit | 5cd44f0ab75fd82c9d7734c91e2ef783b2d53c4e | 0 | CoderDojo/cp-dojos-service,CoderDojo/cp-dojos-service | module.exports = function () {
/*
* Format of a permission {
* role: 'basic-user' || {'basic-user':{match: true}}
* customValidator: functionName
* }
*/
// TODO:50 ensure is_own_dojo for dojo-admin && belongs_to for champion
return {
'cd-dojos':{
'get_dojo_config': [{
role: 'none'
}],
'search_bounding_box': [{
role: 'none'
}],
//Used by front-e resolver, must restrict fields
'find': [{
role: 'none'
}],
'search': [{
role: 'cdf-admin'
}],
// TODO : perm for ctrl:'dojo', cmd: 'save'
'update': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'update_image': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'dojos_by_country': [{
role: 'none'
}],
'list': [{
role: 'none',
}],
'load': [{
role: 'none'
}],
'bulk_delete': [{
role: 'cdf-admin'
}],
'get_stats': [{
role: 'cdf-admin'
}],
'load_setup_dojo_steps': [{
role: 'basic-user'
}],
// TODO:120 split as "belongs_to_dojo"
'load_usersdojos': [{
role: 'basic-user'
}],
'load_dojo_users': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'dojos_for_user': [{
role: 'basic-user',
customValidator:[{
role: 'cd-users',
cmd: 'is_self'
}]
}, {
role: 'basic-user',
customValidator: [{
role: 'cd-users',
cmd: 'is_parent_of',
}]
}],
// TODO:130 split join from manage userdojos
'save_usersdojos': [{
role: 'basic-user'
}],
'remove_usersdojos': [ {
role: 'basic-user',
customValidator:[{
role: 'cd-users',
cmd: 'is_self'
}]
}, {
role: 'basic-user',
customValidator:[{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}, {
role: 'basic-user',
userType: 'parent-guardian',
customValidator:[{
role: 'cd-users',
cmd: 'is_parent_of'
}]
}
],
'export_dojo_users': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'generate_user_invite_token': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'accept_user_invite': [{
role: 'basic-user'
}],
'request_user_invite': [{
role: 'basic-user'
}],
'accept_user_request': [{
// No validator here as check is post-recovery of data
role: 'basic-user'
}],
'search_join_requests': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'decline_user_request': [{
// No validator here as check is post-recovery of data
role: 'basic-user'
}],
'update_founder': [{
role: 'basic-user',
userType: 'champion',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_founder'
}]
}],
'notify_all_members': [
{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
// It returns an static object, don't be afraid
'get_user_permissions': [{
role: 'none',
}],
'get_user_types': [{
role: 'none'
}],
'search_nearest_dojos': [{
role: 'none'
}],
'list_countries': [{
role: 'none'
}],
'list_places': [{
role: 'none'
}],
// Not even used
'countries_lat_long': [{
role: 'none'
}],
'continent_codes': [{
role: 'none'
}],
'poll_count': [{
role: 'none'
}],
// It's by design, but we know it's insecure as it could allow to vote as as another dojo
'save_poll_result': [{
role: 'none'
}],
'get_poll_setup': [{
role: 'none'
}],
'get_poll_results': [{
role: 'none'
}],
'remove_poll_result': [{
role: 'cdf-admin',
}],
'send_test_email_poll': [{
role: 'cdf-admin'
}],
'start_poll': [{
role: 'cdf-admin'
}],
'queue_email_poll': [{
role: 'cdf-admin'
}],
'dojo': {
'bulkVerify': [{
role: 'cdf-admin'
}],
'verify': [{
role: 'cdf-admin'
}],
'joinedDojos': [{
role: 'basic-user'
}],
'delete': [{
role: 'cdf-admin'
}]
},
'load_dojo_lead': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_own_lead'
}]
}],
'lead': {
'search': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_own_lead'
}]
}, {
role: 'basic-user',
customValidator: [{
role: 'cd-users',
cmd: 'is_self'
}]
}],
'save': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_own_lead'
}]
}],
'submit': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_own_lead'
}]
}],
'delete': [{
role: 'cdf-admin'
}]
}
}
};
};
| config/permissions-rules.js | module.exports = function () {
/*
* Format of a permission {
* role: 'basic-user' || {'basic-user':{match: true}}
* customValidator: functionName
* }
*/
// TODO:50 ensure is_own_dojo for dojo-admin && belongs_to for champion
return {
'cd-dojos':{
'get_dojo_config': [{
role: 'none'
}],
'search_bounding_box': [{
role: 'none'
}],
//Used by front-e resolver, must restrict fields
'find': [{
role: 'none'
}],
'search': [{
role: 'cdf-admin'
}],
// TODO : perm for ctrl:'dojo', cmd: 'save'
'update': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'update_image': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'dojos_by_country': [{
role: 'none'
}],
'list': [{
role: 'none',
}],
'load': [{
role: 'none'
}],
'bulk_delete': [{
role: 'cdf-admin'
}],
'get_stats': [{
role: 'cdf-admin'
}],
'load_setup_dojo_steps': [{
role: 'basic-user'
}],
// TODO:120 split as "belongs_to_dojo"
'load_usersdojos': [{
role: 'basic-user'
}],
'load_dojo_users': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'dojos_for_user': [{
role: 'basic-user',
customValidator:[{
role: 'cd-users',
cmd: 'is_self'
}]
}, {
role: 'basic-user',
customValidator: [{
role: 'cd-users',
cmd: 'is_parent_of',
}]
}],
// TODO:130 split join from manage userdojos
'save_usersdojos': [{
role: 'basic-user'
}],
'remove_usersdojos': [ {
role: 'basic-user',
customValidator:[{
role: 'cd-users',
cmd: 'is_self'
}]
}, {
role: 'basic-user',
customValidator:[{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}, {
role: 'basic-user',
userType: 'parent-guardian',
customValidator:[{
role: 'cd-users',
cmd: 'is_parent_of'
}]
}
],
'export_dojo_users': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'generate_user_invite_token': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'accept_user_invite': [{
role: 'basic-user'
}],
'request_user_invite': [{
role: 'basic-user'
}],
'accept_user_request': [{
// No validator here as check is post-recovery of data
role: 'basic-user'
}],
'search_join_requests': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
'decline_user_request': [{
// No validator here as check is post-recovery of data
role: 'basic-user'
}],
'update_founder': [{
role: 'basic-user',
userType: 'champion',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_founder'
}]
}],
'notify_all_members': [
{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'have_permissions_on_dojo',
perm: 'dojo-admin'
}]
}],
// It returns an static object, don't be afraid
'get_user_permissions': [{
role: 'none',
}],
'get_user_types': [{
role: 'none'
}],
'search_nearest_dojos': [{
role: 'none'
}],
'list_countries': [{
role: 'none'
}],
'list_places': [{
role: 'none'
}],
// Not even used
'countries_lat_long': [{
role: 'none'
}],
'continent_codes': [{
role: 'none'
}],
'poll_count': [{
role: 'none'
}],
// It's by design, but we know it's insecure as it could allow to vote as as another dojo
'save_poll_result': [{
role: 'none'
}],
'get_poll_setup': [{
role: 'none'
}],
'get-poll-results': [{
role: 'none'
}],
'send_test_email_poll': [{
role: 'cdf-admin'
}],
'start_poll': [{
role: 'cdf-admin'
}],
'queue_email_poll': [{
role: 'cdf-admin'
}],
'dojo': {
'bulkVerify': [{
role: 'cdf-admin'
}],
'verify': [{
role: 'cdf-admin'
}],
'joinedDojos': [{
role: 'basic-user'
}],
'delete': [{
role: 'cdf-admin'
}]
},
'load_dojo_lead': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_own_lead'
}]
}],
'lead': {
'search': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_own_lead'
}]
}, {
role: 'basic-user',
customValidator: [{
role: 'cd-users',
cmd: 'is_self'
}]
}],
'save': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_own_lead'
}]
}],
'submit': [{
role: 'basic-user',
customValidator: [{
role: 'cd-dojos',
cmd: 'is_own_lead'
}]
}],
'delete': [{
role: 'cdf-admin'
}]
}
}
};
};
| Bugfix/api review delete (#400)
* Ensure dojos_for_user is only called from a user/parent perspective
* Add perm to delete poll results
| config/permissions-rules.js | Bugfix/api review delete (#400) | <ide><path>onfig/permissions-rules.js
<ide> 'get_poll_setup': [{
<ide> role: 'none'
<ide> }],
<del> 'get-poll-results': [{
<del> role: 'none'
<add> 'get_poll_results': [{
<add> role: 'none'
<add> }],
<add> 'remove_poll_result': [{
<add> role: 'cdf-admin',
<ide> }],
<ide> 'send_test_email_poll': [{
<ide> role: 'cdf-admin' |
|
Java | apache-2.0 | 56f1a1d9b5ae81dced70093f2f4120dfaa774e5e | 0 | cbeust/testng,msebire/testng,raindev/testng,raindev/testng,tremes/testng,jerome-jacob/testng,emopers/testng,raindev/testng,AJ-72/testng,VikingDen/testng,gjuillot/testng,VladRassokhin/testng,bmlct/testng,emopers/testng,AJ-72/testng,s2oBCN/testng,krmahadevan/testng,cbeust/testng,meeroslaph/testng,rschmitt/testng,meeroslaph/testng,aledsage/testng,cbeust/testng,tobecrazy/testng,scr/testng,gjuillot/testng,aledsage/testng,jerome-jacob/testng,smaudet/testng,VikingDen/testng,krmahadevan/testng,VikingDen/testng,missedone/testng,AJ-72/testng,tobecrazy/testng,VladRassokhin/testng,akozlova/testng,missedone/testng,raindev/testng,tremes/testng,rschmitt/testng,bmlct/testng,aledsage/testng,rschmitt/testng,scr/testng,missedone/testng,gjuillot/testng,jaypal/testng,emopers/testng,bmlct/testng,6ft-invsbl-rbbt/testng,rschmitt/testng,missedone/testng,scr/testng,VladRassokhin/testng,meeroslaph/testng,6ft-invsbl-rbbt/testng,akozlova/testng,smaudet/testng,krmahadevan/testng,rschmitt/testng,jaypal/testng,raindev/testng,jaypal/testng,akozlova/testng,meeroslaph/testng,VladRassokhin/testng,tremes/testng,bmlct/testng,jerome-jacob/testng,juherr/testng,cbeust/testng,tremes/testng,aledsage/testng,tobecrazy/testng,AJ-72/testng,gjuillot/testng,VikingDen/testng,smaudet/testng,AJ-72/testng,jerome-jacob/testng,6ft-invsbl-rbbt/testng,akozlova/testng,JeshRJ/myRepRJ,emopers/testng,akozlova/testng,msebire/testng,missedone/testng,juherr/testng,juherr/testng,aledsage/testng,krmahadevan/testng,s2oBCN/testng,JeshRJ/myRepRJ,jerome-jacob/testng,emopers/testng,tobecrazy/testng,6ft-invsbl-rbbt/testng,VikingDen/testng,cbeust/testng,scr/testng,AJ-72/testng,msebire/testng,juherr/testng,gjuillot/testng,smaudet/testng,JeshRJ/myRepRJ,s2oBCN/testng,juherr/testng,VladRassokhin/testng,tobecrazy/testng,tremes/testng,krmahadevan/testng,JeshRJ/myRepRJ,bmlct/testng,s2oBCN/testng,jaypal/testng,smaudet/testng,msebire/testng,msebire/testng,scr/testng,s2oBCN/testng,6ft-invsbl-rbbt/testng,meeroslaph/testng,raindev/testng,aledsage/testng,VladRassokhin/testng,JeshRJ/myRepRJ,jaypal/testng | package org.testng;
import static org.testng.internal.EclipseInterface.ASSERT_LEFT;
import static org.testng.internal.EclipseInterface.ASSERT_LEFT2;
import static org.testng.internal.EclipseInterface.ASSERT_MIDDLE;
import static org.testng.internal.EclipseInterface.ASSERT_RIGHT;
import org.testng.collections.Lists;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Assertion tool class. Presents assertion methods with a more natural parameter order.
* The order is always <B>actualValue</B>, <B>expectedValue</B> [, message].
*
* @author <a href='mailto:[email protected]'>Alexandru Popescu</a>
*/
public class Assert {
/**
* Protect constructor since it is a static only class
*/
protected Assert() {
// hide constructor
}
/**
* Asserts that a condition is true. If it isn't,
* an AssertionError, with the given message, is thrown.
* @param condition the condition to evaluate
* @param message the assertion error message
*/
static public void assertTrue(boolean condition, String message) {
if(!condition) {
failNotEquals( Boolean.valueOf(condition), Boolean.TRUE, message);
}
}
/**
* Asserts that a condition is true. If it isn't,
* an AssertionError is thrown.
* @param condition the condition to evaluate
*/
static public void assertTrue(boolean condition) {
assertTrue(condition, null);
}
/**
* Asserts that a condition is false. If it isn't,
* an AssertionError, with the given message, is thrown.
* @param condition the condition to evaluate
* @param message the assertion error message
*/
static public void assertFalse(boolean condition, String message) {
if(condition) {
failNotEquals( Boolean.valueOf(condition), Boolean.FALSE, message); // TESTNG-81
}
}
/**
* Asserts that a condition is false. If it isn't,
* an AssertionError is thrown.
* @param condition the condition to evaluate
*/
static public void assertFalse(boolean condition) {
assertFalse(condition, null);
}
/**
* Fails a test with the given message and wrapping the original exception.
*
* @param message the assertion error message
* @param realCause the original exception
*/
static public void fail(String message, Throwable realCause) {
AssertionError ae = new AssertionError(message);
ae.initCause(realCause);
throw ae;
}
/**
* Fails a test with the given message.
* @param message the assertion error message
*/
static public void fail(String message) {
throw new AssertionError(message);
}
/**
* Fails a test with no message.
*/
static public void fail() {
fail(null);
}
/**
* Asserts that two objects are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Object actual, Object expected, String message) {
if((expected == null) && (actual == null)) {
return;
}
if(expected != null) {
if (expected.getClass().isArray()) {
assertArrayEquals(actual, expected, message);
return;
} else if (expected.equals(actual)) {
return;
}
}
failNotEquals(actual, expected, message);
}
/**
* Asserts that two objects are equal. It they are not, an AssertionError,
* with given message, is thrown.
* @param actual the actual value
* @param expected the expected value (should be an non-null array value)
* @param message the assertion error message
*/
private static void assertArrayEquals(Object actual, Object expected, String message) {
//is called only when expected is an array
if (actual.getClass().isArray()) {
int expectedLength = Array.getLength(expected);
if (expectedLength == Array.getLength(actual)) {
for (int i = 0 ; i < expectedLength ; i++) {
Object _actual = Array.get(actual, i);
Object _expected = Array.get(expected, i);
try {
assertEquals(_actual, _expected);
} catch (AssertionError ae) {
failNotEquals(actual, expected, message == null ? "" : message
+ " (values at index " + i + " are not the same)");
}
}
//array values matched
return;
} else {
failNotEquals(Array.getLength(actual), expectedLength, message == null ? "" : message
+ " (Array lengths are not the same)");
}
}
failNotEquals(actual, expected, message);
}
/**
* Asserts that two objects are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Object actual, Object expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two Strings are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(String actual, String expected, String message) {
assertEquals((Object) actual, (Object) expected, message);
}
/**
* Asserts that two Strings are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(String actual, String expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not,
* an AssertionError, with the given message, is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
* @param message the assertion error message
*/
static public void assertEquals(double actual, double expected, double delta, String message) {
// handle infinity specially since subtracting to infinite values gives NaN and the
// the following test fails
if(Double.isInfinite(expected)) {
if(!(expected == actual)) {
failNotEquals(new Double(actual), new Double(expected), message);
}
}
else if(!(Math.abs(expected - actual) <= delta)) { // Because comparison with NaN always returns false
failNotEquals(new Double(actual), new Double(expected), message);
}
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not,
* an AssertionError is thrown. If the expected value is infinity then the
* delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
*/
static public void assertEquals(double actual, double expected, double delta) {
assertEquals(actual, expected, delta, null);
}
/**
* Asserts that two floats are equal concerning a delta. If they are not,
* an AssertionError, with the given message, is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
* @param message the assertion error message
*/
static public void assertEquals(float actual, float expected, float delta, String message) {
// handle infinity specially since subtracting to infinite values gives NaN and the
// the following test fails
if(Float.isInfinite(expected)) {
if(!(expected == actual)) {
failNotEquals(new Float(actual), new Float(expected), message);
}
}
else if(!(Math.abs(expected - actual) <= delta)) {
failNotEquals(new Float(actual), new Float(expected), message);
}
}
/**
* Asserts that two floats are equal concerning a delta. If they are not,
* an AssertionError is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
*/
static public void assertEquals(float actual, float expected, float delta) {
assertEquals(actual, expected, delta, null);
}
/**
* Asserts that two longs are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(long actual, long expected, String message) {
assertEquals(Long.valueOf(actual), Long.valueOf(expected), message);
}
/**
* Asserts that two longs are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(long actual, long expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two booleans are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(boolean actual, boolean expected, String message) {
assertEquals( Boolean.valueOf(actual), Boolean.valueOf(expected), message);
}
/**
* Asserts that two booleans are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(boolean actual, boolean expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two bytes are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(byte actual, byte expected, String message) {
assertEquals(Byte.valueOf(actual), Byte.valueOf(expected), message);
}
/**
* Asserts that two bytes are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(byte actual, byte expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two chars are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(char actual, char expected, String message) {
assertEquals(Character.valueOf(actual), Character.valueOf(expected), message);
}
/**
* Asserts that two chars are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(char actual, char expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two shorts are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(short actual, short expected, String message) {
assertEquals(Short.valueOf(actual), Short.valueOf(expected), message);
}
/**
* Asserts that two shorts are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(short actual, short expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two ints are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(int actual, int expected, String message) {
assertEquals(Integer.valueOf(actual), Integer.valueOf(expected), message);
}
/**
* Asserts that two ints are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(int actual, int expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that an object isn't null. If it is,
* an AssertionError is thrown.
* @param object the assertion object
*/
static public void assertNotNull(Object object) {
assertNotNull(object, null);
}
/**
* Asserts that an object isn't null. If it is,
* an AssertionFailedError, with the given message, is thrown.
* @param object the assertion object
* @param message the assertion error message
*/
static public void assertNotNull(Object object, String message) {
if (object == null) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + "expected object to not be null");
}
assertTrue(object != null, message);
}
/**
* Asserts that an object is null. If it is not,
* an AssertionError, with the given message, is thrown.
* @param object the assertion object
*/
static public void assertNull(Object object) {
assertNull(object, null);
}
/**
* Asserts that an object is null. If it is not,
* an AssertionFailedError, with the given message, is thrown.
* @param object the assertion object
* @param message the assertion error message
*/
static public void assertNull(Object object, String message) {
if (object != null) {
failNotSame(object, null, message);
}
}
/**
* Asserts that two objects refer to the same object. If they do not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertSame(Object actual, Object expected, String message) {
if(expected == actual) {
return;
}
failNotSame(actual, expected, message);
}
/**
* Asserts that two objects refer to the same object. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertSame(Object actual, Object expected) {
assertSame(actual, expected, null);
}
/**
* Asserts that two objects do not refer to the same objects. If they do,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertNotSame(Object actual, Object expected, String message) {
if(expected == actual) {
failSame(actual, expected, message);
}
}
/**
* Asserts that two objects do not refer to the same object. If they do,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertNotSame(Object actual, Object expected) {
assertNotSame(actual, expected, null);
}
static private void failSame(Object actual, Object expected, String message) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + ASSERT_LEFT2 + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT);
}
static private void failNotSame(Object actual, Object expected, String message) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + ASSERT_LEFT + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT);
}
static private void failNotEquals(Object actual , Object expected, String message ) {
fail(format(actual, expected, message));
}
static String format(Object actual, Object expected, String message) {
String formatted = "";
if (null != message) {
formatted = message + " ";
}
return formatted + ASSERT_LEFT + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT;
}
/**
* Asserts that two collections contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Collection<?> actual, Collection<?> expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two collections contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Collection<?> actual, Collection<?> expected, String message) {
if(actual == expected) {
return;
}
if (actual == null || expected == null) {
if (message != null) {
fail(message);
} else {
fail("Collections not equal: expected: " + expected + " and actual: " + actual);
}
}
assertEquals(actual.size(), expected.size(), message + ": lists don't have the same size");
Iterator<?> actIt = actual.iterator();
Iterator<?> expIt = expected.iterator();
int i = -1;
while(actIt.hasNext() && expIt.hasNext()) {
i++;
Object e = expIt.next();
Object a = actIt.next();
String explanation = "Lists differ at element [" + i + "]: " + e + " != " + a;
String errorMessage = message == null ? explanation : message + ": " + explanation;
assertEquals(a, e, errorMessage);
}
}
/** Asserts that two iterators return the same elements in the same order. If they do not,
* an AssertionError is thrown.
* Please note that this assert iterates over the elements and modifies the state of the iterators.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Iterator<?> actual, Iterator<?> expected) {
assertEquals(actual, expected, null);
}
/** Asserts that two iterators return the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* Please note that this assert iterates over the elements and modifies the state of the iterators.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Iterator<?> actual, Iterator<?> expected, String message) {
if(actual == expected) {
return;
}
if(actual == null || expected == null) {
if(message != null) {
fail(message);
} else {
fail("Iterators not equal: expected: " + expected + " and actual: " + actual);
}
}
int i = -1;
while(actual.hasNext() && expected.hasNext()) {
i++;
Object e = expected.next();
Object a = actual.next();
String explanation = "Iterators differ at element [" + i + "]: " + e + " != " + a;
String errorMessage = message == null ? explanation : message + ": " + explanation;
assertEquals(a, e, errorMessage);
}
if(actual.hasNext()) {
String explanation = "Actual iterator returned more elements than the expected iterator.";
String errorMessage = message == null ? explanation : message + ": " + explanation;
fail(errorMessage);
} else if(expected.hasNext()) {
String explanation = "Expected iterator returned more elements than the actual iterator.";
String errorMessage = message == null ? explanation : message + ": " + explanation;
fail(errorMessage);
}
}
/** Asserts that two iterables return iterators with the same elements in the same order. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Iterable<?> actual, Iterable<?> expected) {
assertEquals(actual, expected, null);
}
/** Asserts that two iterables return iterators with the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Iterable<?> actual, Iterable<?> expected, String message) {
if(actual == expected) {
return;
}
if(actual == null || expected == null) {
if(message != null) {
fail(message);
} else {
fail("Iterables not equal: expected: " + expected + " and actual: " + actual);
}
}
Iterator<?> actIt = actual.iterator();
Iterator<?> expIt = expected.iterator();
assertEquals(actIt, expIt, message);
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Object[] actual, Object[] expected, String message) {
if(actual == expected) {
return;
}
if ((actual == null && expected != null) || (actual != null && expected == null)) {
if (message != null) {
fail(message);
} else {
fail("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual));
}
}
assertEquals(Arrays.asList(actual), Arrays.asList(expected), message);
}
/**
* Asserts that two arrays contain the same elements in no particular order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEqualsNoOrder(Object[] actual, Object[] expected, String message) {
if(actual == expected) {
return;
}
if ((actual == null && expected != null) || (actual != null && expected == null)) {
failAssertNoEqual(
"Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual),
message);
}
if (actual.length != expected.length) {
failAssertNoEqual(
"Arrays do not have the same size:" + actual.length + " != " + expected.length,
message);
}
List<Object> actualCollection = Lists.newArrayList();
for (Object a : actual) {
actualCollection.add(a);
}
for (Object o : expected) {
actualCollection.remove(o);
}
if (actualCollection.size() != 0) {
failAssertNoEqual(
"Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual),
message);
}
}
private static void failAssertNoEqual(String defaultMessage, String message) {
if (message != null) {
fail(message);
} else {
fail(defaultMessage);
}
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Object[] actual, Object[] expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two arrays contain the same elements in no particular order. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEqualsNoOrder(Object[] actual, Object[] expected) {
assertEqualsNoOrder(actual, expected, null);
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(final byte[] actual, final byte[] expected) {
assertEquals(actual, expected, "");
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
*
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(final byte[] actual, final byte[] expected, final String message) {
if(expected == actual) {
return;
}
if(null == expected) {
fail("expected a null array, but not null found. " + message);
}
if(null == actual) {
fail("expected not null array, but null found. " + message);
}
assertEquals(actual.length, expected.length, "arrays don't have the same size. " + message);
for(int i= 0; i < expected.length; i++) {
if(expected[i] != actual[i]) {
fail("arrays differ firstly at element [" + i +"]; "
+ "expected value is <" + expected[i] +"> but was <"
+ actual[i] + ">. "
+ message);
}
}
}
/**
* Asserts that two sets are equal.
*/
static public void assertEquals(Set<?> actual, Set<?> expected) {
assertEquals(actual, expected, null);
}
/**
* Assert set equals
*/
static public void assertEquals(Set<?> actual, Set<?> expected, String message) {
if (actual == expected) {
return;
}
if (actual == null || expected == null) {
// Keep the back compatible
if (message == null) {
fail("Sets not equal: expected: " + expected + " and actual: " + actual);
} else {
failNotEquals(actual, expected, message);
}
}
if (!actual.equals(expected)) {
if (message == null) {
fail("Sets differ: expected " + expected + " but got " + actual);
} else {
failNotEquals(actual, expected, message);
}
}
}
/**
* Asserts that two maps are equal.
*/
static public void assertEquals(Map<?, ?> actual, Map<?, ?> expected) {
if (actual == expected) {
return;
}
if (actual == null || expected == null) {
fail("Maps not equal: expected: " + expected + " and actual: " + actual);
}
if (actual.size() != expected.size()) {
fail("Maps do not have the same size:" + actual.size() + " != " + expected.size());
}
Set<?> entrySet = actual.entrySet();
for (Iterator<?> iterator = entrySet.iterator(); iterator.hasNext();) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
Object expectedValue = expected.get(key);
assertEquals(value, expectedValue, "Maps do not match for key:" + key + " actual:" + value
+ " expected:" + expectedValue);
}
}
/////
// assertNotEquals
//
public static void assertNotEquals(Object actual1, Object actual2, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
public static void assertNotEquals(Object actual1, Object actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(String actual1, String actual2, String message) {
assertNotEquals((Object) actual1, (Object) actual2, message);
}
static void assertNotEquals(String actual1, String actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(long actual1, long actual2, String message) {
assertNotEquals(Long.valueOf(actual1), Long.valueOf(actual2), message);
}
static void assertNotEquals(long actual1, long actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(boolean actual1, boolean actual2, String message) {
assertNotEquals(Boolean.valueOf(actual1), Boolean.valueOf(actual2), message);
}
static void assertNotEquals(boolean actual1, boolean actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(byte actual1, byte actual2, String message) {
assertNotEquals(Byte.valueOf(actual1), Byte.valueOf(actual2), message);
}
static void assertNotEquals(byte actual1, byte actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(char actual1, char actual2, String message) {
assertNotEquals(Character.valueOf(actual1), Character.valueOf(actual2), message);
}
static void assertNotEquals(char actual1, char actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(short actual1, short actual2, String message) {
assertNotEquals(Short.valueOf(actual1), Short.valueOf(actual2), message);
}
static void assertNotEquals(short actual1, short actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(int actual1, int actual2, String message) {
assertNotEquals(Integer.valueOf(actual1), Integer.valueOf(actual2), message);
}
static void assertNotEquals(int actual1, int actual2) {
assertNotEquals(actual1, actual2, null);
}
static public void assertNotEquals(float actual1, float actual2, float delta, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2, delta, message);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
static public void assertNotEquals(float actual1, float actual2, float delta) {
assertNotEquals(actual1, actual2, delta, null);
}
static public void assertNotEquals(double actual1, double actual2, double delta, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2, delta, message);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
static public void assertNotEquals(double actual1, double actual2, double delta) {
assertNotEquals(actual1, actual2, delta, null);
}
}
| src/main/java/org/testng/Assert.java | package org.testng;
import static org.testng.internal.EclipseInterface.ASSERT_LEFT;
import static org.testng.internal.EclipseInterface.ASSERT_LEFT2;
import static org.testng.internal.EclipseInterface.ASSERT_MIDDLE;
import static org.testng.internal.EclipseInterface.ASSERT_RIGHT;
import org.testng.collections.Lists;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Assertion tool class. Presents assertion methods with a more natural parameter order.
* The order is always <B>actualValue</B>, <B>expectedValue</B> [, message].
*
* @author <a href='mailto:[email protected]'>Alexandru Popescu</a>
*/
public class Assert {
/**
* Protect constructor since it is a static only class
*/
protected Assert() {
// hide constructor
}
/**
* Asserts that a condition is true. If it isn't,
* an AssertionError, with the given message, is thrown.
* @param condition the condition to evaluate
* @param message the assertion error message
*/
static public void assertTrue(boolean condition, String message) {
if(!condition) {
failNotEquals( Boolean.valueOf(condition), Boolean.TRUE, message);
}
}
/**
* Asserts that a condition is true. If it isn't,
* an AssertionError is thrown.
* @param condition the condition to evaluate
*/
static public void assertTrue(boolean condition) {
assertTrue(condition, null);
}
/**
* Asserts that a condition is false. If it isn't,
* an AssertionError, with the given message, is thrown.
* @param condition the condition to evaluate
* @param message the assertion error message
*/
static public void assertFalse(boolean condition, String message) {
if(condition) {
failNotEquals( Boolean.valueOf(condition), Boolean.FALSE, message); // TESTNG-81
}
}
/**
* Asserts that a condition is false. If it isn't,
* an AssertionError is thrown.
* @param condition the condition to evaluate
*/
static public void assertFalse(boolean condition) {
assertFalse(condition, null);
}
/**
* Fails a test with the given message and wrapping the original exception.
*
* @param message the assertion error message
* @param realCause the original exception
*/
static public void fail(String message, Throwable realCause) {
AssertionError ae = new AssertionError(message);
ae.initCause(realCause);
throw ae;
}
/**
* Fails a test with the given message.
* @param message the assertion error message
*/
static public void fail(String message) {
throw new AssertionError(message);
}
/**
* Fails a test with no message.
*/
static public void fail() {
fail(null);
}
/**
* Asserts that two objects are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Object actual, Object expected, String message) {
if((expected == null) && (actual == null)) {
return;
}
if(expected != null) {
if (expected.getClass().isArray()) {
assertArrayEquals(actual, expected, message);
return;
} else if (expected.equals(actual)) {
return;
}
}
failNotEquals(actual, expected, message);
}
/**
* Asserts that two objects are equal. It they are not, an AssertionError,
* with given message, is thrown.
* @param actual the actual value
* @param expected the expected value (should be an non-null array value)
* @param message the assertion error message
*/
private static void assertArrayEquals(Object actual, Object expected, String message) {
//is called only when expected is an array
if (actual.getClass().isArray()) {
int expectedLength = Array.getLength(expected);
if (expectedLength == Array.getLength(actual)) {
for (int i = 0 ; i < expectedLength ; i++) {
Object _actual = Array.get(actual, i);
Object _expected = Array.get(expected, i);
try {
assertEquals(_actual, _expected);
} catch (AssertionError ae) {
failNotEquals(actual, expected, message == null ? "" : message
+ " (values as index " + i + " are not the same)");
}
}
//array values matched
return;
} else {
failNotEquals(Array.getLength(actual), expectedLength, message == null ? "" : message
+ " (Array lengths are not the same)");
}
}
failNotEquals(actual, expected, message);
}
/**
* Asserts that two objects are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Object actual, Object expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two Strings are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(String actual, String expected, String message) {
assertEquals((Object) actual, (Object) expected, message);
}
/**
* Asserts that two Strings are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(String actual, String expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not,
* an AssertionError, with the given message, is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
* @param message the assertion error message
*/
static public void assertEquals(double actual, double expected, double delta, String message) {
// handle infinity specially since subtracting to infinite values gives NaN and the
// the following test fails
if(Double.isInfinite(expected)) {
if(!(expected == actual)) {
failNotEquals(new Double(actual), new Double(expected), message);
}
}
else if(!(Math.abs(expected - actual) <= delta)) { // Because comparison with NaN always returns false
failNotEquals(new Double(actual), new Double(expected), message);
}
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not,
* an AssertionError is thrown. If the expected value is infinity then the
* delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
*/
static public void assertEquals(double actual, double expected, double delta) {
assertEquals(actual, expected, delta, null);
}
/**
* Asserts that two floats are equal concerning a delta. If they are not,
* an AssertionError, with the given message, is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
* @param message the assertion error message
*/
static public void assertEquals(float actual, float expected, float delta, String message) {
// handle infinity specially since subtracting to infinite values gives NaN and the
// the following test fails
if(Float.isInfinite(expected)) {
if(!(expected == actual)) {
failNotEquals(new Float(actual), new Float(expected), message);
}
}
else if(!(Math.abs(expected - actual) <= delta)) {
failNotEquals(new Float(actual), new Float(expected), message);
}
}
/**
* Asserts that two floats are equal concerning a delta. If they are not,
* an AssertionError is thrown. If the expected
* value is infinity then the delta value is ignored.
* @param actual the actual value
* @param expected the expected value
* @param delta the absolute tolerable difference between the actual and expected values
*/
static public void assertEquals(float actual, float expected, float delta) {
assertEquals(actual, expected, delta, null);
}
/**
* Asserts that two longs are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(long actual, long expected, String message) {
assertEquals(Long.valueOf(actual), Long.valueOf(expected), message);
}
/**
* Asserts that two longs are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(long actual, long expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two booleans are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(boolean actual, boolean expected, String message) {
assertEquals( Boolean.valueOf(actual), Boolean.valueOf(expected), message);
}
/**
* Asserts that two booleans are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(boolean actual, boolean expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two bytes are equal. If they are not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(byte actual, byte expected, String message) {
assertEquals(Byte.valueOf(actual), Byte.valueOf(expected), message);
}
/**
* Asserts that two bytes are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(byte actual, byte expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two chars are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(char actual, char expected, String message) {
assertEquals(Character.valueOf(actual), Character.valueOf(expected), message);
}
/**
* Asserts that two chars are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(char actual, char expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two shorts are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(short actual, short expected, String message) {
assertEquals(Short.valueOf(actual), Short.valueOf(expected), message);
}
/**
* Asserts that two shorts are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(short actual, short expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two ints are equal. If they are not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(int actual, int expected, String message) {
assertEquals(Integer.valueOf(actual), Integer.valueOf(expected), message);
}
/**
* Asserts that two ints are equal. If they are not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(int actual, int expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that an object isn't null. If it is,
* an AssertionError is thrown.
* @param object the assertion object
*/
static public void assertNotNull(Object object) {
assertNotNull(object, null);
}
/**
* Asserts that an object isn't null. If it is,
* an AssertionFailedError, with the given message, is thrown.
* @param object the assertion object
* @param message the assertion error message
*/
static public void assertNotNull(Object object, String message) {
if (object == null) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + "expected object to not be null");
}
assertTrue(object != null, message);
}
/**
* Asserts that an object is null. If it is not,
* an AssertionError, with the given message, is thrown.
* @param object the assertion object
*/
static public void assertNull(Object object) {
assertNull(object, null);
}
/**
* Asserts that an object is null. If it is not,
* an AssertionFailedError, with the given message, is thrown.
* @param object the assertion object
* @param message the assertion error message
*/
static public void assertNull(Object object, String message) {
if (object != null) {
failNotSame(object, null, message);
}
}
/**
* Asserts that two objects refer to the same object. If they do not,
* an AssertionFailedError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertSame(Object actual, Object expected, String message) {
if(expected == actual) {
return;
}
failNotSame(actual, expected, message);
}
/**
* Asserts that two objects refer to the same object. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertSame(Object actual, Object expected) {
assertSame(actual, expected, null);
}
/**
* Asserts that two objects do not refer to the same objects. If they do,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertNotSame(Object actual, Object expected, String message) {
if(expected == actual) {
failSame(actual, expected, message);
}
}
/**
* Asserts that two objects do not refer to the same object. If they do,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertNotSame(Object actual, Object expected) {
assertNotSame(actual, expected, null);
}
static private void failSame(Object actual, Object expected, String message) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + ASSERT_LEFT2 + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT);
}
static private void failNotSame(Object actual, Object expected, String message) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
fail(formatted + ASSERT_LEFT + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT);
}
static private void failNotEquals(Object actual , Object expected, String message ) {
fail(format(actual, expected, message));
}
static String format(Object actual, Object expected, String message) {
String formatted = "";
if (null != message) {
formatted = message + " ";
}
return formatted + ASSERT_LEFT + expected + ASSERT_MIDDLE + actual + ASSERT_RIGHT;
}
/**
* Asserts that two collections contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Collection<?> actual, Collection<?> expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two collections contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Collection<?> actual, Collection<?> expected, String message) {
if(actual == expected) {
return;
}
if (actual == null || expected == null) {
if (message != null) {
fail(message);
} else {
fail("Collections not equal: expected: " + expected + " and actual: " + actual);
}
}
assertEquals(actual.size(), expected.size(), message + ": lists don't have the same size");
Iterator<?> actIt = actual.iterator();
Iterator<?> expIt = expected.iterator();
int i = -1;
while(actIt.hasNext() && expIt.hasNext()) {
i++;
Object e = expIt.next();
Object a = actIt.next();
String explanation = "Lists differ at element [" + i + "]: " + e + " != " + a;
String errorMessage = message == null ? explanation : message + ": " + explanation;
assertEquals(a, e, errorMessage);
}
}
/** Asserts that two iterators return the same elements in the same order. If they do not,
* an AssertionError is thrown.
* Please note that this assert iterates over the elements and modifies the state of the iterators.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Iterator<?> actual, Iterator<?> expected) {
assertEquals(actual, expected, null);
}
/** Asserts that two iterators return the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* Please note that this assert iterates over the elements and modifies the state of the iterators.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Iterator<?> actual, Iterator<?> expected, String message) {
if(actual == expected) {
return;
}
if(actual == null || expected == null) {
if(message != null) {
fail(message);
} else {
fail("Iterators not equal: expected: " + expected + " and actual: " + actual);
}
}
int i = -1;
while(actual.hasNext() && expected.hasNext()) {
i++;
Object e = expected.next();
Object a = actual.next();
String explanation = "Iterators differ at element [" + i + "]: " + e + " != " + a;
String errorMessage = message == null ? explanation : message + ": " + explanation;
assertEquals(a, e, errorMessage);
}
if(actual.hasNext()) {
String explanation = "Actual iterator returned more elements than the expected iterator.";
String errorMessage = message == null ? explanation : message + ": " + explanation;
fail(errorMessage);
} else if(expected.hasNext()) {
String explanation = "Expected iterator returned more elements than the actual iterator.";
String errorMessage = message == null ? explanation : message + ": " + explanation;
fail(errorMessage);
}
}
/** Asserts that two iterables return iterators with the same elements in the same order. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Iterable<?> actual, Iterable<?> expected) {
assertEquals(actual, expected, null);
}
/** Asserts that two iterables return iterators with the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Iterable<?> actual, Iterable<?> expected, String message) {
if(actual == expected) {
return;
}
if(actual == null || expected == null) {
if(message != null) {
fail(message);
} else {
fail("Iterables not equal: expected: " + expected + " and actual: " + actual);
}
}
Iterator<?> actIt = actual.iterator();
Iterator<?> expIt = expected.iterator();
assertEquals(actIt, expIt, message);
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(Object[] actual, Object[] expected, String message) {
if(actual == expected) {
return;
}
if ((actual == null && expected != null) || (actual != null && expected == null)) {
if (message != null) {
fail(message);
} else {
fail("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual));
}
}
assertEquals(Arrays.asList(actual), Arrays.asList(expected), message);
}
/**
* Asserts that two arrays contain the same elements in no particular order. If they do not,
* an AssertionError, with the given message, is thrown.
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEqualsNoOrder(Object[] actual, Object[] expected, String message) {
if(actual == expected) {
return;
}
if ((actual == null && expected != null) || (actual != null && expected == null)) {
failAssertNoEqual(
"Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual),
message);
}
if (actual.length != expected.length) {
failAssertNoEqual(
"Arrays do not have the same size:" + actual.length + " != " + expected.length,
message);
}
List<Object> actualCollection = Lists.newArrayList();
for (Object a : actual) {
actualCollection.add(a);
}
for (Object o : expected) {
actualCollection.remove(o);
}
if (actualCollection.size() != 0) {
failAssertNoEqual(
"Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual),
message);
}
}
private static void failAssertNoEqual(String defaultMessage, String message) {
if (message != null) {
fail(message);
} else {
fail(defaultMessage);
}
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(Object[] actual, Object[] expected) {
assertEquals(actual, expected, null);
}
/**
* Asserts that two arrays contain the same elements in no particular order. If they do not,
* an AssertionError is thrown.
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEqualsNoOrder(Object[] actual, Object[] expected) {
assertEqualsNoOrder(actual, expected, null);
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError is thrown.
*
* @param actual the actual value
* @param expected the expected value
*/
static public void assertEquals(final byte[] actual, final byte[] expected) {
assertEquals(actual, expected, "");
}
/**
* Asserts that two arrays contain the same elements in the same order. If they do not,
* an AssertionError, with the given message, is thrown.
*
* @param actual the actual value
* @param expected the expected value
* @param message the assertion error message
*/
static public void assertEquals(final byte[] actual, final byte[] expected, final String message) {
if(expected == actual) {
return;
}
if(null == expected) {
fail("expected a null array, but not null found. " + message);
}
if(null == actual) {
fail("expected not null array, but null found. " + message);
}
assertEquals(actual.length, expected.length, "arrays don't have the same size. " + message);
for(int i= 0; i < expected.length; i++) {
if(expected[i] != actual[i]) {
fail("arrays differ firstly at element [" + i +"]; "
+ "expected value is <" + expected[i] +"> but was <"
+ actual[i] + ">. "
+ message);
}
}
}
/**
* Asserts that two sets are equal.
*/
static public void assertEquals(Set<?> actual, Set<?> expected) {
assertEquals(actual, expected, null);
}
/**
* Assert set equals
*/
static public void assertEquals(Set<?> actual, Set<?> expected, String message) {
if (actual == expected) {
return;
}
if (actual == null || expected == null) {
// Keep the back compatible
if (message == null) {
fail("Sets not equal: expected: " + expected + " and actual: " + actual);
} else {
failNotEquals(actual, expected, message);
}
}
if (!actual.equals(expected)) {
if (message == null) {
fail("Sets differ: expected " + expected + " but got " + actual);
} else {
failNotEquals(actual, expected, message);
}
}
}
/**
* Asserts that two maps are equal.
*/
static public void assertEquals(Map<?, ?> actual, Map<?, ?> expected) {
if (actual == expected) {
return;
}
if (actual == null || expected == null) {
fail("Maps not equal: expected: " + expected + " and actual: " + actual);
}
if (actual.size() != expected.size()) {
fail("Maps do not have the same size:" + actual.size() + " != " + expected.size());
}
Set<?> entrySet = actual.entrySet();
for (Iterator<?> iterator = entrySet.iterator(); iterator.hasNext();) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
Object expectedValue = expected.get(key);
assertEquals(value, expectedValue, "Maps do not match for key:" + key + " actual:" + value
+ " expected:" + expectedValue);
}
}
/////
// assertNotEquals
//
public static void assertNotEquals(Object actual1, Object actual2, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
public static void assertNotEquals(Object actual1, Object actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(String actual1, String actual2, String message) {
assertNotEquals((Object) actual1, (Object) actual2, message);
}
static void assertNotEquals(String actual1, String actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(long actual1, long actual2, String message) {
assertNotEquals(Long.valueOf(actual1), Long.valueOf(actual2), message);
}
static void assertNotEquals(long actual1, long actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(boolean actual1, boolean actual2, String message) {
assertNotEquals(Boolean.valueOf(actual1), Boolean.valueOf(actual2), message);
}
static void assertNotEquals(boolean actual1, boolean actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(byte actual1, byte actual2, String message) {
assertNotEquals(Byte.valueOf(actual1), Byte.valueOf(actual2), message);
}
static void assertNotEquals(byte actual1, byte actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(char actual1, char actual2, String message) {
assertNotEquals(Character.valueOf(actual1), Character.valueOf(actual2), message);
}
static void assertNotEquals(char actual1, char actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(short actual1, short actual2, String message) {
assertNotEquals(Short.valueOf(actual1), Short.valueOf(actual2), message);
}
static void assertNotEquals(short actual1, short actual2) {
assertNotEquals(actual1, actual2, null);
}
static void assertNotEquals(int actual1, int actual2, String message) {
assertNotEquals(Integer.valueOf(actual1), Integer.valueOf(actual2), message);
}
static void assertNotEquals(int actual1, int actual2) {
assertNotEquals(actual1, actual2, null);
}
static public void assertNotEquals(float actual1, float actual2, float delta, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2, delta, message);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
static public void assertNotEquals(float actual1, float actual2, float delta) {
assertNotEquals(actual1, actual2, delta, null);
}
static public void assertNotEquals(double actual1, double actual2, double delta, String message) {
boolean fail = false;
try {
Assert.assertEquals(actual1, actual2, delta, message);
fail = true;
} catch (AssertionError e) {
}
if (fail) {
Assert.fail(message);
}
}
static public void assertNotEquals(double actual1, double actual2, double delta) {
assertNotEquals(actual1, actual2, delta, null);
}
}
| Update Assert.java
Tiny typo in the Error message that shows up when arrays are not equal (but have same length) | src/main/java/org/testng/Assert.java | Update Assert.java | <ide><path>rc/main/java/org/testng/Assert.java
<ide> assertEquals(_actual, _expected);
<ide> } catch (AssertionError ae) {
<ide> failNotEquals(actual, expected, message == null ? "" : message
<del> + " (values as index " + i + " are not the same)");
<add> + " (values at index " + i + " are not the same)");
<ide> }
<ide> }
<ide> //array values matched |
|
JavaScript | mit | 50b3262063147523ca2f84dcac6ac525433c08be | 0 | babel/babel,babel/babel,hzoo/babel,babel/babel,jridgewell/babel,hzoo/babel,jridgewell/babel,jridgewell/babel,jridgewell/babel,babel/babel,hzoo/babel,hzoo/babel | // @flow
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
import { types as tt, type TokenType } from "../tokenizer/types";
import { types as ct } from "../tokenizer/context";
import * as N from "../types";
import LValParser from "./lval";
import {
isKeyword,
isReservedWord,
isStrictReservedWord,
isStrictBindReservedWord,
isIdentifierStart,
} from "../util/identifier";
import type { Pos, Position } from "../util/location";
import * as charCodes from "charcodes";
import {
BIND_OUTSIDE,
BIND_VAR,
SCOPE_ARROW,
SCOPE_CLASS,
SCOPE_DIRECT_SUPER,
SCOPE_FUNCTION,
SCOPE_SUPER,
SCOPE_PROGRAM,
} from "../util/scopeflags";
import { ExpressionErrors } from "./util";
import {
PARAM_AWAIT,
PARAM_RETURN,
PARAM,
functionFlags,
} from "../util/production-parameter";
import { Errors } from "./error";
export default class ExpressionParser extends LValParser {
// Forward-declaration: defined in statement.js
/*::
+parseBlock: (
allowDirectives?: boolean,
createNewLexicalScope?: boolean,
afterBlockParse?: (hasStrictModeDirective: boolean) => void,
) => N.BlockStatement;
+parseClass: (
node: N.Class,
isStatement: boolean,
optionalId?: boolean,
) => N.Class;
+parseDecorators: (allowExport?: boolean) => void;
+parseFunction: <T: N.NormalFunction>(
node: T,
statement?: number,
allowExpressionBody?: boolean,
isAsync?: boolean,
) => T;
+parseFunctionParams: (node: N.Function, allowModifiers?: boolean) => void;
+takeDecorators: (node: N.HasDecorators) => void;
*/
// For object literal, check if property __proto__ has been used more than once.
// If the expression is a destructuring assignment, then __proto__ may appear
// multiple times. Otherwise, __proto__ is a duplicated key.
// For record expression, check if property __proto__ exists
checkProto(
prop: N.ObjectMember | N.SpreadElement,
isRecord: boolean,
protoRef: { used: boolean },
refExpressionErrors: ?ExpressionErrors,
): void {
if (
prop.type === "SpreadElement" ||
prop.type === "ObjectMethod" ||
prop.computed ||
prop.shorthand
) {
return;
}
const key = prop.key;
// It is either an Identifier or a String/NumericLiteral
const name = key.type === "Identifier" ? key.name : key.value;
if (name === "__proto__") {
if (isRecord) {
this.raise(key.start, Errors.RecordNoProto);
return;
}
if (protoRef.used) {
if (refExpressionErrors) {
// Store the first redefinition's position, otherwise ignore because
// we are parsing ambiguous pattern
if (refExpressionErrors.doubleProto === -1) {
refExpressionErrors.doubleProto = key.start;
}
} else {
this.raise(key.start, Errors.DuplicateProto);
}
}
protoRef.used = true;
}
}
shouldExitDescending(expr: N.Expression, potentialArrowAt: number): boolean {
return (
expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt
);
}
// Convenience method to parse an Expression only
getExpression(): N.Expression {
let paramFlags = PARAM;
if (this.hasPlugin("topLevelAwait") && this.inModule) {
paramFlags |= PARAM_AWAIT;
}
this.scope.enter(SCOPE_PROGRAM);
this.prodParam.enter(paramFlags);
this.nextToken();
const expr = this.parseExpression();
if (!this.match(tt.eof)) {
this.unexpected();
}
expr.comments = this.state.comments;
expr.errors = this.state.errors;
return expr;
}
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function (s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression.
// - `noIn`
// is used to forbid the `in` operator (in for loops initialization expressions)
// When `noIn` is true, the production parameter [In] is not present.
// Whenever [?In] appears in the right-hand sides of a production, we pass
// `noIn` to the subroutine calls.
// - `refExpressionErrors `
// provides reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
// https://tc39.es/ecma262/#prod-Expression
parseExpression(
noIn?: boolean,
refExpressionErrors?: ExpressionErrors,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
const expr = this.parseMaybeAssign(noIn, refExpressionErrors);
if (this.match(tt.comma)) {
const node = this.startNodeAt(startPos, startLoc);
node.expressions = [expr];
while (this.eat(tt.comma)) {
node.expressions.push(this.parseMaybeAssign(noIn, refExpressionErrors));
}
this.toReferencedList(node.expressions);
return this.finishNode(node, "SequenceExpression");
}
return expr;
}
// Parse an assignment expression. This includes applications of
// operators like `+=`.
// https://tc39.es/ecma262/#prod-AssignmentExpression
parseMaybeAssign(
noIn?: ?boolean,
refExpressionErrors?: ?ExpressionErrors,
afterLeftParse?: Function,
refNeedsArrowPos?: ?Pos,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
if (this.isContextual("yield")) {
if (this.prodParam.hasYield) {
let left = this.parseYield(noIn);
if (afterLeftParse) {
left = afterLeftParse.call(this, left, startPos, startLoc);
}
return left;
} else {
// The tokenizer will assume an expression is allowed after
// `yield`, but this isn't that kind of yield
this.state.exprAllowed = false;
}
}
let ownExpressionErrors;
if (refExpressionErrors) {
ownExpressionErrors = false;
} else {
refExpressionErrors = new ExpressionErrors();
ownExpressionErrors = true;
}
if (this.match(tt.parenL) || this.match(tt.name)) {
this.state.potentialArrowAt = this.state.start;
}
let left = this.parseMaybeConditional(
noIn,
refExpressionErrors,
refNeedsArrowPos,
);
if (afterLeftParse) {
left = afterLeftParse.call(this, left, startPos, startLoc);
}
if (this.state.type.isAssign) {
const node = this.startNodeAt(startPos, startLoc);
const operator = this.state.value;
node.operator = operator;
if (this.match(tt.eq)) {
node.left = this.toAssignable(left);
refExpressionErrors.doubleProto = -1; // reset because double __proto__ is valid in assignment expression
} else {
node.left = left;
}
if (refExpressionErrors.shorthandAssign >= node.left.start) {
refExpressionErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
}
this.checkLVal(left, undefined, undefined, "assignment expression");
this.next();
node.right = this.parseMaybeAssign(noIn);
return this.finishNode(node, "AssignmentExpression");
} else if (ownExpressionErrors) {
this.checkExpressionErrors(refExpressionErrors, true);
}
return left;
}
// Parse a ternary conditional (`?:`) operator.
// https://tc39.es/ecma262/#prod-ConditionalExpression
parseMaybeConditional(
noIn: ?boolean,
refExpressionErrors: ExpressionErrors,
refNeedsArrowPos?: ?Pos,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
const potentialArrowAt = this.state.potentialArrowAt;
const expr = this.parseExprOps(noIn, refExpressionErrors);
if (this.shouldExitDescending(expr, potentialArrowAt)) {
return expr;
}
return this.parseConditional(
expr,
noIn,
startPos,
startLoc,
refNeedsArrowPos,
);
}
parseConditional(
expr: N.Expression,
noIn: ?boolean,
startPos: number,
startLoc: Position,
// FIXME: Disabling this for now since can't seem to get it to play nicely
// eslint-disable-next-line no-unused-vars
refNeedsArrowPos?: ?Pos,
): N.Expression {
if (this.eat(tt.question)) {
const node = this.startNodeAt(startPos, startLoc);
node.test = expr;
node.consequent = this.parseMaybeAssign();
this.expect(tt.colon);
node.alternate = this.parseMaybeAssign(noIn);
return this.finishNode(node, "ConditionalExpression");
}
return expr;
}
// Start the precedence parser.
// https://tc39.es/ecma262/#prod-ShortCircuitExpression
parseExprOps(
noIn: ?boolean,
refExpressionErrors: ExpressionErrors,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
const potentialArrowAt = this.state.potentialArrowAt;
const expr = this.parseMaybeUnary(refExpressionErrors);
if (this.shouldExitDescending(expr, potentialArrowAt)) {
return expr;
}
return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
}
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
parseExprOp(
left: N.Expression,
leftStartPos: number,
leftStartLoc: Position,
minPrec: number,
noIn: ?boolean,
): N.Expression {
let prec = this.state.type.binop;
if (prec != null && (!noIn || !this.match(tt._in))) {
if (prec > minPrec) {
const op = this.state.type;
if (op === tt.pipeline) {
this.expectPlugin("pipelineOperator");
if (this.state.inFSharpPipelineDirectBody) {
return left;
}
this.state.inPipeline = true;
this.checkPipelineAtInfixOperator(left, leftStartPos);
}
const node = this.startNodeAt(leftStartPos, leftStartLoc);
node.left = left;
node.operator = this.state.value;
if (
op === tt.exponent &&
left.type === "UnaryExpression" &&
(this.options.createParenthesizedExpressions ||
!(left.extra && left.extra.parenthesized))
) {
this.raise(
left.argument.start,
Errors.UnexpectedTokenUnaryExponentiation,
);
}
const logical = op === tt.logicalOR || op === tt.logicalAND;
const coalesce = op === tt.nullishCoalescing;
if (coalesce) {
// Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
// In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
prec = ((tt.logicalAND: any): { binop: number }).binop;
}
this.next();
if (
op === tt.pipeline &&
this.getPluginOption("pipelineOperator", "proposal") === "minimal"
) {
if (
this.match(tt.name) &&
this.state.value === "await" &&
this.prodParam.hasAwait
) {
throw this.raise(
this.state.start,
Errors.UnexpectedAwaitAfterPipelineBody,
);
}
}
node.right = this.parseExprOpRightExpr(op, prec, noIn);
this.finishNode(
node,
logical || coalesce ? "LogicalExpression" : "BinaryExpression",
);
/* this check is for all ?? operators
* a ?? b && c for this example
* when op is coalesce and nextOp is logical (&&), throw at the pos of nextOp that it can not be mixed.
* Symmetrically it also throws when op is logical and nextOp is coalesce
*/
const nextOp = this.state.type;
if (
(coalesce && (nextOp === tt.logicalOR || nextOp === tt.logicalAND)) ||
(logical && nextOp === tt.nullishCoalescing)
) {
throw this.raise(this.state.start, Errors.MixingCoalesceWithLogical);
}
return this.parseExprOp(
node,
leftStartPos,
leftStartLoc,
minPrec,
noIn,
);
}
}
return left;
}
// Helper function for `parseExprOp`. Parse the right-hand side of binary-
// operator expressions, then apply any operator-specific functions.
parseExprOpRightExpr(
op: TokenType,
prec: number,
noIn: ?boolean,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
switch (op) {
case tt.pipeline:
switch (this.getPluginOption("pipelineOperator", "proposal")) {
case "smart":
return this.withTopicPermittingContext(() => {
return this.parseSmartPipelineBody(
this.parseExprOpBaseRightExpr(op, prec, noIn),
startPos,
startLoc,
);
});
case "fsharp":
return this.withSoloAwaitPermittingContext(() => {
return this.parseFSharpPipelineBody(prec, noIn);
});
}
// falls through
default:
return this.parseExprOpBaseRightExpr(op, prec, noIn);
}
}
// Helper function for `parseExprOpRightExpr`. Parse the right-hand side of
// binary-operator expressions without applying any operator-specific functions.
parseExprOpBaseRightExpr(
op: TokenType,
prec: number,
noIn: ?boolean,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
return this.parseExprOp(
this.parseMaybeUnary(),
startPos,
startLoc,
op.rightAssociative ? prec - 1 : prec,
noIn,
);
}
// Parse unary operators, both prefix and postfix.
// https://tc39.es/ecma262/#prod-UnaryExpression
parseMaybeUnary(refExpressionErrors: ?ExpressionErrors): N.Expression {
if (this.isContextual("await") && this.isAwaitAllowed()) {
return this.parseAwait();
}
const update = this.match(tt.incDec);
const node = this.startNode();
if (this.state.type.prefix) {
node.operator = this.state.value;
node.prefix = true;
if (this.match(tt._throw)) {
this.expectPlugin("throwExpressions");
}
const isDelete = this.match(tt._delete);
this.next();
node.argument = this.parseMaybeUnary();
this.checkExpressionErrors(refExpressionErrors, true);
if (this.state.strict && isDelete) {
const arg = node.argument;
if (arg.type === "Identifier") {
this.raise(node.start, Errors.StrictDelete);
} else if (
(arg.type === "MemberExpression" ||
arg.type === "OptionalMemberExpression") &&
arg.property.type === "PrivateName"
) {
this.raise(node.start, Errors.DeletePrivateField);
}
}
if (!update) {
return this.finishNode(node, "UnaryExpression");
}
}
return this.parseUpdate(node, update, refExpressionErrors);
}
// https://tc39.es/ecma262/#prod-UpdateExpression
parseUpdate(
node: N.Expression,
update: boolean,
refExpressionErrors: ?ExpressionErrors,
): N.Expression {
if (update) {
this.checkLVal(node.argument, undefined, undefined, "prefix operation");
return this.finishNode(node, "UpdateExpression");
}
const startPos = this.state.start;
const startLoc = this.state.startLoc;
let expr = this.parseExprSubscripts(refExpressionErrors);
if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
while (this.state.type.postfix && !this.canInsertSemicolon()) {
const node = this.startNodeAt(startPos, startLoc);
node.operator = this.state.value;
node.prefix = false;
node.argument = expr;
this.checkLVal(expr, undefined, undefined, "postfix operation");
this.next();
expr = this.finishNode(node, "UpdateExpression");
}
return expr;
}
// Parse call, dot, and `[]`-subscript expressions.
// https://tc39.es/ecma262/#prod-LeftHandSideExpression
parseExprSubscripts(refExpressionErrors: ?ExpressionErrors): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
const potentialArrowAt = this.state.potentialArrowAt;
const expr = this.parseExprAtom(refExpressionErrors);
if (this.shouldExitDescending(expr, potentialArrowAt)) {
return expr;
}
return this.parseSubscripts(expr, startPos, startLoc);
}
parseSubscripts(
base: N.Expression,
startPos: number,
startLoc: Position,
noCalls?: ?boolean,
): N.Expression {
const state = {
optionalChainMember: false,
maybeAsyncArrow: this.atPossibleAsyncArrow(base),
stop: false,
};
do {
const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
if (state.maybeAsyncArrow) {
this.state.maybeInAsyncArrowHead = true;
}
base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
// After parsing a subscript, this isn't "async" for sure.
state.maybeAsyncArrow = false;
this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
} while (!state.stop);
return base;
}
/**
* @param state Set 'state.stop = true' to indicate that we should stop parsing subscripts.
* state.optionalChainMember to indicate that the member is currently in OptionalChain
*/
parseSubscript(
base: N.Expression,
startPos: number,
startLoc: Position,
noCalls: ?boolean,
state: N.ParseSubscriptState,
): N.Expression {
if (!noCalls && this.eat(tt.doubleColon)) {
return this.parseBind(base, startPos, startLoc, noCalls, state);
} else if (this.match(tt.backQuote)) {
return this.parseTaggedTemplateExpression(
base,
startPos,
startLoc,
state,
);
}
let optional = false;
if (this.match(tt.questionDot)) {
state.optionalChainMember = optional = true;
if (noCalls && this.lookaheadCharCode() === charCodes.leftParenthesis) {
// stop at `?.` when parsing `new a?.()`
state.stop = true;
return base;
}
this.next();
}
if (!noCalls && this.match(tt.parenL)) {
return this.parseCoverCallAndAsyncArrowHead(
base,
startPos,
startLoc,
state,
optional,
);
} else if (optional || this.match(tt.bracketL) || this.eat(tt.dot)) {
return this.parseMember(base, startPos, startLoc, state, optional);
} else {
state.stop = true;
return base;
}
}
// base[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ]
// base[?Yield, ?Await] . IdentifierName
// base[?Yield, ?Await] . PrivateIdentifier
// where `base` is one of CallExpression, MemberExpression and OptionalChain
parseMember(
base: N.Expression,
startPos: number,
startLoc: Position,
state: N.ParseSubscriptState,
optional: boolean,
): N.OptionalMemberExpression | N.MemberExpression {
const node = this.startNodeAt(startPos, startLoc);
const computed = this.eat(tt.bracketL);
node.object = base;
node.computed = computed;
const property = computed
? this.parseExpression()
: this.parseMaybePrivateName(true);
if (property.type === "PrivateName") {
if (node.object.type === "Super") {
this.raise(startPos, Errors.SuperPrivateField);
}
this.classScope.usePrivateName(property.id.name, property.start);
}
node.property = property;
if (computed) {
this.expect(tt.bracketR);
}
if (state.optionalChainMember) {
node.optional = optional;
return this.finishNode(node, "OptionalMemberExpression");
} else {
return this.finishNode(node, "MemberExpression");
}
}
// https://github.com/tc39/proposal-bind-operator#syntax
parseBind(
base: N.Expression,
startPos: number,
startLoc: Position,
noCalls: ?boolean,
state: N.ParseSubscriptState,
): N.Expression {
const node = this.startNodeAt(startPos, startLoc);
node.object = base;
node.callee = this.parseNoCallExpr();
state.stop = true;
return this.parseSubscripts(
this.finishNode(node, "BindExpression"),
startPos,
startLoc,
noCalls,
);
}
// https://tc39.es/ecma262/#prod-CoverCallExpressionAndAsyncArrowHead
// CoverCallExpressionAndAsyncArrowHead
// CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await]
// OptionalChain[?Yield, ?Await] Arguments[?Yield, ?Await]
parseCoverCallAndAsyncArrowHead(
base: N.Expression,
startPos: number,
startLoc: Position,
state: N.ParseSubscriptState,
optional: boolean,
): N.Expression {
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
this.state.maybeInArrowParameters = true;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.next(); // eat `(`
let node = this.startNodeAt(startPos, startLoc);
node.callee = base;
if (state.optionalChainMember) {
node.optional = optional;
}
if (optional) {
node.arguments = this.parseCallExpressionArguments(tt.parenR, false);
} else {
node.arguments = this.parseCallExpressionArguments(
tt.parenR,
state.maybeAsyncArrow,
base.type === "Import",
base.type !== "Super",
node,
);
}
this.finishCallExpression(node, state.optionalChainMember);
if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
state.stop = true;
node = this.parseAsyncArrowFromCallExpression(
this.startNodeAt(startPos, startLoc),
node,
);
this.checkYieldAwaitInDefaultParams();
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
} else {
this.toReferencedListDeep(node.arguments);
// We keep the old value if it isn't null, for cases like
// (x = async(yield)) => {}
//
// Hi developer of the future :) If you are implementing generator
// arrow functions, please read the note below about "await" and
// verify if the same logic is needed for yield.
if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
// Await is trickier than yield. When parsing a possible arrow function
// (e.g. something starting with `async(`) we don't know if its possible
// parameters will actually be inside an async arrow function or if it is
// a normal call expression.
// If it ended up being a call expression, if we are in a context where
// await expression are disallowed (and thus "await" is an identifier)
// we must be careful not to leak this.state.awaitPos to an even outer
// context, where "await" could not be an identifier.
// For example, this code is valid because "await" isn't directly inside
// an async function:
//
// async function a() {
// function b(param = async (await)) {
// }
// }
//
if (
(!this.isAwaitAllowed() && !oldMaybeInArrowParameters) ||
oldAwaitPos !== -1
) {
this.state.awaitPos = oldAwaitPos;
}
}
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
return node;
}
// MemberExpression [?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]
// CallExpression [?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]
parseTaggedTemplateExpression(
base: N.Expression,
startPos: number,
startLoc: Position,
state: N.ParseSubscriptState,
): N.TaggedTemplateExpression {
const node: N.TaggedTemplateExpression = this.startNodeAt(
startPos,
startLoc,
);
node.tag = base;
node.quasi = this.parseTemplate(true);
if (state.optionalChainMember) {
this.raise(startPos, Errors.OptionalChainingNoTemplate);
}
return this.finishNode(node, "TaggedTemplateExpression");
}
atPossibleAsyncArrow(base: N.Expression): boolean {
return (
base.type === "Identifier" &&
base.name === "async" &&
this.state.lastTokEnd === base.end &&
!this.canInsertSemicolon() &&
// check there are no escape sequences, such as \u{61}sync
base.end - base.start === 5 &&
base.start === this.state.potentialArrowAt
);
}
finishCallExpression<T: N.CallExpression | N.OptionalCallExpression>(
node: T,
optional: boolean,
): N.Expression {
if (node.callee.type === "Import") {
if (node.arguments.length === 2) {
this.expectPlugin("moduleAttributes");
}
if (node.arguments.length === 0 || node.arguments.length > 2) {
this.raise(
node.start,
Errors.ImportCallArity,
this.hasPlugin("moduleAttributes")
? "one or two arguments"
: "one argument",
);
} else {
for (const arg of node.arguments) {
if (arg.type === "SpreadElement") {
this.raise(arg.start, Errors.ImportCallSpreadArgument);
}
}
}
}
return this.finishNode(
node,
optional ? "OptionalCallExpression" : "CallExpression",
);
}
parseCallExpressionArguments(
close: TokenType,
possibleAsyncArrow: boolean,
dynamicImport?: boolean,
allowPlaceholder?: boolean,
nodeForExtra?: ?N.Node,
): $ReadOnlyArray<?N.Expression> {
const elts = [];
let innerParenStart;
let first = true;
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.inFSharpPipelineDirectBody = false;
while (!this.eat(close)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.match(close)) {
if (dynamicImport && !this.hasPlugin("moduleAttributes")) {
this.raise(
this.state.lastTokStart,
Errors.ImportCallArgumentTrailingComma,
);
}
if (nodeForExtra) {
this.addExtra(
nodeForExtra,
"trailingComma",
this.state.lastTokStart,
);
}
this.next();
break;
}
}
// we need to make sure that if this is an async arrow functions,
// that we don't allow inner parens inside the params
if (this.match(tt.parenL) && !innerParenStart) {
innerParenStart = this.state.start;
}
elts.push(
this.parseExprListItem(
false,
possibleAsyncArrow ? new ExpressionErrors() : undefined,
possibleAsyncArrow ? { start: 0 } : undefined,
allowPlaceholder,
),
);
}
// we found an async arrow function so let's not allow any inner parens
if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
this.unexpected();
}
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
return elts;
}
shouldParseAsyncArrow(): boolean {
return this.match(tt.arrow) && !this.canInsertSemicolon();
}
parseAsyncArrowFromCallExpression(
node: N.ArrowFunctionExpression,
call: N.CallExpression,
): N.ArrowFunctionExpression {
this.expect(tt.arrow);
this.parseArrowExpression(
node,
call.arguments,
true,
call.extra?.trailingComma,
);
return node;
}
// Parse a no-call expression (like argument of `new` or `::` operators).
// https://tc39.es/ecma262/#prod-MemberExpression
parseNoCallExpr(): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
// https://tc39.es/ecma262/#prod-PrimaryExpression
// https://tc39.es/ecma262/#prod-AsyncArrowFunction
// PrimaryExpression
// Super
// Import
// AsyncArrowFunction
parseExprAtom(refExpressionErrors?: ?ExpressionErrors): N.Expression {
// If a division operator appears in an expression position, the
// tokenizer got confused, and we force it to read a regexp instead.
if (this.state.type === tt.slash) this.readRegexp();
const canBeArrow = this.state.potentialArrowAt === this.state.start;
let node;
switch (this.state.type) {
case tt._super:
return this.parseSuper();
case tt._import:
node = this.startNode();
this.next();
if (this.match(tt.dot)) {
return this.parseImportMetaProperty(node);
}
if (!this.match(tt.parenL)) {
this.raise(this.state.lastTokStart, Errors.UnsupportedImport);
}
return this.finishNode(node, "Import");
case tt._this:
node = this.startNode();
this.next();
return this.finishNode(node, "ThisExpression");
case tt.name: {
const containsEsc = this.state.containsEsc;
const id = this.parseIdentifier();
if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
if (this.match(tt._function)) {
const last = this.state.context.length - 1;
if (this.state.context[last] !== ct.functionStatement) {
// Since "async" is an identifier and normally identifiers
// can't be followed by expression, the tokenizer assumes
// that "function" starts a statement.
// Fixing it in the tokenizer would mean tracking not only the
// previous token ("async"), but also the one before to know
// its beforeExpr value.
// It's easier and more efficient to adjust the context here.
throw new Error("Internal error");
}
this.state.context[last] = ct.functionExpression;
this.next();
return this.parseFunction(
this.startNodeAtNode(id),
undefined,
true,
);
} else if (this.match(tt.name)) {
return this.parseAsyncArrowUnaryFunction(id);
}
}
if (canBeArrow && this.match(tt.arrow) && !this.canInsertSemicolon()) {
this.next();
return this.parseArrowExpression(
this.startNodeAtNode(id),
[id],
false,
);
}
return id;
}
case tt._do: {
return this.parseDo();
}
case tt.regexp: {
const value = this.state.value;
node = this.parseLiteral(value.value, "RegExpLiteral");
node.pattern = value.pattern;
node.flags = value.flags;
return node;
}
case tt.num:
return this.parseLiteral(this.state.value, "NumericLiteral");
case tt.bigint:
return this.parseLiteral(this.state.value, "BigIntLiteral");
case tt.decimal:
return this.parseLiteral(this.state.value, "DecimalLiteral");
case tt.string:
return this.parseLiteral(this.state.value, "StringLiteral");
case tt._null:
node = this.startNode();
this.next();
return this.finishNode(node, "NullLiteral");
case tt._true:
case tt._false:
return this.parseBooleanLiteral();
case tt.parenL:
return this.parseParenAndDistinguishExpression(canBeArrow);
case tt.bracketBarL:
case tt.bracketHashL: {
return this.parseArrayLike(
this.state.type === tt.bracketBarL ? tt.bracketBarR : tt.bracketR,
/* canBePattern */ false,
/* isTuple */ true,
refExpressionErrors,
);
}
case tt.bracketL: {
return this.parseArrayLike(
tt.bracketR,
/* canBePattern */ true,
/* isTuple */ false,
refExpressionErrors,
);
}
case tt.braceBarL:
case tt.braceHashL: {
return this.parseObjectLike(
this.state.type === tt.braceBarL ? tt.braceBarR : tt.braceR,
/* isPattern */ false,
/* isRecord */ true,
refExpressionErrors,
);
}
case tt.braceL: {
return this.parseObjectLike(
tt.braceR,
/* isPattern */ false,
/* isRecord */ false,
refExpressionErrors,
);
}
case tt._function:
return this.parseFunctionOrFunctionSent();
case tt.at:
this.parseDecorators();
// fall through
case tt._class:
node = this.startNode();
this.takeDecorators(node);
return this.parseClass(node, false);
case tt._new:
return this.parseNewOrNewTarget();
case tt.backQuote:
return this.parseTemplate(false);
// BindExpression[Yield]
// :: MemberExpression[?Yield]
case tt.doubleColon: {
node = this.startNode();
this.next();
node.object = null;
const callee = (node.callee = this.parseNoCallExpr());
if (callee.type === "MemberExpression") {
return this.finishNode(node, "BindExpression");
} else {
throw this.raise(callee.start, Errors.UnsupportedBind);
}
}
case tt.hash: {
if (this.state.inPipeline) {
node = this.startNode();
if (
this.getPluginOption("pipelineOperator", "proposal") !== "smart"
) {
this.raise(node.start, Errors.PrimaryTopicRequiresSmartPipeline);
}
this.next();
if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
this.raise(node.start, Errors.PrimaryTopicNotAllowed);
}
this.registerTopicReference();
return this.finishNode(node, "PipelinePrimaryTopicReference");
}
// https://tc39.es/proposal-private-fields-in-in
// RelationalExpression [In, Yield, Await]
// [+In] PrivateIdentifier in ShiftExpression[?Yield, ?Await]
const nextCh = this.input.codePointAt(this.state.end);
if (isIdentifierStart(nextCh) || nextCh === charCodes.backslash) {
const start = this.state.start;
// $FlowIgnore It'll either parse a PrivateName or throw.
node = (this.parseMaybePrivateName(true): N.PrivateName);
if (this.match(tt._in)) {
this.expectPlugin("privateIn");
this.classScope.usePrivateName(node.id.name, node.start);
} else if (this.hasPlugin("privateIn")) {
this.raise(
this.state.start,
Errors.PrivateInExpectedIn,
node.id.name,
);
} else {
throw this.unexpected(start);
}
return node;
}
}
// fall through
case tt.relational: {
if (this.state.value === "<") {
const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
if (
isIdentifierStart(lookaheadCh) || // Element/Type Parameter <foo>
lookaheadCh === charCodes.greaterThan // Fragment <>
) {
this.expectOnePlugin(["jsx", "flow", "typescript"]);
}
}
}
// fall through
default:
throw this.unexpected();
}
}
// async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In]
parseAsyncArrowUnaryFunction(id: N.Expression): N.ArrowFunctionExpression {
const node = this.startNodeAtNode(id);
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
this.state.maybeInArrowParameters = true;
this.state.maybeInAsyncArrowHead = true;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
const params = [this.parseIdentifier()];
if (this.hasPrecedingLineBreak()) {
this.raise(this.state.pos, Errors.LineTerminatorBeforeArrow);
}
this.expect(tt.arrow);
this.checkYieldAwaitInDefaultParams();
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
// let foo = async bar => {};
this.parseArrowExpression(node, params, true);
return node;
}
// https://github.com/tc39/proposal-do-expressions
parseDo(): N.DoExpression {
this.expectPlugin("doExpressions");
const node = this.startNode();
this.next(); // eat `do`
const oldLabels = this.state.labels;
this.state.labels = [];
node.body = this.parseBlock();
this.state.labels = oldLabels;
return this.finishNode(node, "DoExpression");
}
// Parse the `super` keyword
parseSuper(): N.Super {
const node = this.startNode();
this.next(); // eat `super`
if (
this.match(tt.parenL) &&
!this.scope.allowDirectSuper &&
!this.options.allowSuperOutsideMethod
) {
this.raise(node.start, Errors.SuperNotAllowed);
} else if (
!this.scope.allowSuper &&
!this.options.allowSuperOutsideMethod
) {
this.raise(node.start, Errors.UnexpectedSuper);
}
if (
!this.match(tt.parenL) &&
!this.match(tt.bracketL) &&
!this.match(tt.dot)
) {
this.raise(node.start, Errors.UnsupportedSuper);
}
return this.finishNode(node, "Super");
}
parseBooleanLiteral(): N.BooleanLiteral {
const node = this.startNode();
node.value = this.match(tt._true);
this.next();
return this.finishNode(node, "BooleanLiteral");
}
parseMaybePrivateName(
isPrivateNameAllowed: boolean,
): N.PrivateName | N.Identifier {
const isPrivate = this.match(tt.hash);
if (isPrivate) {
this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
if (!isPrivateNameAllowed) {
this.raise(this.state.pos, Errors.UnexpectedPrivateField);
}
const node = this.startNode();
this.next();
this.assertNoSpace("Unexpected space between # and identifier");
node.id = this.parseIdentifier(true);
return this.finishNode(node, "PrivateName");
} else {
return this.parseIdentifier(true);
}
}
parseFunctionOrFunctionSent(): N.FunctionExpression | N.MetaProperty {
const node = this.startNode();
// We do not do parseIdentifier here because when parseFunctionOrFunctionSent
// is called we already know that the current token is a "name" with the value "function"
// This will improve perf a tiny little bit as we do not do validation but more importantly
// here is that parseIdentifier will remove an item from the expression stack
// if "function" or "class" is parsed as identifier (in objects e.g.), which should not happen here.
this.next(); // eat `function`
if (this.prodParam.hasYield && this.match(tt.dot)) {
const meta = this.createIdentifier(
this.startNodeAtNode(node),
"function",
);
this.next(); // eat `.`
return this.parseMetaProperty(node, meta, "sent");
}
return this.parseFunction(node);
}
parseMetaProperty(
node: N.MetaProperty,
meta: N.Identifier,
propertyName: string,
): N.MetaProperty {
node.meta = meta;
if (meta.name === "function" && propertyName === "sent") {
// https://github.com/tc39/proposal-function.sent#syntax-1
if (this.isContextual(propertyName)) {
this.expectPlugin("functionSent");
} else if (!this.hasPlugin("functionSent")) {
// The code wasn't `function.sent` but just `function.`, so a simple error is less confusing.
this.unexpected();
}
}
const containsEsc = this.state.containsEsc;
node.property = this.parseIdentifier(true);
if (node.property.name !== propertyName || containsEsc) {
this.raise(
node.property.start,
Errors.UnsupportedMetaProperty,
meta.name,
propertyName,
);
}
return this.finishNode(node, "MetaProperty");
}
// https://tc39.es/ecma262/#prod-ImportMeta
parseImportMetaProperty(node: N.MetaProperty): N.MetaProperty {
const id = this.createIdentifier(this.startNodeAtNode(node), "import");
this.next(); // eat `.`
if (this.isContextual("meta")) {
if (!this.inModule) {
this.raiseWithData(
id.start,
{ code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" },
Errors.ImportMetaOutsideModule,
);
}
this.sawUnambiguousESM = true;
}
return this.parseMetaProperty(node, id, "meta");
}
parseLiteral<T: N.Literal>(
value: any,
type: /*T["kind"]*/ string,
startPos?: number,
startLoc?: Position,
): T {
startPos = startPos || this.state.start;
startLoc = startLoc || this.state.startLoc;
const node = this.startNodeAt(startPos, startLoc);
this.addExtra(node, "rawValue", value);
this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
node.value = value;
this.next();
return this.finishNode(node, type);
}
// https://tc39.es/ecma262/#prod-CoverParenthesizedExpressionAndArrowParameterList
parseParenAndDistinguishExpression(canBeArrow: boolean): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
let val;
this.next(); // eat `(`
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.maybeInArrowParameters = true;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.state.inFSharpPipelineDirectBody = false;
const innerStartPos = this.state.start;
const innerStartLoc = this.state.startLoc;
const exprList = [];
const refExpressionErrors = new ExpressionErrors();
const refNeedsArrowPos = { start: 0 };
let first = true;
let spreadStart;
let optionalCommaStart;
while (!this.match(tt.parenR)) {
if (first) {
first = false;
} else {
this.expect(tt.comma, refNeedsArrowPos.start || null);
if (this.match(tt.parenR)) {
optionalCommaStart = this.state.start;
break;
}
}
if (this.match(tt.ellipsis)) {
const spreadNodeStartPos = this.state.start;
const spreadNodeStartLoc = this.state.startLoc;
spreadStart = this.state.start;
exprList.push(
this.parseParenItem(
this.parseRestBinding(),
spreadNodeStartPos,
spreadNodeStartLoc,
),
);
this.checkCommaAfterRest(charCodes.rightParenthesis);
break;
} else {
exprList.push(
this.parseMaybeAssign(
false,
refExpressionErrors,
this.parseParenItem,
refNeedsArrowPos,
),
);
}
}
const innerEndPos = this.state.lastTokEnd;
const innerEndLoc = this.state.lastTokEndLoc;
this.expect(tt.parenR);
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
let arrowNode = this.startNodeAt(startPos, startLoc);
if (
canBeArrow &&
this.shouldParseArrow() &&
(arrowNode = this.parseArrow(arrowNode))
) {
if (!this.isAwaitAllowed() && !this.state.maybeInAsyncArrowHead) {
this.state.awaitPos = oldAwaitPos;
}
this.checkYieldAwaitInDefaultParams();
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
for (const param of exprList) {
if (param.extra && param.extra.parenthesized) {
this.unexpected(param.extra.parenStart);
}
}
this.parseArrowExpression(arrowNode, exprList, false);
return arrowNode;
}
// We keep the old value if it isn't null, for cases like
// (x = (yield)) => {}
if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos;
if (!exprList.length) {
this.unexpected(this.state.lastTokStart);
}
if (optionalCommaStart) this.unexpected(optionalCommaStart);
if (spreadStart) this.unexpected(spreadStart);
this.checkExpressionErrors(refExpressionErrors, true);
if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
this.toReferencedListDeep(exprList, /* isParenthesizedExpr */ true);
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
} else {
val = exprList[0];
}
if (!this.options.createParenthesizedExpressions) {
this.addExtra(val, "parenthesized", true);
this.addExtra(val, "parenStart", startPos);
return val;
}
const parenExpression = this.startNodeAt(startPos, startLoc);
parenExpression.expression = val;
this.finishNode(parenExpression, "ParenthesizedExpression");
return parenExpression;
}
shouldParseArrow(): boolean {
return !this.canInsertSemicolon();
}
parseArrow(node: N.ArrowFunctionExpression): ?N.ArrowFunctionExpression {
if (this.eat(tt.arrow)) {
return node;
}
}
parseParenItem(
node: N.Expression,
startPos: number, // eslint-disable-line no-unused-vars
startLoc: Position, // eslint-disable-line no-unused-vars
): N.Expression {
return node;
}
parseNewOrNewTarget(): N.NewExpression | N.MetaProperty {
const node = this.startNode();
this.next();
if (this.match(tt.dot)) {
// https://tc39.es/ecma262/#prod-NewTarget
const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
this.next();
const metaProp = this.parseMetaProperty(node, meta, "target");
if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
let error = Errors.UnexpectedNewTarget;
if (this.hasPlugin("classProperties")) {
error += " or class properties";
}
/* eslint-disable @babel/development-internal/dry-error-messages */
this.raise(metaProp.start, error);
/* eslint-enable @babel/development-internal/dry-error-messages */
}
return metaProp;
}
return this.parseNew(node);
}
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
// https://tc39.es/ecma262/#prod-NewExpression
parseNew(node: N.Expression): N.NewExpression {
node.callee = this.parseNoCallExpr();
if (node.callee.type === "Import") {
this.raise(node.callee.start, Errors.ImportCallNotNewExpression);
} else if (
node.callee.type === "OptionalMemberExpression" ||
node.callee.type === "OptionalCallExpression"
) {
this.raise(this.state.lastTokEnd, Errors.OptionalChainingNoNew);
} else if (this.eat(tt.questionDot)) {
this.raise(this.state.start, Errors.OptionalChainingNoNew);
}
this.parseNewArguments(node);
return this.finishNode(node, "NewExpression");
}
parseNewArguments(node: N.NewExpression): void {
if (this.eat(tt.parenL)) {
const args = this.parseExprList(tt.parenR);
this.toReferencedList(args);
// $FlowFixMe (parseExprList should be all non-null in this case)
node.arguments = args;
} else {
node.arguments = [];
}
}
// Parse template expression.
parseTemplateElement(isTagged: boolean): N.TemplateElement {
const elem = this.startNode();
if (this.state.value === null) {
if (!isTagged) {
this.raise(this.state.start + 1, Errors.InvalidEscapeSequenceTemplate);
}
}
elem.value = {
raw: this.input
.slice(this.state.start, this.state.end)
.replace(/\r\n?/g, "\n"),
cooked: this.state.value,
};
this.next();
elem.tail = this.match(tt.backQuote);
return this.finishNode(elem, "TemplateElement");
}
// https://tc39.es/ecma262/#prod-TemplateLiteral
parseTemplate(isTagged: boolean): N.TemplateLiteral {
const node = this.startNode();
this.next();
node.expressions = [];
let curElt = this.parseTemplateElement(isTagged);
node.quasis = [curElt];
while (!curElt.tail) {
this.expect(tt.dollarBraceL);
node.expressions.push(this.parseExpression());
this.expect(tt.braceR);
node.quasis.push((curElt = this.parseTemplateElement(isTagged)));
}
this.next();
return this.finishNode(node, "TemplateLiteral");
}
// Parse an object literal, binding pattern, or record.
parseObjectLike<T: N.ObjectPattern | N.ObjectExpression>(
close: TokenType,
isPattern: boolean,
isRecord?: ?boolean,
refExpressionErrors?: ?ExpressionErrors,
): T {
if (isRecord) {
this.expectPlugin("recordAndTuple");
}
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.inFSharpPipelineDirectBody = false;
const propHash: any = Object.create(null);
let first = true;
const node = this.startNode();
node.properties = [];
this.next();
while (!this.eat(close)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.match(close)) {
this.addExtra(node, "trailingComma", this.state.lastTokStart);
this.next();
break;
}
}
const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
if (!isPattern) {
// $FlowIgnore RestElement will never be returned if !isPattern
this.checkProto(prop, isRecord, propHash, refExpressionErrors);
}
if (
isRecord &&
prop.type !== "ObjectProperty" &&
prop.type !== "SpreadElement"
) {
this.raise(prop.start, Errors.InvalidRecordProperty);
}
// $FlowIgnore
if (prop.shorthand) {
this.addExtra(prop, "shorthand", true);
}
node.properties.push(prop);
}
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
let type = "ObjectExpression";
if (isPattern) {
type = "ObjectPattern";
} else if (isRecord) {
type = "RecordExpression";
}
return this.finishNode(node, type);
}
// Check grammar production:
// IdentifierName *_opt PropertyName
// It is used in `parsePropertyDefinition` to detect AsyncMethod and Accessors
maybeAsyncOrAccessorProp(prop: N.ObjectProperty): boolean {
return (
!prop.computed &&
prop.key.type === "Identifier" &&
(this.isLiteralPropertyName() ||
this.match(tt.bracketL) ||
this.match(tt.star))
);
}
// https://tc39.es/ecma262/#prod-PropertyDefinition
parsePropertyDefinition(
isPattern: boolean,
refExpressionErrors?: ?ExpressionErrors,
): N.ObjectMember | N.SpreadElement | N.RestElement {
let decorators = [];
if (this.match(tt.at)) {
if (this.hasPlugin("decorators")) {
this.raise(this.state.start, Errors.UnsupportedPropertyDecorator);
}
// we needn't check if decorators (stage 0) plugin is enabled since it's checked by
// the call to this.parseDecorator
while (this.match(tt.at)) {
decorators.push(this.parseDecorator());
}
}
const prop = this.startNode();
let isGenerator = false;
let isAsync = false;
let isAccessor = false;
let startPos;
let startLoc;
if (this.match(tt.ellipsis)) {
if (decorators.length) this.unexpected();
if (isPattern) {
this.next();
// Don't use parseRestBinding() as we only allow Identifier here.
prop.argument = this.parseIdentifier();
this.checkCommaAfterRest(charCodes.rightCurlyBrace);
return this.finishNode(prop, "RestElement");
}
return this.parseSpread();
}
if (decorators.length) {
prop.decorators = decorators;
decorators = [];
}
prop.method = false;
if (isPattern || refExpressionErrors) {
startPos = this.state.start;
startLoc = this.state.startLoc;
}
if (!isPattern) {
isGenerator = this.eat(tt.star);
}
const containsEsc = this.state.containsEsc;
const key = this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
if (
!isPattern &&
!isGenerator &&
!containsEsc &&
this.maybeAsyncOrAccessorProp(prop)
) {
const keyName = key.name;
// https://tc39.es/ecma262/#prod-AsyncMethod
// https://tc39.es/ecma262/#prod-AsyncGeneratorMethod
if (keyName === "async" && !this.hasPrecedingLineBreak()) {
isAsync = true;
isGenerator = this.eat(tt.star);
this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
}
// get PropertyName[?Yield, ?Await] () { FunctionBody[~Yield, ~Await] }
// set PropertyName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] }
if (keyName === "get" || keyName === "set") {
isAccessor = true;
isGenerator = this.eat(tt.star); // tt.star is allowed in `maybeAsyncOrAccessorProp`, we will throw in `parseObjectMethod` later
prop.kind = keyName;
this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
}
}
this.parseObjPropValue(
prop,
startPos,
startLoc,
isGenerator,
isAsync,
isPattern,
isAccessor,
refExpressionErrors,
);
return prop;
}
getGetterSetterExpectedParamCount(
method: N.ObjectMethod | N.ClassMethod,
): number {
return method.kind === "get" ? 0 : 1;
}
// get methods aren't allowed to have any parameters
// set methods must have exactly 1 parameter which is not a rest parameter
checkGetterSetterParams(method: N.ObjectMethod | N.ClassMethod): void {
const paramCount = this.getGetterSetterExpectedParamCount(method);
const start = method.start;
if (method.params.length !== paramCount) {
if (method.kind === "get") {
this.raise(start, Errors.BadGetterArity);
} else {
this.raise(start, Errors.BadSetterArity);
}
}
if (
method.kind === "set" &&
method.params[method.params.length - 1].type === "RestElement"
) {
this.raise(start, Errors.BadSetterRestParameter);
}
}
// https://tc39.es/ecma262/#prod-MethodDefinition
parseObjectMethod(
prop: N.ObjectMethod,
isGenerator: boolean,
isAsync: boolean,
isPattern: boolean,
isAccessor: boolean,
): ?N.ObjectMethod {
if (isAccessor) {
// isAccessor implies isAsync: false, isPattern: false
if (isGenerator) this.unexpected();
this.parseMethod(
prop,
/* isGenerator */ false,
/* isAsync */ false,
/* isConstructor */ false,
false,
"ObjectMethod",
);
this.checkGetterSetterParams(prop);
return prop;
}
if (isAsync || isGenerator || this.match(tt.parenL)) {
if (isPattern) this.unexpected();
prop.kind = "method";
prop.method = true;
return this.parseMethod(
prop,
isGenerator,
isAsync,
/* isConstructor */ false,
false,
"ObjectMethod",
);
}
}
// if `isPattern` is true, parse https://tc39.es/ecma262/#prod-BindingProperty
// else https://tc39.es/ecma262/#prod-PropertyDefinition
parseObjectProperty(
prop: N.ObjectProperty,
startPos: ?number,
startLoc: ?Position,
isPattern: boolean,
refExpressionErrors: ?ExpressionErrors,
): ?N.ObjectProperty {
prop.shorthand = false;
if (this.eat(tt.colon)) {
prop.value = isPattern
? this.parseMaybeDefault(this.state.start, this.state.startLoc)
: this.parseMaybeAssign(false, refExpressionErrors);
return this.finishNode(prop, "ObjectProperty");
}
if (!prop.computed && prop.key.type === "Identifier") {
// PropertyDefinition:
// IdentifierReference
// CoveredInitializedName
// Note: `{ eval } = {}` will be checked in `checkLVal` later.
this.checkReservedWord(prop.key.name, prop.key.start, true, false);
if (isPattern) {
prop.value = this.parseMaybeDefault(
startPos,
startLoc,
prop.key.__clone(),
);
} else if (this.match(tt.eq) && refExpressionErrors) {
if (refExpressionErrors.shorthandAssign === -1) {
refExpressionErrors.shorthandAssign = this.state.start;
}
prop.value = this.parseMaybeDefault(
startPos,
startLoc,
prop.key.__clone(),
);
} else {
prop.value = prop.key.__clone();
}
prop.shorthand = true;
return this.finishNode(prop, "ObjectProperty");
}
}
parseObjPropValue(
prop: any,
startPos: ?number,
startLoc: ?Position,
isGenerator: boolean,
isAsync: boolean,
isPattern: boolean,
isAccessor: boolean,
refExpressionErrors?: ?ExpressionErrors,
): void {
const node =
this.parseObjectMethod(
prop,
isGenerator,
isAsync,
isPattern,
isAccessor,
) ||
this.parseObjectProperty(
prop,
startPos,
startLoc,
isPattern,
refExpressionErrors,
);
if (!node) this.unexpected();
// $FlowFixMe
return node;
}
parsePropertyName(
prop: N.ObjectOrClassMember | N.ClassMember | N.TsNamedTypeElementBase,
isPrivateNameAllowed: boolean,
): N.Expression | N.Identifier {
if (this.eat(tt.bracketL)) {
(prop: $FlowSubtype<N.ObjectOrClassMember>).computed = true;
prop.key = this.parseMaybeAssign();
this.expect(tt.bracketR);
} else {
const oldInPropertyName = this.state.inPropertyName;
this.state.inPropertyName = true;
// We check if it's valid for it to be a private name when we push it.
(prop: $FlowFixMe).key =
this.match(tt.num) ||
this.match(tt.string) ||
this.match(tt.bigint) ||
this.match(tt.decimal)
? this.parseExprAtom()
: this.parseMaybePrivateName(isPrivateNameAllowed);
if (prop.key.type !== "PrivateName") {
// ClassPrivateProperty is never computed, so we don't assign in that case.
prop.computed = false;
}
this.state.inPropertyName = oldInPropertyName;
}
return prop.key;
}
// Initialize empty function node.
initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: ?boolean): void {
node.id = null;
node.generator = false;
node.async = !!isAsync;
}
// Parse object or class method.
parseMethod<T: N.MethodLike>(
node: T,
isGenerator: boolean,
isAsync: boolean,
isConstructor: boolean,
allowDirectSuper: boolean,
type: string,
inClassScope: boolean = false,
): T {
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.initFunction(node, isAsync);
node.generator = !!isGenerator;
const allowModifiers = isConstructor; // For TypeScript parameter properties
this.scope.enter(
SCOPE_FUNCTION |
SCOPE_SUPER |
(inClassScope ? SCOPE_CLASS : 0) |
(allowDirectSuper ? SCOPE_DIRECT_SUPER : 0),
);
this.prodParam.enter(functionFlags(isAsync, node.generator));
this.parseFunctionParams((node: any), allowModifiers);
this.parseFunctionBodyAndFinish(node, type, true);
this.prodParam.exit();
this.scope.exit();
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
return node;
}
// parse an array literal or tuple literal
// https://tc39.es/ecma262/#prod-ArrayLiteral
// https://tc39.es/proposal-record-tuple/#prod-TupleLiteral
parseArrayLike(
close: TokenType,
canBePattern: boolean,
isTuple: boolean,
refExpressionErrors: ?ExpressionErrors,
): N.ArrayExpression | N.TupleExpression {
if (isTuple) {
this.expectPlugin("recordAndTuple");
}
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.inFSharpPipelineDirectBody = false;
const node = this.startNode();
this.next();
node.elements = this.parseExprList(
close,
/* allowEmpty */ !isTuple,
refExpressionErrors,
node,
);
if (canBePattern && !this.state.maybeInArrowParameters) {
// This could be an array pattern:
// ([a: string, b: string]) => {}
// In this case, we don't have to call toReferencedList. We will
// call it, if needed, when we are sure that it is a parenthesized
// expression by calling toReferencedListDeep.
this.toReferencedList(node.elements);
}
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
return this.finishNode(
node,
isTuple ? "TupleExpression" : "ArrayExpression",
);
}
// Parse arrow function expression.
// If the parameters are provided, they will be converted to an
// assignable list.
parseArrowExpression(
node: N.ArrowFunctionExpression,
params: ?(N.Expression[]),
isAsync: boolean,
trailingCommaPos: ?number,
): N.ArrowFunctionExpression {
this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
this.prodParam.enter(functionFlags(isAsync, false));
this.initFunction(node, isAsync);
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
if (params) {
this.state.maybeInArrowParameters = true;
this.setArrowFunctionParameters(node, params, trailingCommaPos);
}
this.state.maybeInArrowParameters = false;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.parseFunctionBody(node, true);
this.prodParam.exit();
this.scope.exit();
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
return this.finishNode(node, "ArrowFunctionExpression");
}
setArrowFunctionParameters(
node: N.ArrowFunctionExpression,
params: N.Expression[],
trailingCommaPos: ?number,
): void {
node.params = this.toAssignableList(params, trailingCommaPos);
}
parseFunctionBodyAndFinish(
node: N.BodilessFunctionOrMethodBase,
type: string,
isMethod?: boolean = false,
): void {
// $FlowIgnore (node is not bodiless if we get here)
this.parseFunctionBody(node, false, isMethod);
this.finishNode(node, type);
}
// Parse function body and check parameters.
parseFunctionBody(
node: N.Function,
allowExpression: ?boolean,
isMethod?: boolean = false,
): void {
const isExpression = allowExpression && !this.match(tt.braceL);
const oldInParameters = this.state.inParameters;
this.state.inParameters = false;
if (isExpression) {
node.body = this.parseMaybeAssign();
this.checkParams(node, false, allowExpression, false);
} else {
const oldStrict = this.state.strict;
// Start a new scope with regard to labels
// flag (restore them to their old value afterwards).
const oldLabels = this.state.labels;
this.state.labels = [];
// FunctionBody[Yield, Await]:
// StatementList[?Yield, ?Await, +Return] opt
this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
node.body = this.parseBlock(
true,
false,
// Strict mode function checks after we parse the statements in the function body.
(hasStrictModeDirective: boolean) => {
const nonSimple = !this.isSimpleParamList(node.params);
if (hasStrictModeDirective && nonSimple) {
// This logic is here to align the error location with the ESTree plugin.
const errorPos =
// $FlowIgnore
(node.kind === "method" || node.kind === "constructor") &&
// $FlowIgnore
!!node.key
? node.key.end
: node.start;
this.raise(errorPos, Errors.IllegalLanguageModeDirective);
}
const strictModeChanged = !oldStrict && this.state.strict;
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(
node,
!this.state.strict && !allowExpression && !isMethod && !nonSimple,
allowExpression,
strictModeChanged,
);
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
if (this.state.strict && node.id) {
this.checkLVal(
node.id,
BIND_OUTSIDE,
undefined,
"function name",
undefined,
strictModeChanged,
);
}
},
);
this.prodParam.exit();
this.state.labels = oldLabels;
}
this.state.inParameters = oldInParameters;
}
isSimpleParamList(
params: $ReadOnlyArray<N.Pattern | N.TSParameterProperty>,
): boolean {
for (let i = 0, len = params.length; i < len; i++) {
if (params[i].type !== "Identifier") return false;
}
return true;
}
checkParams(
node: N.Function,
allowDuplicates: boolean,
// eslint-disable-next-line no-unused-vars
isArrowFunction: ?boolean,
strictModeChanged?: boolean = true,
): void {
// $FlowIssue
const nameHash: {} = Object.create(null);
for (let i = 0; i < node.params.length; i++) {
this.checkLVal(
node.params[i],
BIND_VAR,
allowDuplicates ? null : nameHash,
"function parameter list",
undefined,
strictModeChanged,
);
}
}
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
parseExprList(
close: TokenType,
allowEmpty?: boolean,
refExpressionErrors?: ?ExpressionErrors,
nodeForExtra?: ?N.Node,
): $ReadOnlyArray<?N.Expression> {
const elts = [];
let first = true;
while (!this.eat(close)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.match(close)) {
if (nodeForExtra) {
this.addExtra(
nodeForExtra,
"trailingComma",
this.state.lastTokStart,
);
}
this.next();
break;
}
}
elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
}
return elts;
}
parseExprListItem(
allowEmpty: ?boolean,
refExpressionErrors?: ?ExpressionErrors,
refNeedsArrowPos: ?Pos,
allowPlaceholder: ?boolean,
): ?N.Expression {
let elt;
if (this.match(tt.comma)) {
if (!allowEmpty) {
this.raise(this.state.pos, Errors.UnexpectedToken, ",");
}
elt = null;
} else if (this.match(tt.ellipsis)) {
const spreadNodeStartPos = this.state.start;
const spreadNodeStartLoc = this.state.startLoc;
elt = this.parseParenItem(
this.parseSpread(refExpressionErrors, refNeedsArrowPos),
spreadNodeStartPos,
spreadNodeStartLoc,
);
} else if (this.match(tt.question)) {
this.expectPlugin("partialApplication");
if (!allowPlaceholder) {
this.raise(this.state.start, Errors.UnexpectedArgumentPlaceholder);
}
const node = this.startNode();
this.next();
elt = this.finishNode(node, "ArgumentPlaceholder");
} else {
elt = this.parseMaybeAssign(
false,
refExpressionErrors,
this.parseParenItem,
refNeedsArrowPos,
);
}
return elt;
}
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
// This shouldn't be used to parse the keywords of meta properties, since they
// are not identifiers and cannot contain escape sequences.
parseIdentifier(liberal?: boolean): N.Identifier {
const node = this.startNode();
const name = this.parseIdentifierName(node.start, liberal);
return this.createIdentifier(node, name);
}
createIdentifier(node: N.Identifier, name: string): N.Identifier {
node.name = name;
node.loc.identifierName = name;
return this.finishNode(node, "Identifier");
}
parseIdentifierName(pos: number, liberal?: boolean): string {
let name: string;
if (this.match(tt.name)) {
name = this.state.value;
} else if (this.state.type.keyword) {
name = this.state.type.keyword;
// `class` and `function` keywords push function-type token context into this.context.
// But there is no chance to pop the context if the keyword is consumed
// as an identifier such as a property name.
const context = this.state.context;
if (
(name === "class" || name === "function") &&
context[context.length - 1].token === "function"
) {
context.pop();
}
} else {
throw this.unexpected();
}
if (liberal) {
// If the current token is not used as a keyword, set its type to "tt.name".
// This will prevent this.next() from throwing about unexpected escapes.
this.state.type = tt.name;
} else {
this.checkReservedWord(
name,
this.state.start,
!!this.state.type.keyword,
false,
);
}
this.next();
return name;
}
checkReservedWord(
word: string,
startLoc: number,
checkKeywords: boolean,
isBinding: boolean,
): void {
if (this.prodParam.hasYield && word === "yield") {
this.raise(startLoc, Errors.YieldBindingIdentifier);
return;
}
if (word === "await") {
if (this.prodParam.hasAwait) {
this.raise(startLoc, Errors.AwaitBindingIdentifier);
return;
}
if (
this.state.awaitPos === -1 &&
(this.state.maybeInAsyncArrowHead || this.isAwaitAllowed())
) {
this.state.awaitPos = this.state.start;
}
}
if (
this.scope.inClass &&
!this.scope.inNonArrowFunction &&
word === "arguments"
) {
this.raise(startLoc, Errors.ArgumentsDisallowedInInitializer);
return;
}
if (checkKeywords && isKeyword(word)) {
this.raise(startLoc, Errors.UnexpectedKeyword, word);
return;
}
const reservedTest = !this.state.strict
? isReservedWord
: isBinding
? isStrictBindReservedWord
: isStrictReservedWord;
if (reservedTest(word, this.inModule)) {
if (!this.prodParam.hasAwait && word === "await") {
this.raise(startLoc, Errors.AwaitNotInAsyncFunction);
} else {
this.raise(startLoc, Errors.UnexpectedReservedWord, word);
}
}
}
isAwaitAllowed(): boolean {
if (this.scope.inFunction) return this.prodParam.hasAwait;
if (this.options.allowAwaitOutsideFunction) return true;
if (this.hasPlugin("topLevelAwait")) {
return this.inModule && this.prodParam.hasAwait;
}
return false;
}
// Parses await expression inside async function.
parseAwait(): N.AwaitExpression {
const node = this.startNode();
this.next();
if (this.state.inParameters) {
this.raise(node.start, Errors.AwaitExpressionFormalParameter);
} else if (this.state.awaitPos === -1) {
this.state.awaitPos = node.start;
}
if (this.eat(tt.star)) {
this.raise(node.start, Errors.ObsoleteAwaitStar);
}
if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
if (
this.hasPrecedingLineBreak() ||
// All the following expressions are ambiguous:
// await + 0, await - 0, await ( 0 ), await [ 0 ], await / 0 /u, await ``
this.match(tt.plusMin) ||
this.match(tt.parenL) ||
this.match(tt.bracketL) ||
this.match(tt.backQuote) ||
// Sometimes the tokenizer generates tt.slash for regexps, and this is
// handler by parseExprAtom
this.match(tt.regexp) ||
this.match(tt.slash) ||
// This code could be parsed both as a modulo operator or as an intrinsic:
// await %x(0)
(this.hasPlugin("v8intrinsic") && this.match(tt.modulo))
) {
this.ambiguousScriptDifferentAst = true;
} else {
this.sawUnambiguousESM = true;
}
}
if (!this.state.soloAwait) {
node.argument = this.parseMaybeUnary();
}
return this.finishNode(node, "AwaitExpression");
}
// Parses yield expression inside generator.
parseYield(noIn?: ?boolean): N.YieldExpression {
const node = this.startNode();
if (this.state.inParameters) {
this.raise(node.start, Errors.YieldInParameter);
} else if (this.state.yieldPos === -1) {
this.state.yieldPos = node.start;
}
this.next();
if (
this.match(tt.semi) ||
(!this.match(tt.star) && !this.state.type.startsExpr) ||
this.hasPrecedingLineBreak()
) {
node.delegate = false;
node.argument = null;
} else {
node.delegate = this.eat(tt.star);
node.argument = this.parseMaybeAssign(noIn);
}
return this.finishNode(node, "YieldExpression");
}
// Validates a pipeline (for any of the pipeline Babylon plugins) at the point
// of the infix operator `|>`.
checkPipelineAtInfixOperator(left: N.Expression, leftStartPos: number) {
if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
if (left.type === "SequenceExpression") {
// Ensure that the pipeline head is not a comma-delimited
// sequence expression.
this.raise(leftStartPos, Errors.PipelineHeadSequenceExpression);
}
}
}
parseSmartPipelineBody(
childExpression: N.Expression,
startPos: number,
startLoc: Position,
): N.PipelineBody {
const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression);
this.checkSmartPipelineBodyEarlyErrors(
childExpression,
pipelineStyle,
startPos,
);
return this.parseSmartPipelineBodyInStyle(
childExpression,
pipelineStyle,
startPos,
startLoc,
);
}
checkSmartPipelineBodyEarlyErrors(
childExpression: N.Expression,
pipelineStyle: N.PipelineStyle,
startPos: number,
): void {
if (this.match(tt.arrow)) {
// If the following token is invalidly `=>`, then throw a human-friendly error
// instead of something like 'Unexpected token, expected ";"'.
throw this.raise(this.state.start, Errors.PipelineBodyNoArrow);
} else if (
pipelineStyle === "PipelineTopicExpression" &&
childExpression.type === "SequenceExpression"
) {
this.raise(startPos, Errors.PipelineBodySequenceExpression);
}
}
parseSmartPipelineBodyInStyle(
childExpression: N.Expression,
pipelineStyle: N.PipelineStyle,
startPos: number,
startLoc: Position,
): N.PipelineBody {
const bodyNode = this.startNodeAt(startPos, startLoc);
switch (pipelineStyle) {
case "PipelineBareFunction":
bodyNode.callee = childExpression;
break;
case "PipelineBareConstructor":
bodyNode.callee = childExpression.callee;
break;
case "PipelineBareAwaitedFunction":
bodyNode.callee = childExpression.argument;
break;
case "PipelineTopicExpression":
if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
this.raise(startPos, Errors.PipelineTopicUnused);
}
bodyNode.expression = childExpression;
break;
default:
throw new Error(
`Internal @babel/parser error: Unknown pipeline style (${pipelineStyle})`,
);
}
return this.finishNode(bodyNode, pipelineStyle);
}
checkSmartPipelineBodyStyle(expression: N.Expression): N.PipelineStyle {
switch (expression.type) {
default:
return this.isSimpleReference(expression)
? "PipelineBareFunction"
: "PipelineTopicExpression";
}
}
isSimpleReference(expression: N.Expression): boolean {
switch (expression.type) {
case "MemberExpression":
return (
!expression.computed && this.isSimpleReference(expression.object)
);
case "Identifier":
return true;
default:
return false;
}
}
// Enable topic references from outer contexts within smart pipeline bodies.
// The function modifies the parser's topic-context state to enable or disable
// the use of topic references with the smartPipelines plugin. They then run a
// callback, then they reset the parser to the old topic-context state that it
// had before the function was called.
withTopicPermittingContext<T>(callback: () => T): T {
const outerContextTopicState = this.state.topicContext;
this.state.topicContext = {
// Enable the use of the primary topic reference.
maxNumOfResolvableTopics: 1,
// Hide the use of any topic references from outer contexts.
maxTopicIndex: null,
};
try {
return callback();
} finally {
this.state.topicContext = outerContextTopicState;
}
}
// Disable topic references from outer contexts within syntax constructs
// such as the bodies of iteration statements.
// The function modifies the parser's topic-context state to enable or disable
// the use of topic references with the smartPipelines plugin. They then run a
// callback, then they reset the parser to the old topic-context state that it
// had before the function was called.
withTopicForbiddingContext<T>(callback: () => T): T {
const outerContextTopicState = this.state.topicContext;
this.state.topicContext = {
// Disable the use of the primary topic reference.
maxNumOfResolvableTopics: 0,
// Hide the use of any topic references from outer contexts.
maxTopicIndex: null,
};
try {
return callback();
} finally {
this.state.topicContext = outerContextTopicState;
}
}
withSoloAwaitPermittingContext<T>(callback: () => T): T {
const outerContextSoloAwaitState = this.state.soloAwait;
this.state.soloAwait = true;
try {
return callback();
} finally {
this.state.soloAwait = outerContextSoloAwaitState;
}
}
// Register the use of a primary topic reference (`#`) within the current
// topic context.
registerTopicReference(): void {
this.state.topicContext.maxTopicIndex = 0;
}
primaryTopicReferenceIsAllowedInCurrentTopicContext(): boolean {
return this.state.topicContext.maxNumOfResolvableTopics >= 1;
}
topicReferenceWasUsedInCurrentTopicContext(): boolean {
return (
this.state.topicContext.maxTopicIndex != null &&
this.state.topicContext.maxTopicIndex >= 0
);
}
parseFSharpPipelineBody(prec: number, noIn: ?boolean): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
this.state.potentialArrowAt = this.state.start;
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.inFSharpPipelineDirectBody = true;
const ret = this.parseExprOp(
this.parseMaybeUnary(),
startPos,
startLoc,
prec,
noIn,
);
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
return ret;
}
}
| packages/babel-parser/src/parser/expression.js | // @flow
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
import { types as tt, type TokenType } from "../tokenizer/types";
import { types as ct } from "../tokenizer/context";
import * as N from "../types";
import LValParser from "./lval";
import {
isKeyword,
isReservedWord,
isStrictReservedWord,
isStrictBindReservedWord,
isIdentifierStart,
} from "../util/identifier";
import type { Pos, Position } from "../util/location";
import * as charCodes from "charcodes";
import {
BIND_OUTSIDE,
BIND_VAR,
SCOPE_ARROW,
SCOPE_CLASS,
SCOPE_DIRECT_SUPER,
SCOPE_FUNCTION,
SCOPE_SUPER,
SCOPE_PROGRAM,
} from "../util/scopeflags";
import { ExpressionErrors } from "./util";
import {
PARAM_AWAIT,
PARAM_RETURN,
PARAM,
functionFlags,
} from "../util/production-parameter";
import { Errors } from "./error";
export default class ExpressionParser extends LValParser {
// Forward-declaration: defined in statement.js
/*::
+parseBlock: (
allowDirectives?: boolean,
createNewLexicalScope?: boolean,
afterBlockParse?: (hasStrictModeDirective: boolean) => void,
) => N.BlockStatement;
+parseClass: (
node: N.Class,
isStatement: boolean,
optionalId?: boolean,
) => N.Class;
+parseDecorators: (allowExport?: boolean) => void;
+parseFunction: <T: N.NormalFunction>(
node: T,
statement?: number,
allowExpressionBody?: boolean,
isAsync?: boolean,
) => T;
+parseFunctionParams: (node: N.Function, allowModifiers?: boolean) => void;
+takeDecorators: (node: N.HasDecorators) => void;
*/
// For object literal, check if property __proto__ has been used more than once.
// If the expression is a destructuring assignment, then __proto__ may appear
// multiple times. Otherwise, __proto__ is a duplicated key.
// For record expression, check if property __proto__ exists
checkProto(
prop: N.ObjectMember | N.SpreadElement,
isRecord: boolean,
protoRef: { used: boolean },
refExpressionErrors: ?ExpressionErrors,
): void {
if (
prop.type === "SpreadElement" ||
prop.type === "ObjectMethod" ||
prop.computed ||
prop.shorthand
) {
return;
}
const key = prop.key;
// It is either an Identifier or a String/NumericLiteral
const name = key.type === "Identifier" ? key.name : key.value;
if (name === "__proto__") {
if (isRecord) {
this.raise(key.start, Errors.RecordNoProto);
return;
}
if (protoRef.used) {
if (refExpressionErrors) {
// Store the first redefinition's position, otherwise ignore because
// we are parsing ambiguous pattern
if (refExpressionErrors.doubleProto === -1) {
refExpressionErrors.doubleProto = key.start;
}
} else {
this.raise(key.start, Errors.DuplicateProto);
}
}
protoRef.used = true;
}
}
shouldExitDescending(expr: N.Expression, potentialArrowAt: number): boolean {
return (
expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt
);
}
// Convenience method to parse an Expression only
getExpression(): N.Expression {
let paramFlags = PARAM;
if (this.hasPlugin("topLevelAwait") && this.inModule) {
paramFlags |= PARAM_AWAIT;
}
this.scope.enter(SCOPE_PROGRAM);
this.prodParam.enter(paramFlags);
this.nextToken();
const expr = this.parseExpression();
if (!this.match(tt.eof)) {
this.unexpected();
}
expr.comments = this.state.comments;
expr.errors = this.state.errors;
return expr;
}
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function (s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression.
// - `noIn`
// is used to forbid the `in` operator (in for loops initialization expressions)
// When `noIn` is true, the production parameter [In] is not present.
// Whenever [?In] appears in the right-hand sides of a production, we pass
// `noIn` to the subroutine calls.
// - `refExpressionErrors `
// provides reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
// https://tc39.es/ecma262/#prod-Expression
parseExpression(
noIn?: boolean,
refExpressionErrors?: ExpressionErrors,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
const expr = this.parseMaybeAssign(noIn, refExpressionErrors);
if (this.match(tt.comma)) {
const node = this.startNodeAt(startPos, startLoc);
node.expressions = [expr];
while (this.eat(tt.comma)) {
node.expressions.push(this.parseMaybeAssign(noIn, refExpressionErrors));
}
this.toReferencedList(node.expressions);
return this.finishNode(node, "SequenceExpression");
}
return expr;
}
// Parse an assignment expression. This includes applications of
// operators like `+=`.
// https://tc39.es/ecma262/#prod-AssignmentExpression
parseMaybeAssign(
noIn?: ?boolean,
refExpressionErrors?: ?ExpressionErrors,
afterLeftParse?: Function,
refNeedsArrowPos?: ?Pos,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
if (this.isContextual("yield")) {
if (this.prodParam.hasYield) {
let left = this.parseYield(noIn);
if (afterLeftParse) {
left = afterLeftParse.call(this, left, startPos, startLoc);
}
return left;
} else {
// The tokenizer will assume an expression is allowed after
// `yield`, but this isn't that kind of yield
this.state.exprAllowed = false;
}
}
let ownExpressionErrors;
if (refExpressionErrors) {
ownExpressionErrors = false;
} else {
refExpressionErrors = new ExpressionErrors();
ownExpressionErrors = true;
}
if (this.match(tt.parenL) || this.match(tt.name)) {
this.state.potentialArrowAt = this.state.start;
}
let left = this.parseMaybeConditional(
noIn,
refExpressionErrors,
refNeedsArrowPos,
);
if (afterLeftParse) {
left = afterLeftParse.call(this, left, startPos, startLoc);
}
if (this.state.type.isAssign) {
const node = this.startNodeAt(startPos, startLoc);
const operator = this.state.value;
node.operator = operator;
if (this.match(tt.eq)) {
node.left = this.toAssignable(left);
refExpressionErrors.doubleProto = -1; // reset because double __proto__ is valid in assignment expression
} else {
node.left = left;
}
if (refExpressionErrors.shorthandAssign >= node.left.start) {
refExpressionErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
}
this.checkLVal(left, undefined, undefined, "assignment expression");
this.next();
node.right = this.parseMaybeAssign(noIn);
return this.finishNode(node, "AssignmentExpression");
} else if (ownExpressionErrors) {
this.checkExpressionErrors(refExpressionErrors, true);
}
return left;
}
// Parse a ternary conditional (`?:`) operator.
// https://tc39.es/ecma262/#prod-ConditionalExpression
parseMaybeConditional(
noIn: ?boolean,
refExpressionErrors: ExpressionErrors,
refNeedsArrowPos?: ?Pos,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
const potentialArrowAt = this.state.potentialArrowAt;
const expr = this.parseExprOps(noIn, refExpressionErrors);
if (this.shouldExitDescending(expr, potentialArrowAt)) {
return expr;
}
return this.parseConditional(
expr,
noIn,
startPos,
startLoc,
refNeedsArrowPos,
);
}
parseConditional(
expr: N.Expression,
noIn: ?boolean,
startPos: number,
startLoc: Position,
// FIXME: Disabling this for now since can't seem to get it to play nicely
// eslint-disable-next-line no-unused-vars
refNeedsArrowPos?: ?Pos,
): N.Expression {
if (this.eat(tt.question)) {
const node = this.startNodeAt(startPos, startLoc);
node.test = expr;
node.consequent = this.parseMaybeAssign();
this.expect(tt.colon);
node.alternate = this.parseMaybeAssign(noIn);
return this.finishNode(node, "ConditionalExpression");
}
return expr;
}
// Start the precedence parser.
// https://tc39.es/ecma262/#prod-ShortCircuitExpression
parseExprOps(
noIn: ?boolean,
refExpressionErrors: ExpressionErrors,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
const potentialArrowAt = this.state.potentialArrowAt;
const expr = this.parseMaybeUnary(refExpressionErrors);
if (this.shouldExitDescending(expr, potentialArrowAt)) {
return expr;
}
return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
}
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
parseExprOp(
left: N.Expression,
leftStartPos: number,
leftStartLoc: Position,
minPrec: number,
noIn: ?boolean,
): N.Expression {
let prec = this.state.type.binop;
if (prec != null && (!noIn || !this.match(tt._in))) {
if (prec > minPrec) {
const op = this.state.type;
if (op === tt.pipeline) {
this.expectPlugin("pipelineOperator");
if (this.state.inFSharpPipelineDirectBody) {
return left;
}
this.state.inPipeline = true;
this.checkPipelineAtInfixOperator(left, leftStartPos);
}
const node = this.startNodeAt(leftStartPos, leftStartLoc);
node.left = left;
node.operator = this.state.value;
if (
op === tt.exponent &&
left.type === "UnaryExpression" &&
(this.options.createParenthesizedExpressions ||
!(left.extra && left.extra.parenthesized))
) {
this.raise(
left.argument.start,
Errors.UnexpectedTokenUnaryExponentiation,
);
}
const logical = op === tt.logicalOR || op === tt.logicalAND;
const coalesce = op === tt.nullishCoalescing;
if (coalesce) {
// Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
// In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
prec = ((tt.logicalAND: any): { binop: number }).binop;
}
this.next();
if (
op === tt.pipeline &&
this.getPluginOption("pipelineOperator", "proposal") === "minimal"
) {
if (
this.match(tt.name) &&
this.state.value === "await" &&
this.prodParam.hasAwait
) {
throw this.raise(
this.state.start,
Errors.UnexpectedAwaitAfterPipelineBody,
);
}
}
node.right = this.parseExprOpRightExpr(op, prec, noIn);
this.finishNode(
node,
logical || coalesce ? "LogicalExpression" : "BinaryExpression",
);
/* this check is for all ?? operators
* a ?? b && c for this example
* when op is coalesce and nextOp is logical (&&), throw at the pos of nextOp that it can not be mixed.
* Symmetrically it also throws when op is logical and nextOp is coalesce
*/
const nextOp = this.state.type;
if (
(coalesce && (nextOp === tt.logicalOR || nextOp === tt.logicalAND)) ||
(logical && nextOp === tt.nullishCoalescing)
) {
throw this.raise(this.state.start, Errors.MixingCoalesceWithLogical);
}
return this.parseExprOp(
node,
leftStartPos,
leftStartLoc,
minPrec,
noIn,
);
}
}
return left;
}
// Helper function for `parseExprOp`. Parse the right-hand side of binary-
// operator expressions, then apply any operator-specific functions.
parseExprOpRightExpr(
op: TokenType,
prec: number,
noIn: ?boolean,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
switch (op) {
case tt.pipeline:
switch (this.getPluginOption("pipelineOperator", "proposal")) {
case "smart":
return this.withTopicPermittingContext(() => {
return this.parseSmartPipelineBody(
this.parseExprOpBaseRightExpr(op, prec, noIn),
startPos,
startLoc,
);
});
case "fsharp":
return this.withSoloAwaitPermittingContext(() => {
return this.parseFSharpPipelineBody(prec, noIn);
});
}
// falls through
default:
return this.parseExprOpBaseRightExpr(op, prec, noIn);
}
}
// Helper function for `parseExprOpRightExpr`. Parse the right-hand side of
// binary-operator expressions without applying any operator-specific functions.
parseExprOpBaseRightExpr(
op: TokenType,
prec: number,
noIn: ?boolean,
): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
return this.parseExprOp(
this.parseMaybeUnary(),
startPos,
startLoc,
op.rightAssociative ? prec - 1 : prec,
noIn,
);
}
// Parse unary operators, both prefix and postfix.
// https://tc39.es/ecma262/#prod-UnaryExpression
parseMaybeUnary(refExpressionErrors: ?ExpressionErrors): N.Expression {
if (this.isContextual("await") && this.isAwaitAllowed()) {
return this.parseAwait();
}
const update = this.match(tt.incDec);
const node = this.startNode();
if (this.state.type.prefix) {
node.operator = this.state.value;
node.prefix = true;
if (this.match(tt._throw)) {
this.expectPlugin("throwExpressions");
}
const isDelete = this.match(tt._delete);
this.next();
node.argument = this.parseMaybeUnary();
this.checkExpressionErrors(refExpressionErrors, true);
if (this.state.strict && isDelete) {
const arg = node.argument;
if (arg.type === "Identifier") {
this.raise(node.start, Errors.StrictDelete);
} else if (
(arg.type === "MemberExpression" ||
arg.type === "OptionalMemberExpression") &&
arg.property.type === "PrivateName"
) {
this.raise(node.start, Errors.DeletePrivateField);
}
}
if (!update) {
return this.finishNode(node, "UnaryExpression");
}
}
return this.parseUpdate(node, update, refExpressionErrors);
}
// https://tc39.es/ecma262/#prod-UpdateExpression
parseUpdate(
node: N.Expression,
update: boolean,
refExpressionErrors: ?ExpressionErrors,
): N.Expression {
if (update) {
this.checkLVal(node.argument, undefined, undefined, "prefix operation");
return this.finishNode(node, "UpdateExpression");
}
const startPos = this.state.start;
const startLoc = this.state.startLoc;
let expr = this.parseExprSubscripts(refExpressionErrors);
if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
while (this.state.type.postfix && !this.canInsertSemicolon()) {
const node = this.startNodeAt(startPos, startLoc);
node.operator = this.state.value;
node.prefix = false;
node.argument = expr;
this.checkLVal(expr, undefined, undefined, "postfix operation");
this.next();
expr = this.finishNode(node, "UpdateExpression");
}
return expr;
}
// Parse call, dot, and `[]`-subscript expressions.
// https://tc39.es/ecma262/#prod-LeftHandSideExpression
parseExprSubscripts(refExpressionErrors: ?ExpressionErrors): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
const potentialArrowAt = this.state.potentialArrowAt;
const expr = this.parseExprAtom(refExpressionErrors);
if (this.shouldExitDescending(expr, potentialArrowAt)) {
return expr;
}
return this.parseSubscripts(expr, startPos, startLoc);
}
parseSubscripts(
base: N.Expression,
startPos: number,
startLoc: Position,
noCalls?: ?boolean,
): N.Expression {
const state = {
optionalChainMember: false,
maybeAsyncArrow: this.atPossibleAsyncArrow(base),
stop: false,
};
do {
const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
if (state.maybeAsyncArrow) {
this.state.maybeInAsyncArrowHead = true;
}
base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
// After parsing a subscript, this isn't "async" for sure.
state.maybeAsyncArrow = false;
this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
} while (!state.stop);
return base;
}
/**
* @param state Set 'state.stop = true' to indicate that we should stop parsing subscripts.
* state.optionalChainMember to indicate that the member is currently in OptionalChain
*/
parseSubscript(
base: N.Expression,
startPos: number,
startLoc: Position,
noCalls: ?boolean,
state: N.ParseSubscriptState,
): N.Expression {
if (!noCalls && this.eat(tt.doubleColon)) {
return this.parseBind(base, startPos, startLoc, noCalls, state);
} else if (this.match(tt.backQuote)) {
return this.parseTaggedTemplateExpression(
base,
startPos,
startLoc,
state,
);
}
let optional = false;
if (this.match(tt.questionDot)) {
state.optionalChainMember = optional = true;
if (noCalls && this.lookaheadCharCode() === charCodes.leftParenthesis) {
// stop at `?.` when parsing `new a?.()`
state.stop = true;
return base;
}
this.next();
}
if (!noCalls && this.match(tt.parenL)) {
return this.parseCoverCallAndAsyncArrowHead(
base,
startPos,
startLoc,
state,
optional,
);
} else if (optional || this.match(tt.bracketL) || this.eat(tt.dot)) {
return this.parseMember(base, startPos, startLoc, state, optional);
} else {
state.stop = true;
return base;
}
}
// base[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ]
// base[?Yield, ?Await] . IdentifierName
// base[?Yield, ?Await] . PrivateIdentifier
// where `base` is one of CallExpression, MemberExpression and OptionalChain
parseMember(
base: N.Expression,
startPos: number,
startLoc: Position,
state: N.ParseSubscriptState,
optional: boolean,
): N.OptionalMemberExpression | N.MemberExpression {
const node = this.startNodeAt(startPos, startLoc);
const computed = this.eat(tt.bracketL);
node.object = base;
node.computed = computed;
const property = computed
? this.parseExpression()
: this.parseMaybePrivateName(true);
if (property.type === "PrivateName") {
if (node.object.type === "Super") {
this.raise(startPos, Errors.SuperPrivateField);
}
this.classScope.usePrivateName(property.id.name, property.start);
}
node.property = property;
if (computed) {
this.expect(tt.bracketR);
}
if (state.optionalChainMember) {
node.optional = optional;
return this.finishNode(node, "OptionalMemberExpression");
} else {
return this.finishNode(node, "MemberExpression");
}
}
// https://github.com/tc39/proposal-bind-operator#syntax
parseBind(
base: N.Expression,
startPos: number,
startLoc: Position,
noCalls: ?boolean,
state: N.ParseSubscriptState,
): N.Expression {
const node = this.startNodeAt(startPos, startLoc);
node.object = base;
node.callee = this.parseNoCallExpr();
state.stop = true;
return this.parseSubscripts(
this.finishNode(node, "BindExpression"),
startPos,
startLoc,
noCalls,
);
}
// https://tc39.es/ecma262/#prod-CoverCallExpressionAndAsyncArrowHead
// CoverCallExpressionAndAsyncArrowHead
// CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await]
// OptionalChain[?Yield, ?Await] Arguments[?Yield, ?Await]
parseCoverCallAndAsyncArrowHead(
base: N.Expression,
startPos: number,
startLoc: Position,
state: N.ParseSubscriptState,
optional: boolean,
): N.Expression {
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
this.state.maybeInArrowParameters = true;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.next(); // eat `(`
let node = this.startNodeAt(startPos, startLoc);
node.callee = base;
if (state.optionalChainMember) {
node.optional = optional;
}
if (optional) {
node.arguments = this.parseCallExpressionArguments(tt.parenR, false);
} else {
node.arguments = this.parseCallExpressionArguments(
tt.parenR,
state.maybeAsyncArrow,
base.type === "Import",
base.type !== "Super",
node,
);
}
this.finishCallExpression(node, state.optionalChainMember);
if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
state.stop = true;
node = this.parseAsyncArrowFromCallExpression(
this.startNodeAt(startPos, startLoc),
node,
);
this.checkYieldAwaitInDefaultParams();
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
} else {
this.toReferencedListDeep(node.arguments);
// We keep the old value if it isn't null, for cases like
// (x = async(yield)) => {}
//
// Hi developer of the future :) If you are implementing generator
// arrow functions, please read the note below about "await" and
// verify if the same logic is needed for yield.
if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
// Await is trickier than yield. When parsing a possible arrow function
// (e.g. something starting with `async(`) we don't know if its possible
// parameters will actually be inside an async arrow function or if it is
// a normal call expression.
// If it ended up being a call expression, if we are in a context where
// await expression are disallowed (and thus "await" is an identifier)
// we must be careful not to leak this.state.awaitPos to an even outer
// context, where "await" could not be an identifier.
// For example, this code is valid because "await" isn't directly inside
// an async function:
//
// async function a() {
// function b(param = async (await)) {
// }
// }
//
if (
(!this.isAwaitAllowed() && !oldMaybeInArrowParameters) ||
oldAwaitPos !== -1
) {
this.state.awaitPos = oldAwaitPos;
}
}
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
return node;
}
// MemberExpression [?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]
// CallExpression [?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]
parseTaggedTemplateExpression(
base: N.Expression,
startPos: number,
startLoc: Position,
state: N.ParseSubscriptState,
): N.TaggedTemplateExpression {
const node: N.TaggedTemplateExpression = this.startNodeAt(
startPos,
startLoc,
);
node.tag = base;
node.quasi = this.parseTemplate(true);
if (state.optionalChainMember) {
this.raise(startPos, Errors.OptionalChainingNoTemplate);
}
return this.finishNode(node, "TaggedTemplateExpression");
}
atPossibleAsyncArrow(base: N.Expression): boolean {
return (
base.type === "Identifier" &&
base.name === "async" &&
this.state.lastTokEnd === base.end &&
!this.canInsertSemicolon() &&
// check there are no escape sequences, such as \u{61}sync
base.end - base.start === 5 &&
base.start === this.state.potentialArrowAt
);
}
finishCallExpression<T: N.CallExpression | N.OptionalCallExpression>(
node: T,
optional: boolean,
): N.Expression {
if (node.callee.type === "Import") {
if (node.arguments.length === 2) {
this.expectPlugin("moduleAttributes");
}
if (node.arguments.length === 0 || node.arguments.length > 2) {
this.raise(
node.start,
Errors.ImportCallArity,
this.hasPlugin("moduleAttributes")
? "one or two arguments"
: "one argument",
);
} else {
for (const arg of node.arguments) {
if (arg.type === "SpreadElement") {
this.raise(arg.start, Errors.ImportCallSpreadArgument);
}
}
}
}
return this.finishNode(
node,
optional ? "OptionalCallExpression" : "CallExpression",
);
}
parseCallExpressionArguments(
close: TokenType,
possibleAsyncArrow: boolean,
dynamicImport?: boolean,
allowPlaceholder?: boolean,
nodeForExtra?: ?N.Node,
): $ReadOnlyArray<?N.Expression> {
const elts = [];
let innerParenStart;
let first = true;
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.inFSharpPipelineDirectBody = false;
while (!this.eat(close)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.match(close)) {
if (dynamicImport && !this.hasPlugin("moduleAttributes")) {
this.raise(
this.state.lastTokStart,
Errors.ImportCallArgumentTrailingComma,
);
}
if (nodeForExtra) {
this.addExtra(
nodeForExtra,
"trailingComma",
this.state.lastTokStart,
);
}
this.next();
break;
}
}
// we need to make sure that if this is an async arrow functions,
// that we don't allow inner parens inside the params
if (this.match(tt.parenL) && !innerParenStart) {
innerParenStart = this.state.start;
}
elts.push(
this.parseExprListItem(
false,
possibleAsyncArrow ? new ExpressionErrors() : undefined,
possibleAsyncArrow ? { start: 0 } : undefined,
allowPlaceholder,
),
);
}
// we found an async arrow function so let's not allow any inner parens
if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
this.unexpected();
}
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
return elts;
}
shouldParseAsyncArrow(): boolean {
return this.match(tt.arrow) && !this.canInsertSemicolon();
}
parseAsyncArrowFromCallExpression(
node: N.ArrowFunctionExpression,
call: N.CallExpression,
): N.ArrowFunctionExpression {
this.expect(tt.arrow);
this.parseArrowExpression(
node,
call.arguments,
true,
call.extra?.trailingComma,
);
return node;
}
// Parse a no-call expression (like argument of `new` or `::` operators).
// https://tc39.es/ecma262/#prod-MemberExpression
parseNoCallExpr(): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
// https://tc39.es/ecma262/#prod-PrimaryExpression
// https://tc39.es/ecma262/#prod-AsyncArrowFunction
// PrimaryExpression
// Super
// Import
// AsyncArrowFunction
parseExprAtom(refExpressionErrors?: ?ExpressionErrors): N.Expression {
// If a division operator appears in an expression position, the
// tokenizer got confused, and we force it to read a regexp instead.
if (this.state.type === tt.slash) this.readRegexp();
const canBeArrow = this.state.potentialArrowAt === this.state.start;
let node;
switch (this.state.type) {
case tt._super:
return this.parseSuper();
case tt._import:
node = this.startNode();
this.next();
if (this.match(tt.dot)) {
return this.parseImportMetaProperty(node);
}
if (!this.match(tt.parenL)) {
this.raise(this.state.lastTokStart, Errors.UnsupportedImport);
}
return this.finishNode(node, "Import");
case tt._this:
node = this.startNode();
this.next();
return this.finishNode(node, "ThisExpression");
case tt.name: {
const containsEsc = this.state.containsEsc;
const id = this.parseIdentifier();
if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
if (this.match(tt._function)) {
const last = this.state.context.length - 1;
if (this.state.context[last] !== ct.functionStatement) {
// Since "async" is an identifier and normally identifiers
// can't be followed by expression, the tokenizer assumes
// that "function" starts a statement.
// Fixing it in the tokenizer would mean tracking not only the
// previous token ("async"), but also the one before to know
// its beforeExpr value.
// It's easier and more efficient to adjust the context here.
throw new Error("Internal error");
}
this.state.context[last] = ct.functionExpression;
this.next();
return this.parseFunction(
this.startNodeAtNode(id),
undefined,
true,
);
} else if (this.match(tt.name)) {
return this.parseAsyncArrowUnaryFunction(id);
}
}
if (canBeArrow && this.match(tt.arrow) && !this.canInsertSemicolon()) {
this.next();
return this.parseArrowExpression(
this.startNodeAtNode(id),
[id],
false,
);
}
return id;
}
case tt._do: {
return this.parseDo();
}
case tt.regexp: {
const value = this.state.value;
node = this.parseLiteral(value.value, "RegExpLiteral");
node.pattern = value.pattern;
node.flags = value.flags;
return node;
}
case tt.num:
return this.parseLiteral(this.state.value, "NumericLiteral");
case tt.bigint:
return this.parseLiteral(this.state.value, "BigIntLiteral");
case tt.decimal:
return this.parseLiteral(this.state.value, "DecimalLiteral");
case tt.string:
return this.parseLiteral(this.state.value, "StringLiteral");
case tt._null:
node = this.startNode();
this.next();
return this.finishNode(node, "NullLiteral");
case tt._true:
case tt._false:
return this.parseBooleanLiteral();
case tt.parenL:
return this.parseParenAndDistinguishExpression(canBeArrow);
case tt.bracketBarL:
case tt.bracketHashL: {
return this.parseArrayLike(
this.state.type === tt.bracketBarL ? tt.bracketBarR : tt.bracketR,
/* canBePattern */ false,
/* isTuple */ true,
refExpressionErrors,
);
}
case tt.bracketL: {
return this.parseArrayLike(
tt.bracketR,
/* canBePattern */ true,
/* isTuple */ false,
refExpressionErrors,
);
}
case tt.braceBarL:
case tt.braceHashL: {
return this.parseObjectLike(
this.state.type === tt.braceBarL ? tt.braceBarR : tt.braceR,
/* isPattern */ false,
/* isRecord */ true,
refExpressionErrors,
);
}
case tt.braceL: {
return this.parseObjectLike(
tt.braceR,
/* isPattern */ false,
/* isRecord */ false,
refExpressionErrors,
);
}
case tt._function:
return this.parseFunctionOrFunctionSent();
case tt.at:
this.parseDecorators();
// fall through
case tt._class:
node = this.startNode();
this.takeDecorators(node);
return this.parseClass(node, false);
case tt._new:
return this.parseNewOrNewTarget();
case tt.backQuote:
return this.parseTemplate(false);
// BindExpression[Yield]
// :: MemberExpression[?Yield]
case tt.doubleColon: {
node = this.startNode();
this.next();
node.object = null;
const callee = (node.callee = this.parseNoCallExpr());
if (callee.type === "MemberExpression") {
return this.finishNode(node, "BindExpression");
} else {
throw this.raise(callee.start, Errors.UnsupportedBind);
}
}
case tt.hash: {
if (this.state.inPipeline) {
node = this.startNode();
if (
this.getPluginOption("pipelineOperator", "proposal") !== "smart"
) {
this.raise(node.start, Errors.PrimaryTopicRequiresSmartPipeline);
}
this.next();
if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
this.raise(node.start, Errors.PrimaryTopicNotAllowed);
}
this.registerTopicReference();
return this.finishNode(node, "PipelinePrimaryTopicReference");
}
// https://tc39.es/proposal-private-fields-in-in
// RelationalExpression [In, Yield, Await]
// [+In] PrivateIdentifier in ShiftExpression[?Yield, ?Await]
const nextCh = this.input.codePointAt(this.state.end);
if (isIdentifierStart(nextCh) || nextCh === charCodes.backslash) {
const start = this.state.start;
// $FlowIgnore It'll either parse a PrivateName or throw.
node = (this.parseMaybePrivateName(true): N.PrivateName);
if (this.match(tt._in)) {
this.expectPlugin("privateIn");
this.classScope.usePrivateName(node.id.name, node.start);
} else if (this.hasPlugin("privateIn")) {
this.raise(
this.state.start,
Errors.PrivateInExpectedIn,
node.id.name,
);
} else {
throw this.unexpected(start);
}
return node;
}
}
// fall through
case tt.relational: {
if (this.state.value === "<") {
const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
if (
isIdentifierStart(lookaheadCh) || // Element/Type Parameter <foo>
lookaheadCh === charCodes.greaterThan // Fragment <>
) {
this.expectOnePlugin(["jsx", "flow", "typescript"]);
}
}
}
// fall through
default:
throw this.unexpected();
}
}
// async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In]
parseAsyncArrowUnaryFunction(id: N.Expression): N.ArrowFunctionExpression {
const node = this.startNodeAtNode(id);
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldMaybeInAsyncArrowHead = this.state.maybeInAsyncArrowHead;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
this.state.maybeInArrowParameters = true;
this.state.maybeInAsyncArrowHead = true;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
const params = [this.parseIdentifier()];
if (this.hasPrecedingLineBreak()) {
this.raise(this.state.pos, Errors.LineTerminatorBeforeArrow);
}
this.expect(tt.arrow);
this.checkYieldAwaitInDefaultParams();
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
this.state.maybeInAsyncArrowHead = oldMaybeInAsyncArrowHead;
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
// let foo = async bar => {};
this.parseArrowExpression(node, params, true);
return node;
}
// https://github.com/tc39/proposal-do-expressions
parseDo(): N.DoExpression {
this.expectPlugin("doExpressions");
const node = this.startNode();
this.next(); // eat `do`
const oldLabels = this.state.labels;
this.state.labels = [];
node.body = this.parseBlock();
this.state.labels = oldLabels;
return this.finishNode(node, "DoExpression");
}
// Parse the `super` keyword
parseSuper(): N.Super {
const node = this.startNode();
this.next(); // eat `super`
if (
this.match(tt.parenL) &&
!this.scope.allowDirectSuper &&
!this.options.allowSuperOutsideMethod
) {
this.raise(node.start, Errors.SuperNotAllowed);
} else if (
!this.scope.allowSuper &&
!this.options.allowSuperOutsideMethod
) {
this.raise(node.start, Errors.UnexpectedSuper);
}
if (
!this.match(tt.parenL) &&
!this.match(tt.bracketL) &&
!this.match(tt.dot)
) {
this.raise(node.start, Errors.UnsupportedSuper);
}
return this.finishNode(node, "Super");
}
parseBooleanLiteral(): N.BooleanLiteral {
const node = this.startNode();
node.value = this.match(tt._true);
this.next();
return this.finishNode(node, "BooleanLiteral");
}
parseMaybePrivateName(
isPrivateNameAllowed: boolean,
): N.PrivateName | N.Identifier {
const isPrivate = this.match(tt.hash);
if (isPrivate) {
this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
if (!isPrivateNameAllowed) {
this.raise(this.state.pos, Errors.UnexpectedPrivateField);
}
const node = this.startNode();
this.next();
this.assertNoSpace("Unexpected space between # and identifier");
node.id = this.parseIdentifier(true);
return this.finishNode(node, "PrivateName");
} else {
return this.parseIdentifier(true);
}
}
parseFunctionOrFunctionSent(): N.FunctionExpression | N.MetaProperty {
const node = this.startNode();
// We do not do parseIdentifier here because when parseFunctionOrFunctionSent
// is called we already know that the current token is a "name" with the value "function"
// This will improve perf a tiny little bit as we do not do validation but more importantly
// here is that parseIdentifier will remove an item from the expression stack
// if "function" or "class" is parsed as identifier (in objects e.g.), which should not happen here.
this.next(); // eat `function`
if (this.prodParam.hasYield && this.match(tt.dot)) {
const meta = this.createIdentifier(
this.startNodeAtNode(node),
"function",
);
this.next(); // eat `.`
return this.parseMetaProperty(node, meta, "sent");
}
return this.parseFunction(node);
}
parseMetaProperty(
node: N.MetaProperty,
meta: N.Identifier,
propertyName: string,
): N.MetaProperty {
node.meta = meta;
if (meta.name === "function" && propertyName === "sent") {
// https://github.com/tc39/proposal-function.sent#syntax-1
if (this.isContextual(propertyName)) {
this.expectPlugin("functionSent");
} else if (!this.hasPlugin("functionSent")) {
// The code wasn't `function.sent` but just `function.`, so a simple error is less confusing.
this.unexpected();
}
}
const containsEsc = this.state.containsEsc;
node.property = this.parseIdentifier(true);
if (node.property.name !== propertyName || containsEsc) {
this.raise(
node.property.start,
Errors.UnsupportedMetaProperty,
meta.name,
propertyName,
);
}
return this.finishNode(node, "MetaProperty");
}
// https://tc39.es/ecma262/#prod-ImportMeta
parseImportMetaProperty(node: N.MetaProperty): N.MetaProperty {
const id = this.createIdentifier(this.startNodeAtNode(node), "import");
this.next(); // eat `.`
if (this.isContextual("meta")) {
if (!this.inModule) {
this.raiseWithData(
id.start,
{ code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" },
Errors.ImportMetaOutsideModule,
);
}
this.sawUnambiguousESM = true;
}
return this.parseMetaProperty(node, id, "meta");
}
parseLiteral<T: N.Literal>(
value: any,
type: /*T["kind"]*/ string,
startPos?: number,
startLoc?: Position,
): T {
startPos = startPos || this.state.start;
startLoc = startLoc || this.state.startLoc;
const node = this.startNodeAt(startPos, startLoc);
this.addExtra(node, "rawValue", value);
this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
node.value = value;
this.next();
return this.finishNode(node, type);
}
// https://tc39.es/ecma262/#prod-CoverParenthesizedExpressionAndArrowParameterList
parseParenAndDistinguishExpression(canBeArrow: boolean): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
let val;
this.next(); // eat `(`
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.maybeInArrowParameters = true;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.state.inFSharpPipelineDirectBody = false;
const innerStartPos = this.state.start;
const innerStartLoc = this.state.startLoc;
const exprList = [];
const refExpressionErrors = new ExpressionErrors();
const refNeedsArrowPos = { start: 0 };
let first = true;
let spreadStart;
let optionalCommaStart;
while (!this.match(tt.parenR)) {
if (first) {
first = false;
} else {
this.expect(tt.comma, refNeedsArrowPos.start || null);
if (this.match(tt.parenR)) {
optionalCommaStart = this.state.start;
break;
}
}
if (this.match(tt.ellipsis)) {
const spreadNodeStartPos = this.state.start;
const spreadNodeStartLoc = this.state.startLoc;
spreadStart = this.state.start;
exprList.push(
this.parseParenItem(
this.parseRestBinding(),
spreadNodeStartPos,
spreadNodeStartLoc,
),
);
this.checkCommaAfterRest(charCodes.rightParenthesis);
break;
} else {
exprList.push(
this.parseMaybeAssign(
false,
refExpressionErrors,
this.parseParenItem,
refNeedsArrowPos,
),
);
}
}
const innerEndPos = this.state.lastTokEnd;
const innerEndLoc = this.state.lastTokEndLoc;
this.expect(tt.parenR);
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
let arrowNode = this.startNodeAt(startPos, startLoc);
if (
canBeArrow &&
this.shouldParseArrow() &&
(arrowNode = this.parseArrow(arrowNode))
) {
if (!this.isAwaitAllowed() && !this.state.maybeInAsyncArrowHead) {
this.state.awaitPos = oldAwaitPos;
}
this.checkYieldAwaitInDefaultParams();
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
for (const param of exprList) {
if (param.extra && param.extra.parenthesized) {
this.unexpected(param.extra.parenStart);
}
}
this.parseArrowExpression(arrowNode, exprList, false);
return arrowNode;
}
// We keep the old value if it isn't null, for cases like
// (x = (yield)) => {}
if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos;
if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos;
if (!exprList.length) {
this.unexpected(this.state.lastTokStart);
}
if (optionalCommaStart) this.unexpected(optionalCommaStart);
if (spreadStart) this.unexpected(spreadStart);
this.checkExpressionErrors(refExpressionErrors, true);
if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
this.toReferencedListDeep(exprList, /* isParenthesizedExpr */ true);
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
} else {
val = exprList[0];
}
if (!this.options.createParenthesizedExpressions) {
this.addExtra(val, "parenthesized", true);
this.addExtra(val, "parenStart", startPos);
return val;
}
const parenExpression = this.startNodeAt(startPos, startLoc);
parenExpression.expression = val;
this.finishNode(parenExpression, "ParenthesizedExpression");
return parenExpression;
}
shouldParseArrow(): boolean {
return !this.canInsertSemicolon();
}
parseArrow(node: N.ArrowFunctionExpression): ?N.ArrowFunctionExpression {
if (this.eat(tt.arrow)) {
return node;
}
}
parseParenItem(
node: N.Expression,
startPos: number, // eslint-disable-line no-unused-vars
startLoc: Position, // eslint-disable-line no-unused-vars
): N.Expression {
return node;
}
parseNewOrNewTarget(): N.NewExpression | N.MetaProperty {
const node = this.startNode();
this.next();
if (this.match(tt.dot)) {
// https://tc39.es/ecma262/#prod-NewTarget
const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
this.next();
const metaProp = this.parseMetaProperty(node, meta, "target");
if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
let error = Errors.UnexpectedNewTarget;
if (this.hasPlugin("classProperties")) {
error += " or class properties";
}
/* eslint-disable @babel/development-internal/dry-error-messages */
this.raise(metaProp.start, error);
/* eslint-enable @babel/development-internal/dry-error-messages */
}
return metaProp;
}
return this.parseNew(node);
}
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
// https://tc39.es/ecma262/#prod-NewExpression
parseNew(node: N.Expression): N.NewExpression {
node.callee = this.parseNoCallExpr();
if (node.callee.type === "Import") {
this.raise(node.callee.start, Errors.ImportCallNotNewExpression);
} else if (
node.callee.type === "OptionalMemberExpression" ||
node.callee.type === "OptionalCallExpression"
) {
this.raise(this.state.lastTokEnd, Errors.OptionalChainingNoNew);
} else if (this.eat(tt.questionDot)) {
this.raise(this.state.start, Errors.OptionalChainingNoNew);
}
this.parseNewArguments(node);
return this.finishNode(node, "NewExpression");
}
parseNewArguments(node: N.NewExpression): void {
if (this.eat(tt.parenL)) {
const args = this.parseExprList(tt.parenR);
this.toReferencedList(args);
// $FlowFixMe (parseExprList should be all non-null in this case)
node.arguments = args;
} else {
node.arguments = [];
}
}
// Parse template expression.
parseTemplateElement(isTagged: boolean): N.TemplateElement {
const elem = this.startNode();
if (this.state.value === null) {
if (!isTagged) {
this.raise(this.state.start + 1, Errors.InvalidEscapeSequenceTemplate);
}
}
elem.value = {
raw: this.input
.slice(this.state.start, this.state.end)
.replace(/\r\n?/g, "\n"),
cooked: this.state.value,
};
this.next();
elem.tail = this.match(tt.backQuote);
return this.finishNode(elem, "TemplateElement");
}
// https://tc39.es/ecma262/#prod-TemplateLiteral
parseTemplate(isTagged: boolean): N.TemplateLiteral {
const node = this.startNode();
this.next();
node.expressions = [];
let curElt = this.parseTemplateElement(isTagged);
node.quasis = [curElt];
while (!curElt.tail) {
this.expect(tt.dollarBraceL);
node.expressions.push(this.parseExpression());
this.expect(tt.braceR);
node.quasis.push((curElt = this.parseTemplateElement(isTagged)));
}
this.next();
return this.finishNode(node, "TemplateLiteral");
}
// Parse an object literal, binding pattern, or record.
parseObjectLike<T: N.ObjectPattern | N.ObjectExpression>(
close: TokenType,
isPattern: boolean,
isRecord?: ?boolean,
refExpressionErrors?: ?ExpressionErrors,
): T {
if (isRecord) {
this.expectPlugin("recordAndTuple");
}
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.inFSharpPipelineDirectBody = false;
const propHash: any = Object.create(null);
let first = true;
const node = this.startNode();
node.properties = [];
this.next();
while (!this.eat(close)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.match(close)) {
this.addExtra(node, "trailingComma", this.state.lastTokStart);
this.next();
break;
}
}
const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
if (!isPattern) {
// $FlowIgnore RestElement will never be returned if !isPattern
this.checkProto(prop, isRecord, propHash, refExpressionErrors);
}
if (
isRecord &&
prop.type !== "ObjectProperty" &&
prop.type !== "SpreadElement"
) {
this.raise(prop.start, Errors.InvalidRecordProperty);
}
// $FlowIgnore
if (prop.shorthand) {
this.addExtra(prop, "shorthand", true);
}
node.properties.push(prop);
}
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
let type = "ObjectExpression";
if (isPattern) {
type = "ObjectPattern";
} else if (isRecord) {
type = "RecordExpression";
}
return this.finishNode(node, type);
}
// Check grammar production:
// IdentifierName *_opt PropertyName
// It is used in `parsePropertyDefinition` to detect AsyncMethod and Accessors
maybeAsyncOrAccessorProp(prop: N.ObjectProperty): boolean {
return (
!prop.computed &&
prop.key.type === "Identifier" &&
(this.isLiteralPropertyName() ||
this.match(tt.bracketL) ||
this.match(tt.star))
);
}
// https://tc39.es/ecma262/#prod-PropertyDefinition
parsePropertyDefinition(
isPattern: boolean,
refExpressionErrors?: ?ExpressionErrors,
): N.ObjectMember | N.SpreadElement | N.RestElement {
let decorators = [];
if (this.match(tt.at)) {
if (this.hasPlugin("decorators")) {
this.raise(this.state.start, Errors.UnsupportedPropertyDecorator);
}
// we needn't check if decorators (stage 0) plugin is enabled since it's checked by
// the call to this.parseDecorator
while (this.match(tt.at)) {
decorators.push(this.parseDecorator());
}
}
const prop = this.startNode();
let isGenerator = false;
let isAsync = false;
let isAccessor = false;
let startPos;
let startLoc;
if (this.match(tt.ellipsis)) {
if (decorators.length) this.unexpected();
if (isPattern) {
this.next();
// Don't use parseRestBinding() as we only allow Identifier here.
prop.argument = this.parseIdentifier();
this.checkCommaAfterRest(charCodes.rightCurlyBrace);
return this.finishNode(prop, "RestElement");
}
return this.parseSpread();
}
if (decorators.length) {
prop.decorators = decorators;
decorators = [];
}
prop.method = false;
if (isPattern || refExpressionErrors) {
startPos = this.state.start;
startLoc = this.state.startLoc;
}
if (!isPattern) {
isGenerator = this.eat(tt.star);
}
const containsEsc = this.state.containsEsc;
this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
if (
!isPattern &&
!isGenerator &&
!containsEsc &&
this.maybeAsyncOrAccessorProp(prop)
) {
// https://tc39.es/ecma262/#prod-AsyncMethod
// https://tc39.es/ecma262/#prod-AsyncGeneratorMethod
if (prop.key.name === "async" && !this.hasPrecedingLineBreak()) {
isAsync = true;
isGenerator = this.eat(tt.star);
this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
}
// get PropertyName[?Yield, ?Await] () { FunctionBody[~Yield, ~Await] }
// set PropertyName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] }
else if (prop.key.name === "get" || prop.key.name === "set") {
isAccessor = true;
isGenerator = this.eat(tt.star); // tt.star is allowed in `maybeAsyncOrAccessorProp`, we will throw in `parseObjectMethod` later
prop.kind = prop.key.name;
this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
}
}
this.parseObjPropValue(
prop,
startPos,
startLoc,
isGenerator,
isAsync,
isPattern,
isAccessor,
refExpressionErrors,
);
return prop;
}
getGetterSetterExpectedParamCount(
method: N.ObjectMethod | N.ClassMethod,
): number {
return method.kind === "get" ? 0 : 1;
}
// get methods aren't allowed to have any parameters
// set methods must have exactly 1 parameter which is not a rest parameter
checkGetterSetterParams(method: N.ObjectMethod | N.ClassMethod): void {
const paramCount = this.getGetterSetterExpectedParamCount(method);
const start = method.start;
if (method.params.length !== paramCount) {
if (method.kind === "get") {
this.raise(start, Errors.BadGetterArity);
} else {
this.raise(start, Errors.BadSetterArity);
}
}
if (
method.kind === "set" &&
method.params[method.params.length - 1].type === "RestElement"
) {
this.raise(start, Errors.BadSetterRestParameter);
}
}
// https://tc39.es/ecma262/#prod-MethodDefinition
parseObjectMethod(
prop: N.ObjectMethod,
isGenerator: boolean,
isAsync: boolean,
isPattern: boolean,
isAccessor: boolean,
): ?N.ObjectMethod {
if (isAccessor) {
// isAccessor implies isAsync: false, isPattern: false
if (isGenerator) this.unexpected();
this.parseMethod(
prop,
/* isGenerator */ false,
/* isAsync */ false,
/* isConstructor */ false,
false,
"ObjectMethod",
);
this.checkGetterSetterParams(prop);
return prop;
}
if (isAsync || isGenerator || this.match(tt.parenL)) {
if (isPattern) this.unexpected();
prop.kind = "method";
prop.method = true;
return this.parseMethod(
prop,
isGenerator,
isAsync,
/* isConstructor */ false,
false,
"ObjectMethod",
);
}
}
// if `isPattern` is true, parse https://tc39.es/ecma262/#prod-BindingProperty
// else https://tc39.es/ecma262/#prod-PropertyDefinition
parseObjectProperty(
prop: N.ObjectProperty,
startPos: ?number,
startLoc: ?Position,
isPattern: boolean,
refExpressionErrors: ?ExpressionErrors,
): ?N.ObjectProperty {
prop.shorthand = false;
if (this.eat(tt.colon)) {
prop.value = isPattern
? this.parseMaybeDefault(this.state.start, this.state.startLoc)
: this.parseMaybeAssign(false, refExpressionErrors);
return this.finishNode(prop, "ObjectProperty");
}
if (!prop.computed && prop.key.type === "Identifier") {
// PropertyDefinition:
// IdentifierReference
// CoveredInitializedName
// Note: `{ eval } = {}` will be checked in `checkLVal` later.
this.checkReservedWord(prop.key.name, prop.key.start, true, false);
if (isPattern) {
prop.value = this.parseMaybeDefault(
startPos,
startLoc,
prop.key.__clone(),
);
} else if (this.match(tt.eq) && refExpressionErrors) {
if (refExpressionErrors.shorthandAssign === -1) {
refExpressionErrors.shorthandAssign = this.state.start;
}
prop.value = this.parseMaybeDefault(
startPos,
startLoc,
prop.key.__clone(),
);
} else {
prop.value = prop.key.__clone();
}
prop.shorthand = true;
return this.finishNode(prop, "ObjectProperty");
}
}
parseObjPropValue(
prop: any,
startPos: ?number,
startLoc: ?Position,
isGenerator: boolean,
isAsync: boolean,
isPattern: boolean,
isAccessor: boolean,
refExpressionErrors?: ?ExpressionErrors,
): void {
const node =
this.parseObjectMethod(
prop,
isGenerator,
isAsync,
isPattern,
isAccessor,
) ||
this.parseObjectProperty(
prop,
startPos,
startLoc,
isPattern,
refExpressionErrors,
);
if (!node) this.unexpected();
// $FlowFixMe
return node;
}
parsePropertyName(
prop: N.ObjectOrClassMember | N.ClassMember | N.TsNamedTypeElementBase,
isPrivateNameAllowed: boolean,
): N.Expression | N.Identifier {
if (this.eat(tt.bracketL)) {
(prop: $FlowSubtype<N.ObjectOrClassMember>).computed = true;
prop.key = this.parseMaybeAssign();
this.expect(tt.bracketR);
} else {
const oldInPropertyName = this.state.inPropertyName;
this.state.inPropertyName = true;
// We check if it's valid for it to be a private name when we push it.
(prop: $FlowFixMe).key =
this.match(tt.num) ||
this.match(tt.string) ||
this.match(tt.bigint) ||
this.match(tt.decimal)
? this.parseExprAtom()
: this.parseMaybePrivateName(isPrivateNameAllowed);
if (prop.key.type !== "PrivateName") {
// ClassPrivateProperty is never computed, so we don't assign in that case.
prop.computed = false;
}
this.state.inPropertyName = oldInPropertyName;
}
return prop.key;
}
// Initialize empty function node.
initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: ?boolean): void {
node.id = null;
node.generator = false;
node.async = !!isAsync;
}
// Parse object or class method.
parseMethod<T: N.MethodLike>(
node: T,
isGenerator: boolean,
isAsync: boolean,
isConstructor: boolean,
allowDirectSuper: boolean,
type: string,
inClassScope: boolean = false,
): T {
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.initFunction(node, isAsync);
node.generator = !!isGenerator;
const allowModifiers = isConstructor; // For TypeScript parameter properties
this.scope.enter(
SCOPE_FUNCTION |
SCOPE_SUPER |
(inClassScope ? SCOPE_CLASS : 0) |
(allowDirectSuper ? SCOPE_DIRECT_SUPER : 0),
);
this.prodParam.enter(functionFlags(isAsync, node.generator));
this.parseFunctionParams((node: any), allowModifiers);
this.parseFunctionBodyAndFinish(node, type, true);
this.prodParam.exit();
this.scope.exit();
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
return node;
}
// parse an array literal or tuple literal
// https://tc39.es/ecma262/#prod-ArrayLiteral
// https://tc39.es/proposal-record-tuple/#prod-TupleLiteral
parseArrayLike(
close: TokenType,
canBePattern: boolean,
isTuple: boolean,
refExpressionErrors: ?ExpressionErrors,
): N.ArrayExpression | N.TupleExpression {
if (isTuple) {
this.expectPlugin("recordAndTuple");
}
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.inFSharpPipelineDirectBody = false;
const node = this.startNode();
this.next();
node.elements = this.parseExprList(
close,
/* allowEmpty */ !isTuple,
refExpressionErrors,
node,
);
if (canBePattern && !this.state.maybeInArrowParameters) {
// This could be an array pattern:
// ([a: string, b: string]) => {}
// In this case, we don't have to call toReferencedList. We will
// call it, if needed, when we are sure that it is a parenthesized
// expression by calling toReferencedListDeep.
this.toReferencedList(node.elements);
}
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
return this.finishNode(
node,
isTuple ? "TupleExpression" : "ArrayExpression",
);
}
// Parse arrow function expression.
// If the parameters are provided, they will be converted to an
// assignable list.
parseArrowExpression(
node: N.ArrowFunctionExpression,
params: ?(N.Expression[]),
isAsync: boolean,
trailingCommaPos: ?number,
): N.ArrowFunctionExpression {
this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
this.prodParam.enter(functionFlags(isAsync, false));
this.initFunction(node, isAsync);
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
const oldYieldPos = this.state.yieldPos;
const oldAwaitPos = this.state.awaitPos;
if (params) {
this.state.maybeInArrowParameters = true;
this.setArrowFunctionParameters(node, params, trailingCommaPos);
}
this.state.maybeInArrowParameters = false;
this.state.yieldPos = -1;
this.state.awaitPos = -1;
this.parseFunctionBody(node, true);
this.prodParam.exit();
this.scope.exit();
this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
this.state.yieldPos = oldYieldPos;
this.state.awaitPos = oldAwaitPos;
return this.finishNode(node, "ArrowFunctionExpression");
}
setArrowFunctionParameters(
node: N.ArrowFunctionExpression,
params: N.Expression[],
trailingCommaPos: ?number,
): void {
node.params = this.toAssignableList(params, trailingCommaPos);
}
parseFunctionBodyAndFinish(
node: N.BodilessFunctionOrMethodBase,
type: string,
isMethod?: boolean = false,
): void {
// $FlowIgnore (node is not bodiless if we get here)
this.parseFunctionBody(node, false, isMethod);
this.finishNode(node, type);
}
// Parse function body and check parameters.
parseFunctionBody(
node: N.Function,
allowExpression: ?boolean,
isMethod?: boolean = false,
): void {
const isExpression = allowExpression && !this.match(tt.braceL);
const oldInParameters = this.state.inParameters;
this.state.inParameters = false;
if (isExpression) {
node.body = this.parseMaybeAssign();
this.checkParams(node, false, allowExpression, false);
} else {
const oldStrict = this.state.strict;
// Start a new scope with regard to labels
// flag (restore them to their old value afterwards).
const oldLabels = this.state.labels;
this.state.labels = [];
// FunctionBody[Yield, Await]:
// StatementList[?Yield, ?Await, +Return] opt
this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
node.body = this.parseBlock(
true,
false,
// Strict mode function checks after we parse the statements in the function body.
(hasStrictModeDirective: boolean) => {
const nonSimple = !this.isSimpleParamList(node.params);
if (hasStrictModeDirective && nonSimple) {
// This logic is here to align the error location with the ESTree plugin.
const errorPos =
// $FlowIgnore
(node.kind === "method" || node.kind === "constructor") &&
// $FlowIgnore
!!node.key
? node.key.end
: node.start;
this.raise(errorPos, Errors.IllegalLanguageModeDirective);
}
const strictModeChanged = !oldStrict && this.state.strict;
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(
node,
!this.state.strict && !allowExpression && !isMethod && !nonSimple,
allowExpression,
strictModeChanged,
);
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
if (this.state.strict && node.id) {
this.checkLVal(
node.id,
BIND_OUTSIDE,
undefined,
"function name",
undefined,
strictModeChanged,
);
}
},
);
this.prodParam.exit();
this.state.labels = oldLabels;
}
this.state.inParameters = oldInParameters;
}
isSimpleParamList(
params: $ReadOnlyArray<N.Pattern | N.TSParameterProperty>,
): boolean {
for (let i = 0, len = params.length; i < len; i++) {
if (params[i].type !== "Identifier") return false;
}
return true;
}
checkParams(
node: N.Function,
allowDuplicates: boolean,
// eslint-disable-next-line no-unused-vars
isArrowFunction: ?boolean,
strictModeChanged?: boolean = true,
): void {
// $FlowIssue
const nameHash: {} = Object.create(null);
for (let i = 0; i < node.params.length; i++) {
this.checkLVal(
node.params[i],
BIND_VAR,
allowDuplicates ? null : nameHash,
"function parameter list",
undefined,
strictModeChanged,
);
}
}
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
parseExprList(
close: TokenType,
allowEmpty?: boolean,
refExpressionErrors?: ?ExpressionErrors,
nodeForExtra?: ?N.Node,
): $ReadOnlyArray<?N.Expression> {
const elts = [];
let first = true;
while (!this.eat(close)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.match(close)) {
if (nodeForExtra) {
this.addExtra(
nodeForExtra,
"trailingComma",
this.state.lastTokStart,
);
}
this.next();
break;
}
}
elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
}
return elts;
}
parseExprListItem(
allowEmpty: ?boolean,
refExpressionErrors?: ?ExpressionErrors,
refNeedsArrowPos: ?Pos,
allowPlaceholder: ?boolean,
): ?N.Expression {
let elt;
if (this.match(tt.comma)) {
if (!allowEmpty) {
this.raise(this.state.pos, Errors.UnexpectedToken, ",");
}
elt = null;
} else if (this.match(tt.ellipsis)) {
const spreadNodeStartPos = this.state.start;
const spreadNodeStartLoc = this.state.startLoc;
elt = this.parseParenItem(
this.parseSpread(refExpressionErrors, refNeedsArrowPos),
spreadNodeStartPos,
spreadNodeStartLoc,
);
} else if (this.match(tt.question)) {
this.expectPlugin("partialApplication");
if (!allowPlaceholder) {
this.raise(this.state.start, Errors.UnexpectedArgumentPlaceholder);
}
const node = this.startNode();
this.next();
elt = this.finishNode(node, "ArgumentPlaceholder");
} else {
elt = this.parseMaybeAssign(
false,
refExpressionErrors,
this.parseParenItem,
refNeedsArrowPos,
);
}
return elt;
}
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
// This shouldn't be used to parse the keywords of meta properties, since they
// are not identifiers and cannot contain escape sequences.
parseIdentifier(liberal?: boolean): N.Identifier {
const node = this.startNode();
const name = this.parseIdentifierName(node.start, liberal);
return this.createIdentifier(node, name);
}
createIdentifier(node: N.Identifier, name: string): N.Identifier {
node.name = name;
node.loc.identifierName = name;
return this.finishNode(node, "Identifier");
}
parseIdentifierName(pos: number, liberal?: boolean): string {
let name: string;
if (this.match(tt.name)) {
name = this.state.value;
} else if (this.state.type.keyword) {
name = this.state.type.keyword;
// `class` and `function` keywords push function-type token context into this.context.
// But there is no chance to pop the context if the keyword is consumed
// as an identifier such as a property name.
const context = this.state.context;
if (
(name === "class" || name === "function") &&
context[context.length - 1].token === "function"
) {
context.pop();
}
} else {
throw this.unexpected();
}
if (liberal) {
// If the current token is not used as a keyword, set its type to "tt.name".
// This will prevent this.next() from throwing about unexpected escapes.
this.state.type = tt.name;
} else {
this.checkReservedWord(
name,
this.state.start,
!!this.state.type.keyword,
false,
);
}
this.next();
return name;
}
checkReservedWord(
word: string,
startLoc: number,
checkKeywords: boolean,
isBinding: boolean,
): void {
if (this.prodParam.hasYield && word === "yield") {
this.raise(startLoc, Errors.YieldBindingIdentifier);
return;
}
if (word === "await") {
if (this.prodParam.hasAwait) {
this.raise(startLoc, Errors.AwaitBindingIdentifier);
return;
}
if (
this.state.awaitPos === -1 &&
(this.state.maybeInAsyncArrowHead || this.isAwaitAllowed())
) {
this.state.awaitPos = this.state.start;
}
}
if (
this.scope.inClass &&
!this.scope.inNonArrowFunction &&
word === "arguments"
) {
this.raise(startLoc, Errors.ArgumentsDisallowedInInitializer);
return;
}
if (checkKeywords && isKeyword(word)) {
this.raise(startLoc, Errors.UnexpectedKeyword, word);
return;
}
const reservedTest = !this.state.strict
? isReservedWord
: isBinding
? isStrictBindReservedWord
: isStrictReservedWord;
if (reservedTest(word, this.inModule)) {
if (!this.prodParam.hasAwait && word === "await") {
this.raise(startLoc, Errors.AwaitNotInAsyncFunction);
} else {
this.raise(startLoc, Errors.UnexpectedReservedWord, word);
}
}
}
isAwaitAllowed(): boolean {
if (this.scope.inFunction) return this.prodParam.hasAwait;
if (this.options.allowAwaitOutsideFunction) return true;
if (this.hasPlugin("topLevelAwait")) {
return this.inModule && this.prodParam.hasAwait;
}
return false;
}
// Parses await expression inside async function.
parseAwait(): N.AwaitExpression {
const node = this.startNode();
this.next();
if (this.state.inParameters) {
this.raise(node.start, Errors.AwaitExpressionFormalParameter);
} else if (this.state.awaitPos === -1) {
this.state.awaitPos = node.start;
}
if (this.eat(tt.star)) {
this.raise(node.start, Errors.ObsoleteAwaitStar);
}
if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
if (
this.hasPrecedingLineBreak() ||
// All the following expressions are ambiguous:
// await + 0, await - 0, await ( 0 ), await [ 0 ], await / 0 /u, await ``
this.match(tt.plusMin) ||
this.match(tt.parenL) ||
this.match(tt.bracketL) ||
this.match(tt.backQuote) ||
// Sometimes the tokenizer generates tt.slash for regexps, and this is
// handler by parseExprAtom
this.match(tt.regexp) ||
this.match(tt.slash) ||
// This code could be parsed both as a modulo operator or as an intrinsic:
// await %x(0)
(this.hasPlugin("v8intrinsic") && this.match(tt.modulo))
) {
this.ambiguousScriptDifferentAst = true;
} else {
this.sawUnambiguousESM = true;
}
}
if (!this.state.soloAwait) {
node.argument = this.parseMaybeUnary();
}
return this.finishNode(node, "AwaitExpression");
}
// Parses yield expression inside generator.
parseYield(noIn?: ?boolean): N.YieldExpression {
const node = this.startNode();
if (this.state.inParameters) {
this.raise(node.start, Errors.YieldInParameter);
} else if (this.state.yieldPos === -1) {
this.state.yieldPos = node.start;
}
this.next();
if (
this.match(tt.semi) ||
(!this.match(tt.star) && !this.state.type.startsExpr) ||
this.hasPrecedingLineBreak()
) {
node.delegate = false;
node.argument = null;
} else {
node.delegate = this.eat(tt.star);
node.argument = this.parseMaybeAssign(noIn);
}
return this.finishNode(node, "YieldExpression");
}
// Validates a pipeline (for any of the pipeline Babylon plugins) at the point
// of the infix operator `|>`.
checkPipelineAtInfixOperator(left: N.Expression, leftStartPos: number) {
if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
if (left.type === "SequenceExpression") {
// Ensure that the pipeline head is not a comma-delimited
// sequence expression.
this.raise(leftStartPos, Errors.PipelineHeadSequenceExpression);
}
}
}
parseSmartPipelineBody(
childExpression: N.Expression,
startPos: number,
startLoc: Position,
): N.PipelineBody {
const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression);
this.checkSmartPipelineBodyEarlyErrors(
childExpression,
pipelineStyle,
startPos,
);
return this.parseSmartPipelineBodyInStyle(
childExpression,
pipelineStyle,
startPos,
startLoc,
);
}
checkSmartPipelineBodyEarlyErrors(
childExpression: N.Expression,
pipelineStyle: N.PipelineStyle,
startPos: number,
): void {
if (this.match(tt.arrow)) {
// If the following token is invalidly `=>`, then throw a human-friendly error
// instead of something like 'Unexpected token, expected ";"'.
throw this.raise(this.state.start, Errors.PipelineBodyNoArrow);
} else if (
pipelineStyle === "PipelineTopicExpression" &&
childExpression.type === "SequenceExpression"
) {
this.raise(startPos, Errors.PipelineBodySequenceExpression);
}
}
parseSmartPipelineBodyInStyle(
childExpression: N.Expression,
pipelineStyle: N.PipelineStyle,
startPos: number,
startLoc: Position,
): N.PipelineBody {
const bodyNode = this.startNodeAt(startPos, startLoc);
switch (pipelineStyle) {
case "PipelineBareFunction":
bodyNode.callee = childExpression;
break;
case "PipelineBareConstructor":
bodyNode.callee = childExpression.callee;
break;
case "PipelineBareAwaitedFunction":
bodyNode.callee = childExpression.argument;
break;
case "PipelineTopicExpression":
if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
this.raise(startPos, Errors.PipelineTopicUnused);
}
bodyNode.expression = childExpression;
break;
default:
throw new Error(
`Internal @babel/parser error: Unknown pipeline style (${pipelineStyle})`,
);
}
return this.finishNode(bodyNode, pipelineStyle);
}
checkSmartPipelineBodyStyle(expression: N.Expression): N.PipelineStyle {
switch (expression.type) {
default:
return this.isSimpleReference(expression)
? "PipelineBareFunction"
: "PipelineTopicExpression";
}
}
isSimpleReference(expression: N.Expression): boolean {
switch (expression.type) {
case "MemberExpression":
return (
!expression.computed && this.isSimpleReference(expression.object)
);
case "Identifier":
return true;
default:
return false;
}
}
// Enable topic references from outer contexts within smart pipeline bodies.
// The function modifies the parser's topic-context state to enable or disable
// the use of topic references with the smartPipelines plugin. They then run a
// callback, then they reset the parser to the old topic-context state that it
// had before the function was called.
withTopicPermittingContext<T>(callback: () => T): T {
const outerContextTopicState = this.state.topicContext;
this.state.topicContext = {
// Enable the use of the primary topic reference.
maxNumOfResolvableTopics: 1,
// Hide the use of any topic references from outer contexts.
maxTopicIndex: null,
};
try {
return callback();
} finally {
this.state.topicContext = outerContextTopicState;
}
}
// Disable topic references from outer contexts within syntax constructs
// such as the bodies of iteration statements.
// The function modifies the parser's topic-context state to enable or disable
// the use of topic references with the smartPipelines plugin. They then run a
// callback, then they reset the parser to the old topic-context state that it
// had before the function was called.
withTopicForbiddingContext<T>(callback: () => T): T {
const outerContextTopicState = this.state.topicContext;
this.state.topicContext = {
// Disable the use of the primary topic reference.
maxNumOfResolvableTopics: 0,
// Hide the use of any topic references from outer contexts.
maxTopicIndex: null,
};
try {
return callback();
} finally {
this.state.topicContext = outerContextTopicState;
}
}
withSoloAwaitPermittingContext<T>(callback: () => T): T {
const outerContextSoloAwaitState = this.state.soloAwait;
this.state.soloAwait = true;
try {
return callback();
} finally {
this.state.soloAwait = outerContextSoloAwaitState;
}
}
// Register the use of a primary topic reference (`#`) within the current
// topic context.
registerTopicReference(): void {
this.state.topicContext.maxTopicIndex = 0;
}
primaryTopicReferenceIsAllowedInCurrentTopicContext(): boolean {
return this.state.topicContext.maxNumOfResolvableTopics >= 1;
}
topicReferenceWasUsedInCurrentTopicContext(): boolean {
return (
this.state.topicContext.maxTopicIndex != null &&
this.state.topicContext.maxTopicIndex >= 0
);
}
parseFSharpPipelineBody(prec: number, noIn: ?boolean): N.Expression {
const startPos = this.state.start;
const startLoc = this.state.startLoc;
this.state.potentialArrowAt = this.state.start;
const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
this.state.inFSharpPipelineDirectBody = true;
const ret = this.parseExprOp(
this.parseMaybeUnary(),
startPos,
startLoc,
prec,
noIn,
);
this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
return ret;
}
}
| refactor: avoid unnecessary property access (#11918)
* refactor: avoid unnecessary property access
* refactor: `else` is redundant because keyName is const | packages/babel-parser/src/parser/expression.js | refactor: avoid unnecessary property access (#11918) | <ide><path>ackages/babel-parser/src/parser/expression.js
<ide> }
<ide>
<ide> const containsEsc = this.state.containsEsc;
<del> this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
<add> const key = this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
<ide>
<ide> if (
<ide> !isPattern &&
<ide> !containsEsc &&
<ide> this.maybeAsyncOrAccessorProp(prop)
<ide> ) {
<add> const keyName = key.name;
<ide> // https://tc39.es/ecma262/#prod-AsyncMethod
<ide> // https://tc39.es/ecma262/#prod-AsyncGeneratorMethod
<del> if (prop.key.name === "async" && !this.hasPrecedingLineBreak()) {
<add> if (keyName === "async" && !this.hasPrecedingLineBreak()) {
<ide> isAsync = true;
<ide> isGenerator = this.eat(tt.star);
<ide> this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
<ide> }
<ide> // get PropertyName[?Yield, ?Await] () { FunctionBody[~Yield, ~Await] }
<ide> // set PropertyName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] }
<del> else if (prop.key.name === "get" || prop.key.name === "set") {
<add> if (keyName === "get" || keyName === "set") {
<ide> isAccessor = true;
<ide> isGenerator = this.eat(tt.star); // tt.star is allowed in `maybeAsyncOrAccessorProp`, we will throw in `parseObjectMethod` later
<del> prop.kind = prop.key.name;
<add> prop.kind = keyName;
<ide> this.parsePropertyName(prop, /* isPrivateNameAllowed */ false);
<ide> }
<ide> } |
|
Java | apache-2.0 | 0c88f6af20d50705319a0966e2880500097f28ac | 0 | jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package org.jenetics.tool.trial;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Helper class for creating <i>Gnuplot</i> graphs.
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @version !__version__!
* @since !__version__!
*/
public class Gnuplot {
private static final String DATA_NAME = "data";
private static final String OUTPUT_NAME = "output";
private final Path _template;
private final Map<String, String> _parameters = new HashMap<>();
/**
* Create a new {@code Gnuplot} object with the given <i>template</i> path.
*
* @param template the Gnuplot template path
*/
public Gnuplot(final Path template) {
_template = requireNonNull(template);
}
/**
* Generate the Gnuplot graph.
*
* @param data the input data file
* @param output the output path of the graph
* @throws IOException if the Gnuplot generation fails
*/
public void create(final Path data, final Path output)
throws IOException
{
_parameters.put(DATA_NAME, data.toString());
_parameters.put(OUTPUT_NAME, output.toString());
final Process process = new ProcessBuilder()
.command(command())
.start();
System.out.println(IO.toText(process.getErrorStream()));
try {
process.waitFor();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private List<String> command() {
final String params = _parameters.entrySet().stream()
.map(Gnuplot::toParamString)
.collect(Collectors.joining("; "));
return Arrays.asList("gnuplot", "-e", params, _template.toString());
}
private static String toParamString(final Map.Entry<String, String> entry) {
return format("%s='%s'", entry.getKey(), entry.getValue());
}
public static void main(final String[] args)
throws IOException, InterruptedException
{
final String base = "/home/fwilhelm/Workspace/Development/Projects/" +
"Jenetics/org.jenetics/src/tool/resources/org/jenetics/trial/";
final Path data = Paths.get(base, "knapsack_execution_time.dat");
final Path output = Paths.get(base, "knapsack_execution_time.svg");
final Gnuplot gnuplot = new Gnuplot(Paths.get(base, "sub_fitness.gp"));
gnuplot.create(data, output);
}
}
| org.jenetics.tool/src/main/java/org/jenetics/tool/trial/Gnuplot.java | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package org.jenetics.tool.trial;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Helper class for creating <i>Gnuplot</i> graphs.
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @version !__version__!
* @since !__version__!
*/
public class Gnuplot {
private static final String DATA_NAME = "data";
private static final String OUTPUT_NAME = "output";
private final Path _template;
private final Map<String, String> _parameters = new HashMap<>();
/**
* Create a new {@code Gnuplot} object with the given <i>template</i> path.
*
* @param template the Gnuplot template path
*/
public Gnuplot(final Path template) {
_template = requireNonNull(template);
}
/**
* Generate the Gnuplot graph.
*
* @param data the input data file
* @param output the output path of the graph
* @throws IOException if the Gnuplot generation fails
*/
public void create(final Path data, final Path output)
throws IOException
{
_parameters.put(DATA_NAME, data.toString());
_parameters.put(OUTPUT_NAME, output.toString());
final Process process = new ProcessBuilder()
.command(command())
.start();
System.out.println(IO.toText(process.getErrorStream()));
try {
System.out.println("Result: " + process.waitFor());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private List<String> command() {
final String params = _parameters.entrySet().stream()
.map(Gnuplot::toParamString)
.collect(Collectors.joining("; "));
return Arrays.asList("gnuplot", "-e", params, _template.toString());
}
private static String toParamString(final Map.Entry<String, String> entry) {
return format("%s='%s'", entry.getKey(), entry.getValue());
}
public static void main(final String[] args)
throws IOException, InterruptedException
{
final String base = "/home/fwilhelm/Workspace/Development/Projects/" +
"Jenetics/org.jenetics/src/tool/resources/org/jenetics/trial/";
final Path data = Paths.get(base, "knapsack_execution_time.dat");
final Path output = Paths.get(base, "knapsack_execution_time.svg");
final Gnuplot gnuplot = new Gnuplot(Paths.get(base, "sub_fitness.gp"));
gnuplot.create(data, output);
}
}
| Improve console output.
| org.jenetics.tool/src/main/java/org/jenetics/tool/trial/Gnuplot.java | Improve console output. | <ide><path>rg.jenetics.tool/src/main/java/org/jenetics/tool/trial/Gnuplot.java
<ide>
<ide> System.out.println(IO.toText(process.getErrorStream()));
<ide> try {
<del> System.out.println("Result: " + process.waitFor());
<add> process.waitFor();
<ide> } catch (InterruptedException e) {
<ide> Thread.currentThread().interrupt();
<ide> } |
|
Java | mit | 8b11b6b85ada2aa52e27198f71e2cd7268c4c90c | 0 | se-edu/addressbook-level3,damithc/addressbook-level4,damithc/addressbook-level4,damithc/addressbook-level4 | package guitests;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import guitests.guihandles.HelpWindowHandle;
import seedu.address.logic.commands.HelpCommand;
public class HelpWindowTest extends AddressBookGuiTest {
private static final String ERROR_MESSAGE = "ATTENTION!!!! : On some computers, this test may fail when run on "
+ "non-headless mode as FxRobot#clickOn(Node, MouseButton...) clicks on the wrong location. We suspect "
+ "that this is a bug with TestFX library that we are using. If this test fails, you have to run your "
+ "tests on headless mode. See UsingGradle.adoc on how to do so.";
@Test
public void openHelpWindow() {
//use accelerator
getCommandBox().click();
getMainMenu().openHelpWindowUsingAccelerator();
assertHelpWindowOpen();
getResultDisplay().click();
getMainMenu().openHelpWindowUsingAccelerator();
assertHelpWindowOpen();
getPersonListPanel().click();
getMainMenu().openHelpWindowUsingAccelerator();
assertHelpWindowOpen();
getBrowserPanel().click();
getMainMenu().openHelpWindowUsingAccelerator();
assertHelpWindowNotOpen();
//use menu button
getMainMenu().openHelpWindowUsingMenu();
assertHelpWindowOpen();
//use command box
runCommand(HelpCommand.COMMAND_WORD);
assertHelpWindowOpen();
}
/**
* Asserts that the help window is open, and closes it after checking.
*/
private void assertHelpWindowOpen() {
assertTrue(ERROR_MESSAGE, HelpWindowHandle.isWindowPresent());
guiRobot.pauseForHuman();
new HelpWindowHandle(guiRobot.getStage(HelpWindowHandle.HELP_WINDOW_TITLE)).close();
mainWindowHandle.focus();
}
/**
* Asserts that the help window isn't open.
*/
private void assertHelpWindowNotOpen() {
assertFalse(ERROR_MESSAGE, HelpWindowHandle.isWindowPresent());
}
}
| src/test/java/guitests/HelpWindowTest.java | package guitests;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import guitests.guihandles.HelpWindowHandle;
import seedu.address.logic.commands.HelpCommand;
public class HelpWindowTest extends AddressBookGuiTest {
@Test
public void openHelpWindow() {
//use accelerator
getCommandBox().click();
getMainMenu().openHelpWindowUsingAccelerator();
assertHelpWindowOpen();
getResultDisplay().click();
getMainMenu().openHelpWindowUsingAccelerator();
assertHelpWindowOpen();
getPersonListPanel().click();
getMainMenu().openHelpWindowUsingAccelerator();
assertHelpWindowOpen();
getBrowserPanel().click();
getMainMenu().openHelpWindowUsingAccelerator();
assertHelpWindowNotOpen();
//use menu button
getMainMenu().openHelpWindowUsingMenu();
assertHelpWindowOpen();
//use command box
runCommand(HelpCommand.COMMAND_WORD);
assertHelpWindowOpen();
}
/**
* Asserts that the help window is open, and closes it after checking.
*/
private void assertHelpWindowOpen() {
assertTrue(HelpWindowHandle.isWindowPresent());
guiRobot.pauseForHuman();
new HelpWindowHandle(guiRobot.getStage(HelpWindowHandle.HELP_WINDOW_TITLE)).close();
mainWindowHandle.focus();
}
/**
* Asserts that the help window isn't open.
*/
private void assertHelpWindowNotOpen() {
assertFalse(HelpWindowHandle.isWindowPresent());
}
}
| [#680] HelpWindowTest: Write header comments concerning possible test failure (#694)
HelpWindowTest fails on certain computers. The cursor does not move to
the correct location, resulting in the wrong UI component being
clicked. We suspect this to be a bug in the TestFX library.
This causes the wrong UI component to be in focus, which leads to a
test failure.
Let's show an error message when the test fails. | src/test/java/guitests/HelpWindowTest.java | [#680] HelpWindowTest: Write header comments concerning possible test failure (#694) | <ide><path>rc/test/java/guitests/HelpWindowTest.java
<ide> import seedu.address.logic.commands.HelpCommand;
<ide>
<ide> public class HelpWindowTest extends AddressBookGuiTest {
<add> private static final String ERROR_MESSAGE = "ATTENTION!!!! : On some computers, this test may fail when run on "
<add> + "non-headless mode as FxRobot#clickOn(Node, MouseButton...) clicks on the wrong location. We suspect "
<add> + "that this is a bug with TestFX library that we are using. If this test fails, you have to run your "
<add> + "tests on headless mode. See UsingGradle.adoc on how to do so.";
<ide>
<ide> @Test
<ide> public void openHelpWindow() {
<ide> * Asserts that the help window is open, and closes it after checking.
<ide> */
<ide> private void assertHelpWindowOpen() {
<del> assertTrue(HelpWindowHandle.isWindowPresent());
<add> assertTrue(ERROR_MESSAGE, HelpWindowHandle.isWindowPresent());
<ide> guiRobot.pauseForHuman();
<ide>
<ide> new HelpWindowHandle(guiRobot.getStage(HelpWindowHandle.HELP_WINDOW_TITLE)).close();
<ide> * Asserts that the help window isn't open.
<ide> */
<ide> private void assertHelpWindowNotOpen() {
<del> assertFalse(HelpWindowHandle.isWindowPresent());
<add> assertFalse(ERROR_MESSAGE, HelpWindowHandle.isWindowPresent());
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 3503440c142ab9412c36f8aeb54d02e72c49ea69 | 0 | semonte/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,holmes/intellij-community,petteyg/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,clumsy/intellij-community,ryano144/intellij-community,ibinti/intellij-community,da1z/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,kdwink/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,samthor/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,izonder/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,blademainer/intellij-community,semonte/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,izonder/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,slisson/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,signed/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,ibinti/intellij-community,FHannes/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,amith01994/intellij-community,robovm/robovm-studio,robovm/robovm-studio,fitermay/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,apixandru/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,slisson/intellij-community,xfournet/intellij-community,allotria/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,fnouama/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,signed/intellij-community,clumsy/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,caot/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,allotria/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,da1z/intellij-community,samthor/intellij-community,hurricup/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,dslomov/intellij-community,clumsy/intellij-community,hurricup/intellij-community,signed/intellij-community,vladmm/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,signed/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,supersven/intellij-community,Lekanich/intellij-community,caot/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,da1z/intellij-community,kdwink/intellij-community,amith01994/intellij-community,jagguli/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,izonder/intellij-community,allotria/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,semonte/intellij-community,nicolargo/intellij-community,da1z/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,slisson/intellij-community,samthor/intellij-community,semonte/intellij-community,akosyakov/intellij-community,allotria/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,supersven/intellij-community,robovm/robovm-studio,izonder/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,apixandru/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,semonte/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,da1z/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,caot/intellij-community,kool79/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,caot/intellij-community,hurricup/intellij-community,petteyg/intellij-community,kdwink/intellij-community,dslomov/intellij-community,caot/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,fnouama/intellij-community,supersven/intellij-community,dslomov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,caot/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,caot/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,samthor/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,xfournet/intellij-community,dslomov/intellij-community,blademainer/intellij-community,kool79/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,signed/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,kool79/intellij-community,izonder/intellij-community,ryano144/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,caot/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,jagguli/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,jagguli/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,signed/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,izonder/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,petteyg/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,caot/intellij-community,dslomov/intellij-community,ibinti/intellij-community,signed/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,da1z/intellij-community,semonte/intellij-community,kool79/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,amith01994/intellij-community,supersven/intellij-community,signed/intellij-community,FHannes/intellij-community,da1z/intellij-community,semonte/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,samthor/intellij-community,holmes/intellij-community,retomerz/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,izonder/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,retomerz/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,xfournet/intellij-community,dslomov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,allotria/intellij-community,clumsy/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,xfournet/intellij-community,signed/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,slisson/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,slisson/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,xfournet/intellij-community,apixandru/intellij-community,holmes/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,samthor/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,izonder/intellij-community,FHannes/intellij-community,signed/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,supersven/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,robovm/robovm-studio,kool79/intellij-community,amith01994/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,semonte/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ryano144/intellij-community,amith01994/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,samthor/intellij-community,caot/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,holmes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,blademainer/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,apixandru/intellij-community,signed/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,dslomov/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,retomerz/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,caot/intellij-community,signed/intellij-community,samthor/intellij-community,suncycheng/intellij-community,samthor/intellij-community,fnouama/intellij-community,samthor/intellij-community,ibinti/intellij-community,kdwink/intellij-community,fitermay/intellij-community,fnouama/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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.jetbrains.plugins.github;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ThrowableConvertor;
import com.intellij.util.net.HttpConfigurable;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.auth.AuthenticationException;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
/**
* @author Kirill Likhodedov
*/
public class GithubApiUtil {
public static final String DEFAULT_GITHUB_HOST = "github.com";
private static final int CONNECTION_TIMEOUT = 5000;
private static final Logger LOG = Logger.getInstance(GithubApiUtil.class);
private enum HttpVerb {
GET, POST, DELETE, HEAD
}
@Nullable
public static JsonElement getRequest(@NotNull String host, @NotNull String login, @NotNull String password,
@NotNull String path) throws IOException {
return request(host, login, password, path, null, HttpVerb.GET);
}
@Nullable
public static JsonElement getRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException {
return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, null, HttpVerb.GET);
}
@Nullable
public static JsonElement anonymousPostRequest(@NotNull String host, @NotNull String path, @Nullable String requestBody)
throws IOException {
return request(host, null, null, path, requestBody, HttpVerb.POST);
}
@Nullable
public static JsonElement postRequest(@NotNull GithubAuthData auth, @NotNull String path, @Nullable String requestBody)
throws IOException {
return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, requestBody, HttpVerb.POST);
}
@Nullable
public static JsonElement postRequest(@NotNull String host,
@NotNull GithubAuthData auth,
@NotNull String path,
@Nullable String requestBody) throws IOException {
return request(host, auth.getLogin(), auth.getPassword(), path, requestBody, HttpVerb.POST);
}
@Nullable
public static JsonElement deleteRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException {
return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, null, HttpVerb.DELETE);
}
@Nullable
private static JsonElement request(@NotNull String host, @Nullable String login, @Nullable String password,
@NotNull String path,
@Nullable String requestBody, @NotNull HttpVerb verb) throws IOException {
HttpMethod method = null;
try {
method = doREST(host, login, password, path, requestBody, verb);
String resp = method.getResponseBodyAsString();
if (resp == null) {
LOG.info(String.format("Unexpectedly empty response: %s", resp));
return null;
}
if (method.getStatusCode() >= 400 && method.getStatusCode() <= 404) {
throw new AuthenticationException("Request response: " + method.getStatusText());
}
JsonElement ret = parseResponse(resp);
Header header = method.getResponseHeader("Link");
if (header != null) {
String s = header.getValue();
final int end = s.indexOf(">; rel=\"next\"");
final int begin = s.lastIndexOf('<', end);
if (begin >= 0 && end >= 0) {
JsonElement next = request(s.substring(begin + 1, end), login, password, "", requestBody, verb);
if (next != null) {
JsonArray merged = ret.getAsJsonArray();
merged.addAll(next.getAsJsonArray());
return merged;
}
}
}
return ret;
}
finally {
if (method != null) {
method.releaseConnection();
}
}
}
@NotNull
private static HttpMethod doREST(@NotNull String host, @Nullable String login, @Nullable String password, @NotNull String path,
@Nullable final String requestBody,
@NotNull final HttpVerb verb) throws IOException {
HttpClient client = getHttpClient(login, password);
String uri = getApiUrl(host) + path;
return GithubSslSupport.getInstance().executeSelfSignedCertificateAwareRequest(client, uri,
new ThrowableConvertor<String, HttpMethod, IOException>() {
@Override
public HttpMethod convert(String uri) throws IOException {
switch (verb) {
case POST:
PostMethod method = new PostMethod(uri);
if (requestBody != null) {
method.setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8"));
}
return method;
case GET:
return new GetMethod(uri);
case DELETE:
return new DeleteMethod(uri);
case HEAD:
return new HeadMethod(uri);
default:
throw new IllegalStateException("Wrong HttpVerb: unknown method");
}
}
});
}
@NotNull
public static String removeProtocolPrefix(final String url) {
if (url.startsWith("https://")) {
return url.substring(8);
}
else if (url.startsWith("http://")) {
return url.substring(7);
}
else if (url.startsWith("git@")) {
return url.substring(4);
}
else {
return url;
}
}
@NotNull
private static String getApiUrl(@NotNull String urlFromSettings) {
return "https://" + getApiUrlWithoutProtocol(urlFromSettings);
}
@NotNull
public static String getApiUrl() {
return getApiUrl(GithubSettings.getInstance().getHost());
}
/**
* Returns the "host" part of Git URLs.
* E.g.: https://github.com
* Note: there is no trailing slash in the returned url.
*/
@NotNull
public static String getGitHost() {
return "https://" + removeTrailingSlash(removeProtocolPrefix(GithubSettings.getInstance().getHost()));
}
/*
All API access is over HTTPS, and accessed from the api.github.com domain
(or through yourdomain.com/api/v3/ for enterprise).
http://developer.github.com/v3/
*/
@NotNull
private static String getApiUrlWithoutProtocol(String urlFromSettings) {
String url = removeTrailingSlash(removeProtocolPrefix(urlFromSettings));
final String API_PREFIX = "api.";
final String ENTERPRISE_API_SUFFIX = "/api/v3";
if (url.equals(DEFAULT_GITHUB_HOST)) {
return API_PREFIX + url;
}
else if (url.equals(API_PREFIX + DEFAULT_GITHUB_HOST)) {
return url;
}
else if (url.endsWith(ENTERPRISE_API_SUFFIX)) {
return url;
}
else {
return url + ENTERPRISE_API_SUFFIX;
}
}
@NotNull
public static String removeTrailingSlash(@NotNull String s) {
if (s.endsWith("/")) {
return s.substring(0, s.length() - 1);
}
return s;
}
@NotNull
private static HttpClient getHttpClient(@Nullable final String login, @Nullable final String password) {
final HttpClient client = new HttpClient();
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host)
params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host)
client.getParams().setContentCharset("UTF-8");
// Configure proxySettings if it is required
final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
if (proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)){
client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
if (proxySettings.PROXY_AUTHENTICATION) {
client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxySettings.PROXY_LOGIN,
proxySettings.getPlainProxyPassword()));
}
}
if (login != null && password != null) {
client.getParams().setCredentialCharset("UTF-8");
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(login, password));
}
return client;
}
@NotNull
private static JsonElement parseResponse(@NotNull String githubResponse) throws IOException {
try {
return new JsonParser().parse(githubResponse);
}
catch (JsonSyntaxException jse) {
throw new IOException(String.format("Couldn't parse GitHub response:%n%s", githubResponse), jse);
}
}
}
| plugins/github/src/org/jetbrains/plugins/github/GithubApiUtil.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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.jetbrains.plugins.github;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ThrowableConvertor;
import com.intellij.util.net.HttpConfigurable;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.auth.AuthenticationException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
/**
* @author Kirill Likhodedov
*/
public class GithubApiUtil {
public static final String DEFAULT_GITHUB_HOST = "github.com";
private static final int CONNECTION_TIMEOUT = 5000;
private static final Logger LOG = Logger.getInstance(GithubApiUtil.class);
@Nullable
public static JsonElement getRequest(@NotNull String host, @NotNull String login, @NotNull String password,
@NotNull String path) throws IOException {
return request(host, login, password, path, null, false);
}
@Nullable
public static JsonElement getRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException {
return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, null, false);
}
@Nullable
public static JsonElement anonymousPostRequest(@NotNull String host, @NotNull String path, @Nullable String requestBody)
throws IOException {
return request(host, null, null, path, requestBody, true);
}
@Nullable
public static JsonElement postRequest(@NotNull GithubAuthData auth, @NotNull String path, @Nullable String requestBody)
throws IOException {
return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, requestBody, true);
}
@Nullable
public static JsonElement postRequest(@NotNull String host,
@NotNull GithubAuthData auth,
@NotNull String path,
@Nullable String requestBody) throws IOException {
return request(host, auth.getLogin(), auth.getPassword(), path, requestBody, true);
}
@Nullable
private static JsonElement request(@NotNull String host, @Nullable String login, @Nullable String password,
@NotNull String path,
@Nullable String requestBody,
boolean post) throws IOException {
HttpMethod method = null;
try {
method = doREST(host, login, password, path, requestBody, post);
String resp = method.getResponseBodyAsString();
if (resp == null) {
LOG.info(String.format("Unexpectedly empty response: %s", resp));
return null;
}
if (method.getStatusCode() >= 400 && method.getStatusCode() <= 404) {
throw new AuthenticationException("Request response: " + method.getStatusText());
}
JsonElement ret = parseResponse(resp);
Header header = method.getResponseHeader("Link");
if (header != null) {
String s = header.getValue();
final int end = s.indexOf(">; rel=\"next\"");
final int begin = s.lastIndexOf('<', end);
if (begin >= 0 && end >= 0) {
JsonElement next = request(s.substring(begin + 1, end), login, password, "", requestBody, post);
if (next != null) {
JsonArray merged = ret.getAsJsonArray();
merged.addAll(next.getAsJsonArray());
return merged;
}
}
}
return ret;
}
finally {
if (method != null) {
method.releaseConnection();
}
}
}
@NotNull
private static HttpMethod doREST(@NotNull String host, @Nullable String login, @Nullable String password, @NotNull String path,
@Nullable final String requestBody, final boolean post) throws IOException {
HttpClient client = getHttpClient(login, password);
String uri = getApiUrl(host) + path;
return GithubSslSupport.getInstance().executeSelfSignedCertificateAwareRequest(client, uri,
new ThrowableConvertor<String, HttpMethod, IOException>() {
@Override
public HttpMethod convert(String uri) throws IOException {
if (post) {
PostMethod method = new PostMethod(uri);
if (requestBody != null) {
method.setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8"));
}
return method;
}
return new GetMethod(uri);
}
});
}
@NotNull
public static String removeProtocolPrefix(final String url) {
if (url.startsWith("https://")) {
return url.substring(8);
}
else if (url.startsWith("http://")) {
return url.substring(7);
}
else if (url.startsWith("git@")) {
return url.substring(4);
}
else {
return url;
}
}
@NotNull
private static String getApiUrl(@NotNull String urlFromSettings) {
return "https://" + getApiUrlWithoutProtocol(urlFromSettings);
}
@NotNull
public static String getApiUrl() {
return getApiUrl(GithubSettings.getInstance().getHost());
}
/**
* Returns the "host" part of Git URLs.
* E.g.: https://github.com
* Note: there is no trailing slash in the returned url.
*/
@NotNull
public static String getGitHost() {
return "https://" + removeTrailingSlash(removeProtocolPrefix(GithubSettings.getInstance().getHost()));
}
/*
All API access is over HTTPS, and accessed from the api.github.com domain
(or through yourdomain.com/api/v3/ for enterprise).
http://developer.github.com/v3/
*/
@NotNull
private static String getApiUrlWithoutProtocol(String urlFromSettings) {
String url = removeTrailingSlash(removeProtocolPrefix(urlFromSettings));
final String API_PREFIX = "api.";
final String ENTERPRISE_API_SUFFIX = "/api/v3";
if (url.equals(DEFAULT_GITHUB_HOST)) {
return API_PREFIX + url;
}
else if (url.equals(API_PREFIX + DEFAULT_GITHUB_HOST)) {
return url;
}
else if (url.endsWith(ENTERPRISE_API_SUFFIX)) {
return url;
}
else {
return url + ENTERPRISE_API_SUFFIX;
}
}
@NotNull
public static String removeTrailingSlash(@NotNull String s) {
if (s.endsWith("/")) {
return s.substring(0, s.length() - 1);
}
return s;
}
@NotNull
private static HttpClient getHttpClient(@Nullable final String login, @Nullable final String password) {
final HttpClient client = new HttpClient();
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host)
params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host)
client.getParams().setContentCharset("UTF-8");
// Configure proxySettings if it is required
final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
if (proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)){
client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
if (proxySettings.PROXY_AUTHENTICATION) {
client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxySettings.PROXY_LOGIN,
proxySettings.getPlainProxyPassword()));
}
}
if (login != null && password != null) {
client.getParams().setCredentialCharset("UTF-8");
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(login, password));
}
return client;
}
@NotNull
private static JsonElement parseResponse(@NotNull String githubResponse) throws IOException {
try {
return new JsonParser().parse(githubResponse);
}
catch (JsonSyntaxException jse) {
throw new IOException(String.format("Couldn't parse GitHub response:%n%s", githubResponse), jse);
}
}
}
| Github: add DELETE/HEAD http methods support
| plugins/github/src/org/jetbrains/plugins/github/GithubApiUtil.java | Github: add DELETE/HEAD http methods support | <ide><path>lugins/github/src/org/jetbrains/plugins/github/GithubApiUtil.java
<ide> import org.apache.commons.httpclient.UsernamePasswordCredentials;
<ide> import org.apache.commons.httpclient.auth.AuthScope;
<ide> import org.apache.commons.httpclient.auth.AuthenticationException;
<del>import org.apache.commons.httpclient.methods.GetMethod;
<del>import org.apache.commons.httpclient.methods.PostMethod;
<del>import org.apache.commons.httpclient.methods.StringRequestEntity;
<add>import org.apache.commons.httpclient.methods.*;
<ide> import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
<ide> import org.jetbrains.annotations.NotNull;
<ide> import org.jetbrains.annotations.Nullable;
<ide> private static final int CONNECTION_TIMEOUT = 5000;
<ide> private static final Logger LOG = Logger.getInstance(GithubApiUtil.class);
<ide>
<add> private enum HttpVerb {
<add> GET, POST, DELETE, HEAD
<add> }
<add>
<ide> @Nullable
<ide> public static JsonElement getRequest(@NotNull String host, @NotNull String login, @NotNull String password,
<ide> @NotNull String path) throws IOException {
<del> return request(host, login, password, path, null, false);
<add> return request(host, login, password, path, null, HttpVerb.GET);
<ide> }
<ide>
<ide> @Nullable
<ide> public static JsonElement getRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException {
<del> return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, null, false);
<add> return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, null, HttpVerb.GET);
<ide> }
<ide>
<ide> @Nullable
<ide> public static JsonElement anonymousPostRequest(@NotNull String host, @NotNull String path, @Nullable String requestBody)
<ide> throws IOException {
<del> return request(host, null, null, path, requestBody, true);
<add> return request(host, null, null, path, requestBody, HttpVerb.POST);
<ide> }
<ide>
<ide> @Nullable
<ide> public static JsonElement postRequest(@NotNull GithubAuthData auth, @NotNull String path, @Nullable String requestBody)
<ide> throws IOException {
<del> return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, requestBody, true);
<add> return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, requestBody, HttpVerb.POST);
<ide> }
<ide>
<ide> @Nullable
<ide> @NotNull GithubAuthData auth,
<ide> @NotNull String path,
<ide> @Nullable String requestBody) throws IOException {
<del> return request(host, auth.getLogin(), auth.getPassword(), path, requestBody, true);
<add> return request(host, auth.getLogin(), auth.getPassword(), path, requestBody, HttpVerb.POST);
<add> }
<add>
<add> @Nullable
<add> public static JsonElement deleteRequest(@NotNull GithubAuthData auth, @NotNull String path) throws IOException {
<add> return request(auth.getHost(), auth.getLogin(), auth.getPassword(), path, null, HttpVerb.DELETE);
<ide> }
<ide>
<ide> @Nullable
<ide> private static JsonElement request(@NotNull String host, @Nullable String login, @Nullable String password,
<ide> @NotNull String path,
<del> @Nullable String requestBody,
<del> boolean post) throws IOException {
<add> @Nullable String requestBody, @NotNull HttpVerb verb) throws IOException {
<ide> HttpMethod method = null;
<ide> try {
<del> method = doREST(host, login, password, path, requestBody, post);
<add> method = doREST(host, login, password, path, requestBody, verb);
<ide> String resp = method.getResponseBodyAsString();
<ide> if (resp == null) {
<ide> LOG.info(String.format("Unexpectedly empty response: %s", resp));
<ide> final int end = s.indexOf(">; rel=\"next\"");
<ide> final int begin = s.lastIndexOf('<', end);
<ide> if (begin >= 0 && end >= 0) {
<del> JsonElement next = request(s.substring(begin + 1, end), login, password, "", requestBody, post);
<add> JsonElement next = request(s.substring(begin + 1, end), login, password, "", requestBody, verb);
<ide> if (next != null) {
<ide> JsonArray merged = ret.getAsJsonArray();
<ide> merged.addAll(next.getAsJsonArray());
<ide>
<ide> @NotNull
<ide> private static HttpMethod doREST(@NotNull String host, @Nullable String login, @Nullable String password, @NotNull String path,
<del> @Nullable final String requestBody, final boolean post) throws IOException {
<add> @Nullable final String requestBody,
<add> @NotNull final HttpVerb verb) throws IOException {
<ide> HttpClient client = getHttpClient(login, password);
<ide> String uri = getApiUrl(host) + path;
<ide> return GithubSslSupport.getInstance().executeSelfSignedCertificateAwareRequest(client, uri,
<ide> new ThrowableConvertor<String, HttpMethod, IOException>() {
<ide> @Override
<ide> public HttpMethod convert(String uri) throws IOException {
<del> if (post) {
<del> PostMethod method = new PostMethod(uri);
<del> if (requestBody != null) {
<del> method.setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8"));
<del> }
<del> return method;
<add> switch (verb) {
<add> case POST:
<add> PostMethod method = new PostMethod(uri);
<add> if (requestBody != null) {
<add> method.setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8"));
<add> }
<add> return method;
<add> case GET:
<add> return new GetMethod(uri);
<add> case DELETE:
<add> return new DeleteMethod(uri);
<add> case HEAD:
<add> return new HeadMethod(uri);
<add> default:
<add> throw new IllegalStateException("Wrong HttpVerb: unknown method");
<ide> }
<del> return new GetMethod(uri);
<ide> }
<ide> });
<ide> } |
|
Java | apache-2.0 | 18d011c93e08b552eafb0cd33dfba9e530a04459 | 0 | fgreinus/jwebpoll,fgreinus/jwebpoll,fgreinus/jwebpoll | package de.lebk.jwebpoll.client;
import com.j256.ormlite.dao.Dao;
import de.lebk.jwebpoll.Database;
import de.lebk.jwebpoll.Frontend;
import de.lebk.jwebpoll.data.*;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
public class Client extends Application {
//- Main -
public static void main(String[] args) {
Client.launch(args);
}
//- Data -
private List<Poll> polls = new ArrayList<>();
//poll selected in client window
private Poll poll;
//poll running on serve
private Poll activePoll;
//- View -
private ListView<Poll> pollList;
private TextField titleTxF;
private Button pollRemoveBtn;
private TextArea descTxF;
private TextField createdDateTxF, createdTimeTxF;
private ComboBox<PollState> stateCbo;
private Button openBtn, closeBtn, resultsBtn;
private Accordion questionsAccordion;
private Button questionsAddBtn;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("JWebPoll");
primaryStage.setOnCloseRequest((WindowEvent we) ->
{
try {
Frontend.kill();
} catch (Exception e) {
e.printStackTrace();
}
});
// Start DB
spawnDatabase();
// Example polls (to be deleted in future)
Poll poll1 = new Poll("1. Umfrage", "Eine Beschreibung", PollState.NEW);
Poll bundestagswahl = new Poll("Bundestagswahl", "Kurze Beschreibung", PollState.NEW);
Question kanzlerkandidat = new Question("Wer ist ihr Kanzlerkandidat?", true, QuestionType.SINGLE, bundestagswahl);
Answer merkel = new Answer("Merkel", -100, kanzlerkandidat);
Answer trump = new Answer("Trump", -666, kanzlerkandidat);
Answer haustier = new Answer("Mein Haustier", 1000, kanzlerkandidat);
Answer nachbar = new Answer("Mein Nachbar", 10, kanzlerkandidat);
Vote vote1 = new Vote("", kanzlerkandidat, haustier, "");
Dao pollDao = Database.getInstance().getDaoForClass(Poll.class.getName());
haustier.getVotes().add(vote1);
kanzlerkandidat.getAnswers().add(merkel);
kanzlerkandidat.getAnswers().add(trump);
kanzlerkandidat.getAnswers().add(haustier);
kanzlerkandidat.getAnswers().add(nachbar);
bundestagswahl.getQuestions().add(kanzlerkandidat);
this.polls.add(poll1);
this.polls.add(bundestagswahl);
pollDao.create(poll1);
pollDao.create(bundestagswahl);
for (Poll p : this.polls) {
if (p.getState() == PollState.OPEN) {
this.activePoll = p;
try {
spawnWebServer(activePoll);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
// ListView (Left side)
SplitPane rootSplit = FXMLLoader.load(this.getClass().getResource("/client/client.fxml"));
GridPane pollListView = FXMLLoader.load(this.getClass().getResource("/client/pollListView.fxml"));
this.pollList = (ListView<Poll>) pollListView.lookup("#pollList");
this.pollList.setCellFactory((ListView<Poll> param) ->
{
return new PollListCell();
});
for (Poll p : this.polls) {
this.pollList.getItems().add(p);
}
this.pollList.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Poll> observable, Poll oldValue, Poll newValue) ->
{
if (newValue != null)
Client.this.setPoll(newValue);
});
rootSplit.getItems().add(pollListView);
rootSplit.setDividerPositions(1d / 5d);
// PollView (Right side)
ScrollPane pollDetailScroller = new ScrollPane();
pollDetailScroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
pollDetailScroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
pollDetailScroller.setFitToWidth(true);
pollDetailScroller.setFitToHeight(true);
GridPane pollDetail = (GridPane) FXMLLoader.load(this.getClass().getResource("/client/pollView.fxml"));
this.titleTxF = (TextField) pollDetail.lookup("#titleTxF");
this.titleTxF.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) ->
{
if (Client.this.poll != null
&& !Client.this.poll.getTitle().equals(newValue)) {
Client.this.poll.setTitle(newValue);
Client.this.pollList.refresh();
}
});
this.pollRemoveBtn = (Button) pollDetail.lookup("#pollRemoveBtn");
this.pollRemoveBtn.setOnAction((ActionEvent ev) ->
{
ConfirmDialog.show("Umfrage wirklich entfernen?", (boolean confirmed) ->
{
if (confirmed) {
// TODO Umfrage entfernen!
}
});
});
this.descTxF = (TextArea) pollDetail.lookup("#descTxF");
this.descTxF.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) ->
{
if (Client.this.poll != null
&& !Client.this.poll.getDescription().equals(newValue))
Client.this.poll.setDescription(newValue);
});
this.createdDateTxF = (TextField) pollDetail.lookup("#createdDateTxF");
this.createdTimeTxF = (TextField) pollDetail.lookup("#createdTimeTxF");
this.stateCbo = (ComboBox<PollState>) pollDetail.lookup("#stateCbo");
this.stateCbo.getItems().addAll(PollState.NEW, PollState.OPEN, PollState.CLOSED);
this.stateCbo.setCellFactory((ListView<PollState> param) ->
{
return new PollStateListCell();
});
this.stateCbo.setButtonCell(new PollStateListCell());
this.openBtn = (Button) pollDetail.lookup("#openBtn");
this.openBtn.setOnAction((ActionEvent event) ->
{
this.poll.setState(PollState.OPEN);
this.activePoll = this.poll;
this.openBtn.setVisible(false);
this.closeBtn.setVisible(true);
this.stateCbo.setValue(this.poll.getState());
this.enableControls();
try {
spawnWebServer(activePoll);
} catch (Exception e) {
e.printStackTrace();
}
});
this.closeBtn = (Button) pollDetail.lookup("#closeBtn");
this.closeBtn.setOnAction((ActionEvent event) ->
{
this.poll.setState(PollState.CLOSED);
this.activePoll = null;
this.closeBtn.setVisible(false);
this.openBtn.setVisible(true);
this.stateCbo.setValue(this.poll.getState());
this.enableControls();
try {
spawnWebServer(activePoll);
} catch (Exception e) {
e.printStackTrace();
}
});
this.resultsBtn = (Button) pollDetail.lookup("#resultsBtn");
this.resultsBtn.setOnAction((ActionEvent event) ->
{
//TODO View Results
for (Question question : Client.this.poll.questions) {
for (Answer answer : question.getAnswers()) {
System.out.println(answer.getValue());
}
}
});
this.questionsAccordion = (Accordion) pollDetail.lookup("#questionsAccordion");
this.questionsAddBtn = (Button) pollDetail.lookup("#questionsAddBtn");
this.questionsAddBtn.setOnAction((ActionEvent event) ->
{
Question newQuestion = new Question("", true, QuestionType.SINGLE, this.poll);
this.poll.getQuestions().add(newQuestion);
QuestionView.setQuestionView(this.questionsAccordion, newQuestion, this.activePoll != null && this.activePoll == this.poll);
});
pollDetailScroller.setContent(pollDetail);
rootSplit.getItems().add(pollDetailScroller);
// Stage size and finally show
this.pollList.getSelectionModel().selectFirst();
primaryStage.setScene(new Scene(rootSplit));
primaryStage.sizeToScene();
primaryStage.show();
}
public void setPoll(Poll newPoll) {
this.poll = newPoll;
this.titleTxF.setText(this.poll.getTitle());
this.descTxF.setText(this.poll.getDescription());
SimpleDateFormat outputFormatDate = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat outputFormatTime = new SimpleDateFormat("HH:mm:ss");
this.createdDateTxF.setText(outputFormatDate.format(this.poll.getCreated()));
this.createdTimeTxF.setText(outputFormatTime.format(this.poll.getCreated()));
this.stateCbo.setValue(this.poll.getState());
this.openBtn.setVisible(this.poll.getState() == PollState.NEW || this.poll.getState() == PollState.CLOSED);
this.closeBtn.setVisible(this.poll.getState() == PollState.OPEN);
this.enableControls();
boolean disabled = this.activePoll != null && this.activePoll == this.poll;
this.questionsAccordion.getPanes().clear();
for (Question item : this.poll.getQuestions())
QuestionView.setQuestionView(this.questionsAccordion, item, disabled);
}
public void enableControls() {
boolean disable = this.activePoll != null && this.activePoll == this.poll;
this.titleTxF.setDisable(disable);
this.descTxF.setDisable(disable);
this.createdDateTxF.setDisable(disable);
this.createdTimeTxF.setDisable(disable);
this.openBtn.setDisable(this.activePoll != null);
this.closeBtn.setDisable(!disable);
//TODO Enable / disable Accordion
this.questionsAddBtn.setDisable(disable);
}
private void spawnWebServer(Poll poll) throws Exception {
Frontend.getInstance(poll);
}
private void spawnDatabase() throws Exception {
Database.getInstance();
}
} | src/main/java/de/lebk/jwebpoll/client/Client.java | package de.lebk.jwebpoll.client;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.Where;
import de.lebk.jwebpoll.Database;
import de.lebk.jwebpoll.Frontend;
import de.lebk.jwebpoll.data.*;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
public class Client extends Application {
//- Main -
public static void main(String[] args) {
Client.launch(args);
}
//- Data -
private List<Poll> polls = new ArrayList<>();
//poll selected in client window
private Poll poll;
//poll running on serve
private Poll activePoll;
//- View -
private ListView<Poll> pollList;
private TextField titleTxF;
private Button pollRemoveBtn;
private TextArea descTxF;
private TextField createdDateTxF, createdTimeTxF;
private ComboBox<PollState> stateCbo;
private Button openBtn, closeBtn, resultsBtn;
private Accordion questionsAccordion;
private Button questionsAddBtn;
@Override
public void start(Stage primaryStage) throws Exception {
//Title
primaryStage.setTitle("JWebPoll");
//Set on close action
primaryStage.setOnCloseRequest((WindowEvent we) ->
{
try {
Frontend.kill();
} catch (Exception e) {
e.printStackTrace();
}
});
//start DB
spawnDatabase();
//Default Poll: new poll
//Poll newPoll = new Poll("Neue Umfrage", "", PollState.NEW);
//this.polls.add(newPoll);
//Example polls (to be deleted in future)
Poll poll1 = new Poll("1. Umfrage", "Eine Beschreibung", PollState.NEW);
Poll poll2 = new Poll("Bundestagswahl", "Kurze Beschreibung", PollState.NEW);
Question question1 = new Question("title", true, QuestionType.SINGLE, poll2);
Answer answer1 = new Answer("Ja", 1, question1);
Answer answer2 = new Answer("Nein", 2, question1);
Vote vote1 = new Vote("", question1, answer1, "");
Dao pollDao = Database.getInstance().getDaoForClass(Poll.class.getName());
//pollDao.queryBuilder().where().eq("title", "Bundestagswahl").queryForFirst();
answer1.getVotes().add(vote1);
question1.getAnswers().add(answer1);
question1.getAnswers().add(answer2);
poll2.getQuestions().add(question1);
this.polls.add(poll1);
this.polls.add(poll2);
pollDao.create(poll1);
pollDao.create(poll2);
for (Poll p : this.polls) {
if (p.getState() == PollState.OPEN) {
this.activePoll = p;
try {
spawnWebServer(activePoll);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
//ListView (Left side)
SplitPane rootSplit = FXMLLoader.load(this.getClass().getResource("/client/client.fxml"));
GridPane pollListView = FXMLLoader.load(this.getClass().getResource("/client/pollListView.fxml"));
this.pollList = (ListView<Poll>) pollListView.lookup("#pollList");
this.pollList.setCellFactory((ListView<Poll> param) ->
{
return new PollListCell();
});
for (Poll p : this.polls) {
this.pollList.getItems().add(p);
}
this.pollList.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Poll> observable, Poll oldValue, Poll newValue) ->
{
if (newValue != null)
Client.this.setPoll(newValue);
});
rootSplit.getItems().add(pollListView);
rootSplit.setDividerPositions(1d / 5d);
//PollView (Right side)
ScrollPane pollDetailScroller = new ScrollPane();
pollDetailScroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
pollDetailScroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
pollDetailScroller.setFitToWidth(true);
pollDetailScroller.setFitToHeight(true);
GridPane pollDetail = (GridPane) FXMLLoader.load(this.getClass().getResource("/client/pollView.fxml"));
this.titleTxF = (TextField) pollDetail.lookup("#titleTxF");
this.titleTxF.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) ->
{
if (Client.this.poll != null
&& !Client.this.poll.getTitle().equals(newValue)) {
Client.this.poll.setTitle(newValue);
Client.this.pollList.refresh();
}
});
this.pollRemoveBtn = (Button) pollDetail.lookup("#pollRemoveBtn");
this.pollRemoveBtn.setOnAction((ActionEvent ev) ->
{
ConfirmDialog.show("Umfrage wirklich entfernen?", (boolean confirmed) ->
{
if (confirmed) {
// TODO Umfrage entfernen!
}
});
});
this.descTxF = (TextArea) pollDetail.lookup("#descTxF");
this.descTxF.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) ->
{
if (Client.this.poll != null
&& !Client.this.poll.getDescription().equals(newValue))
Client.this.poll.setDescription(newValue);
});
this.createdDateTxF = (TextField) pollDetail.lookup("#createdDateTxF");
this.createdTimeTxF = (TextField) pollDetail.lookup("#createdTimeTxF");
this.stateCbo = (ComboBox<PollState>) pollDetail.lookup("#stateCbo");
this.stateCbo.getItems().addAll(PollState.NEW, PollState.OPEN, PollState.CLOSED);
this.stateCbo.setCellFactory((ListView<PollState> param) ->
{
return new PollStateListCell();
});
this.stateCbo.setButtonCell(new PollStateListCell());
this.openBtn = (Button) pollDetail.lookup("#openBtn");
this.openBtn.setOnAction((ActionEvent event) ->
{
this.poll.setState(PollState.OPEN);
this.activePoll = this.poll;
this.openBtn.setVisible(false);
this.closeBtn.setVisible(true);
this.stateCbo.setValue(this.poll.getState());
this.enableControls();
try {
spawnWebServer(activePoll);
} catch (Exception e) {
e.printStackTrace();
}
});
this.closeBtn = (Button) pollDetail.lookup("#closeBtn");
this.closeBtn.setOnAction((ActionEvent event) ->
{
this.poll.setState(PollState.CLOSED);
this.activePoll = null;
this.closeBtn.setVisible(false);
this.openBtn.setVisible(true);
this.stateCbo.setValue(this.poll.getState());
this.enableControls();
try {
spawnWebServer(activePoll);
} catch (Exception e) {
e.printStackTrace();
}
});
this.resultsBtn = (Button) pollDetail.lookup("#resultsBtn");
this.resultsBtn.setOnAction((ActionEvent event) ->
{
//TODO View Results
for (Question question : Client.this.poll.questions) {
for (Answer answer : question.getAnswers()) {
System.out.println(answer.getValue());
}
}
});
this.questionsAccordion = (Accordion) pollDetail.lookup("#questionsAccordion");
this.questionsAddBtn = (Button) pollDetail.lookup("#questionsAddBtn");
this.questionsAddBtn.setOnAction((ActionEvent event) ->
{
Question newQuestion = new Question("", true, QuestionType.SINGLE, this.poll);
this.poll.getQuestions().add(newQuestion);
QuestionView.setQuestionView(this.questionsAccordion, newQuestion, this.activePoll != null && this.activePoll == this.poll);
});
pollDetailScroller.setContent(pollDetail);
rootSplit.getItems().add(pollDetailScroller);
//Stage size and finally show
this.pollList.getSelectionModel().selectFirst();
primaryStage.setScene(new Scene(rootSplit, 800, 600));
primaryStage.show();
}
public void setPoll(Poll newPoll) {
this.poll = newPoll;
this.titleTxF.setText(this.poll.getTitle());
this.descTxF.setText(this.poll.getDescription());
SimpleDateFormat outputFormatDate = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat outputFormatTime = new SimpleDateFormat("HH:mm:ss");
this.createdDateTxF.setText(outputFormatDate.format(this.poll.getCreated()));
this.createdTimeTxF.setText(outputFormatTime.format(this.poll.getCreated()));
this.stateCbo.setValue(this.poll.getState());
this.openBtn.setVisible(this.poll.getState() == PollState.NEW || this.poll.getState() == PollState.CLOSED);
this.closeBtn.setVisible(this.poll.getState() == PollState.OPEN);
this.enableControls();
boolean disabled = this.activePoll != null && this.activePoll == this.poll;
this.questionsAccordion.getPanes().clear();
for (Question item : this.poll.getQuestions())
QuestionView.setQuestionView(this.questionsAccordion, item, disabled);
}
public void enableControls() {
boolean disable = this.activePoll != null && this.activePoll == this.poll;
this.titleTxF.setDisable(disable);
this.descTxF.setDisable(disable);
this.createdDateTxF.setDisable(disable);
this.createdTimeTxF.setDisable(disable);
this.openBtn.setDisable(this.activePoll != null);
this.closeBtn.setDisable(!disable);
//TODO Enable / disable Accordion
this.questionsAddBtn.setDisable(disable);
}
private void spawnWebServer(Poll poll) throws Exception {
Frontend.getInstance(poll);
}
private void spawnDatabase() throws Exception {
Database.getInstance();
}
} | Example poll
| src/main/java/de/lebk/jwebpoll/client/Client.java | Example poll | <ide><path>rc/main/java/de/lebk/jwebpoll/client/Client.java
<ide> package de.lebk.jwebpoll.client;
<ide>
<ide> import com.j256.ormlite.dao.Dao;
<del>import com.j256.ormlite.stmt.Where;
<ide> import de.lebk.jwebpoll.Database;
<ide> import de.lebk.jwebpoll.Frontend;
<ide> import de.lebk.jwebpoll.data.*;
<ide>
<ide> @Override
<ide> public void start(Stage primaryStage) throws Exception {
<del> //Title
<ide> primaryStage.setTitle("JWebPoll");
<del> //Set on close action
<ide> primaryStage.setOnCloseRequest((WindowEvent we) ->
<ide> {
<ide> try {
<ide> e.printStackTrace();
<ide> }
<ide> });
<del> //start DB
<add>
<add> // Start DB
<ide> spawnDatabase();
<del> //Default Poll: new poll
<del> //Poll newPoll = new Poll("Neue Umfrage", "", PollState.NEW);
<del> //this.polls.add(newPoll);
<del>
<del> //Example polls (to be deleted in future)
<add>
<add> // Example polls (to be deleted in future)
<ide> Poll poll1 = new Poll("1. Umfrage", "Eine Beschreibung", PollState.NEW);
<del> Poll poll2 = new Poll("Bundestagswahl", "Kurze Beschreibung", PollState.NEW);
<del>
<del> Question question1 = new Question("title", true, QuestionType.SINGLE, poll2);
<del>
<del> Answer answer1 = new Answer("Ja", 1, question1);
<del> Answer answer2 = new Answer("Nein", 2, question1);
<del>
<del> Vote vote1 = new Vote("", question1, answer1, "");
<add>
<add> Poll bundestagswahl = new Poll("Bundestagswahl", "Kurze Beschreibung", PollState.NEW);
<add> Question kanzlerkandidat = new Question("Wer ist ihr Kanzlerkandidat?", true, QuestionType.SINGLE, bundestagswahl);
<add> Answer merkel = new Answer("Merkel", -100, kanzlerkandidat);
<add> Answer trump = new Answer("Trump", -666, kanzlerkandidat);
<add> Answer haustier = new Answer("Mein Haustier", 1000, kanzlerkandidat);
<add> Answer nachbar = new Answer("Mein Nachbar", 10, kanzlerkandidat);
<add> Vote vote1 = new Vote("", kanzlerkandidat, haustier, "");
<ide>
<ide> Dao pollDao = Database.getInstance().getDaoForClass(Poll.class.getName());
<del> //pollDao.queryBuilder().where().eq("title", "Bundestagswahl").queryForFirst();
<del> answer1.getVotes().add(vote1);
<del> question1.getAnswers().add(answer1);
<del> question1.getAnswers().add(answer2);
<del> poll2.getQuestions().add(question1);
<add> haustier.getVotes().add(vote1);
<add> kanzlerkandidat.getAnswers().add(merkel);
<add> kanzlerkandidat.getAnswers().add(trump);
<add> kanzlerkandidat.getAnswers().add(haustier);
<add> kanzlerkandidat.getAnswers().add(nachbar);
<add> bundestagswahl.getQuestions().add(kanzlerkandidat);
<ide> this.polls.add(poll1);
<del> this.polls.add(poll2);
<add> this.polls.add(bundestagswahl);
<ide> pollDao.create(poll1);
<del> pollDao.create(poll2);
<add> pollDao.create(bundestagswahl);
<ide>
<ide> for (Poll p : this.polls) {
<ide> if (p.getState() == PollState.OPEN) {
<ide> }
<ide> }
<ide>
<del> //ListView (Left side)
<add> // ListView (Left side)
<ide> SplitPane rootSplit = FXMLLoader.load(this.getClass().getResource("/client/client.fxml"));
<ide> GridPane pollListView = FXMLLoader.load(this.getClass().getResource("/client/pollListView.fxml"));
<ide> this.pollList = (ListView<Poll>) pollListView.lookup("#pollList");
<ide> rootSplit.getItems().add(pollListView);
<ide> rootSplit.setDividerPositions(1d / 5d);
<ide>
<del> //PollView (Right side)
<add> // PollView (Right side)
<ide> ScrollPane pollDetailScroller = new ScrollPane();
<ide> pollDetailScroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
<ide> pollDetailScroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
<ide> pollDetailScroller.setContent(pollDetail);
<ide> rootSplit.getItems().add(pollDetailScroller);
<ide>
<del> //Stage size and finally show
<add> // Stage size and finally show
<ide> this.pollList.getSelectionModel().selectFirst();
<del> primaryStage.setScene(new Scene(rootSplit, 800, 600));
<add> primaryStage.setScene(new Scene(rootSplit));
<add> primaryStage.sizeToScene();
<ide> primaryStage.show();
<ide> }
<ide> |
|
Java | apache-2.0 | 79424e50043a12562d188be075b3bb20542b5cb5 | 0 | JackQueen/JackQueenWeather | package com.jackqueenweather.android;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.jackqueenweather.android.databinding.ForecastBinding;
import com.jackqueenweather.android.databinding.WeatherBinding;
import com.jackqueenweather.android.model_gson.Weather;
import com.jackqueenweather.android.util.GsonUtil;
import com.jackqueenweather.android.util.HttpUtil;
import com.jackqueenweather.android.util.ImageUtil;
import com.jackqueenweather.android.util.SPUtil;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.RunnableFuture;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
@BindView(R.id.ll_forecast_layout)
LinearLayout llForecastLayout;
@BindView(R.id.scrollv_weather_layout)
ScrollView scrollvWeatherLayout;
@BindView(R.id.iv_bg_pic)
ImageView ivBgPic;
private WeatherBinding weatherBinding;
private Weather.HeWeatherBean heWeatherBean;
private Unbinder unbinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_weather);
initImmerseBar();
weatherBinding = DataBindingUtil.setContentView(this, R.layout.activity_weather);
unbinder = ButterKnife.bind(this);
initWeatherInfo();
initBackgroundPic();
}
private void initImmerseBar() {
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
// "|"或运算
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);//透明色
}
}
private void initBackgroundPic() {
String backgPic = SPUtil.getBackgPic(WeatherActivity.this);
if (backgPic != null) {
ImageUtil.HelloImage(WeatherActivity.this,backgPic,ivBgPic);
}else {
loadingBackPic();
}
}
private void loadingBackPic() {
HttpUtil.getRequest(Constant.PIC_HOST, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String backgroundPic = response.body().string();
SPUtil.saveBackPic(WeatherActivity.this,backgroundPic);
runOnUiThread(new Runnable() {
@Override
public void run() {
ImageUtil.HelloImage(WeatherActivity.this, backgroundPic,ivBgPic);
}
});
}
});
}
private void initWeatherInfo() {
String weatherInfo = SPUtil.getWeather(WeatherActivity.this);
if (weatherInfo != null) {
//有缓存则直接解析
Weather weather = GsonUtil.parseWeatherFrom(weatherInfo);
showWeatherInfo(weather);
} else {
//无缓存到服务器查询
String weatherId = getIntent().getStringExtra("weather_id");
scrollvWeatherLayout.setVisibility(View.INVISIBLE);
requesWeather(weatherId);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
/**
* 根据地区的天气id请求天气信息
*/
private void requesWeather(final String weatherId) {
String weatherUrl = Constant.WEATHER_HOST + weatherId + Constant.WEATHER_KEY;
HttpUtil.getRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = GsonUtil.parseWeatherFrom(responseText);
//在主线程保存天气信息到本地共享参数
runOnUiThread(new Runnable() {
@Override
public void run() {
//如果请求成功
if (weather != null && "ok".equals(weather.getHeWeather().get(0).getStatus())) {
SPUtil.saveWeather(WeatherActivity.this, responseText);
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
}
});
}
});
loadingBackPic();
}
private void showWeatherInfo(Weather weather) {
heWeatherBean = weather.getHeWeather().get(0);
Weather.HeWeatherBean.Now now = heWeatherBean.getNow();
Weather.HeWeatherBean.Basic basic = heWeatherBean.getBasic();
Weather.HeWeatherBean.Suggestion suggestion = heWeatherBean.getSuggestion();
Weather.HeWeatherBean.AQI aqi = heWeatherBean.getAqi();
List<Weather.HeWeatherBean.DailyForecast> daily_forecast = heWeatherBean.getDaily_forecast();
weatherBinding.setNow(now);
weatherBinding.setBasic(basic);
weatherBinding.setAqi(aqi);
weatherBinding.setSuggestion(suggestion);
llForecastLayout.removeAllViews();
for (int i = 0; i < daily_forecast.size(); i++) {
View view = LayoutInflater.from(WeatherActivity.this).inflate(R.layout.forecast_item, llForecastLayout, false);
Weather.HeWeatherBean.DailyForecast forecast = daily_forecast.get(i);
ForecastBinding bind = DataBindingUtil.bind(view);
llForecastLayout.addView(view);
bind.setForecast(forecast);
}
scrollvWeatherLayout.setVisibility(View.VISIBLE);
}
}
| app/src/main/java/com/jackqueenweather/android/WeatherActivity.java | package com.jackqueenweather.android;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import com.jackqueenweather.android.databinding.ForecastBinding;
import com.jackqueenweather.android.databinding.WeatherBinding;
import com.jackqueenweather.android.model_gson.Weather;
import com.jackqueenweather.android.util.GsonUtil;
import com.jackqueenweather.android.util.HttpUtil;
import com.jackqueenweather.android.util.SPUtil;
import java.io.IOException;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
@BindView(R.id.ll_forecast_layout)
LinearLayout llForecastLayout;
@BindView(R.id.scrollv_weather_layout)
ScrollView scrollvWeatherLayout;
private WeatherBinding weatherBinding;
private Weather.HeWeatherBean heWeatherBean;
private Unbinder unbinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_weather);
weatherBinding = DataBindingUtil.setContentView(this, R.layout.activity_weather);
unbinder = ButterKnife.bind(this);
String weatherInfo = SPUtil.getWeather(WeatherActivity.this);
if (weatherInfo != null) {
//有缓存则直接解析
Weather weather = GsonUtil.parseWeatherFrom(weatherInfo);
showWeatherInfo(weather);
} else {
//无缓存到服务器查询
String weatherId = getIntent().getStringExtra("weather_id");
scrollvWeatherLayout.setVisibility(View.INVISIBLE);
requesWeather(weatherId);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
/**
* 根据地区的天气id请求天气信息
*/
private void requesWeather(final String weatherId) {
String weatherUrl = Constant.WEATHER_HOST + weatherId + Constant.WEATHER_KEY;
HttpUtil.getRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = GsonUtil.parseWeatherFrom(responseText);
//在主线程保存天气信息到本地共享参数
runOnUiThread(new Runnable() {
@Override
public void run() {
//如果请求成功
if (weather != null && "ok".equals(weather.getHeWeather().get(0).getStatus())) {
SPUtil.saveWeather(WeatherActivity.this, responseText);
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void showWeatherInfo(Weather weather) {
heWeatherBean = weather.getHeWeather().get(0);
Weather.HeWeatherBean.Now now = heWeatherBean.getNow();
Weather.HeWeatherBean.Basic basic = heWeatherBean.getBasic();
Weather.HeWeatherBean.Suggestion suggestion = heWeatherBean.getSuggestion();
Weather.HeWeatherBean.AQI aqi = heWeatherBean.getAqi();
List<Weather.HeWeatherBean.DailyForecast> daily_forecast = heWeatherBean.getDaily_forecast();
weatherBinding.setNow(now);
weatherBinding.setBasic(basic);
weatherBinding.setAqi(aqi);
weatherBinding.setSuggestion(suggestion);
llForecastLayout.removeAllViews();
for (int i = 0; i < daily_forecast.size(); i++) {
View view = LayoutInflater.from(WeatherActivity.this).inflate(R.layout.forecast_item, llForecastLayout, false);
Weather.HeWeatherBean.DailyForecast forecast = daily_forecast.get(i);
ForecastBinding bind = DataBindingUtil.bind(view);
llForecastLayout.addView(view);
bind.setForecast(forecast);
}
scrollvWeatherLayout.setVisibility(View.VISIBLE);
}
}
| 5.0版本更新沉浸式效果
| app/src/main/java/com/jackqueenweather/android/WeatherActivity.java | 5.0版本更新沉浸式效果 | <ide><path>pp/src/main/java/com/jackqueenweather/android/WeatherActivity.java
<ide> package com.jackqueenweather.android;
<ide>
<ide> import android.databinding.DataBindingUtil;
<del>import android.databinding.ViewDataBinding;
<add>import android.graphics.Color;
<add>import android.os.Build;
<ide> import android.os.Bundle;
<ide> import android.support.v7.app.AppCompatActivity;
<ide> import android.view.LayoutInflater;
<ide> import android.view.View;
<add>import android.widget.ImageView;
<ide> import android.widget.LinearLayout;
<ide> import android.widget.ScrollView;
<ide> import android.widget.Toast;
<ide>
<add>import com.bumptech.glide.Glide;
<ide> import com.jackqueenweather.android.databinding.ForecastBinding;
<ide> import com.jackqueenweather.android.databinding.WeatherBinding;
<ide> import com.jackqueenweather.android.model_gson.Weather;
<ide> import com.jackqueenweather.android.util.GsonUtil;
<ide> import com.jackqueenweather.android.util.HttpUtil;
<add>import com.jackqueenweather.android.util.ImageUtil;
<ide> import com.jackqueenweather.android.util.SPUtil;
<ide>
<ide> import java.io.IOException;
<ide> import java.util.List;
<add>import java.util.concurrent.RunnableFuture;
<ide>
<ide> import butterknife.BindView;
<ide> import butterknife.ButterKnife;
<ide> LinearLayout llForecastLayout;
<ide> @BindView(R.id.scrollv_weather_layout)
<ide> ScrollView scrollvWeatherLayout;
<add> @BindView(R.id.iv_bg_pic)
<add> ImageView ivBgPic;
<ide> private WeatherBinding weatherBinding;
<ide> private Weather.HeWeatherBean heWeatherBean;
<ide> private Unbinder unbinder;
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide> // setContentView(R.layout.activity_weather);
<add> initImmerseBar();
<ide> weatherBinding = DataBindingUtil.setContentView(this, R.layout.activity_weather);
<ide> unbinder = ButterKnife.bind(this);
<add> initWeatherInfo();
<add> initBackgroundPic();
<add> }
<add>
<add> private void initImmerseBar() {
<add> if (Build.VERSION.SDK_INT >= 21) {
<add> View decorView = getWindow().getDecorView();
<add> // "|"或运算
<add> decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
<add> getWindow().setStatusBarColor(Color.TRANSPARENT);//透明色
<add> }
<add> }
<add>
<add> private void initBackgroundPic() {
<add> String backgPic = SPUtil.getBackgPic(WeatherActivity.this);
<add> if (backgPic != null) {
<add> ImageUtil.HelloImage(WeatherActivity.this,backgPic,ivBgPic);
<add> }else {
<add> loadingBackPic();
<add> }
<add> }
<add>
<add> private void loadingBackPic() {
<add> HttpUtil.getRequest(Constant.PIC_HOST, new Callback() {
<add> @Override
<add> public void onFailure(Call call, IOException e) {
<add>
<add> }
<add>
<add> @Override
<add> public void onResponse(Call call, Response response) throws IOException {
<add> final String backgroundPic = response.body().string();
<add> SPUtil.saveBackPic(WeatherActivity.this,backgroundPic);
<add> runOnUiThread(new Runnable() {
<add> @Override
<add> public void run() {
<add> ImageUtil.HelloImage(WeatherActivity.this, backgroundPic,ivBgPic);
<add> }
<add> });
<add> }
<add> });
<add> }
<add>
<add> private void initWeatherInfo() {
<ide> String weatherInfo = SPUtil.getWeather(WeatherActivity.this);
<ide> if (weatherInfo != null) {
<ide> //有缓存则直接解析
<ide> });
<ide> }
<ide> });
<add> loadingBackPic();
<ide> }
<ide>
<ide> private void showWeatherInfo(Weather weather) { |
|
Java | apache-2.0 | b01f859189fd061552374c405fdf931ef9fe2059 | 0 | foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2 | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.dao.index;
import foam.core.FObject;
import foam.core.PropertyInfo;
import foam.dao.index.TreeNode;
public class TreeLookupFindPlan implements FindPlan {
protected PropertyInfo prop_;
protected long size_;
public TreeLookupFindPlan(PropertyInfo prop, long size) {
prop_ = prop;
size_ = size;
}
public long cost() {
return ((Double) Math.log(Long.valueOf(size_).doubleValue())).longValue();
}
public FObject find(Object state, Object key) {
if ( state != null && state instanceof TreeNode ) {
return ( (TreeNode) state ).get(( (TreeNode) state ), key, prop_) == null ? null : (FObject) ( (TreeNode) state ).get(( (TreeNode) state ), key, prop_).value;
}
return null;
}
}
| src/foam/dao/index/TreeLookupFindPlan.java | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.dao.index;
import foam.core.FObject;
import foam.core.PropertyInfo;
import foam.dao.index.TreeNode;
public class TreeLookupFindPlan implements FindPlan {
protected PropertyInfo prop_;
protected long size_;
public TreeLookupFindPlan(PropertyInfo prop, long size) {
prop_ = prop;
size_ = size;
}
public long cost() {
return ((Double) Math.log(Long.valueOf(size_).doubleValue())).longValue();
}
public FObject find(Object state, Object key) {
if ( state != null && state instanceof TreeNode ) {
return (FObject)((TreeNode) state).get(((TreeNode) state), key, prop_);
}
return null;
}
}
| 1.fix find() Nullpointer bug
| src/foam/dao/index/TreeLookupFindPlan.java | 1.fix find() Nullpointer bug | <ide><path>rc/foam/dao/index/TreeLookupFindPlan.java
<ide>
<ide> public FObject find(Object state, Object key) {
<ide> if ( state != null && state instanceof TreeNode ) {
<del> return (FObject)((TreeNode) state).get(((TreeNode) state), key, prop_);
<add> return ( (TreeNode) state ).get(( (TreeNode) state ), key, prop_) == null ? null : (FObject) ( (TreeNode) state ).get(( (TreeNode) state ), key, prop_).value;
<ide> }
<ide>
<ide> return null; |
|
Java | apache-2.0 | 43a900f866b28031423e8419c4258e7b422a1e2c | 0 | jexp/idea2,blademainer/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,signed/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,signed/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,supersven/intellij-community,retomerz/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,supersven/intellij-community,diorcety/intellij-community,jagguli/intellij-community,dslomov/intellij-community,semonte/intellij-community,robovm/robovm-studio,da1z/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,joewalnes/idea-community,amith01994/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ibinti/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,kool79/intellij-community,joewalnes/idea-community,izonder/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,caot/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,fitermay/intellij-community,semonte/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,izonder/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,caot/intellij-community,robovm/robovm-studio,retomerz/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,kool79/intellij-community,slisson/intellij-community,wreckJ/intellij-community,supersven/intellij-community,izonder/intellij-community,blademainer/intellij-community,clumsy/intellij-community,kool79/intellij-community,blademainer/intellij-community,izonder/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ernestp/consulo,asedunov/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,ryano144/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,slisson/intellij-community,robovm/robovm-studio,hurricup/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,robovm/robovm-studio,vladmm/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,caot/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,da1z/intellij-community,consulo/consulo,holmes/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,fnouama/intellij-community,retomerz/intellij-community,holmes/intellij-community,retomerz/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,caot/intellij-community,FHannes/intellij-community,diorcety/intellij-community,retomerz/intellij-community,jagguli/intellij-community,da1z/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,holmes/intellij-community,slisson/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,caot/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,supersven/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,supersven/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,dslomov/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,slisson/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,ibinti/intellij-community,consulo/consulo,nicolargo/intellij-community,holmes/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,izonder/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,signed/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,fitermay/intellij-community,amith01994/intellij-community,signed/intellij-community,diorcety/intellij-community,semonte/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,samthor/intellij-community,fnouama/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,FHannes/intellij-community,semonte/intellij-community,jexp/idea2,ol-loginov/intellij-community,xfournet/intellij-community,samthor/intellij-community,samthor/intellij-community,gnuhub/intellij-community,caot/intellij-community,jexp/idea2,apixandru/intellij-community,slisson/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,signed/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,allotria/intellij-community,kdwink/intellij-community,allotria/intellij-community,samthor/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,jexp/idea2,pwoodworth/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,dslomov/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,robovm/robovm-studio,apixandru/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ibinti/intellij-community,adedayo/intellij-community,adedayo/intellij-community,petteyg/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,samthor/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,amith01994/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,signed/intellij-community,xfournet/intellij-community,petteyg/intellij-community,da1z/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,signed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,samthor/intellij-community,ryano144/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ernestp/consulo,dslomov/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,kdwink/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,samthor/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,holmes/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,jexp/idea2,jagguli/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,FHannes/intellij-community,FHannes/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,clumsy/intellij-community,consulo/consulo,jexp/idea2,muntasirsyed/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,da1z/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,fitermay/intellij-community,jagguli/intellij-community,caot/intellij-community,izonder/intellij-community,amith01994/intellij-community,robovm/robovm-studio,petteyg/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,jexp/idea2,TangHao1987/intellij-community,semonte/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,kdwink/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,slisson/intellij-community,consulo/consulo,suncycheng/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,caot/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,ernestp/consulo,adedayo/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ahb0327/intellij-community,holmes/intellij-community,caot/intellij-community,Distrotech/intellij-community,izonder/intellij-community,samthor/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,allotria/intellij-community,semonte/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,holmes/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,da1z/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,robovm/robovm-studio,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,signed/intellij-community,supersven/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,kool79/intellij-community,adedayo/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,consulo/consulo,vladmm/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,allotria/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,semonte/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,semonte/intellij-community,apixandru/intellij-community,signed/intellij-community,amith01994/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,allotria/intellij-community,kdwink/intellij-community,asedunov/intellij-community,clumsy/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,allotria/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,jexp/idea2,idea4bsd/idea4bsd,MER-GROUP/intellij-community,retomerz/intellij-community,da1z/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,adedayo/intellij-community,petteyg/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,slisson/intellij-community,signed/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,vladmm/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,robovm/robovm-studio,ryano144/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fnouama/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,caot/intellij-community,adedayo/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,xfournet/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,clumsy/intellij-community,amith01994/intellij-community,da1z/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,vladmm/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,samthor/intellij-community,joewalnes/idea-community,ryano144/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,izonder/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,clumsy/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,ernestp/consulo,orekyuu/intellij-community,robovm/robovm-studio,caot/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,semonte/intellij-community,blademainer/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,izonder/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,semonte/intellij-community,amith01994/intellij-community,ibinti/intellij-community | package com.intellij.openapi.actionSystem.impl;
import com.intellij.CommonBundle;
import com.intellij.diagnostic.PluginException;
import com.intellij.ide.ActivityTracker;
import com.intellij.ide.DataManager;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.idea.IdeaLogger;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.util.ArrayUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import gnu.trove.TObjectIntHashMap;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.picocontainer.defaults.ConstructorInjectionComponentAdapter;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Constructor;
import java.util.*;
public final class ActionManagerImpl extends ActionManagerEx implements JDOMExternalizable, ApplicationComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.actionSystem.impl.ActionManagerImpl");
private static final int TIMER_DELAY = 500;
private static final int UPDATE_DELAY_AFTER_TYPING = 500;
private final Object myLock = new Object();
private final THashMap<String,Object> myId2Action;
private final THashMap<PluginId, THashSet<String>> myPlugin2Id;
private final TObjectIntHashMap<String> myId2Index;
private final THashMap<Object,String> myAction2Id;
private final ArrayList<String> myNotRegisteredInternalActionIds;
private MyTimer myTimer;
private int myRegisteredActionsCount;
private final ArrayList<AnActionListener> myActionListeners;
private AnActionListener[] myCachedActionListeners;
private String myLastPreformedActionId;
private final KeymapManager myKeymapManager;
private final DataManager myDataManager;
private String myPrevPerformedActionId;
private long myLastTimeEditorWasTypedIn = 0;
@NonNls public static final String ACTION_ELEMENT_NAME = "action";
@NonNls public static final String GROUP_ELEMENT_NAME = "group";
@NonNls public static final String ACTIONS_ELEMENT_NAME = "actions";
@NonNls public static final String CLASS_ATTR_NAME = "class";
@NonNls public static final String ID_ATTR_NAME = "id";
@NonNls public static final String INTERNAL_ATTR_NAME = "internal";
@NonNls public static final String ICON_ATTR_NAME = "icon";
@NonNls public static final String ADD_TO_GROUP_ELEMENT_NAME = "add-to-group";
@NonNls public static final String SHORTCUT_ELEMENT_NAME = "keyboard-shortcut";
@NonNls public static final String MOUSE_SHORTCUT_ELEMENT_NAME = "mouse-shortcut";
@NonNls public static final String DESCRIPTION = "description";
@NonNls public static final String TEXT_ATTR_NAME = "text";
@NonNls public static final String POPUP_ATTR_NAME = "popup";
@NonNls public static final String SEPARATOR_ELEMENT_NAME = "separator";
@NonNls public static final String REFERENCE_ELEMENT_NAME = "reference";
@NonNls public static final String GROUPID_ATTR_NAME = "group-id";
@NonNls public static final String ANCHOR_ELEMENT_NAME = "anchor";
@NonNls public static final String FIRST = "first";
@NonNls public static final String LAST = "last";
@NonNls public static final String BEFORE = "before";
@NonNls public static final String AFTER = "after";
@NonNls public static final String RELATIVE_TO_ACTION_ATTR_NAME = "relative-to-action";
@NonNls public static final String FIRST_KEYSTROKE_ATTR_NAME = "first-keystroke";
@NonNls public static final String SECOND_KEYSTROKE_ATTR_NAME = "second-keystroke";
@NonNls public static final String KEYMAP_ATTR_NAME = "keymap";
@NonNls public static final String KEYSTROKE_ATTR_NAME = "keystroke";
@NonNls public static final String REF_ATTR_NAME = "ref";
@NonNls public static final String ACTIONS_BUNDLE = "messages.ActionsBundle";
@NonNls public static final String USE_SHORTCUT_OF_ATTR_NAME = "use-shortcut-of";
private List<ActionPopupMenuImpl> myPopups = new ArrayList<ActionPopupMenuImpl>();
private Map<AnAction, DataContext> myQueuedNotifications = new LinkedHashMap<AnAction, DataContext>();
private Runnable myPreloadActionsRunnable;
ActionManagerImpl(KeymapManager keymapManager, DataManager dataManager) {
myId2Action = new THashMap<String, Object>();
myId2Index = new TObjectIntHashMap<String>();
myAction2Id = new THashMap<Object, String>();
myPlugin2Id = new THashMap<PluginId, THashSet<String>>();
myNotRegisteredInternalActionIds = new ArrayList<String>();
myActionListeners = new ArrayList<AnActionListener>();
myCachedActionListeners = null;
myKeymapManager = keymapManager;
myDataManager = dataManager;
}
public void initComponent() {}
public void disposeComponent() {
if (myTimer != null) {
myTimer.stop();
myTimer = null;
}
}
public void addTimerListener(int delay, final TimerListener listener) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
if (myTimer == null) {
myTimer = new MyTimer();
myTimer.start();
}
myTimer.addTimerListener(listener);
}
public void removeTimerListener(TimerListener listener) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
LOG.assertTrue(myTimer != null);
myTimer.removeTimerListener(listener);
}
public ActionPopupMenu createActionPopupMenu(String place, @NotNull ActionGroup group) {
return new ActionPopupMenuImpl(place, group, this);
}
public ActionToolbar createActionToolbar(final String place, final ActionGroup group, final boolean horizontal) {
return new ActionToolbarImpl(place, group, horizontal, myDataManager, this, (KeymapManagerEx)myKeymapManager);
}
public void readExternal(Element element) {
final ClassLoader classLoader = getClass().getClassLoader();
for (final Object o : element.getChildren()) {
Element children = (Element)o;
if (ACTIONS_ELEMENT_NAME.equals(children.getName())) {
processActionsElement(children, classLoader, null);
}
}
registerPluginActions();
}
private void registerPluginActions() {
final Application app = ApplicationManager.getApplication();
final IdeaPluginDescriptor[] plugins = app.getPlugins();
for (IdeaPluginDescriptor plugin : plugins) {
if (PluginManager.shouldSkipPlugin(plugin)) continue;
final List<Element> elementList = plugin.getActionsDescriptionElements();
if (elementList != null) {
for (Element e : elementList) {
processActionsChildElement(plugin.getPluginClassLoader(), plugin.getPluginId(), e);
}
}
}
}
public void writeExternal(Element element) throws WriteExternalException {
throw new WriteExternalException();
}
public AnAction getAction(@NotNull String id) {
return getActionImpl(id, false);
}
private AnAction getActionImpl(String id, boolean canReturnStub) {
synchronized (myLock) {
AnAction action = (AnAction)myId2Action.get(id);
if (!canReturnStub && action instanceof ActionStub) {
action = convert((ActionStub)action);
}
return action;
}
}
/**
* Converts action's stub to normal action.
*/
private AnAction convert(ActionStub stub) {
LOG.assertTrue(myAction2Id.contains(stub));
myAction2Id.remove(stub);
LOG.assertTrue(myId2Action.contains(stub.getId()));
AnAction action = (AnAction)myId2Action.remove(stub.getId());
LOG.assertTrue(action != null);
LOG.assertTrue(action.equals(stub));
Object obj;
String className = stub.getClassName();
try {
Constructor<?> constructor = Class.forName(className, true, stub.getLoader()).getDeclaredConstructor();
constructor.setAccessible(true);
obj = constructor.newInstance();
}
catch (ClassNotFoundException e) {
PluginId pluginId = stub.getPluginId();
if (pluginId != null) {
throw new PluginException("class with name \"" + className + "\" not found", e, pluginId);
}
else {
throw new IllegalStateException("class with name \"" + className + "\" not found");
}
}
catch(UnsupportedClassVersionError e) {
PluginId pluginId = stub.getPluginId();
if (pluginId != null) {
throw new PluginException(e, pluginId);
}
else {
throw new IllegalStateException(e);
}
}
catch (Exception e) {
PluginId pluginId = stub.getPluginId();
if (pluginId != null) {
throw new PluginException("cannot create class \"" + className + "\"", e, pluginId);
}
else {
throw new IllegalStateException("cannot create class \"" + className + "\"", e);
}
}
if (!(obj instanceof AnAction)) {
throw new IllegalStateException("class with name \"" + className + "\" should be instance of " + AnAction.class.getName());
}
AnAction anAction = (AnAction)obj;
stub.initAction(anAction);
anAction.getTemplatePresentation().setText(stub.getText());
String iconPath = stub.getIconPath();
if (iconPath != null) {
setIconFromClass(anAction.getClass(), iconPath, stub.getClassName(), anAction.getTemplatePresentation(), stub.getPluginId());
}
myId2Action.put(stub.getId(), obj);
myAction2Id.put(obj, stub.getId());
return anAction;
}
public String getId(@NotNull AnAction action) {
LOG.assertTrue(!(action instanceof ActionStub));
synchronized (myLock) {
return myAction2Id.get(action);
}
}
public String[] getActionIds(@NotNull String idPrefix) {
synchronized (myLock) {
ArrayList<String> idList = new ArrayList<String>();
for (String id : myId2Action.keySet()) {
if (id.startsWith(idPrefix)) {
idList.add(id);
}
}
return idList.toArray(new String[idList.size()]);
}
}
public boolean isGroup(@NotNull String actionId) {
return getActionImpl(actionId, true) instanceof ActionGroup;
}
public JComponent createButtonToolbar(final String actionPlace, final ActionGroup messageActionGroup) {
return new ButtonToolbarImpl(actionPlace, messageActionGroup, myDataManager, this);
}
public AnAction getActionOrStub(String id) {
return getActionImpl(id, true);
}
/**
* @return instance of ActionGroup or ActionStub. The method never returns real subclasses
* of <code>AnAction</code>.
*/
@Nullable
private AnAction processActionElement(Element element, final ClassLoader loader, PluginId pluginId) {
final Application app = ApplicationManager.getApplication();
final IdeaPluginDescriptor plugin = app.getPlugin(pluginId);
@NonNls final String resBundleName = plugin != null ? plugin.getResourceBundleBaseName() : ACTIONS_BUNDLE;
ResourceBundle bundle = null;
if (resBundleName != null) {
bundle = getBundle(loader, resBundleName);
}
if (!ACTION_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return null;
}
String className = element.getAttributeValue(CLASS_ATTR_NAME);
if (className == null || className.length() == 0) {
reportActionError(pluginId, "action element should have specified \"class\" attribute");
return null;
}
// read ID and register loaded action
String id = element.getAttributeValue(ID_ATTR_NAME);
if (id == null || id.length() == 0) {
reportActionError(pluginId, "ID of the action cannot be an empty string");
return null;
}
if (Boolean.valueOf(element.getAttributeValue(INTERNAL_ATTR_NAME)).booleanValue() && !ApplicationManagerEx.getApplicationEx().isInternal()) {
myNotRegisteredInternalActionIds.add(id);
return null;
}
String text = loadTextForElement(element, bundle, id, ACTION_ELEMENT_NAME);
String iconPath = element.getAttributeValue(ICON_ATTR_NAME);
if (text == null) {
@NonNls String message = "'text' attribute is mandatory (action ID=" + id + ";" +
(plugin == null ? "" : " plugin path: "+plugin.getPath()) + ")";
reportActionError(pluginId, message);
return null;
}
ActionStub stub = new ActionStub(className, id, text, loader, pluginId, iconPath);
Presentation presentation = stub.getTemplatePresentation();
presentation.setText(text);
// description
presentation.setDescription(loadDescriptionForElement(element, bundle, id, ACTION_ELEMENT_NAME));
// process all links and key bindings if any
for (final Object o : element.getChildren()) {
Element e = (Element)o;
if (ADD_TO_GROUP_ELEMENT_NAME.equals(e.getName())) {
processAddToGroupNode(stub, e, pluginId);
}
else if (SHORTCUT_ELEMENT_NAME.equals(e.getName())) {
processKeyboardShortcutNode(e, id, pluginId);
}
else if (MOUSE_SHORTCUT_ELEMENT_NAME.equals(e.getName())) {
processMouseShortcutNode(e, id, pluginId);
}
else {
reportActionError(pluginId, "unexpected name of element \"" + e.getName() + "\"");
return null;
}
}
if (element.getAttributeValue(USE_SHORTCUT_OF_ATTR_NAME) != null) {
((KeymapManagerEx)myKeymapManager).bindShortcuts(element.getAttributeValue(USE_SHORTCUT_OF_ATTR_NAME), id);
}
// register action
registerAction(id, stub, pluginId);
return stub;
}
private static void setIcon(@Nullable final String iconPath, final String className, final ClassLoader loader, final Presentation presentation,
final PluginId pluginId) {
if (iconPath == null) return;
try {
final Class actionClass = Class.forName(className, true, loader);
setIconFromClass(actionClass, iconPath, className, presentation, pluginId);
}
catch (ClassNotFoundException e) {
LOG.error(e);
reportActionError(pluginId, "class with name \"" + className + "\" not found");
}
catch (NoClassDefFoundError e) {
LOG.error(e);
reportActionError(pluginId, "class with name \"" + className + "\" not found");
}
}
private static void setIconFromClass(@NotNull final Class actionClass, @NotNull final String iconPath, final String className,
final Presentation presentation, final PluginId pluginId) {
//try to find icon in idea class path
final Icon icon = IconLoader.findIcon(iconPath, actionClass);
if (icon == null) {
reportActionError(pluginId, "Icon cannot be found in '" + iconPath + "', action class='" + className + "'");
}
else {
presentation.setIcon(icon);
}
}
private static String loadDescriptionForElement(final Element element, final ResourceBundle bundle, final String id, String elementType) {
final String value = element.getAttributeValue(DESCRIPTION);
if (bundle != null) {
@NonNls final String key = elementType + "." + id + ".description";
return CommonBundle.messageOrDefault(bundle, key, value == null ? "" : value);
} else {
return value;
}
}
private static String loadTextForElement(final Element element, final ResourceBundle bundle, final String id, String elementType) {
final String value = element.getAttributeValue(TEXT_ATTR_NAME);
return CommonBundle.messageOrDefault(bundle, elementType + "." + id + "." + TEXT_ATTR_NAME, value == null ? "" : value);
}
private AnAction processGroupElement(Element element, final ClassLoader loader, PluginId pluginId) {
final Application app = ApplicationManager.getApplication();
final IdeaPluginDescriptor plugin = app.getPlugin(pluginId);
@NonNls final String resBundleName = plugin != null ? plugin.getResourceBundleBaseName() : ACTIONS_BUNDLE;
ResourceBundle bundle = null;
if (resBundleName != null) {
bundle = getBundle(loader, resBundleName);
}
if (!GROUP_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return null;
}
String className = element.getAttributeValue(CLASS_ATTR_NAME);
if (className == null) { // use default group if class isn't specified
className = DefaultActionGroup.class.getName();
}
try {
Class aClass = Class.forName(className, true, loader);
Object obj = new ConstructorInjectionComponentAdapter(className, aClass).getComponentInstance(ApplicationManager.getApplication().getPicoContainer());
if (!(obj instanceof ActionGroup)) {
reportActionError(pluginId, "class with name \"" + className + "\" should be instance of " + ActionGroup.class.getName());
return null;
}
if (element.getChildren().size() != element.getChildren(ADD_TO_GROUP_ELEMENT_NAME).size() ) { //
if (!(obj instanceof DefaultActionGroup)) {
reportActionError(pluginId, "class with name \"" + className + "\" should be instance of " + DefaultActionGroup.class.getName() +
" because there are children specified");
return null;
}
}
ActionGroup group = (ActionGroup)obj;
// read ID and register loaded group
String id = element.getAttributeValue(ID_ATTR_NAME);
if (id != null && id.length() == 0) {
reportActionError(pluginId, "ID of the group cannot be an empty string");
return null;
}
if (Boolean.valueOf(element.getAttributeValue(INTERNAL_ATTR_NAME)).booleanValue() && !ApplicationManagerEx.getApplicationEx().isInternal()) {
myNotRegisteredInternalActionIds.add(id);
return null;
}
if (id != null) {
registerAction(id, group);
}
// text
Presentation presentation = group.getTemplatePresentation();
String text = loadTextForElement(element, bundle, id, GROUP_ELEMENT_NAME);
presentation.setText(text);
// description
String description = loadDescriptionForElement(element, bundle, id, GROUP_ELEMENT_NAME);
presentation.setDescription(description);
// icon
setIcon(element.getAttributeValue(ICON_ATTR_NAME), className, loader, presentation, pluginId);
// popup
String popup = element.getAttributeValue(POPUP_ATTR_NAME);
if (popup != null) {
group.setPopup(Boolean.valueOf(popup).booleanValue());
}
// process all group's children. There are other groups, actions, references and links
for (final Object o : element.getChildren()) {
Element child = (Element)o;
String name = child.getName();
if (ACTION_ELEMENT_NAME.equals(name)) {
AnAction action = processActionElement(child, loader, pluginId);
if (action != null) {
assertActionIsGroupOrStub(action);
((DefaultActionGroup)group).add(action, this);
}
}
else if (SEPARATOR_ELEMENT_NAME.equals(name)) {
processSeparatorNode((DefaultActionGroup)group, child, pluginId);
}
else if (GROUP_ELEMENT_NAME.equals(name)) {
AnAction action = processGroupElement(child, loader, pluginId);
if (action != null) {
((DefaultActionGroup)group).add(action, this);
}
}
else if (ADD_TO_GROUP_ELEMENT_NAME.equals(name)) {
processAddToGroupNode(group, child, pluginId);
}
else if (REFERENCE_ELEMENT_NAME.equals(name)) {
AnAction action = processReferenceElement(child, pluginId);
if (action != null) {
((DefaultActionGroup)group).add(action, this);
}
}
else {
reportActionError(pluginId, "unexpected name of element \"" + name + "\n");
return null;
}
}
return group;
}
catch (ClassNotFoundException e) {
reportActionError(pluginId, "class with name \"" + className + "\" not found");
return null;
}
catch (NoClassDefFoundError e) {
reportActionError(pluginId, "class with name \"" + e.getMessage() + "\" not found");
return null;
}
catch(UnsupportedClassVersionError e) {
reportActionError(pluginId, "unsupported class version for " + className);
return null;
}
catch (Exception e) {
final String message = "cannot create class \"" + className + "\"";
if (pluginId == null) {
LOG.error(message, e);
}
else {
LOG.error(new PluginException(message, e, pluginId));
}
return null;
}
}
private void processReferenceNode(final Element element, final PluginId pluginId) {
final AnAction action = processReferenceElement(element, pluginId);
for (final Object o : element.getChildren()) {
Element child = (Element)o;
if (ADD_TO_GROUP_ELEMENT_NAME.equals(child.getName())) {
processAddToGroupNode(action, child, pluginId);
}
}
}
private static Map<String, ResourceBundle> ourBundlesCache = new HashMap<String, ResourceBundle>();
private static ResourceBundle getBundle(final ClassLoader loader, final String resBundleName) {
if (ourBundlesCache.containsKey(resBundleName)) {
return ourBundlesCache.get(resBundleName);
}
final ResourceBundle bundle = ResourceBundle.getBundle(resBundleName, Locale.getDefault(), loader);
ourBundlesCache.put(resBundleName, bundle);
return bundle;
}
/**
* @param element description of link
* @param pluginId
*/
private void processAddToGroupNode(AnAction action, Element element, final PluginId pluginId) {
// Real subclasses of AnAction should not be here
if (!(action instanceof Separator)) {
assertActionIsGroupOrStub(action);
}
String actionName = action instanceof ActionStub ? ((ActionStub)action).getClassName() : action.getClass().getName();
if (!ADD_TO_GROUP_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
String groupId = element.getAttributeValue(GROUPID_ATTR_NAME);
if (groupId == null || groupId.length() == 0) {
reportActionError(pluginId, actionName + ": attribute \"group-id\" should be defined");
return;
}
AnAction parentGroup = getActionImpl(groupId, true);
if (parentGroup == null) {
reportActionError(pluginId, actionName + ": action with id \"" + groupId + "\" isn't registered; action will be added to the \"Other\" group");
parentGroup = getActionImpl(IdeActions.GROUP_OTHER_MENU, true);
}
if (!(parentGroup instanceof DefaultActionGroup)) {
reportActionError(pluginId, actionName + ": action with id \"" + groupId + "\" should be instance of " + DefaultActionGroup.class.getName() +
" but was " + parentGroup.getClass());
return;
}
String anchorStr = element.getAttributeValue(ANCHOR_ELEMENT_NAME);
if (anchorStr == null) {
reportActionError(pluginId, actionName + ": attribute \"anchor\" should be defined");
return;
}
Anchor anchor;
if (FIRST.equalsIgnoreCase(anchorStr)) {
anchor = Anchor.FIRST;
}
else if (LAST.equalsIgnoreCase(anchorStr)) {
anchor = Anchor.LAST;
}
else if (BEFORE.equalsIgnoreCase(anchorStr)) {
anchor = Anchor.BEFORE;
}
else if (AFTER.equalsIgnoreCase(anchorStr)) {
anchor = Anchor.AFTER;
}
else {
reportActionError(pluginId, actionName + ": anchor should be one of the following constants: \"first\", \"last\", \"before\" or \"after\"");
return;
}
String relativeToActionId = element.getAttributeValue(RELATIVE_TO_ACTION_ATTR_NAME);
if ((Anchor.BEFORE == anchor || Anchor.AFTER == anchor) && relativeToActionId == null) {
reportActionError(pluginId, actionName + ": \"relative-to-action\" cannot be null if anchor is \"after\" or \"before\"");
return;
}
((DefaultActionGroup)parentGroup).add(action, new Constraints(anchor, relativeToActionId), this);
}
/**
* @param parentGroup group wich is the parent of the separator. It can be <code>null</code> in that
* case separator will be added to group described in the <add-to-group ....> subelement.
* @param element XML element which represent separator.
*/
private void processSeparatorNode(DefaultActionGroup parentGroup, Element element, PluginId pluginId) {
if (!SEPARATOR_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
Separator separator = Separator.getInstance();
if (parentGroup != null) {
parentGroup.add(separator, this);
}
// try to find inner <add-to-parent...> tag
for (final Object o : element.getChildren()) {
Element child = (Element)o;
if (ADD_TO_GROUP_ELEMENT_NAME.equals(child.getName())) {
processAddToGroupNode(separator, child, pluginId);
}
}
}
private void processKeyboardShortcutNode(Element element, String actionId, PluginId pluginId) {
String firstStrokeString = element.getAttributeValue(FIRST_KEYSTROKE_ATTR_NAME);
if (firstStrokeString == null) {
reportActionError(pluginId, "\"first-keystroke\" attribute must be specified for action with id=" + actionId);
return;
}
KeyStroke firstKeyStroke = getKeyStroke(firstStrokeString);
if (firstKeyStroke == null) {
reportActionError(pluginId, "\"first-keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
KeyStroke secondKeyStroke = null;
String secondStrokeString = element.getAttributeValue(SECOND_KEYSTROKE_ATTR_NAME);
if (secondStrokeString != null) {
secondKeyStroke = getKeyStroke(secondStrokeString);
if (secondKeyStroke == null) {
reportActionError(pluginId, "\"second-keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
}
String keymapName = element.getAttributeValue(KEYMAP_ATTR_NAME);
if (keymapName == null || keymapName.trim().length() == 0) {
reportActionError(pluginId, "attribute \"keymap\" should be defined");
return;
}
Keymap keymap = myKeymapManager.getKeymap(keymapName);
if (keymap == null) {
reportActionError(pluginId, "keymap \"" + keymapName + "\" not found");
return;
}
keymap.addShortcut(actionId, new KeyboardShortcut(firstKeyStroke, secondKeyStroke));
}
private static void processMouseShortcutNode(Element element, String actionId, PluginId pluginId) {
String keystrokeString = element.getAttributeValue(KEYSTROKE_ATTR_NAME);
if (keystrokeString == null || keystrokeString.trim().length() == 0) {
reportActionError(pluginId, "\"keystroke\" attribute must be specified for action with id=" + actionId);
return;
}
MouseShortcut shortcut;
try {
shortcut = KeymapUtil.parseMouseShortcut(keystrokeString);
}
catch (Exception ex) {
reportActionError(pluginId, "\"keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
String keymapName = element.getAttributeValue(KEYMAP_ATTR_NAME);
if (keymapName == null || keymapName.length() == 0) {
reportActionError(pluginId, "attribute \"keymap\" should be defined");
return;
}
Keymap keymap = KeymapManager.getInstance().getKeymap(keymapName);
if (keymap == null) {
reportActionError(pluginId, "keymap \"" + keymapName + "\" not found");
return;
}
keymap.addShortcut(actionId, shortcut);
}
@Nullable
private AnAction processReferenceElement(Element element, PluginId pluginId) {
if (!REFERENCE_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return null;
}
String ref = element.getAttributeValue(REF_ATTR_NAME);
if (ref==null) {
// support old style references by id
ref = element.getAttributeValue(ID_ATTR_NAME);
}
if (ref == null || ref.length() == 0) {
reportActionError(pluginId, "ID of reference element should be defined");
return null;
}
AnAction action = getActionImpl(ref, true);
if (action == null) {
if (!myNotRegisteredInternalActionIds.contains(ref)) {
reportActionError(pluginId, "action specified by reference isn't registered (ID=" + ref + ")");
}
return null;
}
assertActionIsGroupOrStub(action);
return action;
}
private void processActionsElement(Element element, ClassLoader loader, PluginId pluginId) {
if (!ACTIONS_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
synchronized (myLock) {
for (final Object o : element.getChildren()) {
Element child = (Element)o;
processActionsChildElement(loader, pluginId, child);
}
}
}
private void processActionsChildElement(final ClassLoader loader, final PluginId pluginId, final Element child) {
String name = child.getName();
if (ACTION_ELEMENT_NAME.equals(name)) {
AnAction action = processActionElement(child, loader, pluginId);
if (action != null) {
assertActionIsGroupOrStub(action);
}
}
else if (GROUP_ELEMENT_NAME.equals(name)) {
processGroupElement(child, loader, pluginId);
}
else if (SEPARATOR_ELEMENT_NAME.equals(name)) {
processSeparatorNode(null, child, pluginId);
}
else if (REFERENCE_ELEMENT_NAME.equals(name)) {
processReferenceNode(child, pluginId);
}
else {
reportActionError(pluginId, "unexpected name of element \"" + name + "\n");
}
}
private static void assertActionIsGroupOrStub(final AnAction action) {
if (!(action instanceof ActionGroup || action instanceof ActionStub)) {
LOG.assertTrue(false, "Action : "+action + "; class: "+action.getClass());
}
}
public void registerAction(@NotNull String actionId, @NotNull AnAction action, @Nullable PluginId pluginId) {
synchronized (myLock) {
if (myId2Action.containsKey(actionId)) {
reportActionError(pluginId, "action with the ID \"" + actionId + "\" was already registered. Action being registered is " + action.toString() +
"; Registered action is " +
myId2Action.get(actionId) + getPluginInfo(pluginId));
return;
}
if (myAction2Id.containsKey(action)) {
reportActionError(pluginId, "action was already registered for another ID. ID is " + myAction2Id.get(action) +
getPluginInfo(pluginId));
return;
}
myId2Action.put(actionId, action);
myId2Index.put(actionId, myRegisteredActionsCount++);
myAction2Id.put(action, actionId);
if (pluginId != null && !(action instanceof ActionGroup)){
THashSet<String> pluginActionIds = myPlugin2Id.get(pluginId);
if (pluginActionIds == null){
pluginActionIds = new THashSet<String>();
myPlugin2Id.put(pluginId, pluginActionIds);
}
pluginActionIds.add(actionId);
}
action.registerCustomShortcutSet(new ProxyShortcutSet(actionId, myKeymapManager), null);
}
}
private static void reportActionError(final PluginId pluginId, @NonNls final String message) {
if (pluginId == null) {
LOG.error(message);
}
else {
LOG.error(new PluginException(message, null, pluginId));
}
}
@NonNls
private static String getPluginInfo(@Nullable PluginId id) {
if (id != null) {
final IdeaPluginDescriptor plugin = ApplicationManager.getApplication().getPlugin(id);
if (plugin != null) {
String name = plugin.getName();
if (name == null) {
name = id.getIdString();
}
return " Plugin: " + name;
}
}
return "";
}
public void registerAction(@NotNull String actionId, @NotNull AnAction action) {
registerAction(actionId, action, null);
}
public void unregisterAction(@NotNull String actionId) {
synchronized (myLock) {
if (!myId2Action.containsKey(actionId)) {
if (LOG.isDebugEnabled()) {
LOG.debug("action with ID " + actionId + " wasn't registered");
return;
}
}
AnAction oldValue = (AnAction)myId2Action.remove(actionId);
myAction2Id.remove(oldValue);
myId2Index.remove(actionId);
for (PluginId pluginName : myPlugin2Id.keySet()) {
final THashSet<String> pluginActions = myPlugin2Id.get(pluginName);
if (pluginActions != null) {
pluginActions.remove(actionId);
}
}
}
}
@NotNull
public String getComponentName() {
final String platformPrefix = System.getProperty("idea.platform.prefix");
return platformPrefix != null ? platformPrefix + "ActionManager" : "ActionManager";
}
public Comparator<String> getRegistrationOrderComparator() {
return new Comparator<String>() {
public int compare(String id1, String id2) {
return myId2Index.get(id1) - myId2Index.get(id2);
}
};
}
public String[] getPluginActions(PluginId pluginName) {
if (myPlugin2Id.containsKey(pluginName)){
final THashSet<String> pluginActions = myPlugin2Id.get(pluginName);
return pluginActions.toArray(new String[pluginActions.size()]);
}
return ArrayUtil.EMPTY_STRING_ARRAY;
}
public void addActionPopup(final ActionPopupMenuImpl menu) {
myPopups.add(menu);
}
public void removeActionPopup(final ActionPopupMenuImpl menu) {
final boolean removed = myPopups.remove(menu);
if (removed && myPopups.size() == 0) {
flushActionPerformed();
}
}
public void queueActionPerformedEvent(final AnAction action, DataContext context) {
if (myPopups.size() > 0) {
myQueuedNotifications.put(action, context);
} else {
fireAfterActionPerformed(action, context);
}
}
public boolean isActionPopupStackEmpty() {
return myPopups.size() == 0;
}
private void flushActionPerformed() {
final Set<AnAction> actions = myQueuedNotifications.keySet();
for (final AnAction eachAction : actions) {
final DataContext eachContext = myQueuedNotifications.get(eachAction);
fireAfterActionPerformed(eachAction, eachContext);
}
myQueuedNotifications.clear();
}
private AnActionListener[] getActionListeners() {
if (myCachedActionListeners == null) {
myCachedActionListeners = myActionListeners.toArray(new AnActionListener[myActionListeners.size()]);
}
return myCachedActionListeners;
}
public void addAnActionListener(AnActionListener listener) {
myActionListeners.add(listener);
myCachedActionListeners = null;
}
public void addAnActionListener(final AnActionListener listener, final Disposable parentDisposable) {
addAnActionListener(listener);
Disposer.register(parentDisposable, new Disposable() {
public void dispose() {
removeAnActionListener(listener);
}
});
}
public void removeAnActionListener(AnActionListener listener) {
myActionListeners.remove(listener);
myCachedActionListeners = null;
}
public void fireBeforeActionPerformed(AnAction action, DataContext dataContext) {
if (action != null) {
myPrevPerformedActionId = myLastPreformedActionId;
myLastPreformedActionId = getId(action);
IdeaLogger.ourLastActionId = myLastPreformedActionId;
}
AnActionListener[] listeners = getActionListeners();
for (AnActionListener listener : listeners) {
listener.beforeActionPerformed(action, dataContext);
}
}
public void fireAfterActionPerformed(AnAction action, DataContext dataContext) {
if (action != null) {
myPrevPerformedActionId = myLastPreformedActionId;
myLastPreformedActionId = getId(action);
IdeaLogger.ourLastActionId = myLastPreformedActionId;
}
AnActionListener[] listeners = getActionListeners();
for (AnActionListener listener : listeners) {
try {
listener.afterActionPerformed(action, dataContext);
}
catch(AbstractMethodError e) {
// ignore
}
}
}
public void fireBeforeEditorTyping(char c, DataContext dataContext) {
myLastTimeEditorWasTypedIn = System.currentTimeMillis();
AnActionListener[] listeners = getActionListeners();
for (AnActionListener listener : listeners) {
listener.beforeEditorTyping(c, dataContext);
}
}
public String getLastPreformedActionId() {
return myLastPreformedActionId;
}
public String getPrevPreformedActionId() {
return myPrevPerformedActionId;
}
public Set<String> getActionIds(){
return new HashSet<String>(myId2Action.keySet());
}
private int myActionsPreloaded = 0;
public void preloadActions() {
if (myPreloadActionsRunnable == null) {
myPreloadActionsRunnable = new Runnable() {
public void run() {
doPreloadActions();
}
};
ApplicationManager.getApplication().executeOnPooledThread(myPreloadActionsRunnable);
}
}
private void doPreloadActions() {
try {
Thread.sleep(5000); // wait for project initialization to complete
}
catch (InterruptedException e) {
// ignore
}
preloadActionGroup(IdeActions.GROUP_EDITOR_POPUP);
preloadActionGroup(IdeActions.GROUP_EDITOR_TAB_POPUP);
preloadActionGroup(IdeActions.GROUP_PROJECT_VIEW_POPUP);
preloadActionGroup(IdeActions.GROUP_MAIN_MENU);
// TODO anything else?
LOG.debug("Actions preloading completed");
}
public void preloadActionGroup(final String groupId) {
final AnAction action = getAction(groupId);
if (action instanceof DefaultActionGroup) {
preloadActionGroup((DefaultActionGroup) action);
}
}
private void preloadActionGroup(final DefaultActionGroup group) {
final AnAction[] actions = group.getChildActionsOrStubs(null);
for (AnAction action : actions) {
if (action instanceof ActionStub) {
AnAction convertedAction = null;
synchronized (myLock) {
final String id = myAction2Id.get(action);
if (id != null) {
convertedAction = convert((ActionStub)action);
}
}
if (convertedAction instanceof PreloadableAction) {
final PreloadableAction preloadableAction = (PreloadableAction)convertedAction;
preloadableAction.preload();
}
myActionsPreloaded++;
if (myActionsPreloaded % 10 == 0) {
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
// ignore
}
}
}
else if (action instanceof DefaultActionGroup) {
preloadActionGroup((DefaultActionGroup) action);
}
}
}
private class MyTimer extends Timer implements ActionListener {
private final List<TimerListener> myTimerListeners = Collections.synchronizedList(new ArrayList<TimerListener>());
private int myLastTimePerformed;
MyTimer() {
super(TIMER_DELAY, null);
addActionListener(this);
setRepeats(true);
}
public void addTimerListener(TimerListener listener){
myTimerListeners.add(listener);
}
public void removeTimerListener(TimerListener listener){
final boolean removed = myTimerListeners.remove(listener);
if (!removed) {
LOG.assertTrue(false, "Unknown listener " + listener);
}
}
public void actionPerformed(ActionEvent e) {
if (myLastTimeEditorWasTypedIn + UPDATE_DELAY_AFTER_TYPING > System.currentTimeMillis()) {
return;
}
final int lastEventCount = myLastTimePerformed;
myLastTimePerformed = ActivityTracker.getInstance().getCount();
if (myLastTimePerformed == lastEventCount) {
return;
}
TimerListener[] listeners = myTimerListeners.toArray(new TimerListener[myTimerListeners.size()]);
for (TimerListener listener : listeners) {
runListenerAction(listener);
}
}
private void runListenerAction(final TimerListener listener) {
ModalityState modalityState = listener.getModalityState();
if (modalityState == null) return;
if (!ModalityState.current().dominates(modalityState)) {
listener.run();
}
}
}
}
| platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java | package com.intellij.openapi.actionSystem.impl;
import com.intellij.CommonBundle;
import com.intellij.diagnostic.PluginException;
import com.intellij.ide.ActivityTracker;
import com.intellij.ide.DataManager;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.idea.IdeaLogger;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.ex.AnActionListener;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.util.ArrayUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import gnu.trove.TObjectIntHashMap;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.picocontainer.defaults.ConstructorInjectionComponentAdapter;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Constructor;
import java.util.*;
public final class ActionManagerImpl extends ActionManagerEx implements JDOMExternalizable, ApplicationComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.actionSystem.impl.ActionManagerImpl");
private static final int TIMER_DELAY = 500;
private static final int UPDATE_DELAY_AFTER_TYPING = 500;
private final Object myLock = new Object();
private final THashMap<String,Object> myId2Action;
private final THashMap<PluginId, THashSet<String>> myPlugin2Id;
private final TObjectIntHashMap<String> myId2Index;
private final THashMap<Object,String> myAction2Id;
private final ArrayList<String> myNotRegisteredInternalActionIds;
private MyTimer myTimer;
private int myRegisteredActionsCount;
private final ArrayList<AnActionListener> myActionListeners;
private AnActionListener[] myCachedActionListeners;
private String myLastPreformedActionId;
private final KeymapManager myKeymapManager;
private final DataManager myDataManager;
private String myPrevPerformedActionId;
private long myLastTimeEditorWasTypedIn = 0;
@NonNls public static final String ACTION_ELEMENT_NAME = "action";
@NonNls public static final String GROUP_ELEMENT_NAME = "group";
@NonNls public static final String ACTIONS_ELEMENT_NAME = "actions";
@NonNls public static final String CLASS_ATTR_NAME = "class";
@NonNls public static final String ID_ATTR_NAME = "id";
@NonNls public static final String INTERNAL_ATTR_NAME = "internal";
@NonNls public static final String ICON_ATTR_NAME = "icon";
@NonNls public static final String ADD_TO_GROUP_ELEMENT_NAME = "add-to-group";
@NonNls public static final String SHORTCUT_ELEMENT_NAME = "keyboard-shortcut";
@NonNls public static final String MOUSE_SHORTCUT_ELEMENT_NAME = "mouse-shortcut";
@NonNls public static final String DESCRIPTION = "description";
@NonNls public static final String TEXT_ATTR_NAME = "text";
@NonNls public static final String POPUP_ATTR_NAME = "popup";
@NonNls public static final String SEPARATOR_ELEMENT_NAME = "separator";
@NonNls public static final String REFERENCE_ELEMENT_NAME = "reference";
@NonNls public static final String GROUPID_ATTR_NAME = "group-id";
@NonNls public static final String ANCHOR_ELEMENT_NAME = "anchor";
@NonNls public static final String FIRST = "first";
@NonNls public static final String LAST = "last";
@NonNls public static final String BEFORE = "before";
@NonNls public static final String AFTER = "after";
@NonNls public static final String RELATIVE_TO_ACTION_ATTR_NAME = "relative-to-action";
@NonNls public static final String FIRST_KEYSTROKE_ATTR_NAME = "first-keystroke";
@NonNls public static final String SECOND_KEYSTROKE_ATTR_NAME = "second-keystroke";
@NonNls public static final String KEYMAP_ATTR_NAME = "keymap";
@NonNls public static final String KEYSTROKE_ATTR_NAME = "keystroke";
@NonNls public static final String REF_ATTR_NAME = "ref";
@NonNls public static final String ACTIONS_BUNDLE = "messages.ActionsBundle";
@NonNls public static final String USE_SHORTCUT_OF_ATTR_NAME = "use-shortcut-of";
private List<ActionPopupMenuImpl> myPopups = new ArrayList<ActionPopupMenuImpl>();
private Map<AnAction, DataContext> myQueuedNotifications = new LinkedHashMap<AnAction, DataContext>();
private Runnable myPreloadActionsRunnable;
ActionManagerImpl(KeymapManager keymapManager, DataManager dataManager) {
myId2Action = new THashMap<String, Object>();
myId2Index = new TObjectIntHashMap<String>();
myAction2Id = new THashMap<Object, String>();
myPlugin2Id = new THashMap<PluginId, THashSet<String>>();
myNotRegisteredInternalActionIds = new ArrayList<String>();
myActionListeners = new ArrayList<AnActionListener>();
myCachedActionListeners = null;
myKeymapManager = keymapManager;
myDataManager = dataManager;
}
public void initComponent() {}
public void disposeComponent() {
if (myTimer != null) {
myTimer.stop();
myTimer = null;
}
}
public void addTimerListener(int delay, final TimerListener listener) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
if (myTimer == null) {
myTimer = new MyTimer();
myTimer.start();
}
myTimer.addTimerListener(listener);
}
public void removeTimerListener(TimerListener listener) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
LOG.assertTrue(myTimer != null);
myTimer.removeTimerListener(listener);
}
public ActionPopupMenu createActionPopupMenu(String place, @NotNull ActionGroup group) {
return new ActionPopupMenuImpl(place, group, this);
}
public ActionToolbar createActionToolbar(final String place, final ActionGroup group, final boolean horizontal) {
return new ActionToolbarImpl(place, group, horizontal, myDataManager, this, (KeymapManagerEx)myKeymapManager);
}
public void readExternal(Element element) {
final ClassLoader classLoader = getClass().getClassLoader();
for (final Object o : element.getChildren()) {
Element children = (Element)o;
if (ACTIONS_ELEMENT_NAME.equals(children.getName())) {
processActionsElement(children, classLoader, null);
}
}
registerPluginActions();
}
private void registerPluginActions() {
final Application app = ApplicationManager.getApplication();
final IdeaPluginDescriptor[] plugins = app.getPlugins();
for (IdeaPluginDescriptor plugin : plugins) {
if (PluginManager.shouldSkipPlugin(plugin)) continue;
final List<Element> elementList = plugin.getActionsDescriptionElements();
if (elementList != null) {
for (Element e : elementList) {
processActionsChildElement(plugin.getPluginClassLoader(), plugin.getPluginId(), e);
}
}
}
}
public void writeExternal(Element element) throws WriteExternalException {
throw new WriteExternalException();
}
public AnAction getAction(@NotNull String id) {
return getActionImpl(id, false);
}
private AnAction getActionImpl(String id, boolean canReturnStub) {
synchronized (myLock) {
AnAction action = (AnAction)myId2Action.get(id);
if (!canReturnStub && action instanceof ActionStub) {
action = convert((ActionStub)action);
}
return action;
}
}
/**
* Converts action's stub to normal action.
*/
private AnAction convert(ActionStub stub) {
LOG.assertTrue(myAction2Id.contains(stub));
myAction2Id.remove(stub);
LOG.assertTrue(myId2Action.contains(stub.getId()));
AnAction action = (AnAction)myId2Action.remove(stub.getId());
LOG.assertTrue(action != null);
LOG.assertTrue(action.equals(stub));
Object obj;
String className = stub.getClassName();
try {
Constructor<?> constructor = Class.forName(className, true, stub.getLoader()).getDeclaredConstructor();
constructor.setAccessible(true);
obj = constructor.newInstance();
}
catch (ClassNotFoundException e) {
PluginId pluginId = stub.getPluginId();
if (pluginId != null) {
throw new PluginException("class with name \"" + className + "\" not found", e, pluginId);
}
else {
throw new IllegalStateException("class with name \"" + className + "\" not found");
}
}
catch(UnsupportedClassVersionError e) {
PluginId pluginId = stub.getPluginId();
if (pluginId != null) {
throw new PluginException(e, pluginId);
}
else {
throw new IllegalStateException(e);
}
}
catch (Exception e) {
PluginId pluginId = stub.getPluginId();
if (pluginId != null) {
throw new PluginException("cannot create class \"" + className + "\"", e, pluginId);
}
else {
throw new IllegalStateException("cannot create class \"" + className + "\"", e);
}
}
if (!(obj instanceof AnAction)) {
throw new IllegalStateException("class with name \"" + className + "\" should be instance of " + AnAction.class.getName());
}
AnAction anAction = (AnAction)obj;
stub.initAction(anAction);
anAction.getTemplatePresentation().setText(stub.getText());
String iconPath = stub.getIconPath();
if (iconPath != null) {
setIconFromClass(anAction.getClass(), iconPath, stub.getClassName(), anAction.getTemplatePresentation(), stub.getPluginId());
}
myId2Action.put(stub.getId(), obj);
myAction2Id.put(obj, stub.getId());
return anAction;
}
public String getId(@NotNull AnAction action) {
LOG.assertTrue(!(action instanceof ActionStub));
synchronized (myLock) {
return myAction2Id.get(action);
}
}
public String[] getActionIds(@NotNull String idPrefix) {
synchronized (myLock) {
ArrayList<String> idList = new ArrayList<String>();
for (String id : myId2Action.keySet()) {
if (id.startsWith(idPrefix)) {
idList.add(id);
}
}
return idList.toArray(new String[idList.size()]);
}
}
public boolean isGroup(@NotNull String actionId) {
return getActionImpl(actionId, true) instanceof ActionGroup;
}
public JComponent createButtonToolbar(final String actionPlace, final ActionGroup messageActionGroup) {
return new ButtonToolbarImpl(actionPlace, messageActionGroup, myDataManager, this);
}
public AnAction getActionOrStub(String id) {
return getActionImpl(id, true);
}
/**
* @return instance of ActionGroup or ActionStub. The method never returns real subclasses
* of <code>AnAction</code>.
*/
@Nullable
private AnAction processActionElement(Element element, final ClassLoader loader, PluginId pluginId) {
final Application app = ApplicationManager.getApplication();
final IdeaPluginDescriptor plugin = app.getPlugin(pluginId);
@NonNls final String resBundleName = plugin != null ? plugin.getResourceBundleBaseName() : ACTIONS_BUNDLE;
ResourceBundle bundle = null;
if (resBundleName != null) {
bundle = getBundle(loader, resBundleName);
}
if (!ACTION_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return null;
}
String className = element.getAttributeValue(CLASS_ATTR_NAME);
if (className == null || className.length() == 0) {
reportActionError(pluginId, "action element should have specified \"class\" attribute");
return null;
}
// read ID and register loaded action
String id = element.getAttributeValue(ID_ATTR_NAME);
if (id == null || id.length() == 0) {
reportActionError(pluginId, "ID of the action cannot be an empty string");
return null;
}
if (Boolean.valueOf(element.getAttributeValue(INTERNAL_ATTR_NAME)).booleanValue() && !ApplicationManagerEx.getApplicationEx().isInternal()) {
myNotRegisteredInternalActionIds.add(id);
return null;
}
String text = loadTextForElement(element, bundle, id, ACTION_ELEMENT_NAME);
String iconPath = element.getAttributeValue(ICON_ATTR_NAME);
if (text == null) {
@NonNls String message = "'text' attribute is mandatory (action ID=" + id + ";" +
(plugin == null ? "" : " plugin path: "+plugin.getPath()) + ")";
reportActionError(pluginId, message);
return null;
}
ActionStub stub = new ActionStub(className, id, text, loader, pluginId, iconPath);
Presentation presentation = stub.getTemplatePresentation();
presentation.setText(text);
// description
presentation.setDescription(loadDescriptionForElement(element, bundle, id, ACTION_ELEMENT_NAME));
// process all links and key bindings if any
for (final Object o : element.getChildren()) {
Element e = (Element)o;
if (ADD_TO_GROUP_ELEMENT_NAME.equals(e.getName())) {
processAddToGroupNode(stub, e, pluginId);
}
else if (SHORTCUT_ELEMENT_NAME.equals(e.getName())) {
processKeyboardShortcutNode(e, id, pluginId);
}
else if (MOUSE_SHORTCUT_ELEMENT_NAME.equals(e.getName())) {
processMouseShortcutNode(e, id, pluginId);
}
else {
reportActionError(pluginId, "unexpected name of element \"" + e.getName() + "\"");
return null;
}
}
if (element.getAttributeValue(USE_SHORTCUT_OF_ATTR_NAME) != null) {
((KeymapManagerEx)myKeymapManager).bindShortcuts(element.getAttributeValue(USE_SHORTCUT_OF_ATTR_NAME), id);
}
// register action
registerAction(id, stub, pluginId);
return stub;
}
private static void setIcon(@Nullable final String iconPath, final String className, final ClassLoader loader, final Presentation presentation,
final PluginId pluginId) {
if (iconPath == null) return;
try {
final Class actionClass = Class.forName(className, true, loader);
setIconFromClass(actionClass, iconPath, className, presentation, pluginId);
}
catch (ClassNotFoundException e) {
LOG.error(e);
reportActionError(pluginId, "class with name \"" + className + "\" not found");
}
catch (NoClassDefFoundError e) {
LOG.error(e);
reportActionError(pluginId, "class with name \"" + className + "\" not found");
}
}
private static void setIconFromClass(@NotNull final Class actionClass, @NotNull final String iconPath, final String className,
final Presentation presentation, final PluginId pluginId) {
//try to find icon in idea class path
final Icon icon = IconLoader.findIcon(iconPath, actionClass);
if (icon == null) {
reportActionError(pluginId, "Icon cannot be found in '" + iconPath + "', action class='" + className + "'");
}
else {
presentation.setIcon(icon);
}
}
private static String loadDescriptionForElement(final Element element, final ResourceBundle bundle, final String id, String elementType) {
final String value = element.getAttributeValue(DESCRIPTION);
if (bundle != null) {
@NonNls final String key = elementType + "." + id + ".description";
return CommonBundle.messageOrDefault(bundle, key, value == null ? "" : value);
} else {
return value;
}
}
private static String loadTextForElement(final Element element, final ResourceBundle bundle, final String id, String elementType) {
final String value = element.getAttributeValue(TEXT_ATTR_NAME);
return CommonBundle.messageOrDefault(bundle, elementType + "." + id + "." + TEXT_ATTR_NAME, value == null ? "" : value);
}
private AnAction processGroupElement(Element element, final ClassLoader loader, PluginId pluginId) {
final Application app = ApplicationManager.getApplication();
final IdeaPluginDescriptor plugin = app.getPlugin(pluginId);
@NonNls final String resBundleName = plugin != null ? plugin.getResourceBundleBaseName() : ACTIONS_BUNDLE;
ResourceBundle bundle = null;
if (resBundleName != null) {
bundle = getBundle(loader, resBundleName);
}
if (!GROUP_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return null;
}
String className = element.getAttributeValue(CLASS_ATTR_NAME);
if (className == null) { // use default group if class isn't specified
className = DefaultActionGroup.class.getName();
}
try {
Class aClass = Class.forName(className, true, loader);
Object obj = new ConstructorInjectionComponentAdapter(className, aClass).getComponentInstance(ApplicationManager.getApplication().getPicoContainer());
if (!(obj instanceof ActionGroup)) {
reportActionError(pluginId, "class with name \"" + className + "\" should be instance of " + ActionGroup.class.getName());
return null;
}
if (element.getChildren().size() != element.getChildren(ADD_TO_GROUP_ELEMENT_NAME).size() ) { //
if (!(obj instanceof DefaultActionGroup)) {
reportActionError(pluginId, "class with name \"" + className + "\" should be instance of " + DefaultActionGroup.class.getName() +
" because there are children specified");
return null;
}
}
ActionGroup group = (ActionGroup)obj;
// read ID and register loaded group
String id = element.getAttributeValue(ID_ATTR_NAME);
if (id != null && id.length() == 0) {
reportActionError(pluginId, "ID of the group cannot be an empty string");
return null;
}
if (Boolean.valueOf(element.getAttributeValue(INTERNAL_ATTR_NAME)).booleanValue() && !ApplicationManagerEx.getApplicationEx().isInternal()) {
myNotRegisteredInternalActionIds.add(id);
return null;
}
if (id != null) {
registerAction(id, group);
}
// text
Presentation presentation = group.getTemplatePresentation();
String text = loadTextForElement(element, bundle, id, GROUP_ELEMENT_NAME);
presentation.setText(text);
// description
String description = loadDescriptionForElement(element, bundle, id, GROUP_ELEMENT_NAME);
presentation.setDescription(description);
// icon
setIcon(element.getAttributeValue(ICON_ATTR_NAME), className, loader, presentation, pluginId);
// popup
String popup = element.getAttributeValue(POPUP_ATTR_NAME);
if (popup != null) {
group.setPopup(Boolean.valueOf(popup).booleanValue());
}
// process all group's children. There are other groups, actions, references and links
for (final Object o : element.getChildren()) {
Element child = (Element)o;
String name = child.getName();
if (ACTION_ELEMENT_NAME.equals(name)) {
AnAction action = processActionElement(child, loader, pluginId);
if (action != null) {
assertActionIsGroupOrStub(action);
((DefaultActionGroup)group).add(action, this);
}
}
else if (SEPARATOR_ELEMENT_NAME.equals(name)) {
processSeparatorNode((DefaultActionGroup)group, child, pluginId);
}
else if (GROUP_ELEMENT_NAME.equals(name)) {
AnAction action = processGroupElement(child, loader, pluginId);
if (action != null) {
((DefaultActionGroup)group).add(action, this);
}
}
else if (ADD_TO_GROUP_ELEMENT_NAME.equals(name)) {
processAddToGroupNode(group, child, pluginId);
}
else if (REFERENCE_ELEMENT_NAME.equals(name)) {
AnAction action = processReferenceElement(child, pluginId);
if (action != null) {
((DefaultActionGroup)group).add(action, this);
}
}
else {
reportActionError(pluginId, "unexpected name of element \"" + name + "\n");
return null;
}
}
return group;
}
catch (ClassNotFoundException e) {
reportActionError(pluginId, "class with name \"" + className + "\" not found");
return null;
}
catch (NoClassDefFoundError e) {
reportActionError(pluginId, "class with name \"" + e.getMessage() + "\" not found");
return null;
}
catch(UnsupportedClassVersionError e) {
reportActionError(pluginId, "unsupported class version for " + className);
return null;
}
catch (Exception e) {
final String message = "cannot create class \"" + className + "\"";
if (pluginId == null) {
LOG.error(message, e);
}
else {
LOG.error(new PluginException(message, e, pluginId));
}
return null;
}
}
private void processReferenceNode(final Element element, final PluginId pluginId) {
final AnAction action = processReferenceElement(element, pluginId);
for (final Object o : element.getChildren()) {
Element child = (Element)o;
if (ADD_TO_GROUP_ELEMENT_NAME.equals(child.getName())) {
processAddToGroupNode(action, child, pluginId);
}
}
}
private static Map<String, ResourceBundle> ourBundlesCache = new HashMap<String, ResourceBundle>();
private static ResourceBundle getBundle(final ClassLoader loader, final String resBundleName) {
if (ourBundlesCache.containsKey(resBundleName)) {
return ourBundlesCache.get(resBundleName);
}
final ResourceBundle bundle = ResourceBundle.getBundle(resBundleName, Locale.getDefault(), loader);
ourBundlesCache.put(resBundleName, bundle);
return bundle;
}
/**
* @param element description of link
* @param pluginId
*/
private void processAddToGroupNode(AnAction action, Element element, final PluginId pluginId) {
// Real subclasses of AnAction should not be here
if (!(action instanceof Separator)) {
assertActionIsGroupOrStub(action);
}
String actionName = action instanceof ActionStub ? ((ActionStub)action).getClassName() : action.getClass().getName();
if (!ADD_TO_GROUP_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
String groupId = element.getAttributeValue(GROUPID_ATTR_NAME);
if (groupId == null || groupId.length() == 0) {
reportActionError(pluginId, actionName + ": attribute \"group-id\" should be defined");
return;
}
AnAction parentGroup = getActionImpl(groupId, true);
if (parentGroup == null) {
reportActionError(pluginId, actionName + ": action with id \"" + groupId + "\" isn't registered; action will be added to the \"Other\" group");
parentGroup = getActionImpl(IdeActions.GROUP_OTHER_MENU, true);
}
if (!(parentGroup instanceof DefaultActionGroup)) {
reportActionError(pluginId, actionName + ": action with id \"" + groupId + "\" should be instance of " + DefaultActionGroup.class.getName() +
" but was " + parentGroup.getClass());
return;
}
String anchorStr = element.getAttributeValue(ANCHOR_ELEMENT_NAME);
if (anchorStr == null) {
reportActionError(pluginId, actionName + ": attribute \"anchor\" should be defined");
return;
}
Anchor anchor;
if (FIRST.equalsIgnoreCase(anchorStr)) {
anchor = Anchor.FIRST;
}
else if (LAST.equalsIgnoreCase(anchorStr)) {
anchor = Anchor.LAST;
}
else if (BEFORE.equalsIgnoreCase(anchorStr)) {
anchor = Anchor.BEFORE;
}
else if (AFTER.equalsIgnoreCase(anchorStr)) {
anchor = Anchor.AFTER;
}
else {
reportActionError(pluginId, actionName + ": anchor should be one of the following constants: \"first\", \"last\", \"before\" or \"after\"");
return;
}
String relativeToActionId = element.getAttributeValue(RELATIVE_TO_ACTION_ATTR_NAME);
if ((Anchor.BEFORE == anchor || Anchor.AFTER == anchor) && relativeToActionId == null) {
reportActionError(pluginId, actionName + ": \"relative-to-action\" cannot be null if anchor is \"after\" or \"before\"");
return;
}
((DefaultActionGroup)parentGroup).add(action, new Constraints(anchor, relativeToActionId), this);
}
/**
* @param parentGroup group wich is the parent of the separator. It can be <code>null</code> in that
* case separator will be added to group described in the <add-to-group ....> subelement.
* @param element XML element which represent separator.
*/
private void processSeparatorNode(DefaultActionGroup parentGroup, Element element, PluginId pluginId) {
if (!SEPARATOR_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
Separator separator = Separator.getInstance();
if (parentGroup != null) {
parentGroup.add(separator, this);
}
// try to find inner <add-to-parent...> tag
for (final Object o : element.getChildren()) {
Element child = (Element)o;
if (ADD_TO_GROUP_ELEMENT_NAME.equals(child.getName())) {
processAddToGroupNode(separator, child, pluginId);
}
}
}
private void processKeyboardShortcutNode(Element element, String actionId, PluginId pluginId) {
String firstStrokeString = element.getAttributeValue(FIRST_KEYSTROKE_ATTR_NAME);
if (firstStrokeString == null) {
reportActionError(pluginId, "\"first-keystroke\" attribute must be specified for action with id=" + actionId);
return;
}
KeyStroke firstKeyStroke = getKeyStroke(firstStrokeString);
if (firstKeyStroke == null) {
reportActionError(pluginId, "\"first-keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
KeyStroke secondKeyStroke = null;
String secondStrokeString = element.getAttributeValue(SECOND_KEYSTROKE_ATTR_NAME);
if (secondStrokeString != null) {
secondKeyStroke = getKeyStroke(secondStrokeString);
if (secondKeyStroke == null) {
reportActionError(pluginId, "\"second-keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
}
String keymapName = element.getAttributeValue(KEYMAP_ATTR_NAME);
if (keymapName == null || keymapName.trim().length() == 0) {
reportActionError(pluginId, "attribute \"keymap\" should be defined");
return;
}
Keymap keymap = myKeymapManager.getKeymap(keymapName);
if (keymap == null) {
reportActionError(pluginId, "keymap \"" + keymapName + "\" not found");
return;
}
keymap.addShortcut(actionId, new KeyboardShortcut(firstKeyStroke, secondKeyStroke));
}
private static void processMouseShortcutNode(Element element, String actionId, PluginId pluginId) {
String keystrokeString = element.getAttributeValue(KEYSTROKE_ATTR_NAME);
if (keystrokeString == null || keystrokeString.trim().length() == 0) {
reportActionError(pluginId, "\"keystroke\" attribute must be specified for action with id=" + actionId);
return;
}
MouseShortcut shortcut;
try {
shortcut = KeymapUtil.parseMouseShortcut(keystrokeString);
}
catch (Exception ex) {
reportActionError(pluginId, "\"keystroke\" attribute has invalid value for action with id=" + actionId);
return;
}
String keymapName = element.getAttributeValue(KEYMAP_ATTR_NAME);
if (keymapName == null || keymapName.length() == 0) {
reportActionError(pluginId, "attribute \"keymap\" should be defined");
return;
}
Keymap keymap = KeymapManager.getInstance().getKeymap(keymapName);
if (keymap == null) {
reportActionError(pluginId, "keymap \"" + keymapName + "\" not found");
return;
}
keymap.addShortcut(actionId, shortcut);
}
@Nullable
private AnAction processReferenceElement(Element element, PluginId pluginId) {
if (!REFERENCE_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return null;
}
String ref = element.getAttributeValue(REF_ATTR_NAME);
if (ref==null) {
// support old style references by id
ref = element.getAttributeValue(ID_ATTR_NAME);
}
if (LOG.isDebugEnabled()) {
LOG.debug("ref=\"" + ref + "\"");
}
if (ref == null || ref.length() == 0) {
reportActionError(pluginId, "ID of reference element should be defined");
return null;
}
AnAction action = getActionImpl(ref, true);
if (action == null) {
if (!myNotRegisteredInternalActionIds.contains(ref)) {
reportActionError(pluginId, "action specified by reference isn't registered (ID=" + ref + ")");
}
return null;
}
assertActionIsGroupOrStub(action);
return action;
}
private void processActionsElement(Element element, ClassLoader loader, PluginId pluginId) {
if (!ACTIONS_ELEMENT_NAME.equals(element.getName())) {
reportActionError(pluginId, "unexpected name of element \"" + element.getName() + "\"");
return;
}
synchronized (myLock) {
for (final Object o : element.getChildren()) {
Element child = (Element)o;
processActionsChildElement(loader, pluginId, child);
}
}
}
private void processActionsChildElement(final ClassLoader loader, final PluginId pluginId, final Element child) {
String name = child.getName();
if (ACTION_ELEMENT_NAME.equals(name)) {
AnAction action = processActionElement(child, loader, pluginId);
if (action != null) {
assertActionIsGroupOrStub(action);
}
}
else if (GROUP_ELEMENT_NAME.equals(name)) {
processGroupElement(child, loader, pluginId);
}
else if (SEPARATOR_ELEMENT_NAME.equals(name)) {
processSeparatorNode(null, child, pluginId);
}
else if (REFERENCE_ELEMENT_NAME.equals(name)) {
processReferenceNode(child, pluginId);
}
else {
reportActionError(pluginId, "unexpected name of element \"" + name + "\n");
}
}
private static void assertActionIsGroupOrStub(final AnAction action) {
if (!(action instanceof ActionGroup || action instanceof ActionStub)) {
LOG.assertTrue(false, "Action : "+action + "; class: "+action.getClass());
}
}
public void registerAction(@NotNull String actionId, @NotNull AnAction action, @Nullable PluginId pluginId) {
synchronized (myLock) {
if (myId2Action.containsKey(actionId)) {
reportActionError(pluginId, "action with the ID \"" + actionId + "\" was already registered. Action being registered is " + action.toString() +
"; Registered action is " +
myId2Action.get(actionId) + getPluginInfo(pluginId));
return;
}
if (myAction2Id.containsKey(action)) {
reportActionError(pluginId, "action was already registered for another ID. ID is " + myAction2Id.get(action) +
getPluginInfo(pluginId));
return;
}
myId2Action.put(actionId, action);
myId2Index.put(actionId, myRegisteredActionsCount++);
myAction2Id.put(action, actionId);
if (pluginId != null && !(action instanceof ActionGroup)){
THashSet<String> pluginActionIds = myPlugin2Id.get(pluginId);
if (pluginActionIds == null){
pluginActionIds = new THashSet<String>();
myPlugin2Id.put(pluginId, pluginActionIds);
}
pluginActionIds.add(actionId);
}
action.registerCustomShortcutSet(new ProxyShortcutSet(actionId, myKeymapManager), null);
}
}
private static void reportActionError(final PluginId pluginId, @NonNls final String message) {
if (pluginId == null) {
LOG.error(message);
}
else {
LOG.error(new PluginException(message, null, pluginId));
}
}
@NonNls
private static String getPluginInfo(@Nullable PluginId id) {
if (id != null) {
final IdeaPluginDescriptor plugin = ApplicationManager.getApplication().getPlugin(id);
if (plugin != null) {
String name = plugin.getName();
if (name == null) {
name = id.getIdString();
}
return " Plugin: " + name;
}
}
return "";
}
public void registerAction(@NotNull String actionId, @NotNull AnAction action) {
registerAction(actionId, action, null);
}
public void unregisterAction(@NotNull String actionId) {
synchronized (myLock) {
if (!myId2Action.containsKey(actionId)) {
if (LOG.isDebugEnabled()) {
LOG.debug("action with ID " + actionId + " wasn't registered");
return;
}
}
AnAction oldValue = (AnAction)myId2Action.remove(actionId);
myAction2Id.remove(oldValue);
myId2Index.remove(actionId);
for (PluginId pluginName : myPlugin2Id.keySet()) {
final THashSet<String> pluginActions = myPlugin2Id.get(pluginName);
if (pluginActions != null) {
pluginActions.remove(actionId);
}
}
}
}
@NotNull
public String getComponentName() {
final String platformPrefix = System.getProperty("idea.platform.prefix");
return platformPrefix != null ? platformPrefix + "ActionManager" : "ActionManager";
}
public Comparator<String> getRegistrationOrderComparator() {
return new Comparator<String>() {
public int compare(String id1, String id2) {
return myId2Index.get(id1) - myId2Index.get(id2);
}
};
}
public String[] getPluginActions(PluginId pluginName) {
if (myPlugin2Id.containsKey(pluginName)){
final THashSet<String> pluginActions = myPlugin2Id.get(pluginName);
return pluginActions.toArray(new String[pluginActions.size()]);
}
return ArrayUtil.EMPTY_STRING_ARRAY;
}
public void addActionPopup(final ActionPopupMenuImpl menu) {
myPopups.add(menu);
}
public void removeActionPopup(final ActionPopupMenuImpl menu) {
final boolean removed = myPopups.remove(menu);
if (removed && myPopups.size() == 0) {
flushActionPerformed();
}
}
public void queueActionPerformedEvent(final AnAction action, DataContext context) {
if (myPopups.size() > 0) {
myQueuedNotifications.put(action, context);
} else {
fireAfterActionPerformed(action, context);
}
}
public boolean isActionPopupStackEmpty() {
return myPopups.size() == 0;
}
private void flushActionPerformed() {
final Set<AnAction> actions = myQueuedNotifications.keySet();
for (final AnAction eachAction : actions) {
final DataContext eachContext = myQueuedNotifications.get(eachAction);
fireAfterActionPerformed(eachAction, eachContext);
}
myQueuedNotifications.clear();
}
private AnActionListener[] getActionListeners() {
if (myCachedActionListeners == null) {
myCachedActionListeners = myActionListeners.toArray(new AnActionListener[myActionListeners.size()]);
}
return myCachedActionListeners;
}
public void addAnActionListener(AnActionListener listener) {
myActionListeners.add(listener);
myCachedActionListeners = null;
}
public void addAnActionListener(final AnActionListener listener, final Disposable parentDisposable) {
addAnActionListener(listener);
Disposer.register(parentDisposable, new Disposable() {
public void dispose() {
removeAnActionListener(listener);
}
});
}
public void removeAnActionListener(AnActionListener listener) {
myActionListeners.remove(listener);
myCachedActionListeners = null;
}
public void fireBeforeActionPerformed(AnAction action, DataContext dataContext) {
if (action != null) {
myPrevPerformedActionId = myLastPreformedActionId;
myLastPreformedActionId = getId(action);
IdeaLogger.ourLastActionId = myLastPreformedActionId;
}
AnActionListener[] listeners = getActionListeners();
for (AnActionListener listener : listeners) {
listener.beforeActionPerformed(action, dataContext);
}
}
public void fireAfterActionPerformed(AnAction action, DataContext dataContext) {
if (action != null) {
myPrevPerformedActionId = myLastPreformedActionId;
myLastPreformedActionId = getId(action);
IdeaLogger.ourLastActionId = myLastPreformedActionId;
}
AnActionListener[] listeners = getActionListeners();
for (AnActionListener listener : listeners) {
try {
listener.afterActionPerformed(action, dataContext);
}
catch(AbstractMethodError e) {
// ignore
}
}
}
public void fireBeforeEditorTyping(char c, DataContext dataContext) {
myLastTimeEditorWasTypedIn = System.currentTimeMillis();
AnActionListener[] listeners = getActionListeners();
for (AnActionListener listener : listeners) {
listener.beforeEditorTyping(c, dataContext);
}
}
public String getLastPreformedActionId() {
return myLastPreformedActionId;
}
public String getPrevPreformedActionId() {
return myPrevPerformedActionId;
}
public Set<String> getActionIds(){
return new HashSet<String>(myId2Action.keySet());
}
private int myActionsPreloaded = 0;
public void preloadActions() {
if (myPreloadActionsRunnable == null) {
myPreloadActionsRunnable = new Runnable() {
public void run() {
doPreloadActions();
}
};
ApplicationManager.getApplication().executeOnPooledThread(myPreloadActionsRunnable);
}
}
private void doPreloadActions() {
try {
Thread.sleep(5000); // wait for project initialization to complete
}
catch (InterruptedException e) {
// ignore
}
preloadActionGroup(IdeActions.GROUP_EDITOR_POPUP);
preloadActionGroup(IdeActions.GROUP_EDITOR_TAB_POPUP);
preloadActionGroup(IdeActions.GROUP_PROJECT_VIEW_POPUP);
preloadActionGroup(IdeActions.GROUP_MAIN_MENU);
// TODO anything else?
LOG.debug("Actions preloading completed");
}
public void preloadActionGroup(final String groupId) {
final AnAction action = getAction(groupId);
if (action instanceof DefaultActionGroup) {
preloadActionGroup((DefaultActionGroup) action);
}
}
private void preloadActionGroup(final DefaultActionGroup group) {
final AnAction[] actions = group.getChildActionsOrStubs(null);
for (AnAction action : actions) {
if (action instanceof ActionStub) {
AnAction convertedAction = null;
synchronized (myLock) {
final String id = myAction2Id.get(action);
if (id != null) {
convertedAction = convert((ActionStub)action);
}
}
if (convertedAction instanceof PreloadableAction) {
final PreloadableAction preloadableAction = (PreloadableAction)convertedAction;
preloadableAction.preload();
}
myActionsPreloaded++;
if (myActionsPreloaded % 10 == 0) {
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
// ignore
}
}
}
else if (action instanceof DefaultActionGroup) {
preloadActionGroup((DefaultActionGroup) action);
}
}
}
private class MyTimer extends Timer implements ActionListener {
private final List<TimerListener> myTimerListeners = Collections.synchronizedList(new ArrayList<TimerListener>());
private int myLastTimePerformed;
MyTimer() {
super(TIMER_DELAY, null);
addActionListener(this);
setRepeats(true);
}
public void addTimerListener(TimerListener listener){
myTimerListeners.add(listener);
}
public void removeTimerListener(TimerListener listener){
final boolean removed = myTimerListeners.remove(listener);
if (!removed) {
LOG.assertTrue(false, "Unknown listener " + listener);
}
}
public void actionPerformed(ActionEvent e) {
if (myLastTimeEditorWasTypedIn + UPDATE_DELAY_AFTER_TYPING > System.currentTimeMillis()) {
return;
}
final int lastEventCount = myLastTimePerformed;
myLastTimePerformed = ActivityTracker.getInstance().getCount();
if (myLastTimePerformed == lastEventCount) {
return;
}
TimerListener[] listeners = myTimerListeners.toArray(new TimerListener[myTimerListeners.size()]);
for (TimerListener listener : listeners) {
runListenerAction(listener);
}
}
private void runListenerAction(final TimerListener listener) {
ModalityState modalityState = listener.getModalityState();
if (modalityState == null) return;
if (!ModalityState.current().dominates(modalityState)) {
listener.run();
}
}
}
}
| remove unnecessary debugging
| platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java | remove unnecessary debugging | <ide><path>latform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java
<ide> ref = element.getAttributeValue(ID_ATTR_NAME);
<ide> }
<ide>
<del> if (LOG.isDebugEnabled()) {
<del> LOG.debug("ref=\"" + ref + "\"");
<del> }
<ide> if (ref == null || ref.length() == 0) {
<ide> reportActionError(pluginId, "ID of reference element should be defined");
<ide> return null; |
|
JavaScript | mit | 1dd9ee2397c11c34f2fcdf9a0bec70ba2e12c0f9 | 0 | BernhardRode/lodash,jshanson7/lodash,AndBicScadMedia/lodash,gdi2290/lodash,jacwright/lodash,af7/lodash,tonyonodi/lodash,neouser99/lodash,developer-prosenjit/lodash,javiosyc/lodash,rlugojr/lodash,Droogans/lodash,phillipalexander/lodash,IveWong/lodash,r14r/fork_javascript_lodash,transGLUKator/lodash,tonyonodi/lodash,phillipalexander/lodash,AneesMohammed/lodash,codydaig/lodash,tquetano-r7/lodash,krahman/lodash,studiowangfei/lodash,greyhwndz/lodash,schnerd/lodash,mshoaibraja/lodash,rlugojr/lodash,af7/lodash,zestia/lodash,tquetano-r7/lodash,enng0227/lodash,therebelbeta/lodash,jshanson7/lodash,af7/lodash,MaxPRafferty/lodash,codydaig/lodash,krahman/lodash,jasnell/lodash,justintung/lodash,IveWong/lodash,schnerd/lodash,Droogans/lodash,PhiLhoSoft/lodash,jzning-martian/lodash,joshuaprior/lodash,nsamarcos/lodash,julianocomg/lodash,benweet/lodash,ror/lodash,jacwright/lodash,jasnell/lodash,justintung/lodash,leolin1229/lodash,justintung/lodash,Xotic750/lodash,Andrey-Pavlov/lodash,gutenye/lodash,hitesh97/lodash,mshoaibraja/lodash,Droogans/lodash,tgriesser/lodash,ror/lodash,timruffles/lodash,hafeez-syed/lodash,Moykn/lodash,bnicart/lodash,dgoncalves1/lodash,leolin1229/lodash,benweet/lodash,krahman/lodash,PhiLhoSoft/lodash,steelsojka/lodash,beaugunderson/lodash,PhiLhoSoft/lodash,beaugunderson/lodash,studiowangfei/lodash,xixilive/lodash,imjerrybao/lodash,r14r-work/fork_javascript_lodash,reggi/lodash,youprofit/lodash,enng0227/lodash,shwaydogg/lodash,nsamarcos/lodash,woldie/lodash,gutenye/lodash,ajefremovs/lodash,naoina/lodash,zhangguangyong/lodash,felixshu/lodash,lekoaf/lodash,chrootsu/lodash,boneskull/lodash,polarbird/lodash,AndBicScadMedia/lodash,jasnell/lodash,zhangguangyong/lodash,samuelbeek/lodash,greyhwndz/lodash,jshanson7/lodash,felixshu/lodash,polarbird/lodash,lekkas/lodash,ricardohbin/lodash,samuelbeek/lodash,stewx/lodash,shwaydogg/lodash,transGLUKator/lodash,tgriesser/lodash,mshoaibraja/lodash,lekkas/lodash,AneesMohammed/lodash,imjerrybao/lodash,lekoaf/lodash,ricardohbin/lodash,tejokumar/lodash,bnicart/lodash,Moykn/lodash,IveWong/lodash,mjosh954/lodash,r14r-work/fork_javascript_lodash,hafeez-syed/lodash,stewx/lodash,BernhardRode/lodash,BernhardRode/lodash,MaxPRafferty/lodash,msmorgan/lodash,rtorr/lodash,xixilive/lodash,ricardohbin/lodash,jzning-martian/lodash,Andrey-Pavlov/lodash,youprofit/lodash,studiowangfei/lodash,therebelbeta/lodash,Lottid/lodash,krrg/lodash,gdi2290/lodash,MaxPRafferty/lodash,gutenye/lodash,stewx/lodash,developer-prosenjit/lodash,lzheng571/lodash,timruffles/lodash,prawnsalad/lodash,Xotic750/lodash,woldie/lodash,reggi/lodash,Lottid/lodash,javiosyc/lodash,andersonaguiar/lodash,joshuaprior/lodash,ror/lodash,Jaspersoft/lodash,krrg/lodash,Moykn/lodash,rtorr/lodash,boneskull/lodash,tquetano-r7/lodash,woldie/lodash,reggi/lodash,nbellowe/lodash,Jaspersoft/lodash,hafeez-syed/lodash,naoina/lodash,rtorr/lodash,ajefremovs/lodash,ajefremovs/lodash,samuelbeek/lodash,tgriesser/lodash,nbellowe/lodash,felixshu/lodash,julianocomg/lodash,huyinghuan/lodash,msmorgan/lodash,Andrey-Pavlov/lodash,chrootsu/lodash,andersonaguiar/lodash,zestia/lodash,jzning-martian/lodash,mjosh954/lodash,dgoncalves1/lodash,prawnsalad/lodash,xiwc/lodash,lzheng571/lodash,javiosyc/lodash,prawnsalad/lodash,imjerrybao/lodash,steelsojka/lodash,lzheng571/lodash,nsamarcos/lodash,benweet/lodash,hitesh97/lodash,timruffles/lodash,huyinghuan/lodash,neouser99/lodash,jacwright/lodash,tejokumar/lodash,enng0227/lodash,nbellowe/lodash,r14r-work/fork_javascript_lodash,greyhwndz/lodash,krrg/lodash,schnerd/lodash,dgoncalves1/lodash,xiwc/lodash,r14r/fork_javascript_lodash,r14r/fork_javascript_lodash,andersonaguiar/lodash,Jaspersoft/lodash,leolin1229/lodash,phillipalexander/lodash,Xotic750/lodash,transGLUKator/lodash,bnicart/lodash,xixilive/lodash,neouser99/lodash,Lottid/lodash,mjosh954/lodash,huyinghuan/lodash,joshuaprior/lodash,lekkas/lodash,therebelbeta/lodash,zhangguangyong/lodash,AndBicScadMedia/lodash,shwaydogg/lodash,julianocomg/lodash,developer-prosenjit/lodash,lekoaf/lodash,hitesh97/lodash,xiwc/lodash,polarbird/lodash,youprofit/lodash,AneesMohammed/lodash,naoina/lodash,zestia/lodash,codydaig/lodash,chrootsu/lodash,tejokumar/lodash | #!/usr/bin/env node
;(function() {
'use strict';
/** The Node filesystem, path, `zlib`, and child process modules */
var fs = require('fs'),
gzip = require('zlib').gzip,
path = require('path'),
spawn = require('child_process').spawn;
/** The directory that is the base of the repository */
var basePath = path.join(__dirname, '../');
/** The directory where the Closure Compiler is located */
var closurePath = path.join(basePath, 'vendor', 'closure-compiler', 'compiler.jar');
/** The distribution directory */
var distPath = path.join(basePath, 'dist');
/** Load other modules */
var preprocess = require(path.join(__dirname, 'pre-compile')),
postprocess = require(path.join(__dirname, 'post-compile')),
uglifyJS = require(path.join(basePath, 'vendor', 'uglifyjs', 'uglify-js'));
/** Closure Compiler command-line options */
var closureOptions = [
'--compilation_level=ADVANCED_OPTIMIZATIONS',
'--language_in=ECMASCRIPT5_STRICT',
'--warning_level=QUIET'
];
/*--------------------------------------------------------------------------*/
/**
* The exposed `minify` function minifies a given `source` and invokes the
* `onComplete` callback when finished.
*
* @param {String} source The source to minify.
* @param {String} workingName The name to give temporary files creates during the minification process.
* @param {Function} onComplete A function called when minification has completed.
*/
function minify(source, workingName, onComplete) {
new Minify(source, workingName, onComplete);
}
/**
* The Minify constructor used to keep state of each `minify` invocation.
*
* @private
* @constructor
* @param {String} source The source to minify.
* @param {String} workingName The name to give temporary files creates during the minification process.
* @param {Function} onComplete A function called when minification has completed.
*/
function Minify(source, workingName, onComplete) {
// create the destination directory if it doesn't exist
if (!fs.existsSync(distPath)) {
fs.mkdirSync(distPath);
}
this.compiled = {};
this.hybrid = {};
this.uglified = {};
this.onComplete = onComplete;
this.source = source = preprocess(source);
this.workingName = workingName;
// begin the minification process
closureCompile.call(this, source, onClosureCompile.bind(this));
}
/*--------------------------------------------------------------------------*/
/**
* Compresses a `source` string using the Closure Compiler. Yields the
* minified result, and any exceptions encountered, to a `callback` function.
*
* @private
* @param {String} source The JavaScript source to minify.
* @param {String} [message] The message to log.
* @param {Function} callback The function to call once the process completes.
*/
function closureCompile(source, message, callback) {
// the standard error stream, standard output stream, and Closure Compiler process
var error = '',
output = '',
compiler = spawn('java', ['-jar', closurePath].concat(closureOptions));
// juggle arguments
if (typeof message == 'function') {
callback = message;
message = null;
}
console.log(message == null
? 'Compressing ' + this.workingName + ' using the Closure Compiler...'
: message
);
compiler.stdout.on('data', function(data) {
// append the data to the output stream
output += data;
});
compiler.stderr.on('data', function(data) {
// append the error message to the error stream
error += data;
});
compiler.on('exit', function(status) {
var exception = null;
// `status` contains the process exit code
if (status) {
exception = new Error(error);
exception.status = status;
}
callback(exception, output);
});
// proxy the standard input to the Closure Compiler
compiler.stdin.end(source);
}
/**
* Compresses a `source` string using UglifyJS. Yields the result to a
* `callback` function. This function is synchronous; the `callback` is used
* for symmetry.
*
* @private
* @param {String} source The JavaScript source to minify.
* @param {String} [message] The message to log.
* @param {Function} callback The function to call once the process completes.
*/
function uglify(source, message, callback) {
var exception,
result,
ugly = uglifyJS.uglify;
// juggle arguments
if (typeof message == 'function') {
callback = message;
message = null;
}
console.log(message == null
? 'Compressing ' + this.workingName + ' using UglifyJS...'
: message
);
try {
result = ugly.gen_code(
// enable unsafe transformations
ugly.ast_squeeze_more(
ugly.ast_squeeze(
// munge variable and function names, excluding the special `define`
// function exposed by AMD loaders
ugly.ast_mangle(uglifyJS.parser.parse(source), {
'except': ['define']
}
))), {
'ascii_only': true
});
} catch(e) {
exception = e;
}
// lines are restricted to 500 characters for consistency with the Closure Compiler
callback(exception, result && ugly.split_lines(result, 500));
}
/*--------------------------------------------------------------------------*/
/**
* The `closureCompile()` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onClosureCompile(exception, result) {
if (exception) {
throw exception;
}
// store the post-processed Closure Compiler result and gzip it
this.compiled.source = result = postprocess(result);
gzip(result, onClosureGzip.bind(this));
}
/**
* The Closure Compiler `gzip` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onClosureGzip(exception, result) {
if (exception) {
throw exception;
}
// store the gzipped result and report the size
this.compiled.gzip = result;
console.log('Done. Size: %d bytes.', result.length);
// next, minify the source using only UglifyJS
uglify.call(this, this.source, onUglify.bind(this));
}
/**
* The `uglify()` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onUglify(exception, result) {
if (exception) {
throw exception;
}
// store the post-processed Uglified result and gzip it
this.uglified.source = result = postprocess(result);
gzip(result, onUglifyGzip.bind(this));
}
/**
* The UglifyJS `gzip` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onUglifyGzip(exception, result) {
if (exception) {
throw exception;
}
var message = 'Compressing ' + this.workingName + ' using hybrid minification...';
// store the gzipped result and report the size
this.uglified.gzip = result;
console.log('Done. Size: %d bytes.', result.length);
// next, minify the Closure Compiler minified source using UglifyJS
uglify.call(this, this.compiled.source, message, onHybrid.bind(this));
}
/**
* The hybrid `uglify()` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onHybrid(exception, result) {
if (exception) {
throw exception;
}
// store the post-processed Uglified result and gzip it
this.hybrid.source = result = postprocess(result);
gzip(result, onHybridGzip.bind(this));
}
/**
* The hybrid `gzip` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onHybridGzip(exception, result) {
if (exception) {
throw exception;
}
// store the gzipped result and report the size
this.hybrid.gzip = result;
console.log('Done. Size: %d bytes.', result.length);
// finish by choosing the smallest compressed file
onComplete.call(this);
}
/**
* The callback executed after JavaScript source is minified and gzipped.
*
* @private
*/
function onComplete() {
var compiled = this.compiled,
hybrid = this.hybrid,
name = this.workingName,
uglified = this.uglified;
// save the Closure Compiled version to disk
fs.writeFileSync(path.join(distPath, name + '.compiler.js'), compiled.source);
fs.writeFileSync(path.join(distPath, name + '.compiler.js.gz'), compiled.gzip);
// save the Uglified version to disk
fs.writeFileSync(path.join(distPath, name + '.uglify.js'), uglified.source);
fs.writeFileSync(path.join(distPath, name + '.uglify.js.gz'), uglified.gzip);
// save the hybrid minified version to disk
fs.writeFileSync(path.join(distPath, name + '.hybrid.js'), hybrid.source);
fs.writeFileSync(path.join(distPath, name + '.hybrid.js.gz'), hybrid.gzip);
// select the smallest gzipped file and use its minified counterpart as the
// official minified release (ties go to Closure Compiler)
var min = Math.min(compiled.gzip.length, hybrid.gzip.length, uglified.gzip.length);
// pass the minified source to the minify instances "onComplete" callback
this.onComplete(
compiled.gzip.length == min
? compiled.source
: uglified.gzip.length == min
? uglified.source
: hybrid.source
);
}
/*--------------------------------------------------------------------------*/
// expose `minify`
if (module != require.main) {
module.exports = minify;
}
else {
// read the JavaScript source file from the first argument if the script
// was invoked directly (e.g. `node minify.js source.js`) and write to
// the same file
(function() {
var filePath = process.argv[2],
dirPath = path.dirname(filePath),
source = fs.readFileSync(filePath, 'utf8'),
workingName = path.basename(filePath, '.js') + '.min';
minify(source, workingName, function(result) {
fs.writeFileSync(path.join(dirPath, workingName + '.js'), result);
});
}());
}
}());
| build/minify.js | #!/usr/bin/env node
;(function() {
'use strict';
/** The Node filesystem, path, `zlib`, and child process modules */
var fs = require('fs'),
gzip = require('zlib').gzip,
path = require('path'),
spawn = require('child_process').spawn;
/** The directory that is the base of the repository */
var basePath = path.join(__dirname, '../');
/** The directory where the Closure Compiler is located */
var closurePath = path.join(basePath, 'vendor', 'closure-compiler', 'compiler.jar');
/** The distribution directory */
var distPath = path.join(basePath, 'dist');
/** Load other modules */
var preprocess = require(path.join(__dirname, 'pre-compile')),
postprocess = require(path.join(__dirname, 'post-compile')),
uglifyJS = require(path.join(basePath, 'vendor', 'uglifyjs', 'uglify-js'));
/** Closure Compiler command-line options */
var closureOptions = [
'--compilation_level=ADVANCED_OPTIMIZATIONS',
'--language_in=ECMASCRIPT5_STRICT',
'--warning_level=QUIET'
];
/*--------------------------------------------------------------------------*/
/**
* The exposed `minify` function minifies a given `source` and invokes the
* `onComplete` callback when finished.
*
* @param {String} source The source to minify.
* @param {String} workingName The name to give temporary files creates during the minification process.
* @param {Function} onComplete A function called when minification has completed.
*/
function minify(source, workingName, onComplete) {
new Minify(source, workingName, onComplete);
}
/**
* The Minify constructor used to keep state of each `minify` invocation.
*
* @private
* @constructor
* @param {String} source The source to minify.
* @param {String} workingName The name to give temporary files creates during the minification process.
* @param {Function} onComplete A function called when minification has completed.
*/
function Minify(source, workingName, onComplete) {
// create the destination directory if it doesn't exist
if (!path.existsSync(distPath)) {
fs.mkdirSync(distPath);
}
this.compiled = {};
this.hybrid = {};
this.uglified = {};
this.onComplete = onComplete;
this.source = source = preprocess(source);
this.workingName = workingName;
// begin the minification process
closureCompile.call(this, source, onClosureCompile.bind(this));
}
/*--------------------------------------------------------------------------*/
/**
* Compresses a `source` string using the Closure Compiler. Yields the
* minified result, and any exceptions encountered, to a `callback` function.
*
* @private
* @param {String} source The JavaScript source to minify.
* @param {String} [message] The message to log.
* @param {Function} callback The function to call once the process completes.
*/
function closureCompile(source, message, callback) {
// the standard error stream, standard output stream, and Closure Compiler process
var error = '',
output = '',
compiler = spawn('java', ['-jar', closurePath].concat(closureOptions));
// juggle arguments
if (typeof message == 'function') {
callback = message;
message = null;
}
console.log(message == null
? 'Compressing ' + this.workingName + ' using the Closure Compiler...'
: message
);
compiler.stdout.on('data', function(data) {
// append the data to the output stream
output += data;
});
compiler.stderr.on('data', function(data) {
// append the error message to the error stream
error += data;
});
compiler.on('exit', function(status) {
var exception = null;
// `status` contains the process exit code
if (status) {
exception = new Error(error);
exception.status = status;
}
callback(exception, output);
});
// proxy the standard input to the Closure Compiler
compiler.stdin.end(source);
}
/**
* Compresses a `source` string using UglifyJS. Yields the result to a
* `callback` function. This function is synchronous; the `callback` is used
* for symmetry.
*
* @private
* @param {String} source The JavaScript source to minify.
* @param {String} [message] The message to log.
* @param {Function} callback The function to call once the process completes.
*/
function uglify(source, message, callback) {
var exception,
result,
ugly = uglifyJS.uglify;
// juggle arguments
if (typeof message == 'function') {
callback = message;
message = null;
}
console.log(message == null
? 'Compressing ' + this.workingName + ' using UglifyJS...'
: message
);
try {
result = ugly.gen_code(
// enable unsafe transformations
ugly.ast_squeeze_more(
ugly.ast_squeeze(
// munge variable and function names, excluding the special `define`
// function exposed by AMD loaders
ugly.ast_mangle(uglifyJS.parser.parse(source), {
'except': ['define']
}
))), {
'ascii_only': true
});
} catch(e) {
exception = e;
}
// lines are restricted to 500 characters for consistency with the Closure Compiler
callback(exception, result && ugly.split_lines(result, 500));
}
/*--------------------------------------------------------------------------*/
/**
* The `closureCompile()` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onClosureCompile(exception, result) {
if (exception) {
throw exception;
}
// store the post-processed Closure Compiler result and gzip it
this.compiled.source = result = postprocess(result);
gzip(result, onClosureGzip.bind(this));
}
/**
* The Closure Compiler `gzip` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onClosureGzip(exception, result) {
if (exception) {
throw exception;
}
// store the gzipped result and report the size
this.compiled.gzip = result;
console.log('Done. Size: %d bytes.', result.length);
// next, minify the source using only UglifyJS
uglify.call(this, this.source, onUglify.bind(this));
}
/**
* The `uglify()` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onUglify(exception, result) {
if (exception) {
throw exception;
}
// store the post-processed Uglified result and gzip it
this.uglified.source = result = postprocess(result);
gzip(result, onUglifyGzip.bind(this));
}
/**
* The UglifyJS `gzip` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onUglifyGzip(exception, result) {
if (exception) {
throw exception;
}
var message = 'Compressing ' + this.workingName + ' using hybrid minification...';
// store the gzipped result and report the size
this.uglified.gzip = result;
console.log('Done. Size: %d bytes.', result.length);
// next, minify the Closure Compiler minified source using UglifyJS
uglify.call(this, this.compiled.source, message, onHybrid.bind(this));
}
/**
* The hybrid `uglify()` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onHybrid(exception, result) {
if (exception) {
throw exception;
}
// store the post-processed Uglified result and gzip it
this.hybrid.source = result = postprocess(result);
gzip(result, onHybridGzip.bind(this));
}
/**
* The hybrid `gzip` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onHybridGzip(exception, result) {
if (exception) {
throw exception;
}
// store the gzipped result and report the size
this.hybrid.gzip = result;
console.log('Done. Size: %d bytes.', result.length);
// finish by choosing the smallest compressed file
onComplete.call(this);
}
/**
* The callback executed after JavaScript source is minified and gzipped.
*
* @private
*/
function onComplete() {
var compiled = this.compiled,
hybrid = this.hybrid,
name = this.workingName,
uglified = this.uglified;
// save the Closure Compiled version to disk
fs.writeFileSync(path.join(distPath, name + '.compiler.js'), compiled.source);
fs.writeFileSync(path.join(distPath, name + '.compiler.js.gz'), compiled.gzip);
// save the Uglified version to disk
fs.writeFileSync(path.join(distPath, name + '.uglify.js'), uglified.source);
fs.writeFileSync(path.join(distPath, name + '.uglify.js.gz'), uglified.gzip);
// save the hybrid minified version to disk
fs.writeFileSync(path.join(distPath, name + '.hybrid.js'), hybrid.source);
fs.writeFileSync(path.join(distPath, name + '.hybrid.js.gz'), hybrid.gzip);
// select the smallest gzipped file and use its minified counterpart as the
// official minified release (ties go to Closure Compiler)
var min = Math.min(compiled.gzip.length, hybrid.gzip.length, uglified.gzip.length);
// pass the minified source to the minify instances "onComplete" callback
this.onComplete(
compiled.gzip.length == min
? compiled.source
: uglified.gzip.length == min
? uglified.source
: hybrid.source
);
}
/*--------------------------------------------------------------------------*/
// expose `minify`
if (module != require.main) {
module.exports = minify;
}
else {
// read the JavaScript source file from the first argument if the script
// was invoked directly (e.g. `node minify.js source.js`) and write to
// the same file
(function() {
var filePath = process.argv[2],
dirPath = path.dirname(filePath),
source = fs.readFileSync(filePath, 'utf8'),
workingName = path.basename(filePath, '.js') + '.min';
minify(source, workingName, function(result) {
fs.writeFileSync(path.join(dirPath, workingName + '.js'), result);
});
}());
}
}());
| Switch to non-deprecated `fs.existsSync`.
Former-commit-id: 616863cf7e7edfdf919750773a12e8cd2a42ddf1 | build/minify.js | Switch to non-deprecated `fs.existsSync`. | <ide><path>uild/minify.js
<ide> */
<ide> function Minify(source, workingName, onComplete) {
<ide> // create the destination directory if it doesn't exist
<del> if (!path.existsSync(distPath)) {
<add> if (!fs.existsSync(distPath)) {
<ide> fs.mkdirSync(distPath);
<ide> }
<ide> |
|
JavaScript | mit | 9baf8335e523294b8266dba58dd1586cb096b219 | 0 | dayo7116/scenejs,tsherif/scenejs,dayo7116/scenejs,tsherif/scenejs | /**
* A scene node that defines one or more layers of texture to apply to geometries within its subgraph
* that have UV coordinates.
*/
var SceneJS_textureModule = new (function() {
var idStack = [];
var textureStack = [];
var stackLen = 0;
var dirty;
SceneJS_eventModule.addListener(
SceneJS_eventModule.INIT,
function() {
});
SceneJS_eventModule.addListener(
SceneJS_eventModule.SCENE_COMPILING,
function() {
stackLen = 0;
dirty = true;
});
SceneJS_eventModule.addListener(
SceneJS_eventModule.SCENE_RENDERING,
function() {
if (dirty) {
if (stackLen > 0) {
SceneJS_DrawList.setTexture(idStack[stackLen - 1], textureStack[stackLen - 1]);
} else {
SceneJS_DrawList.setTexture();
}
dirty = false;
}
});
/** Creates texture from either image URL or image object
*/
function createTexture(scene, cfg, onComplete) {
var context = scene.canvas.context;
var textureId = SceneJS._createUUID();
var update;
try {
if (cfg.autoUpdate) {
update = function() {
//TODO: fix this when minefield is upto spec
try {
context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, image);
}
catch(e) {
context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, image, null);
}
context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);
//context.generateMipmap(context.TEXTURE_2D);
};
}
return new SceneJS_webgl_Texture2D(context, {
textureId : textureId,
canvas: scene.canvas,
image : cfg.image,
url: cfg.uri,
texels :cfg.texels,
minFilter : getGLOption("minFilter", context, cfg, context.NEAREST_MIPMAP_NEAREST),
magFilter : getGLOption("magFilter", context, cfg, context.LINEAR),
wrapS : getGLOption("wrapS", context, cfg, context.CLAMP_TO_EDGE),
wrapT : getGLOption("wrapT", context, cfg, context.CLAMP_TO_EDGE),
isDepth : getOption(cfg.isDepth, false),
depthMode : getGLOption("depthMode", context, cfg, context.LUMINANCE),
depthCompareMode : getGLOption("depthCompareMode", context, cfg, context.COMPARE_R_TO_TEXTURE),
depthCompareFunc : getGLOption("depthCompareFunc", context, cfg, context.LEQUAL),
flipY : getOption(cfg.flipY, true),
width: getOption(cfg.width, 1),
height: getOption(cfg.height, 1),
internalFormat : getGLOption("internalFormat", context, cfg, context.LEQUAL),
sourceFormat : getGLOption("sourceType", context, cfg, context.ALPHA),
sourceType : getGLOption("sourceType", context, cfg, context.UNSIGNED_BYTE),
logging: SceneJS_loggingModule ,
update: update
}, onComplete);
} catch (e) {
throw SceneJS_errorModule.fatalError(SceneJS.errors.ERROR, "Failed to create texture: " + e.message || e);
}
}
function getGLOption(name, context, cfg, defaultVal) {
var value = cfg[name];
if (value == undefined) {
return defaultVal;
}
var glName = SceneJS_webgl_enumMap[value];
if (glName == undefined) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.ILLEGAL_NODE_CONFIG,
"Unrecognised value for texture node property '" + name + "' value: '" + value + "'");
}
var glValue = context[glName];
// if (!glValue) {
// throw new SceneJS.errors.WebGLUnsupportedNodeConfigException(
// "This browser's WebGL does not support value of SceneJS.texture node property '" + name + "' value: '" + value + "'");
// }
return glValue;
}
function getOption(value, defaultVal) {
return (value == undefined) ? defaultVal : value;
}
function destroyTexture(texture) {
texture.destroy();
}
/*----------------------------------------------------------------------------------------------------------------
* Texture node
*---------------------------------------------------------------------------------------------------------------*/
var Texture = SceneJS.createNodeType("texture");
Texture.prototype._init = function(params) {
if (this.core._nodeCount == 1) { // This node is the resource definer
this.core.layers = [];
this.core.params = {};
var config = SceneJS_debugModule.getConfigs("texturing") || {};
var waitForLoad = (config.waitForLoad != undefined && config.waitForLoad != null)
? config.waitForLoad
: params.waitForLoad;
if (!params.layers) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layers missing");
}
if (!SceneJS._isArray(params.layers)) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layers should be an array");
}
for (var i = 0; i < params.layers.length; i++) {
var layerParam = params.layers[i];
if (!layerParam.uri && !layerParam.frameBuf && !layerParam.video && !layerParam.image && !layerParam.canvasId) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layer " + i + " has no uri, frameBuf, video or canvasId specified");
}
if (layerParam.applyFrom) {
if (layerParam.applyFrom != "uv" &&
layerParam.applyFrom != "uv2" &&
layerParam.applyFrom != "normal" &&
layerParam.applyFrom != "geometry") {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layer " + i + " applyFrom value is unsupported - " +
"should be either 'uv', 'uv2', 'normal' or 'geometry'");
}
}
if (layerParam.applyTo) {
if (layerParam.applyTo != "baseColor" && // Colour map
layerParam.applyTo != "specular" && // Specular map
layerParam.applyTo != "emit" && // Emission map
layerParam.applyTo != "alpha" && // Alpha map
// layerParam.applyTo != "diffuseColor" &&
layerParam.applyTo != "normals") {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layer " + i + " applyTo value is unsupported - " +
"should be either 'baseColor', 'specular' or 'normals'");
}
}
if (layerParam.blendMode) {
if (layerParam.blendMode != "add" && layerParam.blendMode != "multiply") {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layer " + i + " blendMode value is unsupported - " +
"should be either 'add' or 'multiply'");
}
}
var layer = {
image : null, // Initialised when state == IMAGE_LOADED
creationParams: layerParam, // Create texture using this
waitForLoad: waitForLoad,
texture: null, // Initialised when state == TEXTURE_LOADED
applyFrom: layerParam.applyFrom || "uv",
applyTo: layerParam.applyTo || "baseColor",
blendMode: layerParam.blendMode || "add",
blendFactor: (layerParam.blendFactor != undefined && layerParam.blendFactor != null) ? layerParam.blendFactor : 1.0,
translate: { x:0, y: 0},
scale: { x: 1, y: 1 },
rotate: { z: 0.0 }
};
this.core.layers.push(layer);
this._setLayerTransform(layerParam, layer);
if (layer.creationParams.frameBuf) {
layer.texture = SceneJS._compilationStates.getState("frameBuf", this.scene.attr.id, layer.creationParams.frameBuf);
} else if (layer.creationParams.video) {
layer.texture = SceneJS._compilationStates.getState("video", this.scene.attr.id, layer.creationParams.video);
} else {
var self = this;
layer.texture = createTexture(
this.scene,
layer.creationParams,
function() {
if (self._destroyed) {
destroyTexture(layer.texture);
}
SceneJS_compileModule.nodeUpdated(self, "loaded"); // Trigger display list redraw
});
}
}
}
};
Texture.prototype.setLayer = function(cfg) {
if (cfg.index == undefined || cfg.index == null) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.ILLEGAL_NODE_CONFIG,
"Invalid texture set layer argument: index null or undefined");
}
if (cfg.index < 0 || cfg.index >= this.core.layers.length) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.ILLEGAL_NODE_CONFIG,
"Invalid texture set layer argument: index out of range (" + this.core.layers.length + " layers defined)");
}
this._setLayer(parseInt(cfg.index), cfg);
};
Texture.prototype.setLayers = function(layers) {
var indexNum;
for (var index in layers) {
if (layers.hasOwnProperty(index)) {
if (index != undefined || index != null) {
indexNum = parseInt(index);
if (indexNum < 0 || indexNum >= this.core.layers.length) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.ILLEGAL_NODE_CONFIG,
"Invalid texture set layer argument: index out of range (" + this.core.layers.length + " layers defined)");
}
this._setLayer(indexNum, layers[index] || {});
}
}
}
};
Texture.prototype._setLayer = function(index, cfg) {
cfg = cfg || {};
var layer = this.core.layers[index];
if (cfg.blendFactor != undefined && cfg.blendFactor != null) {
layer.blendFactor = cfg.blendFactor;
}
this._setLayerTransform(cfg, layer);
};
Texture.prototype._setLayerTransform = function(cfg, layer) {
var matrix;
var t;
if (cfg.translate) {
var translate = cfg.translate;
if (translate.x != undefined) {
layer.translate.x = translate.x;
}
if (translate.y != undefined) {
layer.translate.y = translate.y;
}
matrix = SceneJS_math_translationMat4v([ translate.x || 0, translate.y || 0, 0]);
}
if (cfg.scale) {
var scale = cfg.scale;
if (scale.x != undefined) {
layer.scale.x = scale.x;
}
if (scale.y != undefined) {
layer.scale.y = scale.y;
}
t = SceneJS_math_scalingMat4v([ scale.x || 1, scale.y || 1, 1]);
matrix = matrix ? SceneJS_math_mulMat4(matrix, t) : t;
}
if (cfg.rotate) {
var rotate = cfg.rotate;
if (rotate.z != undefined) {
layer.rotate.z = rotate.z || 0;
}
t = SceneJS_math_rotationMat4v(rotate.z * 0.0174532925, [0,0,1]);
matrix = matrix ? SceneJS_math_mulMat4(matrix, t) : t;
}
if (matrix) {
layer.matrix = matrix;
if (!layer.matrixAsArray) {
layer.matrixAsArray = new Float32Array(layer.matrix);
} else {
layer.matrixAsArray.set(layer.matrix);
}
layer.matrixAsArray = new Float32Array(layer.matrix); // TODO - reinsert into array
}
};
Texture.prototype._compile = function() {
idStack[stackLen] = this.core._coreId; // Tie draw list state to core, not to scene node
textureStack[stackLen] = this.core;
stackLen++;
dirty = true;
this._compileNodes();
stackLen--;
dirty = true;
};
Texture.prototype._destroy = function() {
if (this.core._nodeCount == 1) { // Last resource user
var layer;
for (var i = 0, len = this.core.layers.length; i < len; i++) {
layer = this.core.layers[i];
if (layer.texture) {
destroyTexture(layer.texture);
}
}
}
};
})(); | src/scenejs/texture/texture.js | /**
* A scene node that defines one or more layers of texture to apply to geometries within its subgraph
* that have UV coordinates.
*/
var SceneJS_textureModule = new (function() {
var idStack = [];
var textureStack = [];
var stackLen = 0;
var dirty;
SceneJS_eventModule.addListener(
SceneJS_eventModule.INIT,
function() {
});
SceneJS_eventModule.addListener(
SceneJS_eventModule.SCENE_COMPILING,
function() {
stackLen = 0;
dirty = true;
});
SceneJS_eventModule.addListener(
SceneJS_eventModule.SCENE_RENDERING,
function() {
if (dirty) {
if (stackLen > 0) {
SceneJS_DrawList.setTexture(idStack[stackLen - 1], textureStack[stackLen - 1]);
} else {
SceneJS_DrawList.setTexture();
}
dirty = false;
}
});
/** Creates texture from either image URL or image object
*/
function createTexture(scene, cfg, onComplete) {
var context = scene.canvas.context;
var textureId = SceneJS._createUUID();
try {
if (cfg.autoUpdate) {
var update = function() {
//TODO: fix this when minefield is upto spec
try {
context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, image);
}
catch(e) {
context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, image, null);
}
context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);
//context.generateMipmap(context.TEXTURE_2D);
};
}
return new SceneJS_webgl_Texture2D(context, {
textureId : textureId,
canvas: scene.canvas,
image : cfg.image,
url: cfg.uri,
texels :cfg.texels,
minFilter : getGLOption("minFilter", context, cfg, context.NEAREST_MIPMAP_NEAREST),
magFilter : getGLOption("magFilter", context, cfg, context.LINEAR),
wrapS : getGLOption("wrapS", context, cfg, context.CLAMP_TO_EDGE),
wrapT : getGLOption("wrapT", context, cfg, context.CLAMP_TO_EDGE),
isDepth : getOption(cfg.isDepth, false),
depthMode : getGLOption("depthMode", context, cfg, context.LUMINANCE),
depthCompareMode : getGLOption("depthCompareMode", context, cfg, context.COMPARE_R_TO_TEXTURE),
depthCompareFunc : getGLOption("depthCompareFunc", context, cfg, context.LEQUAL),
flipY : getOption(cfg.flipY, true),
width: getOption(cfg.width, 1),
height: getOption(cfg.height, 1),
internalFormat : getGLOption("internalFormat", context, cfg, context.LEQUAL),
sourceFormat : getGLOption("sourceType", context, cfg, context.ALPHA),
sourceType : getGLOption("sourceType", context, cfg, context.UNSIGNED_BYTE),
logging: SceneJS_loggingModule ,
update: update
}, onComplete);
} catch (e) {
throw SceneJS_errorModule.fatalError(SceneJS.errors.ERROR, "Failed to create texture: " + e.message || e);
}
}
function getGLOption(name, context, cfg, defaultVal) {
var value = cfg[name];
if (value == undefined) {
return defaultVal;
}
var glName = SceneJS_webgl_enumMap[value];
if (glName == undefined) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.ILLEGAL_NODE_CONFIG,
"Unrecognised value for texture node property '" + name + "' value: '" + value + "'");
}
var glValue = context[glName];
// if (!glValue) {
// throw new SceneJS.errors.WebGLUnsupportedNodeConfigException(
// "This browser's WebGL does not support value of SceneJS.texture node property '" + name + "' value: '" + value + "'");
// }
return glValue;
}
function getOption(value, defaultVal) {
return (value == undefined) ? defaultVal : value;
}
function destroyTexture(texture) {
texture.destroy();
}
/*----------------------------------------------------------------------------------------------------------------
* Texture node
*---------------------------------------------------------------------------------------------------------------*/
var Texture = SceneJS.createNodeType("texture");
Texture.prototype._init = function(params) {
if (this.core._nodeCount == 1) { // This node is the resource definer
this.core.layers = [];
this.core.params = {};
var config = SceneJS_debugModule.getConfigs("texturing") || {};
var waitForLoad = (config.waitForLoad != undefined && config.waitForLoad != null)
? config.waitForLoad
: params.waitForLoad;
if (!params.layers) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layers missing");
}
if (!SceneJS._isArray(params.layers)) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layers should be an array");
}
for (var i = 0; i < params.layers.length; i++) {
var layerParam = params.layers[i];
if (!layerParam.uri && !layerParam.frameBuf && !layerParam.video && !layerParam.image && !layerParam.canvasId) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layer " + i + " has no uri, frameBuf, video or canvasId specified");
}
if (layerParam.applyFrom) {
if (layerParam.applyFrom != "uv" &&
layerParam.applyFrom != "uv2" &&
layerParam.applyFrom != "normal" &&
layerParam.applyFrom != "geometry") {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layer " + i + " applyFrom value is unsupported - " +
"should be either 'uv', 'uv2', 'normal' or 'geometry'");
}
}
if (layerParam.applyTo) {
if (layerParam.applyTo != "baseColor" && // Colour map
layerParam.applyTo != "specular" && // Specular map
layerParam.applyTo != "emit" && // Emission map
layerParam.applyTo != "alpha" && // Alpha map
// layerParam.applyTo != "diffuseColor" &&
layerParam.applyTo != "normals") {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layer " + i + " applyTo value is unsupported - " +
"should be either 'baseColor', 'specular' or 'normals'");
}
}
if (layerParam.blendMode) {
if (layerParam.blendMode != "add" && layerParam.blendMode != "multiply") {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.NODE_CONFIG_EXPECTED,
"texture layer " + i + " blendMode value is unsupported - " +
"should be either 'add' or 'multiply'");
}
}
var layer = {
image : null, // Initialised when state == IMAGE_LOADED
creationParams: layerParam, // Create texture using this
waitForLoad: waitForLoad,
texture: null, // Initialised when state == TEXTURE_LOADED
applyFrom: layerParam.applyFrom || "uv",
applyTo: layerParam.applyTo || "baseColor",
blendMode: layerParam.blendMode || "add",
blendFactor: (layerParam.blendFactor != undefined && layerParam.blendFactor != null) ? layerParam.blendFactor : 1.0,
translate: { x:0, y: 0},
scale: { x: 1, y: 1 },
rotate: { z: 0.0 }
};
this.core.layers.push(layer);
this._setLayerTransform(layerParam, layer);
if (layer.creationParams.frameBuf) {
layer.texture = SceneJS._compilationStates.getState("frameBuf", this.scene.attr.id, layer.creationParams.frameBuf);
} else if (layer.creationParams.video) {
layer.texture = SceneJS._compilationStates.getState("video", this.scene.attr.id, layer.creationParams.video);
} else {
var self = this;
layer.texture = createTexture(
this.scene,
layer.creationParams,
function() {
if (self._destroyed) {
destroyTexture(layer.texture);
}
SceneJS_compileModule.nodeUpdated(self, "loaded"); // Trigger display list redraw
});
}
}
}
};
Texture.prototype.setLayer = function(cfg) {
if (cfg.index == undefined || cfg.index == null) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.ILLEGAL_NODE_CONFIG,
"Invalid texture set layer argument: index null or undefined");
}
if (cfg.index < 0 || cfg.index >= this.core.layers.length) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.ILLEGAL_NODE_CONFIG,
"Invalid texture set layer argument: index out of range (" + this.core.layers.length + " layers defined)");
}
this._setLayer(parseInt(cfg.index), cfg);
};
Texture.prototype.setLayers = function(layers) {
var indexNum;
for (var index in layers) {
if (layers.hasOwnProperty(index)) {
if (index != undefined || index != null) {
indexNum = parseInt(index);
if (indexNum < 0 || indexNum >= this.core.layers.length) {
throw SceneJS_errorModule.fatalError(
SceneJS.errors.ILLEGAL_NODE_CONFIG,
"Invalid texture set layer argument: index out of range (" + this.core.layers.length + " layers defined)");
}
this._setLayer(indexNum, layers[index] || {});
}
}
}
};
Texture.prototype._setLayer = function(index, cfg) {
cfg = cfg || {};
var layer = this.core.layers[index];
if (cfg.blendFactor != undefined && cfg.blendFactor != null) {
layer.blendFactor = cfg.blendFactor;
}
this._setLayerTransform(cfg, layer);
};
Texture.prototype._setLayerTransform = function(cfg, layer) {
var matrix;
var t;
if (cfg.translate) {
var translate = cfg.translate;
if (translate.x != undefined) {
layer.translate.x = translate.x;
}
if (translate.y != undefined) {
layer.translate.y = translate.y;
}
matrix = SceneJS_math_translationMat4v([ translate.x || 0, translate.y || 0, 0]);
}
if (cfg.scale) {
var scale = cfg.scale;
if (scale.x != undefined) {
layer.scale.x = scale.x;
}
if (scale.y != undefined) {
layer.scale.y = scale.y;
}
t = SceneJS_math_scalingMat4v([ scale.x || 1, scale.y || 1, 1]);
matrix = matrix ? SceneJS_math_mulMat4(matrix, t) : t;
}
if (cfg.rotate) {
var rotate = cfg.rotate;
if (rotate.z != undefined) {
layer.rotate.z = rotate.z || 0;
}
t = SceneJS_math_rotationMat4v(rotate.z * 0.0174532925, [0,0,1]);
matrix = matrix ? SceneJS_math_mulMat4(matrix, t) : t;
}
if (matrix) {
layer.matrix = matrix;
if (!layer.matrixAsArray) {
layer.matrixAsArray = new Float32Array(layer.matrix);
} else {
layer.matrixAsArray.set(layer.matrix);
}
layer.matrixAsArray = new Float32Array(layer.matrix); // TODO - reinsert into array
}
};
Texture.prototype._compile = function() {
idStack[stackLen] = this.core._coreId; // Tie draw list state to core, not to scene node
textureStack[stackLen] = this.core;
stackLen++;
dirty = true;
this._compileNodes();
stackLen--;
dirty = true;
};
Texture.prototype._destroy = function() {
if (this.core._nodeCount == 1) { // Last resource user
var layer;
for (var i = 0, len = this.core.layers.length; i < len; i++) {
layer = this.core.layers[i];
if (layer.texture) {
destroyTexture(layer.texture);
}
}
}
};
})(); | avoid out of scope (update is included in return as parameter) | src/scenejs/texture/texture.js | avoid out of scope (update is included in return as parameter) | <ide><path>rc/scenejs/texture/texture.js
<ide> function createTexture(scene, cfg, onComplete) {
<ide> var context = scene.canvas.context;
<ide> var textureId = SceneJS._createUUID();
<add> var update;
<ide> try {
<ide> if (cfg.autoUpdate) {
<del> var update = function() {
<add> update = function() {
<ide> //TODO: fix this when minefield is upto spec
<ide> try {
<ide> context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, context.RGBA, context.UNSIGNED_BYTE, image); |
|
Java | apache-2.0 | 85740b09081813cb1f833a4c0aa6875e66dc31a0 | 0 | xfournet/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,slisson/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ibinti/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,kool79/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,blademainer/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,blademainer/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,kool79/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,kdwink/intellij-community,samthor/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,signed/intellij-community,adedayo/intellij-community,signed/intellij-community,jagguli/intellij-community,hurricup/intellij-community,holmes/intellij-community,orekyuu/intellij-community,caot/intellij-community,semonte/intellij-community,allotria/intellij-community,nicolargo/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,hurricup/intellij-community,diorcety/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ryano144/intellij-community,blademainer/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,allotria/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,caot/intellij-community,fnouama/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,allotria/intellij-community,da1z/intellij-community,retomerz/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,jagguli/intellij-community,adedayo/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,signed/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vladmm/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,retomerz/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,jagguli/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,caot/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,slisson/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,signed/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,supersven/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ibinti/intellij-community,da1z/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,supersven/intellij-community,semonte/intellij-community,ibinti/intellij-community,slisson/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,Distrotech/intellij-community,allotria/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,ryano144/intellij-community,da1z/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,kool79/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,signed/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,vladmm/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,caot/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,slisson/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,xfournet/intellij-community,signed/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,samthor/intellij-community,ibinti/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,FHannes/intellij-community,supersven/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,signed/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,allotria/intellij-community,xfournet/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,Lekanich/intellij-community,caot/intellij-community,asedunov/intellij-community,dslomov/intellij-community,izonder/intellij-community,ibinti/intellij-community,blademainer/intellij-community,jagguli/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,fitermay/intellij-community,dslomov/intellij-community,FHannes/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,apixandru/intellij-community,robovm/robovm-studio,caot/intellij-community,clumsy/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,kdwink/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,kdwink/intellij-community,retomerz/intellij-community,ibinti/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,izonder/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,da1z/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,fitermay/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,semonte/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,vladmm/intellij-community,ryano144/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,hurricup/intellij-community,semonte/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,slisson/intellij-community,asedunov/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,apixandru/intellij-community,petteyg/intellij-community,supersven/intellij-community,blademainer/intellij-community,da1z/intellij-community,kool79/intellij-community,vvv1559/intellij-community,slisson/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,supersven/intellij-community,holmes/intellij-community,ryano144/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,vladmm/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,kool79/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,hurricup/intellij-community,holmes/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,xfournet/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,holmes/intellij-community,apixandru/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,apixandru/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,kdwink/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,samthor/intellij-community,fitermay/intellij-community,blademainer/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,kdwink/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,signed/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,kool79/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,youdonghai/intellij-community,semonte/intellij-community,signed/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,caot/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,xfournet/intellij-community,supersven/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,allotria/intellij-community,Distrotech/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,signed/intellij-community,robovm/robovm-studio,signed/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,hurricup/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,izonder/intellij-community,caot/intellij-community,asedunov/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,fnouama/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,adedayo/intellij-community,petteyg/intellij-community,retomerz/intellij-community,samthor/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,signed/intellij-community,fnouama/intellij-community,asedunov/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,caot/intellij-community,fitermay/intellij-community,da1z/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.ide.caches;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated use {@link com.intellij.openapi.project.DumbModeTask}
* to be removed in IDEA 15
*/
public interface CacheUpdater {
int getNumberOfPendingUpdateJobs();
@NotNull
VirtualFile[] queryNeededFiles(@NotNull ProgressIndicator indicator);
void processFile(@NotNull FileContent fileContent);
void updatingDone();
void canceled();
}
| platform/platform-api/src/com/intellij/ide/caches/CacheUpdater.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.ide.caches;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated use {@link com.intellij.openapi.project.DumbModeTask}
*/
public interface CacheUpdater {
int getNumberOfPendingUpdateJobs();
@NotNull
VirtualFile[] queryNeededFiles(@NotNull ProgressIndicator indicator);
void processFile(@NotNull FileContent fileContent);
void updatingDone();
void canceled();
}
| remove CacheUpdater in v.15
| platform/platform-api/src/com/intellij/ide/caches/CacheUpdater.java | remove CacheUpdater in v.15 | <ide><path>latform/platform-api/src/com/intellij/ide/caches/CacheUpdater.java
<ide>
<ide> /**
<ide> * @deprecated use {@link com.intellij.openapi.project.DumbModeTask}
<add> * to be removed in IDEA 15
<ide> */
<ide> public interface CacheUpdater {
<ide> int getNumberOfPendingUpdateJobs(); |
|
Java | epl-1.0 | db69153fc99fd08b737b9121c776742c58681443 | 0 | subclipse/subclipse,subclipse/subclipse,subclipse/subclipse | /*******************************************************************************
* Copyright (c) 2005, 2006 Subclipse project 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:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.core.resources;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileModificationValidator;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.team.core.RepositoryProvider;
import org.tigris.subversion.subclipse.core.Policy;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.SVNProviderPlugin;
import org.tigris.subversion.subclipse.core.SVNTeamProvider;
import org.tigris.subversion.subclipse.core.commands.LockResourcesCommand;
public class SVNFileModificationValidator implements IFileModificationValidator {
/*
* A validator plugged in the the Team UI that will prompt
* the user to make read-only files writtable. In the absense of
* this validator, edit/save fail on read-only files.
*/
private IFileModificationValidator uiValidator;
// The id of the core team plug-in
private static final String ID = "org.eclipse.team.core"; //$NON-NLS-1$
// The id of the default file modification vaidator extension point
private static final String DEFAULT_FILE_MODIFICATION_VALIDATOR_EXTENSION = "defaultFileModificationValidator"; //$NON-NLS-1$
public IStatus validateEdit(IFile[] files, Object context) {
String comment = "";
boolean stealLock = false;
// reduce the array to just read only files
ReadOnlyFiles readOnlyFiles = processFileArray(files);
if (readOnlyFiles.size() == 0) return Status.OK_STATUS;
// of the read-only files, get array of ones which are versioned
IFile[] managedFiles = readOnlyFiles.getManaged();
if (managedFiles.length > 0) {
// Prompt user to lock files
if (context != null) {
ISVNFileModificationValidatorPrompt svnFileModificationValidatorPrompt =
SVNProviderPlugin.getPlugin().getSvnFileModificationValidatorPrompt();
if (svnFileModificationValidatorPrompt != null) {
if (!svnFileModificationValidatorPrompt.prompt(managedFiles, context))
return Status.CANCEL_STATUS;
comment = svnFileModificationValidatorPrompt.getComment();
stealLock = svnFileModificationValidatorPrompt.isStealLock();
}
}
// Run the svn lock command
RepositoryProvider provider = RepositoryProvider.getProvider(managedFiles[0].getProject());
if ((provider != null) && (provider instanceof SVNTeamProvider)) {
SVNTeamProvider svnTeamProvider = (SVNTeamProvider) provider;
LockResourcesCommand command = new LockResourcesCommand(svnTeamProvider.getSVNWorkspaceRoot(), managedFiles, stealLock, comment);
try {
command.run(new NullProgressMonitor());
} catch (SVNException e) {
e.printStackTrace();
return Status.CANCEL_STATUS;
}
}
}
// Process any unmanaged but read-only files. For
// those we need to prompt the user to flip the read only bit
IFile[] unManagedFiles = readOnlyFiles.getUnManaged();
if (unManagedFiles.length > 0) {
synchronized (this) {
if (uiValidator == null)
uiValidator = loadUIValidator();
}
if (uiValidator != null) {
return uiValidator.validateEdit(unManagedFiles, context);
}
// There was no plugged in validator so fail gracefully
return getStatus(unManagedFiles);
}
return Status.OK_STATUS;
}
public IStatus validateSave(IFile file) {
return Status.OK_STATUS;
}
/**
* This method processes the file array and separates
* the read-only files into managed and unmanaged lists.
*/
private ReadOnlyFiles processFileArray(IFile[] files) {
ReadOnlyFiles result = new ReadOnlyFiles();
for (int i = 0; i < files.length; i++) {
IFile file = files[i];
if (isReadOnly(file)) {
try {
if (SVNWorkspaceRoot.getSVNResourceFor(file).isManaged())
result.addManaged(file);
else
result.addUnManaged(file);
} catch (SVNException e) {
result.addUnManaged(file);
}
}
}
return result;
}
private boolean isReadOnly(IFile file) {
if (file == null) return false;
File fsFile = file.getLocation().toFile();
if (fsFile == null || fsFile.canWrite())
return false;
else
return true;
}
private IStatus getDefaultStatus(IFile file) {
return
isReadOnly(file)
? new Status(IStatus.ERROR, SVNProviderPlugin.ID, IResourceStatus.READ_ONLY_LOCAL, Policy.bind("FileModificationValidator.fileIsReadOnly", new String[] { file.getFullPath().toString() }), null)
: Status.OK_STATUS;
}
protected IStatus getStatus(IFile[] files) {
if (files.length == 1) {
return getDefaultStatus(files[0]);
}
IStatus[] stati = new Status[files.length];
boolean allOK = true;
for (int i = 0; i < files.length; i++) {
stati[i] = getDefaultStatus(files[i]);
if(! stati[i].isOK())
allOK = false;
}
return new MultiStatus(SVNProviderPlugin.ID,
0, stati,
allOK
? Policy.bind("ok")
: Policy.bind("FileModificationValidator.someReadOnly"),
null);
}
private IFileModificationValidator loadUIValidator() {
IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(ID, DEFAULT_FILE_MODIFICATION_VALIDATOR_EXTENSION);
if (extension != null) {
IExtension[] extensions = extension.getExtensions();
if (extensions.length > 0) {
IConfigurationElement[] configElements = extensions[0].getConfigurationElements();
if (configElements.length > 0) {
try {
Object o = configElements[0].createExecutableExtension("class"); //$NON-NLS-1$
if (o instanceof IFileModificationValidator) {
return (IFileModificationValidator)o;
}
} catch (CoreException e) {
SVNProviderPlugin.log(e.getStatus().getSeverity(), e.getMessage(), e);
}
}
}
}
return null;
}
private class ReadOnlyFiles {
private List managed;
private List unManaged;
public ReadOnlyFiles() {
super();
managed = new ArrayList();
unManaged = new ArrayList();
}
public void addManaged(IFile file) {
managed.add(file);
}
public void addUnManaged(IFile file) {
unManaged.add(file);
}
public IFile[] getManaged() {
return (IFile[]) managed.toArray(new IFile[managed.size()]);
}
public IFile[] getUnManaged() {
return (IFile[]) unManaged.toArray(new IFile[unManaged.size()]);
}
public int size() {
return managed.size() + unManaged.size();
}
}
}
| core/src/org/tigris/subversion/subclipse/core/resources/SVNFileModificationValidator.java | /*******************************************************************************
* Copyright (c) 2005, 2006 Subclipse project 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:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.core.resources;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileModificationValidator;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.team.core.RepositoryProvider;
import org.tigris.subversion.subclipse.core.Policy;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.SVNProviderPlugin;
import org.tigris.subversion.subclipse.core.SVNTeamProvider;
import org.tigris.subversion.subclipse.core.commands.LockResourcesCommand;
public class SVNFileModificationValidator implements IFileModificationValidator {
/*
* A validator plugged in the the Team UI that will prompt
* the user to make read-only files writtable. In the absense of
* this validator, edit/save fail on read-only files.
*/
private IFileModificationValidator uiValidator;
// The id of the core team plug-in
private static final String ID = "org.eclipse.team.core"; //$NON-NLS-1$
// The id of the default file modification vaidator extension point
private static final String DEFAULT_FILE_MODIFICATION_VALIDATOR_EXTENSION = "defaultFileModificationValidator"; //$NON-NLS-1$
public IStatus validateEdit(IFile[] files, Object context) {
String comment = "";
boolean stealLock = false;
// reduce the array to just read only files
IFile[] readOnlyFiles = getReadOnly(files);
if (readOnlyFiles.length == 0) return Status.OK_STATUS;
int managedCount = readOnlyFiles.length;
SVNTeamProvider svnTeamProvider = null;
IFile[] managedFiles = checkManaged(readOnlyFiles);
managedCount = managedFiles.length;
if (managedCount > 0) {
if (context != null) {
ISVNFileModificationValidatorPrompt svnFileModificationValidatorPrompt =
SVNProviderPlugin.getPlugin().getSvnFileModificationValidatorPrompt();
if (svnFileModificationValidatorPrompt != null) {
if (!svnFileModificationValidatorPrompt.prompt(managedFiles, context))
return Status.CANCEL_STATUS;
comment = svnFileModificationValidatorPrompt.getComment();
stealLock = svnFileModificationValidatorPrompt.isStealLock();
}
}
RepositoryProvider provider = RepositoryProvider.getProvider(managedFiles[0].getProject());
if ((provider != null) && (provider instanceof SVNTeamProvider)) {
svnTeamProvider = (SVNTeamProvider) provider;
LockResourcesCommand command = new LockResourcesCommand(svnTeamProvider.getSVNWorkspaceRoot(), managedFiles, stealLock, comment);
try {
command.run(new NullProgressMonitor());
} catch (SVNException e) {
e.printStackTrace();
return Status.CANCEL_STATUS;
}
}
}
// This is to prompt the user to flip the read only bit
// on files that are not managed by SVN
if (readOnlyFiles.length > managedCount) {
synchronized (this) {
if (uiValidator == null)
uiValidator = loadUIValidator();
}
if (uiValidator != null) {
return uiValidator.validateEdit(files, context);
}
// There was no plugged in validator so fail gracefully
return getStatus(files);
}
return Status.OK_STATUS;
}
public IStatus validateSave(IFile file) {
return Status.OK_STATUS;
}
/**
* This method does a second check on the files in the array
* to verify tey are managed.
*/
private IFile[] checkManaged(IFile[] files) {
List result = new ArrayList(files.length);
for (int i = 0; i < files.length; i++) {
try {
if (SVNWorkspaceRoot.getSVNResourceFor(files[i]).isManaged()) {
result.add(files[i]);
}
} catch (SVNException e) {
}
}
return (IFile[]) result.toArray(new IFile[result.size()]);
}
private IFile[] getReadOnly(IFile[] files) {
List result = new ArrayList(files.length);
for (int i = 0; i < files.length; i++) {
if (isReadOnly(files[i])) {
result.add(files[i]);
}
}
return (IFile[]) result.toArray(new IFile[result.size()]);
}
private boolean isReadOnly(IFile file) {
if (file == null) return false;
File fsFile = file.getLocation().toFile();
if (fsFile == null || fsFile.canWrite())
return false;
else
return true;
}
private IStatus getDefaultStatus(IFile file) {
return
isReadOnly(file)
? new Status(IStatus.ERROR, SVNProviderPlugin.ID, IResourceStatus.READ_ONLY_LOCAL, Policy.bind("FileModificationValidator.fileIsReadOnly", new String[] { file.getFullPath().toString() }), null)
: Status.OK_STATUS;
}
protected IStatus getStatus(IFile[] files) {
if (files.length == 1) {
return getDefaultStatus(files[0]);
}
IStatus[] stati = new Status[files.length];
boolean allOK = true;
for (int i = 0; i < files.length; i++) {
stati[i] = getDefaultStatus(files[i]);
if(! stati[i].isOK())
allOK = false;
}
return new MultiStatus(SVNProviderPlugin.ID,
0, stati,
allOK
? Policy.bind("ok")
: Policy.bind("FileModificationValidator.someReadOnly"),
null);
}
private IFileModificationValidator loadUIValidator() {
IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(ID, DEFAULT_FILE_MODIFICATION_VALIDATOR_EXTENSION);
if (extension != null) {
IExtension[] extensions = extension.getExtensions();
if (extensions.length > 0) {
IConfigurationElement[] configElements = extensions[0].getConfigurationElements();
if (configElements.length > 0) {
try {
Object o = configElements[0].createExecutableExtension("class"); //$NON-NLS-1$
if (o instanceof IFileModificationValidator) {
return (IFileModificationValidator)o;
}
} catch (CoreException e) {
SVNProviderPlugin.log(e.getStatus().getSeverity(), e.getMessage(), e);
}
}
}
}
return null;
}
}
| Major refactoring. Split the read-only files into lists of managed and
unmanaged and process each separately.
| core/src/org/tigris/subversion/subclipse/core/resources/SVNFileModificationValidator.java | Major refactoring. Split the read-only files into lists of managed and unmanaged and process each separately. | <ide><path>ore/src/org/tigris/subversion/subclipse/core/resources/SVNFileModificationValidator.java
<ide> String comment = "";
<ide> boolean stealLock = false;
<ide> // reduce the array to just read only files
<del> IFile[] readOnlyFiles = getReadOnly(files);
<del> if (readOnlyFiles.length == 0) return Status.OK_STATUS;
<del> int managedCount = readOnlyFiles.length;
<del> SVNTeamProvider svnTeamProvider = null;
<del> IFile[] managedFiles = checkManaged(readOnlyFiles);
<del> managedCount = managedFiles.length;
<del> if (managedCount > 0) {
<add> ReadOnlyFiles readOnlyFiles = processFileArray(files);
<add> if (readOnlyFiles.size() == 0) return Status.OK_STATUS;
<add> // of the read-only files, get array of ones which are versioned
<add> IFile[] managedFiles = readOnlyFiles.getManaged();
<add> if (managedFiles.length > 0) {
<add> // Prompt user to lock files
<ide> if (context != null) {
<ide> ISVNFileModificationValidatorPrompt svnFileModificationValidatorPrompt =
<ide> SVNProviderPlugin.getPlugin().getSvnFileModificationValidatorPrompt();
<ide> stealLock = svnFileModificationValidatorPrompt.isStealLock();
<ide> }
<ide> }
<add> // Run the svn lock command
<ide> RepositoryProvider provider = RepositoryProvider.getProvider(managedFiles[0].getProject());
<ide> if ((provider != null) && (provider instanceof SVNTeamProvider)) {
<del> svnTeamProvider = (SVNTeamProvider) provider;
<add> SVNTeamProvider svnTeamProvider = (SVNTeamProvider) provider;
<ide> LockResourcesCommand command = new LockResourcesCommand(svnTeamProvider.getSVNWorkspaceRoot(), managedFiles, stealLock, comment);
<ide> try {
<ide> command.run(new NullProgressMonitor());
<ide> }
<ide> }
<ide> }
<del> // This is to prompt the user to flip the read only bit
<del> // on files that are not managed by SVN
<del> if (readOnlyFiles.length > managedCount) {
<add> // Process any unmanaged but read-only files. For
<add> // those we need to prompt the user to flip the read only bit
<add> IFile[] unManagedFiles = readOnlyFiles.getUnManaged();
<add> if (unManagedFiles.length > 0) {
<ide> synchronized (this) {
<ide> if (uiValidator == null)
<ide> uiValidator = loadUIValidator();
<ide> }
<ide> if (uiValidator != null) {
<del> return uiValidator.validateEdit(files, context);
<add> return uiValidator.validateEdit(unManagedFiles, context);
<ide> }
<ide> // There was no plugged in validator so fail gracefully
<del> return getStatus(files);
<add> return getStatus(unManagedFiles);
<ide> }
<ide> return Status.OK_STATUS;
<ide> }
<ide>
<ide>
<ide> /**
<del> * This method does a second check on the files in the array
<del> * to verify tey are managed.
<add> * This method processes the file array and separates
<add> * the read-only files into managed and unmanaged lists.
<ide> */
<del> private IFile[] checkManaged(IFile[] files) {
<del> List result = new ArrayList(files.length);
<del> for (int i = 0; i < files.length; i++) {
<del> try {
<del> if (SVNWorkspaceRoot.getSVNResourceFor(files[i]).isManaged()) {
<del> result.add(files[i]);
<del> }
<del> } catch (SVNException e) {
<del> }
<del> }
<del> return (IFile[]) result.toArray(new IFile[result.size()]);
<del> }
<del>
<del> private IFile[] getReadOnly(IFile[] files) {
<del> List result = new ArrayList(files.length);
<del> for (int i = 0; i < files.length; i++) {
<del> if (isReadOnly(files[i])) {
<del> result.add(files[i]);
<del> }
<del> }
<del> return (IFile[]) result.toArray(new IFile[result.size()]);
<del> }
<add> private ReadOnlyFiles processFileArray(IFile[] files) {
<add> ReadOnlyFiles result = new ReadOnlyFiles();
<add> for (int i = 0; i < files.length; i++) {
<add> IFile file = files[i];
<add> if (isReadOnly(file)) {
<add> try {
<add> if (SVNWorkspaceRoot.getSVNResourceFor(file).isManaged())
<add> result.addManaged(file);
<add> else
<add> result.addUnManaged(file);
<add> } catch (SVNException e) {
<add> result.addUnManaged(file);
<add> }
<add> }
<add> }
<add> return result;
<add> }
<add>
<ide>
<ide> private boolean isReadOnly(IFile file) {
<ide> if (file == null) return false;
<ide> }
<ide> return null;
<ide> }
<add>
<add> private class ReadOnlyFiles {
<add> private List managed;
<add> private List unManaged;
<add> public ReadOnlyFiles() {
<add> super();
<add> managed = new ArrayList();
<add> unManaged = new ArrayList();
<add> }
<add> public void addManaged(IFile file) {
<add> managed.add(file);
<add> }
<add> public void addUnManaged(IFile file) {
<add> unManaged.add(file);
<add> }
<add> public IFile[] getManaged() {
<add> return (IFile[]) managed.toArray(new IFile[managed.size()]);
<add> }
<add> public IFile[] getUnManaged() {
<add> return (IFile[]) unManaged.toArray(new IFile[unManaged.size()]);
<add> }
<add> public int size() {
<add> return managed.size() + unManaged.size();
<add> }
<add> }
<ide>
<ide> } |
|
Java | apache-2.0 | ad1a6e8361c38a74f69ab448cf39827aa8103746 | 0 | ouit0408/sakai,conder/sakai,frasese/sakai,OpenCollabZA/sakai,Fudan-University/sakai,udayg/sakai,liubo404/sakai,pushyamig/sakai,ktakacs/sakai,pushyamig/sakai,hackbuteer59/sakai,whumph/sakai,Fudan-University/sakai,noondaysun/sakai,kwedoff1/sakai,surya-janani/sakai,joserabal/sakai,zqian/sakai,pushyamig/sakai,conder/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,wfuedu/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,puramshetty/sakai,ktakacs/sakai,ouit0408/sakai,hackbuteer59/sakai,liubo404/sakai,joserabal/sakai,ouit0408/sakai,noondaysun/sakai,kingmook/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,surya-janani/sakai,kingmook/sakai,puramshetty/sakai,hackbuteer59/sakai,colczr/sakai,introp-software/sakai,zqian/sakai,puramshetty/sakai,noondaysun/sakai,clhedrick/sakai,lorenamgUMU/sakai,ouit0408/sakai,frasese/sakai,kwedoff1/sakai,colczr/sakai,surya-janani/sakai,kwedoff1/sakai,zqian/sakai,zqian/sakai,colczr/sakai,OpenCollabZA/sakai,whumph/sakai,pushyamig/sakai,clhedrick/sakai,introp-software/sakai,whumph/sakai,whumph/sakai,introp-software/sakai,willkara/sakai,zqian/sakai,rodriguezdevera/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,clhedrick/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,conder/sakai,duke-compsci290-spring2016/sakai,Fudan-University/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,kwedoff1/sakai,bkirschn/sakai,lorenamgUMU/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,ouit0408/sakai,lorenamgUMU/sakai,zqian/sakai,willkara/sakai,ktakacs/sakai,zqian/sakai,frasese/sakai,kingmook/sakai,kwedoff1/sakai,colczr/sakai,hackbuteer59/sakai,wfuedu/sakai,bzhouduke123/sakai,ouit0408/sakai,colczr/sakai,frasese/sakai,bzhouduke123/sakai,joserabal/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,joserabal/sakai,clhedrick/sakai,puramshetty/sakai,udayg/sakai,noondaysun/sakai,hackbuteer59/sakai,noondaysun/sakai,pushyamig/sakai,wfuedu/sakai,clhedrick/sakai,kingmook/sakai,joserabal/sakai,tl-its-umich-edu/sakai,buckett/sakai-gitflow,OpenCollabZA/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,surya-janani/sakai,OpenCollabZA/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,willkara/sakai,udayg/sakai,bzhouduke123/sakai,whumph/sakai,zqian/sakai,introp-software/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,kwedoff1/sakai,buckett/sakai-gitflow,surya-janani/sakai,Fudan-University/sakai,liubo404/sakai,bkirschn/sakai,bkirschn/sakai,pushyamig/sakai,kingmook/sakai,colczr/sakai,pushyamig/sakai,kingmook/sakai,liubo404/sakai,ktakacs/sakai,tl-its-umich-edu/sakai,clhedrick/sakai,bkirschn/sakai,ouit0408/sakai,rodriguezdevera/sakai,ktakacs/sakai,Fudan-University/sakai,udayg/sakai,whumph/sakai,frasese/sakai,kwedoff1/sakai,surya-janani/sakai,udayg/sakai,joserabal/sakai,whumph/sakai,rodriguezdevera/sakai,Fudan-University/sakai,conder/sakai,lorenamgUMU/sakai,Fudan-University/sakai,bzhouduke123/sakai,wfuedu/sakai,OpenCollabZA/sakai,conder/sakai,buckett/sakai-gitflow,wfuedu/sakai,conder/sakai,kingmook/sakai,lorenamgUMU/sakai,surya-janani/sakai,willkara/sakai,Fudan-University/sakai,wfuedu/sakai,liubo404/sakai,colczr/sakai,buckett/sakai-gitflow,ktakacs/sakai,joserabal/sakai,bkirschn/sakai,puramshetty/sakai,wfuedu/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,noondaysun/sakai,frasese/sakai,bkirschn/sakai,introp-software/sakai,clhedrick/sakai,willkara/sakai,surya-janani/sakai,ktakacs/sakai,conder/sakai,udayg/sakai,hackbuteer59/sakai,kingmook/sakai,OpenCollabZA/sakai,udayg/sakai,liubo404/sakai,kwedoff1/sakai,introp-software/sakai,whumph/sakai,bzhouduke123/sakai,frasese/sakai,rodriguezdevera/sakai,bkirschn/sakai,buckett/sakai-gitflow,frasese/sakai,pushyamig/sakai,bzhouduke123/sakai,tl-its-umich-edu/sakai,bkirschn/sakai,rodriguezdevera/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,udayg/sakai,rodriguezdevera/sakai,conder/sakai,noondaysun/sakai,buckett/sakai-gitflow,joserabal/sakai,puramshetty/sakai,liubo404/sakai,lorenamgUMU/sakai,ouit0408/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,liubo404/sakai,tl-its-umich-edu/sakai | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.tool.assessment.ui.listener.delivery;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemData;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSectionData;
import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAccessControlIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.grading.AssessmentGradingIfc;
import org.sakaiproject.tool.assessment.data.ifc.grading.ItemGradingIfc;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade;
import org.sakaiproject.tool.assessment.services.FinFormatException;
import org.sakaiproject.tool.assessment.services.GradebookServiceException;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.services.ItemService;
import org.sakaiproject.tool.assessment.services.SaLengthException;
import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService;
import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.FinBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.ItemContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.shared.PersonBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.tool.assessment.util.TextFormat;
/**
* <p>
* Title: Samigo
* </p>
* <p>
* Purpose: This listener is called in delivery when the user clicks on submit,
* save, or previous, next, toc.... It calculates and saves scores in DB
*
* @version $Id: SubmitToGradingActionListener.java 11634 2006-07-06 17:35:54Z
* [email protected] $
*/
public class SubmitToGradingActionListener implements ActionListener {
private static Log log = LogFactory
.getLog(SubmitToGradingActionListener.class);
/**
* ACTION.
*
* @param ae
* @throws AbortProcessingException
*/
public void processAction(ActionEvent ae) throws AbortProcessingException, FinFormatException, SaLengthException {
try {
log.debug("SubmitToGradingActionListener.processAction() ");
// get managed bean
DeliveryBean delivery = (DeliveryBean) ContextUtil
.lookupBean("delivery");
if ((ContextUtil.lookupParam("showfeedbacknow") != null
&& "true"
.equals(ContextUtil.lookupParam("showfeedbacknow")) || delivery
.getActionMode() == DeliveryBean.PREVIEW_ASSESSMENT))
delivery.setForGrade(false);
// get service
PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService();
// get assessment
PublishedAssessmentFacade publishedAssessment = null;
if (delivery.getPublishedAssessment() != null)
publishedAssessment = delivery.getPublishedAssessment();
else {
publishedAssessment = publishedAssessmentService
.getPublishedAssessment(delivery.getAssessmentId());
delivery.setPublishedAssessment(publishedAssessment);
}
HashMap invalidFINMap = new HashMap();
ArrayList invalidSALengthList = new ArrayList();
AssessmentGradingData adata = submitToGradingService(ae, publishedAssessment, delivery, invalidFINMap, invalidSALengthList);
// set AssessmentGrading in delivery
delivery.setAssessmentGrading(adata);
// set url & confirmation after saving the record for grade
if (adata != null && delivery.getForGrade())
setConfirmation(adata, publishedAssessment, delivery);
if (isForGrade(adata) && !isUnlimited(publishedAssessment)) {
delivery.setSubmissionsRemaining(delivery
.getSubmissionsRemaining() - 1);
}
if (invalidFINMap.size() != 0) {
delivery.setIsAnyInvalidFinInput(true);
throw new FinFormatException ("Not a valid FIN input");
}
if (invalidSALengthList.size() != 0) {
delivery.setIsAnyInvalidFinInput(true);
throw new SaLengthException ("Short Answer input is too long");
}
delivery.setIsAnyInvalidFinInput(false);
} catch (GradebookServiceException ge) {
ge.printStackTrace();
FacesContext context = FacesContext.getCurrentInstance();
String err = (String) ContextUtil.getLocalizedString(
"org.sakaiproject.tool.assessment.bundle.AuthorMessages",
"gradebook_exception_error");
context.addMessage(null, new FacesMessage(err));
return;
}
}
private boolean isForGrade(AssessmentGradingData aData) {
if (aData != null)
return (Boolean.TRUE).equals(aData.getForGrade());
else
return false;
}
private boolean isUnlimited(PublishedAssessmentFacade publishedAssessment) {
return (Boolean.TRUE).equals(publishedAssessment
.getAssessmentAccessControl().getUnlimitedSubmissions());
}
/**
* This method set the url & confirmation string for submitted.jsp. The
* confirmation string =
* assessmentGradingId-publishedAssessmentId-agentId-submitteddate
*
* @param adata
* @param publishedAssessment
* @param delivery
*/
private void setConfirmation(AssessmentGradingData adata,
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
if (publishedAssessment.getAssessmentAccessControl() != null) {
setFinalPage(publishedAssessment, delivery);
setSubmissionMessage(publishedAssessment, delivery);
}
setConfirmationId(adata, publishedAssessment, delivery);
}
/**
* Set confirmationId which is AssessmentGradingId-TimeStamp.
*
* @param adata
* @param publishedAssessment
* @param delivery
*/
private void setConfirmationId(AssessmentGradingData adata,
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
delivery.setConfirmation(adata.getAssessmentGradingId() + "-"
+ publishedAssessment.getPublishedAssessmentId() + "-"
+ adata.getAgentId() + "-"
+ adata.getSubmittedDate().toString());
}
/**
* Set the submission message.
*
* @param publishedAssessment
* @param delivery
*/
private void setSubmissionMessage(
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
String submissionMessage = publishedAssessment
.getAssessmentAccessControl().getSubmissionMessage();
if (submissionMessage != null)
delivery.setSubmissionMessage(submissionMessage);
}
/**
* Set finalPage url in delivery bean.
*
* @param publishedAssessment
* @param delivery
*/
private void setFinalPage(PublishedAssessmentFacade publishedAssessment,
DeliveryBean delivery) {
String url = publishedAssessment.getAssessmentAccessControl()
.getFinalPageUrl();
if (url != null)
url = url.trim();
delivery.setUrl(url);
}
/**
* Invoke submission and return the grading data
*
* @param publishedAssessment
* @param delivery
* @return
*/
private synchronized AssessmentGradingData submitToGradingService(
ActionEvent ae, PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery, HashMap invalidFINMap, ArrayList invalidSALengthList) throws FinFormatException {
log.debug("****1a. inside submitToGradingService ");
String submissionId = "";
HashSet itemGradingHash = new HashSet();
// daisyf decoding: get page contents contains SectionContentsBean, a
// wrapper for SectionDataIfc
Iterator iter = delivery.getPageContents().getPartsContents()
.iterator();
log.debug("****1b. inside submitToGradingService, iter= " + iter);
HashSet adds = new HashSet();
HashSet removes = new HashSet();
// we go through all the answer collected from JSF form per each
// publsihedItem and
// work out which answer is an new addition and in cases like
// MC/MCMR/Survey, we will
// discard any existing one and just save teh new one. For other
// question type, we
// simply modify the publishedText or publishedAnswer of teh existing
// ones.
while (iter.hasNext()) {
SectionContentsBean part = (SectionContentsBean) iter.next();
log.debug("****1c. inside submitToGradingService, part " + part);
Iterator iter2 = part.getItemContents().iterator();
while (iter2.hasNext()) { // go through each item from form
ItemContentsBean item = (ItemContentsBean) iter2.next();
log.debug("****** before prepareItemGradingPerItem");
prepareItemGradingPerItem(ae, delivery, item, adds, removes);
log.debug("****** after prepareItemGradingPerItem");
}
}
AssessmentGradingData adata = persistAssessmentGrading(ae, delivery,
itemGradingHash, publishedAssessment, adds, removes, invalidFINMap, invalidSALengthList);
StringBuffer redrawAnchorName = new StringBuffer("p");
String tmpAnchorName = "";
Iterator iterPart = delivery.getPageContents().getPartsContents().iterator();
while (iterPart.hasNext()) {
SectionContentsBean part = (SectionContentsBean) iterPart.next();
String partSeq = part.getNumber();
Iterator iterItem = part.getItemContents().iterator();
while (iterItem.hasNext()) { // go through each item from form
ItemContentsBean item = (ItemContentsBean) iterItem.next();
String itemSeq = item.getSequence();
Long itemId = item.getItemData().getItemId();
if (item.getItemData().getTypeId() == 5) {
if (invalidSALengthList.contains(itemId)) {
item.setIsInvalidSALengthInput(true);
redrawAnchorName.append(partSeq);
redrawAnchorName.append("q");
redrawAnchorName.append(itemSeq);
if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
tmpAnchorName = redrawAnchorName.toString();
}
}
else {
item.setIsInvalidSALengthInput(false);
}
}
else if (item.getItemData().getTypeId() == 11) {
if (invalidFINMap.containsKey(itemId)) {
item.setIsInvalidFinInput(true);
redrawAnchorName.append(partSeq);
redrawAnchorName.append("q");
redrawAnchorName.append(itemSeq);
if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
tmpAnchorName = redrawAnchorName.toString();
}
ArrayList list = (ArrayList) invalidFINMap.get(itemId);
ArrayList finArray = item.getFinArray();
Iterator iterFin = finArray.iterator();
while (iterFin.hasNext()) {
FinBean finBean = (FinBean) iterFin.next();
if (finBean.getItemGradingData() != null) {
Long itemGradingId = finBean.getItemGradingData().getItemGradingId();
if (list.contains(itemGradingId)) {
finBean.setIsCorrect(false);
}
}
}
}
else {
item.setIsInvalidFinInput(false);
}
}
}
}
if (tmpAnchorName != null && !tmpAnchorName.equals("")) {
delivery.setRedrawAnchorName(tmpAnchorName.toString());
}
else {
delivery.setRedrawAnchorName("");
}
delivery.setSubmissionId(submissionId);
delivery.setSubmissionTicket(submissionId);// is this the same thing?
// hmmmm
delivery.setSubmissionDate(new Date());
delivery.setSubmitted(true);
return adata;
}
private AssessmentGradingData persistAssessmentGrading(ActionEvent ae,
DeliveryBean delivery, HashSet itemGradingHash,
PublishedAssessmentFacade publishedAssessment, HashSet adds,
HashSet removes, HashMap invalidFINMap, ArrayList invalidSALengthList) throws FinFormatException {
AssessmentGradingData adata = null;
if (delivery.getAssessmentGrading() != null) {
adata = delivery.getAssessmentGrading();
}
GradingService service = new GradingService();
log.debug("**adata=" + adata);
if (adata == null) { // <--- this shouldn't happened 'cos it should
// have been created by BeginDelivery
adata = makeNewAssessmentGrading(publishedAssessment, delivery,
itemGradingHash);
delivery.setAssessmentGrading(adata);
} else {
// 1. add all the new itemgrading for MC/Survey and discard any
// itemgrading for MC/Survey
// 2. add any modified SAQ/TF/FIB/Matching/MCMR/FIN
// 3. save any modified Mark for Review in FileUplaod/Audio
HashMap fibMap = getFIBMap(publishedAssessment);
HashMap finMap = getFINMap(publishedAssessment);
HashMap mcmrMap = getMCMRMap(publishedAssessment);
Set itemGradingSet = adata.getItemGradingSet();
log.debug("*** 2a. before removal & addition " + (new Date()));
if (itemGradingSet != null) {
log.debug("*** 2aa. removing old itemGrading " + (new Date()));
itemGradingSet.removeAll(removes);
service.deleteAll(removes);
// refresh itemGradingSet & assessmentGrading after removal
log.debug("*** 2ab. reload itemGradingSet " + (new Date()));
itemGradingSet = service.getItemGradingSet(adata
.getAssessmentGradingId().toString());
log.debug("*** 2ac. load assessmentGarding " + (new Date()));
adata = service.load(adata.getAssessmentGradingId().toString());
Iterator iter = adds.iterator();
while (iter.hasNext()) {
((ItemGradingIfc) iter.next()).setAssessmentGradingId(adata
.getAssessmentGradingId());
}
// make update to old item and insert new item
// and we will only update item that has been changed
log
.debug("*** 2ad. set assessmentGrading with new/updated itemGrading "
+ (new Date()));
log
.debug("Submitforgrading: before calling .....................oldItemGradingSet.size = "
+ itemGradingSet.size());
log.debug("Submitforgrading: newItemGradingSet.size = "
+ adds.size());
HashSet updateItemGradingSet = getUpdateItemGradingSet(
itemGradingSet, adds, fibMap, finMap, mcmrMap, adata);
adata.setItemGradingSet(updateItemGradingSet);
}
}
adata.setIsLate(isLate(publishedAssessment));
adata.setForGrade(Boolean.valueOf(delivery.getForGrade()));
// If this assessment grading data has been updated (comments or adj. score) by grader and then republic and allow student to resubmit
// when the student submit his answers, we update the status back to 0 and remove the grading entry/info.
if (AssessmentGradingIfc.ASSESSMENT_UPDATED_NEED_RESUBMIT.equals(adata.getStatus()) || AssessmentGradingIfc.ASSESSMENT_UPDATED.equals(adata.getStatus())) {
adata.setStatus(Integer.valueOf(0));
adata.setGradedBy(null);
adata.setGradedDate(null);
adata.setComments(null);
adata.setTotalOverrideScore(Float.valueOf(0f));
}
log.debug("*** 2b. before storingGrades, did all the removes and adds "
+ (new Date()));
if (delivery.getNavigation().equals("1") && ae != null && "showFeedback".equals(ae.getComponent().getId())) {
log.debug("Do not persist to db if it is linear access and the action is show feedback");
// 3. let's build three HashMap with (publishedItemId, publishedItem),
// (publishedItemTextId, publishedItem), (publishedAnswerId,
// publishedItem) to help with storing grades to adata only, not db
HashMap publishedItemHash = delivery.getPublishedItemHash();
HashMap publishedItemTextHash = delivery.getPublishedItemTextHash();
HashMap publishedAnswerHash = delivery.getPublishedAnswerHash();
service.storeGrades(adata, publishedAssessment, publishedItemHash, publishedItemTextHash, publishedAnswerHash, false, invalidFINMap, invalidSALengthList);
}
else {
log.debug("Persist to db otherwise");
// The following line seems redundant. I cannot see a reason why we need to save the adata here
// and then again in following service.storeGrades(). Comment it out.
//service.saveOrUpdateAssessmentGrading(adata);
log.debug("*** 3. before storingGrades, did all the removes and adds " + (new Date()));
// 3. let's build three HashMap with (publishedItemId, publishedItem),
// (publishedItemTextId, publishedItem), (publishedAnswerId,
// publishedItem) to help with storing grades to adata and then persist to DB
HashMap publishedItemHash = delivery.getPublishedItemHash();
HashMap publishedItemTextHash = delivery.getPublishedItemTextHash();
HashMap publishedAnswerHash = delivery.getPublishedAnswerHash();
service.storeGrades(adata, publishedAssessment, publishedItemHash, publishedItemTextHash, publishedAnswerHash, invalidFINMap, invalidSALengthList);
}
return adata;
}
private HashMap getFIBMap(PublishedAssessmentIfc publishedAssessment) {
PublishedAssessmentService s = new PublishedAssessmentService();
return s.prepareFIBItemHash(publishedAssessment);
}
private HashMap getFINMap(PublishedAssessmentIfc publishedAssessment){
PublishedAssessmentService s = new PublishedAssessmentService();
return s.prepareFINItemHash(publishedAssessment);
}
private HashMap getMCMRMap(PublishedAssessmentIfc publishedAssessment) {
PublishedAssessmentService s = new PublishedAssessmentService();
return s.prepareMCMRItemHash(publishedAssessment);
}
private HashSet getUpdateItemGradingSet(Set oldItemGradingSet,
Set newItemGradingSet, HashMap fibMap, HashMap finMap, HashMap mcmrMap,
AssessmentGradingData adata) {
log.debug("Submitforgrading: oldItemGradingSet.size = "
+ oldItemGradingSet.size());
log.debug("Submitforgrading: newItemGradingSet.size = "
+ newItemGradingSet.size());
HashSet updateItemGradingSet = new HashSet();
Iterator iter = oldItemGradingSet.iterator();
HashMap map = new HashMap();
while (iter.hasNext()) { // create a map with old itemGrading
ItemGradingIfc item = (ItemGradingIfc) iter.next();
map.put(item.getItemGradingId(), item);
}
// go through new itemGrading
Iterator iter1 = newItemGradingSet.iterator();
while (iter1.hasNext()) {
ItemGradingIfc newItem = (ItemGradingIfc) iter1.next();
ItemGradingIfc oldItem = (ItemGradingIfc) map.get(newItem
.getItemGradingId());
if (oldItem != null) {
// itemGrading exists and value has been change, then need
// update
Boolean oldReview = oldItem.getReview();
Boolean newReview = newItem.getReview();
Long oldAnswerId = oldItem.getPublishedAnswerId();
Long newAnswerId = newItem.getPublishedAnswerId();
String oldRationale = oldItem.getRationale();
String newRationale = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, newItem.getRationale());
String oldAnswerText = oldItem.getAnswerText();
// Change to allow student submissions in rich-text [SAK-17021]
String newAnswerText = ContextUtil.stringWYSIWYG(newItem.getAnswerText());
if ((oldReview != null && !oldReview.equals(newReview))
|| (newReview!=null && !newReview.equals(oldReview))
|| (oldAnswerId != null && !oldAnswerId
.equals(newAnswerId))
|| (newAnswerId != null && !newAnswerId
.equals(oldAnswerId))
|| (oldRationale != null && !oldRationale
.equals(newRationale))
|| (newRationale != null && !newRationale
.equals(oldRationale))
|| (oldAnswerText != null && !oldAnswerText
.equals(newAnswerText))
|| (newAnswerText != null && !newAnswerText
.equals(oldAnswerText))
|| fibMap.get(oldItem.getPublishedItemId()) != null
|| finMap.get(oldItem.getPublishedItemId())!=null
|| mcmrMap.get(oldItem.getPublishedItemId()) != null) {
oldItem.setReview(newItem.getReview());
oldItem.setPublishedAnswerId(newItem.getPublishedAnswerId());
oldItem.setRationale(newRationale);
oldItem.setAnswerText(newAnswerText);
oldItem.setSubmittedDate(new Date());
oldItem.setAutoScore(newItem.getAutoScore());
oldItem.setOverrideScore(newItem.getOverrideScore());
updateItemGradingSet.add(oldItem);
// log.debug("**** SubmitToGrading: need update
// "+oldItem.getItemGradingId());
}
} else { // itemGrading from new set doesn't exist, add to set in
// this case
// log.debug("**** SubmitToGrading: need add new item");
newItem.setAgentId(adata.getAgentId());
updateItemGradingSet.add(newItem);
}
}
return updateItemGradingSet;
}
/**
* Make a new AssessmentGradingData object for delivery
*
* @param publishedAssessment
* the PublishedAssessmentFacade
* @param delivery
* the DeliveryBean
* @param itemGradingHash
* the item data
* @return
*/
private AssessmentGradingData makeNewAssessmentGrading(
PublishedAssessmentFacade publishedAssessment,
DeliveryBean delivery, HashSet itemGradingHash) {
PersonBean person = (PersonBean) ContextUtil.lookupBean("person");
AssessmentGradingData adata = new AssessmentGradingData();
adata.setAgentId(person.getId());
adata.setPublishedAssessmentId(publishedAssessment
.getPublishedAssessmentId());
adata.setForGrade(Boolean.valueOf(delivery.getForGrade()));
adata.setItemGradingSet(itemGradingHash);
adata.setAttemptDate(new Date());
adata.setIsLate(Boolean.FALSE);
adata.setStatus(Integer.valueOf(0));
adata.setTotalOverrideScore(Float.valueOf(0));
adata.setTimeElapsed(Integer.valueOf("0"));
return adata;
}
/*
* This is specific to JSF - question for each type is layout differently in
* JSF and the answers submitted are being collected differently too. e.g.
* for each MC/Survey/MCMR, an itemgrading is associated with each choice.
* whereas there is only one itemgrading per each question for SAQ/TF/Audio,
* and one for ecah blank in FIB. To understand the logic in this method, it
* is best to study jsf/delivery/item/deliver*.jsp
*/
private void prepareItemGradingPerItem(ActionEvent ae, DeliveryBean delivery,
ItemContentsBean item, HashSet adds, HashSet removes) {
ArrayList grading = item.getItemGradingDataArray();
int typeId = item.getItemData().getTypeId().intValue();
//no matter what kinds of type questions, if it marks as review, add it in.
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() == null && (itemgrading.getReview() != null && itemgrading.getReview().booleanValue()) == true) {
adds.addAll(grading);
}
}
// 1. add all the new itemgrading for MC/Survey and discard any
// itemgrading for MC/Survey
// 2. add any modified SAQ/TF/FIB/Matching/MCMR/Audio/FIN
switch (typeId) {
case 1: // MC
case 12: // MC Single Selection
case 3: // Survey
boolean answerModified = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() == null
|| itemgrading.getItemGradingId().intValue() <= 0) { // =>
// new answer
if (itemgrading.getPublishedAnswerId() != null || (itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
answerModified = true;
break;
}
}
}
// Click the Reset Selection link
if(item.getUnanswered()) {
answerModified = true;
}
if (answerModified) {
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading
.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
// remove all old answer for MC & Surevy
removes.add(itemgrading);
} else {
// add new answer
if (itemgrading.getPublishedAnswerId() != null
|| itemgrading.getAnswerText() != null
|| (itemgrading.getRationale() != null
&& !itemgrading.getRationale().trim().equals(""))) {
// null=> skipping this question
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
if (itemgrading.getRationale() != null && itemgrading.getRationale().length() > 0) {
itemgrading.setRationale(TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, itemgrading.getRationale()));
}
// the rest of the info is collected by
// ItemContentsBean via JSF form
adds.add(itemgrading);
}
}
}
}
else{
handleMarkForReview(grading, adds);
}
break;
case 4: // T/F
case 9: // Matching
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if ((itemgrading.getItemGradingId() != null && itemgrading.getItemGradingId().intValue() > 0) ||
(itemgrading.getPublishedAnswerId() != null || itemgrading.getAnswerText() != null) ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
adds.addAll(grading);
break;
}
}
break;
case 5: // SAQ
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
adds.addAll(grading);
break;
} else if (itemgrading.getAnswerText() != null && !itemgrading.getAnswerText().equals("")) {
// Change to allow student submissions in rich-text [SAK-17021]
itemgrading.setAnswerText(ContextUtil.stringWYSIWYG(itemgrading.getAnswerText()));
adds.addAll(grading);
break;
}
}
break;
case 8: // FIB
case 11: // FIN
boolean addedToAdds = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
adds.addAll(grading);
break;
} else if (itemgrading.getAnswerText() != null && !itemgrading.getAnswerText().equals("")) {
String s = itemgrading.getAnswerText();
log.debug("s = " + s);
// Change to allow student submissions in rich-text [SAK-17021]
itemgrading.setAnswerText(ContextUtil.stringWYSIWYG(s));
adds.addAll(grading);
if (!addedToAdds) {
adds.addAll(grading);
addedToAdds = true;
}
}
}
break;
case 2: // MCMR
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
// old answer, check which one to keep, not keeping null answer
if (itemgrading.getPublishedAnswerId() != null ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
adds.add(itemgrading);
} else {
removes.add(itemgrading);
}
} else {
// new answer
if (itemgrading.getPublishedAnswerId() != null ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
// new addition not accepting any new answer with null for MCMR
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
adds.add(itemgrading);
}
}
}
break;
case 6: // File Upload
case 7: // Audio
handleMarkForReview(grading, adds);
break;
case 13: //Matrix Choices question
answerModified = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading != null) {
log.debug("\n:ItemId>>itemTextId>>answerId "+ itemgrading.getPublishedItemId()+itemgrading.getPublishedItemTextId()+itemgrading.getPublishedAnswerId()+"\n");
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
if (itemgrading.getRationale() != null && itemgrading.getRationale().length() > 0) {
itemgrading.setRationale(TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, itemgrading.getRationale()));
}
adds.add(itemgrading);
}
}
break;
}
// if it is linear access and there is not answer, we add an fake ItemGradingData
String actionCommand = "";
if (ae != null) {
actionCommand = ae.getComponent().getId();
log.debug("ae is not null, getActionCommand() = " + actionCommand);
}
else {
log.debug("ae is null");
}
if (delivery.getNavigation().equals("1") && adds.size() ==0 && !"showFeedback".equals(actionCommand)) {
log.debug("enter here");
Long assessmentGradingId = delivery.getAssessmentGrading().getAssessmentGradingId();
Long publishedItemId = item.getItemData().getItemId();
log.debug("assessmentGradingId = " + assessmentGradingId);
log.debug("publishedItemId = " + publishedItemId);
GradingService gradingService = new GradingService();
if (gradingService.getItemGradingData(assessmentGradingId.toString(), publishedItemId.toString()) == null) {
log.debug("Create a new (fake) ItemGradingData");
ItemGradingData itemGrading = new ItemGradingData();
itemGrading.setAssessmentGradingId(assessmentGradingId);
itemGrading.setAgentId(AgentFacade.getAgentString());
itemGrading.setPublishedItemId(publishedItemId);
ItemService itemService = new ItemService();
Long itemTextId = itemService.getItemTextId(publishedItemId);
log.debug("itemTextId = " + itemTextId);
itemGrading.setPublishedItemTextId(itemTextId);
adds.add(itemGrading);
}
else {
// For File Upload question, if user clicks on "Upload", a ItemGradingData will be created.
// Therefore, when user clicks on "Next", we shouldn't create it again.
// Same for Audio question, if user records anything, a ItemGradingData will be created.
// We don't create it again when user clicks on "Next".
if ((typeId == 6 || typeId == 7)) {
log.debug("File Upload or Audio! Do not create empty ItemGradingData if there exists one");
}
}
}
}
private void handleMarkForReview(ArrayList grading, HashSet adds){
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0
&& itemgrading.getReview() != null) {
// we will save itemgarding even though answer was not modified
// 'cos mark for review may have been modified
adds.add(itemgrading);
}
}
}
private Boolean isLate(PublishedAssessmentIfc pub) {
AssessmentAccessControlIfc a = pub.getAssessmentAccessControl();
if (a.getDueDate() != null && a.getDueDate().before(new Date()))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
}
| samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/delivery/SubmitToGradingActionListener.java | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.tool.assessment.ui.listener.delivery;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemData;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSectionData;
import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAccessControlIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.grading.AssessmentGradingIfc;
import org.sakaiproject.tool.assessment.data.ifc.grading.ItemGradingIfc;
import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade;
import org.sakaiproject.tool.assessment.services.FinFormatException;
import org.sakaiproject.tool.assessment.services.GradebookServiceException;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.services.ItemService;
import org.sakaiproject.tool.assessment.services.SaLengthException;
import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService;
import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.FinBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.ItemContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.shared.PersonBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.tool.assessment.util.TextFormat;
/**
* <p>
* Title: Samigo
* </p>
* <p>
* Purpose: This listener is called in delivery when the user clicks on submit,
* save, or previous, next, toc.... It calculates and saves scores in DB
*
* @version $Id: SubmitToGradingActionListener.java 11634 2006-07-06 17:35:54Z
* [email protected] $
*/
public class SubmitToGradingActionListener implements ActionListener {
private static Log log = LogFactory
.getLog(SubmitToGradingActionListener.class);
/**
* ACTION.
*
* @param ae
* @throws AbortProcessingException
*/
public void processAction(ActionEvent ae) throws AbortProcessingException, FinFormatException, SaLengthException {
try {
log.debug("SubmitToGradingActionListener.processAction() ");
// get managed bean
DeliveryBean delivery = (DeliveryBean) ContextUtil
.lookupBean("delivery");
if ((ContextUtil.lookupParam("showfeedbacknow") != null
&& "true"
.equals(ContextUtil.lookupParam("showfeedbacknow")) || delivery
.getActionMode() == DeliveryBean.PREVIEW_ASSESSMENT))
delivery.setForGrade(false);
// get service
PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService();
// get assessment
PublishedAssessmentFacade publishedAssessment = null;
if (delivery.getPublishedAssessment() != null)
publishedAssessment = delivery.getPublishedAssessment();
else {
publishedAssessment = publishedAssessmentService
.getPublishedAssessment(delivery.getAssessmentId());
delivery.setPublishedAssessment(publishedAssessment);
}
HashMap invalidFINMap = new HashMap();
ArrayList invalidSALengthList = new ArrayList();
AssessmentGradingData adata = submitToGradingService(ae, publishedAssessment, delivery, invalidFINMap, invalidSALengthList);
// set AssessmentGrading in delivery
delivery.setAssessmentGrading(adata);
// set url & confirmation after saving the record for grade
if (adata != null && delivery.getForGrade())
setConfirmation(adata, publishedAssessment, delivery);
if (isForGrade(adata) && !isUnlimited(publishedAssessment)) {
delivery.setSubmissionsRemaining(delivery
.getSubmissionsRemaining() - 1);
}
if (invalidFINMap.size() != 0) {
delivery.setIsAnyInvalidFinInput(true);
throw new FinFormatException ("Not a valid FIN input");
}
if (invalidSALengthList.size() != 0) {
delivery.setIsAnyInvalidFinInput(true);
throw new SaLengthException ("Short Answer input is too long");
}
delivery.setIsAnyInvalidFinInput(false);
} catch (GradebookServiceException ge) {
ge.printStackTrace();
FacesContext context = FacesContext.getCurrentInstance();
String err = (String) ContextUtil.getLocalizedString(
"org.sakaiproject.tool.assessment.bundle.AuthorMessages",
"gradebook_exception_error");
context.addMessage(null, new FacesMessage(err));
return;
}
}
private boolean isForGrade(AssessmentGradingData aData) {
if (aData != null)
return (Boolean.TRUE).equals(aData.getForGrade());
else
return false;
}
private boolean isUnlimited(PublishedAssessmentFacade publishedAssessment) {
return (Boolean.TRUE).equals(publishedAssessment
.getAssessmentAccessControl().getUnlimitedSubmissions());
}
/**
* This method set the url & confirmation string for submitted.jsp. The
* confirmation string =
* assessmentGradingId-publishedAssessmentId-agentId-submitteddate
*
* @param adata
* @param publishedAssessment
* @param delivery
*/
private void setConfirmation(AssessmentGradingData adata,
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
if (publishedAssessment.getAssessmentAccessControl() != null) {
setFinalPage(publishedAssessment, delivery);
setSubmissionMessage(publishedAssessment, delivery);
}
setConfirmationId(adata, publishedAssessment, delivery);
}
/**
* Set confirmationId which is AssessmentGradingId-TimeStamp.
*
* @param adata
* @param publishedAssessment
* @param delivery
*/
private void setConfirmationId(AssessmentGradingData adata,
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
delivery.setConfirmation(adata.getAssessmentGradingId() + "-"
+ publishedAssessment.getPublishedAssessmentId() + "-"
+ adata.getAgentId() + "-"
+ adata.getSubmittedDate().toString());
}
/**
* Set the submission message.
*
* @param publishedAssessment
* @param delivery
*/
private void setSubmissionMessage(
PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery) {
String submissionMessage = publishedAssessment
.getAssessmentAccessControl().getSubmissionMessage();
if (submissionMessage != null)
delivery.setSubmissionMessage(submissionMessage);
}
/**
* Set finalPage url in delivery bean.
*
* @param publishedAssessment
* @param delivery
*/
private void setFinalPage(PublishedAssessmentFacade publishedAssessment,
DeliveryBean delivery) {
String url = publishedAssessment.getAssessmentAccessControl()
.getFinalPageUrl();
if (url != null)
url = url.trim();
delivery.setUrl(url);
}
/**
* Invoke submission and return the grading data
*
* @param publishedAssessment
* @param delivery
* @return
*/
private synchronized AssessmentGradingData submitToGradingService(
ActionEvent ae, PublishedAssessmentFacade publishedAssessment, DeliveryBean delivery, HashMap invalidFINMap, ArrayList invalidSALengthList) throws FinFormatException {
log.debug("****1a. inside submitToGradingService ");
String submissionId = "";
HashSet itemGradingHash = new HashSet();
// daisyf decoding: get page contents contains SectionContentsBean, a
// wrapper for SectionDataIfc
Iterator iter = delivery.getPageContents().getPartsContents()
.iterator();
log.debug("****1b. inside submitToGradingService, iter= " + iter);
HashSet adds = new HashSet();
HashSet removes = new HashSet();
// we go through all the answer collected from JSF form per each
// publsihedItem and
// work out which answer is an new addition and in cases like
// MC/MCMR/Survey, we will
// discard any existing one and just save teh new one. For other
// question type, we
// simply modify the publishedText or publishedAnswer of teh existing
// ones.
while (iter.hasNext()) {
SectionContentsBean part = (SectionContentsBean) iter.next();
log.debug("****1c. inside submitToGradingService, part " + part);
Iterator iter2 = part.getItemContents().iterator();
while (iter2.hasNext()) { // go through each item from form
ItemContentsBean item = (ItemContentsBean) iter2.next();
log.debug("****** before prepareItemGradingPerItem");
prepareItemGradingPerItem(ae, delivery, item, adds, removes);
log.debug("****** after prepareItemGradingPerItem");
}
}
AssessmentGradingData adata = persistAssessmentGrading(ae, delivery,
itemGradingHash, publishedAssessment, adds, removes, invalidFINMap, invalidSALengthList);
StringBuffer redrawAnchorName = new StringBuffer("p");
String tmpAnchorName = "";
Iterator iterPart = delivery.getPageContents().getPartsContents().iterator();
while (iterPart.hasNext()) {
SectionContentsBean part = (SectionContentsBean) iterPart.next();
String partSeq = part.getNumber();
Iterator iterItem = part.getItemContents().iterator();
while (iterItem.hasNext()) { // go through each item from form
ItemContentsBean item = (ItemContentsBean) iterItem.next();
String itemSeq = item.getSequence();
Long itemId = item.getItemData().getItemId();
if (item.getItemData().getTypeId() == 5) {
if (invalidSALengthList.contains(itemId)) {
item.setIsInvalidSALengthInput(true);
redrawAnchorName.append(partSeq);
redrawAnchorName.append("q");
redrawAnchorName.append(itemSeq);
if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
tmpAnchorName = redrawAnchorName.toString();
}
}
else {
item.setIsInvalidSALengthInput(false);
}
}
else if (item.getItemData().getTypeId() == 11) {
if (invalidFINMap.containsKey(itemId)) {
item.setIsInvalidFinInput(true);
redrawAnchorName.append(partSeq);
redrawAnchorName.append("q");
redrawAnchorName.append(itemSeq);
if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) {
tmpAnchorName = redrawAnchorName.toString();
}
ArrayList list = (ArrayList) invalidFINMap.get(itemId);
ArrayList finArray = item.getFinArray();
Iterator iterFin = finArray.iterator();
while (iterFin.hasNext()) {
FinBean finBean = (FinBean) iterFin.next();
if (finBean.getItemGradingData() != null) {
Long itemGradingId = finBean.getItemGradingData().getItemGradingId();
if (list.contains(itemGradingId)) {
finBean.setIsCorrect(false);
}
}
}
}
else {
item.setIsInvalidFinInput(false);
}
}
}
}
if (tmpAnchorName != null && !tmpAnchorName.equals("")) {
delivery.setRedrawAnchorName(tmpAnchorName.toString());
}
else {
delivery.setRedrawAnchorName("");
}
delivery.setSubmissionId(submissionId);
delivery.setSubmissionTicket(submissionId);// is this the same thing?
// hmmmm
delivery.setSubmissionDate(new Date());
delivery.setSubmitted(true);
return adata;
}
private AssessmentGradingData persistAssessmentGrading(ActionEvent ae,
DeliveryBean delivery, HashSet itemGradingHash,
PublishedAssessmentFacade publishedAssessment, HashSet adds,
HashSet removes, HashMap invalidFINMap, ArrayList invalidSALengthList) throws FinFormatException {
AssessmentGradingData adata = null;
if (delivery.getAssessmentGrading() != null) {
adata = delivery.getAssessmentGrading();
}
GradingService service = new GradingService();
log.debug("**adata=" + adata);
if (adata == null) { // <--- this shouldn't happened 'cos it should
// have been created by BeginDelivery
adata = makeNewAssessmentGrading(publishedAssessment, delivery,
itemGradingHash);
delivery.setAssessmentGrading(adata);
} else {
// 1. add all the new itemgrading for MC/Survey and discard any
// itemgrading for MC/Survey
// 2. add any modified SAQ/TF/FIB/Matching/MCMR/FIN
// 3. save any modified Mark for Review in FileUplaod/Audio
HashMap fibMap = getFIBMap(publishedAssessment);
HashMap finMap = getFINMap(publishedAssessment);
HashMap mcmrMap = getMCMRMap(publishedAssessment);
Set itemGradingSet = adata.getItemGradingSet();
log.debug("*** 2a. before removal & addition " + (new Date()));
if (itemGradingSet != null) {
log.debug("*** 2aa. removing old itemGrading " + (new Date()));
itemGradingSet.removeAll(removes);
service.deleteAll(removes);
// refresh itemGradingSet & assessmentGrading after removal
log.debug("*** 2ab. reload itemGradingSet " + (new Date()));
itemGradingSet = service.getItemGradingSet(adata
.getAssessmentGradingId().toString());
log.debug("*** 2ac. load assessmentGarding " + (new Date()));
adata = service.load(adata.getAssessmentGradingId().toString());
Iterator iter = adds.iterator();
while (iter.hasNext()) {
((ItemGradingIfc) iter.next()).setAssessmentGradingId(adata
.getAssessmentGradingId());
}
// make update to old item and insert new item
// and we will only update item that has been changed
log
.debug("*** 2ad. set assessmentGrading with new/updated itemGrading "
+ (new Date()));
log
.debug("Submitforgrading: before calling .....................oldItemGradingSet.size = "
+ itemGradingSet.size());
log.debug("Submitforgrading: newItemGradingSet.size = "
+ adds.size());
HashSet updateItemGradingSet = getUpdateItemGradingSet(
itemGradingSet, adds, fibMap, finMap, mcmrMap, adata);
adata.setItemGradingSet(updateItemGradingSet);
}
}
adata.setIsLate(isLate(publishedAssessment));
adata.setForGrade(Boolean.valueOf(delivery.getForGrade()));
// If this assessment grading data has been updated (comments or adj. score) by grader and then republic and allow student to resubmit
// when the student submit his answers, we update the status back to 0 and remove the grading entry/info.
if (AssessmentGradingIfc.ASSESSMENT_UPDATED_NEED_RESUBMIT.equals(adata.getStatus()) || AssessmentGradingIfc.ASSESSMENT_UPDATED.equals(adata.getStatus())) {
adata.setStatus(Integer.valueOf(0));
adata.setGradedBy(null);
adata.setGradedDate(null);
adata.setComments(null);
adata.setTotalOverrideScore(Float.valueOf(0f));
}
log.debug("*** 2b. before storingGrades, did all the removes and adds "
+ (new Date()));
if (delivery.getNavigation().equals("1") && ae != null && "showFeedback".equals(ae.getComponent().getId())) {
log.debug("Do not persist to db if it is linear access and the action is show feedback");
// 3. let's build three HashMap with (publishedItemId, publishedItem),
// (publishedItemTextId, publishedItem), (publishedAnswerId,
// publishedItem) to help with storing grades to adata only, not db
HashMap publishedItemHash = delivery.getPublishedItemHash();
HashMap publishedItemTextHash = delivery.getPublishedItemTextHash();
HashMap publishedAnswerHash = delivery.getPublishedAnswerHash();
service.storeGrades(adata, publishedAssessment, publishedItemHash, publishedItemTextHash, publishedAnswerHash, false, invalidFINMap, invalidSALengthList);
}
else {
log.debug("Persist to db otherwise");
// The following line seems redundant. I cannot see a reason why we need to save the adata here
// and then again in following service.storeGrades(). Comment it out.
//service.saveOrUpdateAssessmentGrading(adata);
log.debug("*** 3. before storingGrades, did all the removes and adds " + (new Date()));
// 3. let's build three HashMap with (publishedItemId, publishedItem),
// (publishedItemTextId, publishedItem), (publishedAnswerId,
// publishedItem) to help with storing grades to adata and then persist to DB
HashMap publishedItemHash = delivery.getPublishedItemHash();
HashMap publishedItemTextHash = delivery.getPublishedItemTextHash();
HashMap publishedAnswerHash = delivery.getPublishedAnswerHash();
service.storeGrades(adata, publishedAssessment, publishedItemHash, publishedItemTextHash, publishedAnswerHash, invalidFINMap, invalidSALengthList);
}
return adata;
}
private HashMap getFIBMap(PublishedAssessmentIfc publishedAssessment) {
PublishedAssessmentService s = new PublishedAssessmentService();
return s.prepareFIBItemHash(publishedAssessment);
}
private HashMap getFINMap(PublishedAssessmentIfc publishedAssessment){
PublishedAssessmentService s = new PublishedAssessmentService();
return s.prepareFINItemHash(publishedAssessment);
}
private HashMap getMCMRMap(PublishedAssessmentIfc publishedAssessment) {
PublishedAssessmentService s = new PublishedAssessmentService();
return s.prepareMCMRItemHash(publishedAssessment);
}
private HashSet getUpdateItemGradingSet(Set oldItemGradingSet,
Set newItemGradingSet, HashMap fibMap, HashMap finMap, HashMap mcmrMap,
AssessmentGradingData adata) {
log.debug("Submitforgrading: oldItemGradingSet.size = "
+ oldItemGradingSet.size());
log.debug("Submitforgrading: newItemGradingSet.size = "
+ newItemGradingSet.size());
HashSet updateItemGradingSet = new HashSet();
Iterator iter = oldItemGradingSet.iterator();
HashMap map = new HashMap();
while (iter.hasNext()) { // create a map with old itemGrading
ItemGradingIfc item = (ItemGradingIfc) iter.next();
map.put(item.getItemGradingId(), item);
}
// go through new itemGrading
Iterator iter1 = newItemGradingSet.iterator();
while (iter1.hasNext()) {
ItemGradingIfc newItem = (ItemGradingIfc) iter1.next();
ItemGradingIfc oldItem = (ItemGradingIfc) map.get(newItem
.getItemGradingId());
if (oldItem != null) {
// itemGrading exists and value has been change, then need
// update
Boolean oldReview = oldItem.getReview();
Boolean newReview = newItem.getReview();
Long oldAnswerId = oldItem.getPublishedAnswerId();
Long newAnswerId = newItem.getPublishedAnswerId();
String oldRationale = oldItem.getRationale();
String newRationale = TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, newItem.getRationale());
String oldAnswerText = oldItem.getAnswerText();
// Change to allow student submissions in rich-text [SAK-17021]
String newAnswerText = ContextUtil.stringWYSIWYG(newItem.getAnswerText());
if ((oldReview != null && !oldReview.equals(newReview))
|| (newReview!=null && !newReview.equals(oldReview))
|| (oldAnswerId != null && !oldAnswerId
.equals(newAnswerId))
|| (newAnswerId != null && !newAnswerId
.equals(oldAnswerId))
|| (oldRationale != null && !oldRationale
.equals(newRationale))
|| (newRationale != null && !newRationale
.equals(oldRationale))
|| (oldAnswerText != null && !oldAnswerText
.equals(newAnswerText))
|| (newAnswerText != null && !newAnswerText
.equals(oldAnswerText))
|| fibMap.get(oldItem.getPublishedItemId()) != null
|| finMap.get(oldItem.getPublishedItemId())!=null
|| mcmrMap.get(oldItem.getPublishedItemId()) != null) {
oldItem.setReview(newItem.getReview());
oldItem.setPublishedAnswerId(newItem.getPublishedAnswerId());
oldItem.setRationale(newRationale);
oldItem.setAnswerText(newAnswerText);
oldItem.setSubmittedDate(new Date());
oldItem.setAutoScore(newItem.getAutoScore());
oldItem.setOverrideScore(newItem.getOverrideScore());
updateItemGradingSet.add(oldItem);
// log.debug("**** SubmitToGrading: need update
// "+oldItem.getItemGradingId());
}
} else { // itemGrading from new set doesn't exist, add to set in
// this case
// log.debug("**** SubmitToGrading: need add new item");
newItem.setAgentId(adata.getAgentId());
updateItemGradingSet.add(newItem);
}
}
return updateItemGradingSet;
}
/**
* Make a new AssessmentGradingData object for delivery
*
* @param publishedAssessment
* the PublishedAssessmentFacade
* @param delivery
* the DeliveryBean
* @param itemGradingHash
* the item data
* @return
*/
private AssessmentGradingData makeNewAssessmentGrading(
PublishedAssessmentFacade publishedAssessment,
DeliveryBean delivery, HashSet itemGradingHash) {
PersonBean person = (PersonBean) ContextUtil.lookupBean("person");
AssessmentGradingData adata = new AssessmentGradingData();
adata.setAgentId(person.getId());
adata.setPublishedAssessmentId(publishedAssessment
.getPublishedAssessmentId());
adata.setForGrade(Boolean.valueOf(delivery.getForGrade()));
adata.setItemGradingSet(itemGradingHash);
adata.setAttemptDate(new Date());
adata.setIsLate(Boolean.FALSE);
adata.setStatus(Integer.valueOf(0));
adata.setTotalOverrideScore(Float.valueOf(0));
adata.setTimeElapsed(Integer.valueOf("0"));
return adata;
}
/*
* This is specific to JSF - question for each type is layout differently in
* JSF and the answers submitted are being collected differently too. e.g.
* for each MC/Survey/MCMR, an itemgrading is associated with each choice.
* whereas there is only one itemgrading per each question for SAQ/TF/Audio,
* and one for ecah blank in FIB. To understand the logic in this method, it
* is best to study jsf/delivery/item/deliver*.jsp
*/
private void prepareItemGradingPerItem(ActionEvent ae, DeliveryBean delivery,
ItemContentsBean item, HashSet adds, HashSet removes) {
ArrayList grading = item.getItemGradingDataArray();
int typeId = item.getItemData().getTypeId().intValue();
//no matter what kinds of type questions, if it marks as review, add it in.
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() == null && itemgrading.getReview() == true) {
adds.addAll(grading);
}
}
// 1. add all the new itemgrading for MC/Survey and discard any
// itemgrading for MC/Survey
// 2. add any modified SAQ/TF/FIB/Matching/MCMR/Audio/FIN
switch (typeId) {
case 1: // MC
case 12: // MC Single Selection
case 3: // Survey
boolean answerModified = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() == null
|| itemgrading.getItemGradingId().intValue() <= 0) { // =>
// new answer
if (itemgrading.getPublishedAnswerId() != null || (itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
answerModified = true;
break;
}
}
}
// Click the Reset Selection link
if(item.getUnanswered()) {
answerModified = true;
}
if (answerModified) {
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading
.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
// remove all old answer for MC & Surevy
removes.add(itemgrading);
} else {
// add new answer
if (itemgrading.getPublishedAnswerId() != null
|| itemgrading.getAnswerText() != null
|| (itemgrading.getRationale() != null
&& !itemgrading.getRationale().trim().equals(""))) {
// null=> skipping this question
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
if (itemgrading.getRationale() != null && itemgrading.getRationale().length() > 0) {
itemgrading.setRationale(TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, itemgrading.getRationale()));
}
// the rest of the info is collected by
// ItemContentsBean via JSF form
adds.add(itemgrading);
}
}
}
}
else{
handleMarkForReview(grading, adds);
}
break;
case 4: // T/F
case 9: // Matching
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if ((itemgrading.getItemGradingId() != null && itemgrading.getItemGradingId().intValue() > 0) ||
(itemgrading.getPublishedAnswerId() != null || itemgrading.getAnswerText() != null) ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
adds.addAll(grading);
break;
}
}
break;
case 5: // SAQ
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
adds.addAll(grading);
break;
} else if (itemgrading.getAnswerText() != null && !itemgrading.getAnswerText().equals("")) {
// Change to allow student submissions in rich-text [SAK-17021]
itemgrading.setAnswerText(ContextUtil.stringWYSIWYG(itemgrading.getAnswerText()));
adds.addAll(grading);
break;
}
}
break;
case 8: // FIB
case 11: // FIN
boolean addedToAdds = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
}
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
adds.addAll(grading);
break;
} else if (itemgrading.getAnswerText() != null && !itemgrading.getAnswerText().equals("")) {
String s = itemgrading.getAnswerText();
log.debug("s = " + s);
// Change to allow student submissions in rich-text [SAK-17021]
itemgrading.setAnswerText(ContextUtil.stringWYSIWYG(s));
adds.addAll(grading);
if (!addedToAdds) {
adds.addAll(grading);
addedToAdds = true;
}
}
}
break;
case 2: // MCMR
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0) {
// old answer, check which one to keep, not keeping null answer
if (itemgrading.getPublishedAnswerId() != null ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
adds.add(itemgrading);
} else {
removes.add(itemgrading);
}
} else {
// new answer
if (itemgrading.getPublishedAnswerId() != null ||
(itemgrading.getRationale() != null && !itemgrading.getRationale().trim().equals(""))) {
// new addition not accepting any new answer with null for MCMR
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
adds.add(itemgrading);
}
}
}
break;
case 6: // File Upload
case 7: // Audio
handleMarkForReview(grading, adds);
break;
case 13: //Matrix Choices question
answerModified = false;
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading != null) {
log.debug("\n:ItemId>>itemTextId>>answerId "+ itemgrading.getPublishedItemId()+itemgrading.getPublishedItemTextId()+itemgrading.getPublishedAnswerId()+"\n");
itemgrading.setAgentId(AgentFacade.getAgentString());
itemgrading.setSubmittedDate(new Date());
if (itemgrading.getRationale() != null && itemgrading.getRationale().length() > 0) {
itemgrading.setRationale(TextFormat.convertPlaintextToFormattedTextNoHighUnicode(log, itemgrading.getRationale()));
}
adds.add(itemgrading);
}
}
break;
}
// if it is linear access and there is not answer, we add an fake ItemGradingData
String actionCommand = "";
if (ae != null) {
actionCommand = ae.getComponent().getId();
log.debug("ae is not null, getActionCommand() = " + actionCommand);
}
else {
log.debug("ae is null");
}
if (delivery.getNavigation().equals("1") && adds.size() ==0 && !"showFeedback".equals(actionCommand)) {
log.debug("enter here");
Long assessmentGradingId = delivery.getAssessmentGrading().getAssessmentGradingId();
Long publishedItemId = item.getItemData().getItemId();
log.debug("assessmentGradingId = " + assessmentGradingId);
log.debug("publishedItemId = " + publishedItemId);
GradingService gradingService = new GradingService();
if (gradingService.getItemGradingData(assessmentGradingId.toString(), publishedItemId.toString()) == null) {
log.debug("Create a new (fake) ItemGradingData");
ItemGradingData itemGrading = new ItemGradingData();
itemGrading.setAssessmentGradingId(assessmentGradingId);
itemGrading.setAgentId(AgentFacade.getAgentString());
itemGrading.setPublishedItemId(publishedItemId);
ItemService itemService = new ItemService();
Long itemTextId = itemService.getItemTextId(publishedItemId);
log.debug("itemTextId = " + itemTextId);
itemGrading.setPublishedItemTextId(itemTextId);
adds.add(itemGrading);
}
else {
// For File Upload question, if user clicks on "Upload", a ItemGradingData will be created.
// Therefore, when user clicks on "Next", we shouldn't create it again.
// Same for Audio question, if user records anything, a ItemGradingData will be created.
// We don't create it again when user clicks on "Next".
if ((typeId == 6 || typeId == 7)) {
log.debug("File Upload or Audio! Do not create empty ItemGradingData if there exists one");
}
}
}
}
private void handleMarkForReview(ArrayList grading, HashSet adds){
for (int m = 0; m < grading.size(); m++) {
ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
if (itemgrading.getItemGradingId() != null
&& itemgrading.getItemGradingId().intValue() > 0
&& itemgrading.getReview() != null) {
// we will save itemgarding even though answer was not modified
// 'cos mark for review may have been modified
adds.add(itemgrading);
}
}
}
private Boolean isLate(PublishedAssessmentIfc pub) {
AssessmentAccessControlIfc a = pub.getAssessmentAccessControl();
if (a.getDueDate() != null && a.getDueDate().before(new Date()))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
}
| SAM-1301: Samigo / mark for review
git-svn-id: 574bb14f304dbe16c01253ed6697ea749724087f@99069 66ffb92e-73f9-0310-93c1-f5514f145a0a
| samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/delivery/SubmitToGradingActionListener.java | SAM-1301: Samigo / mark for review | <ide><path>amigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/delivery/SubmitToGradingActionListener.java
<ide> //no matter what kinds of type questions, if it marks as review, add it in.
<ide> for (int m = 0; m < grading.size(); m++) {
<ide> ItemGradingData itemgrading = (ItemGradingData) grading.get(m);
<del> if (itemgrading.getItemGradingId() == null && itemgrading.getReview() == true) {
<add> if (itemgrading.getItemGradingId() == null && (itemgrading.getReview() != null && itemgrading.getReview().booleanValue()) == true) {
<ide> adds.addAll(grading);
<ide> }
<ide> } |
|
Java | apache-2.0 | e9867308fd1e8eaf4d155d074b11ce30c76bf67d | 0 | Dominator008/buck,rmaz/buck,liuyang-li/buck,rhencke/buck,illicitonion/buck,dushmis/buck,ilya-klyuchnikov/buck,Heart2009/buck,rhencke/buck,shybovycha/buck,justinmuller/buck,illicitonion/buck,grumpyjames/buck,grumpyjames/buck,JoelMarcey/buck,LegNeato/buck,shybovycha/buck,nguyentruongtho/buck,shs96c/buck,zhuxiaohao/buck,rowillia/buck,ilya-klyuchnikov/buck,janicduplessis/buck,Learn-Android-app/buck,shs96c/buck,rowillia/buck,grumpyjames/buck,Addepar/buck,mikekap/buck,stuhood/buck,robbertvanginkel/buck,rhencke/buck,stuhood/buck,vschs007/buck,davido/buck,luiseduardohdbackup/buck,darkforestzero/buck,nguyentruongtho/buck,Dominator008/buck,saleeh93/buck-cutom,vschs007/buck,romanoid/buck,mnuessler/buck,clonetwin26/buck,luiseduardohdbackup/buck,shs96c/buck,zhan-xiong/buck,liuyang-li/buck,rhencke/buck,mogers/buck,vine/buck,rhencke/buck,shs96c/buck,rmaz/buck,luiseduardohdbackup/buck,OkBuilds/buck,rmaz/buck,ilya-klyuchnikov/buck,lukw00/buck,robbertvanginkel/buck,grumpyjames/buck,vine/buck,OkBuilds/buck,romanoid/buck,grumpyjames/buck,LegNeato/buck,vine/buck,marcinkwiatkowski/buck,brettwooldridge/buck,marcinkwiatkowski/buck,darkforestzero/buck,LegNeato/buck,1yvT0s/buck,MarkRunWu/buck,zhan-xiong/buck,raviagarwal7/buck,saleeh93/buck-cutom,justinmuller/buck,Addepar/buck,Heart2009/buck,ilya-klyuchnikov/buck,vine/buck,sdwilsh/buck,Addepar/buck,neonichu/buck,JoelMarcey/buck,sdwilsh/buck,robbertvanginkel/buck,facebook/buck,romanoid/buck,illicitonion/buck,grumpyjames/buck,mogers/buck,bocon13/buck,MarkRunWu/buck,shybovycha/buck,vschs007/buck,mikekap/buck,janicduplessis/buck,zhuxiaohao/buck,raviagarwal7/buck,davido/buck,sdwilsh/buck,siddhartharay007/buck,Addepar/buck,dpursehouse/buck,1yvT0s/buck,rowillia/buck,shybovycha/buck,dsyang/buck,mnuessler/buck,dushmis/buck,zhan-xiong/buck,saleeh93/buck-cutom,artiya4u/buck,hgl888/buck,justinmuller/buck,justinmuller/buck,hgl888/buck,mogers/buck,siddhartharay007/buck,lukw00/buck,stuhood/buck,luiseduardohdbackup/buck,sdwilsh/buck,Addepar/buck,janicduplessis/buck,janicduplessis/buck,hgl888/buck,LegNeato/buck,saleeh93/buck-cutom,lukw00/buck,rhencke/buck,bocon13/buck,mnuessler/buck,liuyang-li/buck,Addepar/buck,davido/buck,siddhartharay007/buck,stuhood/buck,darkforestzero/buck,hgl888/buck,vine/buck,Dominator008/buck,Heart2009/buck,rowillia/buck,LegNeato/buck,robbertvanginkel/buck,MarkRunWu/buck,shs96c/buck,bocon13/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,JoelMarcey/buck,bocon13/buck,LegNeato/buck,saleeh93/buck-cutom,k21/buck,raviagarwal7/buck,tgummerer/buck,shybovycha/buck,1yvT0s/buck,janicduplessis/buck,bocon13/buck,siddhartharay007/buck,dushmis/buck,raviagarwal7/buck,ilya-klyuchnikov/buck,shs96c/buck,mnuessler/buck,tgummerer/buck,rmaz/buck,neonichu/buck,zhan-xiong/buck,illicitonion/buck,SeleniumHQ/buck,lukw00/buck,Distrotech/buck,brettwooldridge/buck,vine/buck,rmaz/buck,darkforestzero/buck,SeleniumHQ/buck,mread/buck,luiseduardohdbackup/buck,illicitonion/buck,JoelMarcey/buck,rmaz/buck,tgummerer/buck,LegNeato/buck,lukw00/buck,daedric/buck,davido/buck,romanoid/buck,Addepar/buck,zhan-xiong/buck,stuhood/buck,dpursehouse/buck,shs96c/buck,SeleniumHQ/buck,romanoid/buck,k21/buck,SeleniumHQ/buck,dushmis/buck,Learn-Android-app/buck,davido/buck,zhan-xiong/buck,mikekap/buck,lukw00/buck,artiya4u/buck,zpao/buck,sdwilsh/buck,daedric/buck,kageiit/buck,robbertvanginkel/buck,bocon13/buck,brettwooldridge/buck,LegNeato/buck,justinmuller/buck,kageiit/buck,k21/buck,SeleniumHQ/buck,illicitonion/buck,grumpyjames/buck,tgummerer/buck,daedric/buck,pwz3n0/buck,Learn-Android-app/buck,romanoid/buck,mogers/buck,saleeh93/buck-cutom,nguyentruongtho/buck,rowillia/buck,liuyang-li/buck,Distrotech/buck,Addepar/buck,ilya-klyuchnikov/buck,Learn-Android-app/buck,davido/buck,Addepar/buck,dushmis/buck,JoelMarcey/buck,marcinkwiatkowski/buck,marcinkwiatkowski/buck,pwz3n0/buck,dpursehouse/buck,Heart2009/buck,romanoid/buck,LegNeato/buck,zpao/buck,pwz3n0/buck,Distrotech/buck,sdwilsh/buck,marcinkwiatkowski/buck,SeleniumHQ/buck,dpursehouse/buck,clonetwin26/buck,clonetwin26/buck,facebook/buck,shs96c/buck,dsyang/buck,ilya-klyuchnikov/buck,Addepar/buck,zhuxiaohao/buck,rmaz/buck,justinmuller/buck,raviagarwal7/buck,OkBuilds/buck,daedric/buck,Heart2009/buck,daedric/buck,dushmis/buck,Addepar/buck,Addepar/buck,daedric/buck,mikekap/buck,OkBuilds/buck,rmaz/buck,janicduplessis/buck,rmaz/buck,vine/buck,zpao/buck,rowillia/buck,shs96c/buck,mnuessler/buck,rowillia/buck,dpursehouse/buck,marcinkwiatkowski/buck,rmaz/buck,lukw00/buck,grumpyjames/buck,JoelMarcey/buck,Distrotech/buck,rmaz/buck,darkforestzero/buck,davido/buck,k21/buck,luiseduardohdbackup/buck,tgummerer/buck,zpao/buck,brettwooldridge/buck,neonichu/buck,neonichu/buck,rmaz/buck,shs96c/buck,brettwooldridge/buck,Heart2009/buck,vschs007/buck,ilya-klyuchnikov/buck,janicduplessis/buck,mikekap/buck,sdwilsh/buck,shybovycha/buck,darkforestzero/buck,raviagarwal7/buck,mikekap/buck,Distrotech/buck,LegNeato/buck,janicduplessis/buck,dsyang/buck,romanoid/buck,shs96c/buck,Addepar/buck,pwz3n0/buck,rhencke/buck,vine/buck,sdwilsh/buck,mikekap/buck,Dominator008/buck,rowillia/buck,clonetwin26/buck,k21/buck,SeleniumHQ/buck,JoelMarcey/buck,brettwooldridge/buck,liuyang-li/buck,davido/buck,rhencke/buck,shybovycha/buck,rowillia/buck,shybovycha/buck,marcinkwiatkowski/buck,lukw00/buck,k21/buck,neonichu/buck,mnuessler/buck,mread/buck,artiya4u/buck,lukw00/buck,JoelMarcey/buck,grumpyjames/buck,shybovycha/buck,liuyang-li/buck,marcinkwiatkowski/buck,hgl888/buck,justinmuller/buck,brettwooldridge/buck,facebook/buck,MarkRunWu/buck,Distrotech/buck,vschs007/buck,k21/buck,illicitonion/buck,vschs007/buck,bocon13/buck,vine/buck,Distrotech/buck,daedric/buck,sdwilsh/buck,bocon13/buck,artiya4u/buck,sdwilsh/buck,marcinkwiatkowski/buck,mogers/buck,pwz3n0/buck,mikekap/buck,vschs007/buck,MarkRunWu/buck,k21/buck,dsyang/buck,zhan-xiong/buck,illicitonion/buck,shs96c/buck,dsyang/buck,dpursehouse/buck,dpursehouse/buck,daedric/buck,k21/buck,Learn-Android-app/buck,facebook/buck,artiya4u/buck,dsyang/buck,romanoid/buck,zhuxiaohao/buck,1yvT0s/buck,robbertvanginkel/buck,robbertvanginkel/buck,bocon13/buck,zhuxiaohao/buck,clonetwin26/buck,facebook/buck,mread/buck,robbertvanginkel/buck,vine/buck,grumpyjames/buck,dsyang/buck,stuhood/buck,JoelMarcey/buck,janicduplessis/buck,OkBuilds/buck,Distrotech/buck,1yvT0s/buck,k21/buck,brettwooldridge/buck,SeleniumHQ/buck,k21/buck,ilya-klyuchnikov/buck,LegNeato/buck,brettwooldridge/buck,SeleniumHQ/buck,darkforestzero/buck,vschs007/buck,siddhartharay007/buck,siddhartharay007/buck,artiya4u/buck,stuhood/buck,Heart2009/buck,vschs007/buck,vschs007/buck,rowillia/buck,mnuessler/buck,siddhartharay007/buck,nguyentruongtho/buck,raviagarwal7/buck,Learn-Android-app/buck,sdwilsh/buck,Dominator008/buck,LegNeato/buck,grumpyjames/buck,zhuxiaohao/buck,kageiit/buck,zhan-xiong/buck,neonichu/buck,daedric/buck,MarkRunWu/buck,clonetwin26/buck,Learn-Android-app/buck,davido/buck,Distrotech/buck,mnuessler/buck,1yvT0s/buck,1yvT0s/buck,vschs007/buck,justinmuller/buck,siddhartharay007/buck,SeleniumHQ/buck,robbertvanginkel/buck,dpursehouse/buck,zhan-xiong/buck,romanoid/buck,ilya-klyuchnikov/buck,1yvT0s/buck,artiya4u/buck,janicduplessis/buck,luiseduardohdbackup/buck,hgl888/buck,grumpyjames/buck,Distrotech/buck,Learn-Android-app/buck,brettwooldridge/buck,Dominator008/buck,vschs007/buck,stuhood/buck,dsyang/buck,darkforestzero/buck,justinmuller/buck,justinmuller/buck,robbertvanginkel/buck,liuyang-li/buck,rowillia/buck,mread/buck,neonichu/buck,clonetwin26/buck,tgummerer/buck,hgl888/buck,pwz3n0/buck,zhan-xiong/buck,vschs007/buck,zhan-xiong/buck,zhan-xiong/buck,darkforestzero/buck,shybovycha/buck,bocon13/buck,neonichu/buck,shs96c/buck,k21/buck,robbertvanginkel/buck,luiseduardohdbackup/buck,clonetwin26/buck,dushmis/buck,liuyang-li/buck,liuyang-li/buck,shybovycha/buck,daedric/buck,Dominator008/buck,mogers/buck,mikekap/buck,marcinkwiatkowski/buck,stuhood/buck,clonetwin26/buck,zpao/buck,Learn-Android-app/buck,kageiit/buck,stuhood/buck,darkforestzero/buck,Dominator008/buck,tgummerer/buck,brettwooldridge/buck,marcinkwiatkowski/buck,dushmis/buck,pwz3n0/buck,Learn-Android-app/buck,siddhartharay007/buck,brettwooldridge/buck,SeleniumHQ/buck,justinmuller/buck,dsyang/buck,justinmuller/buck,daedric/buck,Dominator008/buck,mnuessler/buck,romanoid/buck,brettwooldridge/buck,romanoid/buck,MarkRunWu/buck,clonetwin26/buck,clonetwin26/buck,dsyang/buck,hgl888/buck,kageiit/buck,LegNeato/buck,mogers/buck,OkBuilds/buck,kageiit/buck,JoelMarcey/buck,shybovycha/buck,tgummerer/buck,OkBuilds/buck,robbertvanginkel/buck,illicitonion/buck,davido/buck,janicduplessis/buck,clonetwin26/buck,shybovycha/buck,zpao/buck,kageiit/buck,SeleniumHQ/buck,illicitonion/buck,dsyang/buck,stuhood/buck,Dominator008/buck,raviagarwal7/buck,nguyentruongtho/buck,raviagarwal7/buck,Heart2009/buck,davido/buck,mread/buck,daedric/buck,pwz3n0/buck,Learn-Android-app/buck,OkBuilds/buck,JoelMarcey/buck,zhuxiaohao/buck,ilya-klyuchnikov/buck,mogers/buck,SeleniumHQ/buck,mread/buck,darkforestzero/buck,mogers/buck,dushmis/buck,pwz3n0/buck,zhuxiaohao/buck,tgummerer/buck,robbertvanginkel/buck,vine/buck,liuyang-li/buck,rhencke/buck,mikekap/buck,tgummerer/buck,raviagarwal7/buck,dsyang/buck,artiya4u/buck,raviagarwal7/buck,artiya4u/buck,pwz3n0/buck,liuyang-li/buck,darkforestzero/buck,1yvT0s/buck,rmaz/buck,zpao/buck,facebook/buck,daedric/buck,bocon13/buck,bocon13/buck,Dominator008/buck,raviagarwal7/buck,illicitonion/buck,sdwilsh/buck,rhencke/buck,Dominator008/buck,marcinkwiatkowski/buck,MarkRunWu/buck,davido/buck,lukw00/buck,mikekap/buck,OkBuilds/buck,OkBuilds/buck,OkBuilds/buck,dushmis/buck,OkBuilds/buck,mogers/buck,ilya-klyuchnikov/buck,janicduplessis/buck,hgl888/buck,Distrotech/buck,mogers/buck,JoelMarcey/buck,tgummerer/buck,nguyentruongtho/buck,artiya4u/buck,artiya4u/buck,romanoid/buck,Heart2009/buck,illicitonion/buck,k21/buck,davido/buck,rowillia/buck,darkforestzero/buck,illicitonion/buck,clonetwin26/buck,mikekap/buck,pwz3n0/buck,zhan-xiong/buck,facebook/buck,luiseduardohdbackup/buck,JoelMarcey/buck,zhuxiaohao/buck,dsyang/buck,lukw00/buck,OkBuilds/buck,nguyentruongtho/buck,sdwilsh/buck,raviagarwal7/buck,justinmuller/buck,neonichu/buck,rhencke/buck | /*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.android.UberRDotJava.BuildOutput;
import com.facebook.buck.dalvik.EstimateLinearAllocStep;
import com.facebook.buck.java.AccumulateClassNamesStep;
import com.facebook.buck.java.JavacOptions;
import com.facebook.buck.java.JavacStep;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbiRule;
import com.facebook.buck.rules.AbstractBuildable;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildOutputInitializer;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.InitializableFromDisk;
import com.facebook.buck.rules.OnDiskBuildInfo;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.Sha1HashCode;
import com.facebook.buck.step.AbstractExecutionStep;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.hash.HashCode;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Buildable that is responsible for:
* <ul>
* <li>Generating a single {@code R.java} file from those directories (aka the uber-R.java).
* <li>Compiling the single {@code R.java} file.
* <li>Dexing the single {@code R.java} to a {@code classes.dex.jar} file (Optional).
* </ul>
* <p>
* Clients of this Buildable may need to know the path to the {@code R.java} file.
*/
public class UberRDotJava extends AbstractBuildable implements
AbiRule, InitializableFromDisk<BuildOutput> {
public static final String R_DOT_JAVA_LINEAR_ALLOC_SIZE = "r_dot_java_linear_alloc_size";
private final BuildTarget buildTarget;
private final FilteredResourcesProvider filteredResourcesProvider;
private final JavacOptions javacOptions;
private final AndroidResourceDepsFinder androidResourceDepsFinder;
private final boolean rDotJavaNeedsDexing;
private final boolean shouldBuildStringSourceMap;
private final BuildOutputInitializer<BuildOutput> buildOutputInitializer;
UberRDotJava(BuildTarget buildTarget,
FilteredResourcesProvider filteredResourcesProvider,
JavacOptions javacOptions,
AndroidResourceDepsFinder androidResourceDepsFinder,
boolean rDotJavaNeedsDexing,
boolean shouldBuildStringSourceMap) {
this.buildTarget = Preconditions.checkNotNull(buildTarget);
this.filteredResourcesProvider = Preconditions.checkNotNull(filteredResourcesProvider);
this.javacOptions = Preconditions.checkNotNull(javacOptions);
this.androidResourceDepsFinder = Preconditions.checkNotNull(androidResourceDepsFinder);
this.rDotJavaNeedsDexing = rDotJavaNeedsDexing;
this.shouldBuildStringSourceMap = shouldBuildStringSourceMap;
this.buildOutputInitializer = new BuildOutputInitializer<>(buildTarget, this);
}
@Override
public RuleKey.Builder appendDetailsToRuleKey(RuleKey.Builder builder) {
javacOptions.appendToRuleKey(builder);
return builder
.set("rDotJavaNeedsDexing", rDotJavaNeedsDexing)
.set("shouldBuildStringSourceMap", shouldBuildStringSourceMap);
}
@Override
public Collection<Path> getInputsToCompareToOutput() {
return ImmutableList.of();
}
@Override
public Path getPathToOutputFile() {
return null;
}
public Optional<DexWithClasses> getRDotJavaDexWithClasses() {
Preconditions.checkState(rDotJavaNeedsDexing,
"Error trying to get R.java dex file: R.java is not supposed to be dexed.");
final Optional<Integer> linearAllocSizeEstimate =
buildOutputInitializer.getBuildOutput().rDotJavaDexLinearAllocEstimate;
if (!linearAllocSizeEstimate.isPresent()) {
return Optional.absent();
}
return Optional.<DexWithClasses>of(new DexWithClasses() {
@Override
public Path getPathToDexFile() {
return getPathToRDotJavaDex();
}
@Override
public ImmutableSet<String> getClassNames() {
throw new RuntimeException(
"Since R.java is unconditionally packed in the primary dex, no" +
"one should call this method.");
}
@Override
public int getSizeEstimate() {
return linearAllocSizeEstimate.get();
}
});
}
BuildTarget getBuildTarget() {
return buildTarget;
}
@Override
public List<Step> getBuildSteps(
BuildContext context,
final BuildableContext buildableContext
) throws IOException {
ImmutableList.Builder<Step> steps = ImmutableList.builder();
AndroidResourceDetails androidResourceDetails =
androidResourceDepsFinder.getAndroidResourceDetails();
ImmutableSet<String> rDotJavaPackages = androidResourceDetails.rDotJavaPackages;
ImmutableSet<Path> resDirectories = filteredResourcesProvider.getResDirectories();
if (!resDirectories.isEmpty()) {
generateAndCompileRDotJavaFiles(resDirectories, rDotJavaPackages, steps, buildableContext);
}
if (rDotJavaNeedsDexing && !resDirectories.isEmpty()) {
Path rDotJavaDexDir = getPathToRDotJavaDexFiles();
steps.add(new MakeCleanDirectoryStep(rDotJavaDexDir));
steps.add(new DxStep(
getPathToRDotJavaDex(),
Collections.singleton(getPathToCompiledRDotJavaFiles()),
EnumSet.of(DxStep.Option.NO_OPTIMIZE)));
final EstimateLinearAllocStep estimateLinearAllocStep = new EstimateLinearAllocStep(
getPathToCompiledRDotJavaFiles());
steps.add(estimateLinearAllocStep);
buildableContext.recordArtifact(getPathToRDotJavaDex());
steps.add(
new AbstractExecutionStep("record_build_output") {
@Override
public int execute(ExecutionContext context) {
buildableContext.addMetadata(
R_DOT_JAVA_LINEAR_ALLOC_SIZE,
estimateLinearAllocStep.get().toString());
return 0;
}
});
}
return steps.build();
}
@Override
public BuildOutput initializeFromDisk(OnDiskBuildInfo onDiskBuildInfo) {
Map<String, HashCode> classesHash = ImmutableMap.of();
if (!filteredResourcesProvider.getResDirectories().isEmpty()) {
List<String> lines;
try {
lines = onDiskBuildInfo.getOutputFileContentsByLine(getPathToRDotJavaClassesTxt());
} catch (IOException e) {
throw new RuntimeException(e);
}
classesHash = AccumulateClassNamesStep.parseClassHashes(lines);
}
Optional<String> linearAllocSizeValue = onDiskBuildInfo.getValue(R_DOT_JAVA_LINEAR_ALLOC_SIZE);
Optional<Integer> linearAllocSize = linearAllocSizeValue.isPresent()
? Optional.of(Integer.parseInt(linearAllocSizeValue.get()))
: Optional.<Integer>absent();
return new BuildOutput(linearAllocSize, classesHash);
}
@Override
public BuildOutputInitializer<BuildOutput> getBuildOutputInitializer() {
return buildOutputInitializer;
}
@Override
public Sha1HashCode getAbiKeyForDeps() throws IOException {
return HasAndroidResourceDeps.ABI_HASHER.apply(androidResourceDepsFinder.getAndroidResources());
}
public static class BuildOutput {
private final Optional<Integer> rDotJavaDexLinearAllocEstimate;
// TODO(user): Remove the annotation once DexWithClasses uses the hash.
@SuppressWarnings("unused")
private final Map<String, HashCode> rDotJavaClassesHash;
public BuildOutput(
Optional<Integer> rDotJavaDexLinearAllocSizeEstimate,
Map<String, HashCode> rDotJavaClassesHash) {
this.rDotJavaDexLinearAllocEstimate =
Preconditions.checkNotNull(rDotJavaDexLinearAllocSizeEstimate);
this.rDotJavaClassesHash = Preconditions.checkNotNull(rDotJavaClassesHash);
}
}
/**
* Adds the commands to generate and compile the {@code R.java} files. The {@code R.class} files
* will be written to {@link #getPathToCompiledRDotJavaFiles()}.
*/
private void generateAndCompileRDotJavaFiles(
Set<Path> resDirectories,
Set<String> rDotJavaPackages,
ImmutableList.Builder<Step> steps,
final BuildableContext buildableContext) {
// Create the path where the R.java files will be generated.
Path rDotJavaSrc = getPathToGeneratedRDotJavaSrcFiles();
steps.add(new MakeCleanDirectoryStep(rDotJavaSrc));
// Generate the R.java files.
GenRDotJavaStep genRDotJava = new GenRDotJavaStep(
resDirectories,
rDotJavaSrc,
rDotJavaPackages.iterator().next(),
/* isTempRDotJava */ false,
rDotJavaPackages);
steps.add(genRDotJava);
if (shouldBuildStringSourceMap) {
// Make sure we have an output directory
Path outputDirPath = getPathForNativeStringInfoDirectory();
steps.add(new MakeCleanDirectoryStep(outputDirPath));
// Add the step that parses R.txt and all the strings.xml files, and
// produces a JSON with android resource id's and xml paths for each string resource.
GenStringSourceMapStep genNativeStringInfo = new GenStringSourceMapStep(
rDotJavaSrc,
resDirectories,
outputDirPath);
steps.add(genNativeStringInfo);
// Cache the generated strings.json file, it will be stored inside outputDirPath
buildableContext.recordArtifactsInDirectory(outputDirPath);
}
// Compile the R.java files.
Set<Path> javaSourceFilePaths = Sets.newHashSet();
for (String rDotJavaPackage : rDotJavaPackages) {
Path path = rDotJavaSrc.resolve(rDotJavaPackage.replace('.', '/')).resolve("R.java");
javaSourceFilePaths.add(path);
}
// Create the path where the R.java files will be compiled.
Path rDotJavaBin = getPathToCompiledRDotJavaFiles();
steps.add(new MakeCleanDirectoryStep(rDotJavaBin));
JavacStep javac = UberRDotJavaUtil.createJavacStepForUberRDotJavaFiles(
javaSourceFilePaths,
rDotJavaBin,
javacOptions,
buildTarget);
steps.add(javac);
Path rDotJavaClassesTxt = getPathToRDotJavaClassesTxt();
steps.add(new MakeCleanDirectoryStep(rDotJavaClassesTxt.getParent()));
steps.add(new AccumulateClassNamesStep(Optional.of(rDotJavaBin), rDotJavaClassesTxt));
// Ensure the generated R.txt, R.java, and R.class files are also recorded.
buildableContext.recordArtifactsInDirectory(rDotJavaSrc);
buildableContext.recordArtifactsInDirectory(rDotJavaBin);
buildableContext.recordArtifact(rDotJavaClassesTxt);
}
private Path getPathForNativeStringInfoDirectory() {
return BuildTargets.getBinPath(buildTarget, "__%s_string_source_map__");
}
/**
* @return path to the directory where the {@code R.class} files can be found after this rule is
* built.
*/
public Path getPathToCompiledRDotJavaFiles() {
return BuildTargets.getBinPath(buildTarget, "__%s_uber_rdotjava_bin__");
}
/**
* This directory contains both the generated {@code R.java} and {@code R.txt} files.
* The {@code R.txt} file will be in the root of the directory whereas the {@code R.java} files
* will be under a directory path that matches the corresponding package structure.
*/
Path getPathToGeneratedRDotJavaSrcFiles() {
return BuildTargets.getBinPath(buildTarget, "__%s_uber_rdotjava_src__");
}
Path getPathToRDotJavaDexFiles() {
return BuildTargets.getBinPath(buildTarget, "__%s_uber_rdotjava_dex__");
}
Path getPathToRDotJavaDex() {
return getPathToRDotJavaDexFiles().resolve("classes.dex.jar");
}
Path getPathToRDotJavaClassesTxt() {
return BuildTargets.getBinPath(buildTarget, "__%s_uber_rdotjava_classes__")
.resolve("classes.txt");
}
}
| src/com/facebook/buck/android/UberRDotJava.java | /*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.android.UberRDotJava.BuildOutput;
import com.facebook.buck.dalvik.EstimateLinearAllocStep;
import com.facebook.buck.java.AccumulateClassNamesStep;
import com.facebook.buck.java.JavacOptions;
import com.facebook.buck.java.JavacStep;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbiRule;
import com.facebook.buck.rules.AbstractBuildable;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildOutputInitializer;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.InitializableFromDisk;
import com.facebook.buck.rules.OnDiskBuildInfo;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.Sha1HashCode;
import com.facebook.buck.step.AbstractExecutionStep;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.hash.HashCode;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Buildable that is responsible for:
* <ul>
* <li>Generating a single {@code R.java} file from those directories (aka the uber-R.java).
* <li>Compiling the single {@code R.java} file.
* <li>Dexing the single {@code R.java} to a {@code classes.dex.jar} file (Optional).
* </ul>
* <p>
* Clients of this Buildable may need to know the path to the {@code R.java} file.
*/
public class UberRDotJava extends AbstractBuildable implements
AbiRule, InitializableFromDisk<BuildOutput> {
public static final String R_DOT_JAVA_LINEAR_ALLOC_SIZE = "r_dot_java_linear_alloc_size";
private final BuildTarget buildTarget;
private final FilteredResourcesProvider filteredResourcesProvider;
private final JavacOptions javacOptions;
private final AndroidResourceDepsFinder androidResourceDepsFinder;
private final boolean rDotJavaNeedsDexing;
private final boolean shouldBuildStringSourceMap;
private final BuildOutputInitializer<BuildOutput> buildOutputInitializer;
UberRDotJava(BuildTarget buildTarget,
FilteredResourcesProvider filteredResourcesProvider,
JavacOptions javacOptions,
AndroidResourceDepsFinder androidResourceDepsFinder,
boolean rDotJavaNeedsDexing,
boolean shouldBuildStringSourceMap) {
this.buildTarget = Preconditions.checkNotNull(buildTarget);
this.filteredResourcesProvider = Preconditions.checkNotNull(filteredResourcesProvider);
this.javacOptions = Preconditions.checkNotNull(javacOptions);
this.androidResourceDepsFinder = Preconditions.checkNotNull(androidResourceDepsFinder);
this.rDotJavaNeedsDexing = rDotJavaNeedsDexing;
this.shouldBuildStringSourceMap = shouldBuildStringSourceMap;
this.buildOutputInitializer = new BuildOutputInitializer<>(buildTarget, this);
}
@Override
public RuleKey.Builder appendDetailsToRuleKey(RuleKey.Builder builder) {
javacOptions.appendToRuleKey(builder);
return builder
.set("rDotJavaNeedsDexing", rDotJavaNeedsDexing)
.set("shouldBuildStringSourceMap", shouldBuildStringSourceMap);
}
@Override
public Collection<Path> getInputsToCompareToOutput() {
return ImmutableList.of();
}
@Override
public Path getPathToOutputFile() {
return null;
}
public Optional<DexWithClasses> getRDotJavaDexWithClasses() {
Preconditions.checkState(rDotJavaNeedsDexing,
"Error trying to get R.java dex file: R.java is not supposed to be dexed.");
final Optional<Integer> linearAllocSizeEstimate =
buildOutputInitializer.getBuildOutput().rDotJavaDexLinearAllocEstimate;
if (!linearAllocSizeEstimate.isPresent()) {
return Optional.absent();
}
return Optional.<DexWithClasses>of(new DexWithClasses() {
@Override
public Path getPathToDexFile() {
return getPathToRDotJavaDex();
}
@Override
public ImmutableSet<String> getClassNames() {
throw new RuntimeException(
"Since R.java is unconditionally packed in the primary dex, no" +
"one should call this method.");
}
@Override
public int getSizeEstimate() {
return linearAllocSizeEstimate.get();
}
});
}
BuildTarget getBuildTarget() {
return buildTarget;
}
@Override
public List<Step> getBuildSteps(
BuildContext context,
final BuildableContext buildableContext
) throws IOException {
ImmutableList.Builder<Step> steps = ImmutableList.builder();
AndroidResourceDetails androidResourceDetails =
androidResourceDepsFinder.getAndroidResourceDetails();
ImmutableSet<String> rDotJavaPackages = androidResourceDetails.rDotJavaPackages;
ImmutableSet<Path> resDirectories = filteredResourcesProvider.getResDirectories();
if (!resDirectories.isEmpty()) {
generateAndCompileRDotJavaFiles(resDirectories, rDotJavaPackages, steps, buildableContext);
}
if (rDotJavaNeedsDexing && !resDirectories.isEmpty()) {
Path rDotJavaDexDir = getPathToRDotJavaDexFiles();
steps.add(new MakeCleanDirectoryStep(rDotJavaDexDir));
steps.add(new DxStep(
getPathToRDotJavaDex(),
Collections.singleton(getPathToCompiledRDotJavaFiles()),
EnumSet.of(DxStep.Option.NO_OPTIMIZE)));
final EstimateLinearAllocStep estimateLinearAllocStep = new EstimateLinearAllocStep(
getPathToCompiledRDotJavaFiles());
steps.add(estimateLinearAllocStep);
buildableContext.recordArtifact(getPathToRDotJavaDex());
steps.add(
new AbstractExecutionStep("record_build_output") {
@Override
public int execute(ExecutionContext context) {
buildableContext.addMetadata(
R_DOT_JAVA_LINEAR_ALLOC_SIZE,
estimateLinearAllocStep.get().toString());
return 0;
}
});
}
return steps.build();
}
@Override
public BuildOutput initializeFromDisk(OnDiskBuildInfo onDiskBuildInfo) {
Map<String, HashCode> classesHash = ImmutableMap.of();
if (!filteredResourcesProvider.getResDirectories().isEmpty()) {
List<String> lines;
try {
lines = onDiskBuildInfo.getOutputFileContentsByLine(getPathToRDotJavaClassesTxt());
} catch (IOException e) {
throw new RuntimeException(e);
}
classesHash = AccumulateClassNamesStep.parseClassHashes(lines);
}
Optional<String> linearAllocSizeValue = onDiskBuildInfo.getValue(R_DOT_JAVA_LINEAR_ALLOC_SIZE);
Optional<Integer> linearAllocSize = linearAllocSizeValue.isPresent()
? Optional.of(Integer.parseInt(linearAllocSizeValue.get()))
: Optional.<Integer>absent();
return new BuildOutput(linearAllocSize, classesHash);
}
@Override
public BuildOutputInitializer<BuildOutput> getBuildOutputInitializer() {
return buildOutputInitializer;
}
@Override
public Sha1HashCode getAbiKeyForDeps() throws IOException {
return HasAndroidResourceDeps.ABI_HASHER.apply(androidResourceDepsFinder.getAndroidResources());
}
public static class BuildOutput {
private final Optional<Integer> rDotJavaDexLinearAllocEstimate;
// TODO(user): Remove the annotation once DexWithClasses uses the hash.
@SuppressWarnings("unused")
private final Map<String, HashCode> rDotJavaClassesHash;
public BuildOutput(
Optional<Integer> rDotJavaDexLinearAllocSizeEstimate,
Map<String, HashCode> rDotJavaClassesHash) {
this.rDotJavaDexLinearAllocEstimate =
Preconditions.checkNotNull(rDotJavaDexLinearAllocSizeEstimate);
this.rDotJavaClassesHash = Preconditions.checkNotNull(rDotJavaClassesHash);
}
}
/**
* Adds the commands to generate and compile the {@code R.java} files. The {@code R.class} files
* will be written to {@link #getPathToCompiledRDotJavaFiles()}.
*/
private void generateAndCompileRDotJavaFiles(
Set<Path> resDirectories,
Set<String> rDotJavaPackages,
ImmutableList.Builder<Step> commands,
final BuildableContext buildableContext) {
// Create the path where the R.java files will be generated.
Path rDotJavaSrc = getPathToGeneratedRDotJavaSrcFiles();
commands.add(new MakeCleanDirectoryStep(rDotJavaSrc));
// Generate the R.java files.
GenRDotJavaStep genRDotJava = new GenRDotJavaStep(
resDirectories,
rDotJavaSrc,
rDotJavaPackages.iterator().next(),
/* isTempRDotJava */ false,
rDotJavaPackages);
commands.add(genRDotJava);
if (shouldBuildStringSourceMap) {
// Make sure we have an output directory
Path outputDirPath = getPathForNativeStringInfoDirectory();
commands.add(new MakeCleanDirectoryStep(outputDirPath));
// Add the step that parses R.txt and all the strings.xml files, and
// produces a JSON with android resource id's and xml paths for each string resource.
GenStringSourceMapStep genNativeStringInfo = new GenStringSourceMapStep(
rDotJavaSrc,
resDirectories,
outputDirPath);
commands.add(genNativeStringInfo);
// Cache the generated strings.json file, it will be stored inside outputDirPath
buildableContext.recordArtifactsInDirectory(outputDirPath);
}
// Compile the R.java files.
Set<Path> javaSourceFilePaths = Sets.newHashSet();
for (String rDotJavaPackage : rDotJavaPackages) {
Path path = rDotJavaSrc.resolve(rDotJavaPackage.replace('.', '/')).resolve("R.java");
javaSourceFilePaths.add(path);
}
// Create the path where the R.java files will be compiled.
Path rDotJavaBin = getPathToCompiledRDotJavaFiles();
commands.add(new MakeCleanDirectoryStep(rDotJavaBin));
JavacStep javac = UberRDotJavaUtil.createJavacStepForUberRDotJavaFiles(
javaSourceFilePaths,
rDotJavaBin,
javacOptions,
buildTarget);
commands.add(javac);
Path rDotJavaClassesTxt = getPathToRDotJavaClassesTxt();
commands.add(new MakeCleanDirectoryStep(rDotJavaClassesTxt.getParent()));
commands.add(new AccumulateClassNamesStep(Optional.of(rDotJavaBin), rDotJavaClassesTxt));
// Ensure the generated R.txt, R.java, and R.class files are also recorded.
buildableContext.recordArtifactsInDirectory(rDotJavaSrc);
buildableContext.recordArtifactsInDirectory(rDotJavaBin);
buildableContext.recordArtifact(rDotJavaClassesTxt);
}
private Path getPathForNativeStringInfoDirectory() {
return BuildTargets.getBinPath(buildTarget, "__%s_string_source_map__");
}
/**
* @return path to the directory where the {@code R.class} files can be found after this rule is
* built.
*/
public Path getPathToCompiledRDotJavaFiles() {
return BuildTargets.getBinPath(buildTarget, "__%s_uber_rdotjava_bin__");
}
/**
* This directory contains both the generated {@code R.java} and {@code R.txt} files.
* The {@code R.txt} file will be in the root of the directory whereas the {@code R.java} files
* will be under a directory path that matches the corresponding package structure.
*/
Path getPathToGeneratedRDotJavaSrcFiles() {
return BuildTargets.getBinPath(buildTarget, "__%s_uber_rdotjava_src__");
}
Path getPathToRDotJavaDexFiles() {
return BuildTargets.getBinPath(buildTarget, "__%s_uber_rdotjava_dex__");
}
Path getPathToRDotJavaDex() {
return getPathToRDotJavaDexFiles().resolve("classes.dex.jar");
}
Path getPathToRDotJavaClassesTxt() {
return BuildTargets.getBinPath(buildTarget, "__%s_uber_rdotjava_classes__")
.resolve("classes.txt");
}
}
| Rename `commands` to `steps` because that's what they are.
Summary: This has been bothering me for a while.
Test Plan: yolo1
| src/com/facebook/buck/android/UberRDotJava.java | Rename `commands` to `steps` because that's what they are. | <ide><path>rc/com/facebook/buck/android/UberRDotJava.java
<ide> private void generateAndCompileRDotJavaFiles(
<ide> Set<Path> resDirectories,
<ide> Set<String> rDotJavaPackages,
<del> ImmutableList.Builder<Step> commands,
<add> ImmutableList.Builder<Step> steps,
<ide> final BuildableContext buildableContext) {
<ide> // Create the path where the R.java files will be generated.
<ide> Path rDotJavaSrc = getPathToGeneratedRDotJavaSrcFiles();
<del> commands.add(new MakeCleanDirectoryStep(rDotJavaSrc));
<add> steps.add(new MakeCleanDirectoryStep(rDotJavaSrc));
<ide>
<ide> // Generate the R.java files.
<ide> GenRDotJavaStep genRDotJava = new GenRDotJavaStep(
<ide> rDotJavaPackages.iterator().next(),
<ide> /* isTempRDotJava */ false,
<ide> rDotJavaPackages);
<del> commands.add(genRDotJava);
<add> steps.add(genRDotJava);
<ide>
<ide> if (shouldBuildStringSourceMap) {
<ide> // Make sure we have an output directory
<ide> Path outputDirPath = getPathForNativeStringInfoDirectory();
<del> commands.add(new MakeCleanDirectoryStep(outputDirPath));
<add> steps.add(new MakeCleanDirectoryStep(outputDirPath));
<ide>
<ide> // Add the step that parses R.txt and all the strings.xml files, and
<ide> // produces a JSON with android resource id's and xml paths for each string resource.
<ide> rDotJavaSrc,
<ide> resDirectories,
<ide> outputDirPath);
<del> commands.add(genNativeStringInfo);
<add> steps.add(genNativeStringInfo);
<ide>
<ide> // Cache the generated strings.json file, it will be stored inside outputDirPath
<ide> buildableContext.recordArtifactsInDirectory(outputDirPath);
<ide>
<ide> // Create the path where the R.java files will be compiled.
<ide> Path rDotJavaBin = getPathToCompiledRDotJavaFiles();
<del> commands.add(new MakeCleanDirectoryStep(rDotJavaBin));
<add> steps.add(new MakeCleanDirectoryStep(rDotJavaBin));
<ide>
<ide> JavacStep javac = UberRDotJavaUtil.createJavacStepForUberRDotJavaFiles(
<ide> javaSourceFilePaths,
<ide> rDotJavaBin,
<ide> javacOptions,
<ide> buildTarget);
<del> commands.add(javac);
<add> steps.add(javac);
<ide>
<ide> Path rDotJavaClassesTxt = getPathToRDotJavaClassesTxt();
<del> commands.add(new MakeCleanDirectoryStep(rDotJavaClassesTxt.getParent()));
<del> commands.add(new AccumulateClassNamesStep(Optional.of(rDotJavaBin), rDotJavaClassesTxt));
<add> steps.add(new MakeCleanDirectoryStep(rDotJavaClassesTxt.getParent()));
<add> steps.add(new AccumulateClassNamesStep(Optional.of(rDotJavaBin), rDotJavaClassesTxt));
<ide>
<ide> // Ensure the generated R.txt, R.java, and R.class files are also recorded.
<ide> buildableContext.recordArtifactsInDirectory(rDotJavaSrc); |
|
Java | apache-2.0 | f02dc3b7b1b9857d06a8c34a4bb1f9605b8299f8 | 0 | taverna-incubator/incubator-taverna-language,taverna-incubator/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language | package uk.org.taverna.scufl2.rdfxml;
import static uk.org.taverna.scufl2.rdfxml.RDFXMLReader.APPLICATION_RDF_XML;
import static uk.org.taverna.scufl2.rdfxml.RDFXMLReader.APPLICATION_VND_TAVERNA_SCUFL2_WORKFLOW_BUNDLE;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import uk.org.taverna.scufl2.api.common.Scufl2Tools;
import uk.org.taverna.scufl2.api.common.URITools;
import uk.org.taverna.scufl2.api.common.WorkflowBean;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.core.BlockingControlLink;
import uk.org.taverna.scufl2.api.core.Workflow;
import uk.org.taverna.scufl2.api.io.ReaderException;
import uk.org.taverna.scufl2.api.port.ReceiverPort;
import uk.org.taverna.scufl2.api.port.SenderPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Blocking;
import uk.org.taverna.scufl2.rdfxml.jaxb.Control;
import uk.org.taverna.scufl2.rdfxml.jaxb.DataLink;
import uk.org.taverna.scufl2.rdfxml.jaxb.DataLinkEntry;
import uk.org.taverna.scufl2.rdfxml.jaxb.DispatchStack;
import uk.org.taverna.scufl2.rdfxml.jaxb.DispatchStackLayer;
import uk.org.taverna.scufl2.rdfxml.jaxb.IterationStrategyStack;
import uk.org.taverna.scufl2.rdfxml.jaxb.ObjectFactory;
import uk.org.taverna.scufl2.rdfxml.jaxb.Processor.InputProcessorPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Processor.OutputProcessorPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Workflow.InputWorkflowPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Workflow.OutputWorkflowPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Workflow.Processor;
import uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundleDocument;
import uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowDocument;
import uk.org.taverna.scufl2.ucfpackage.UCFPackage;
import uk.org.taverna.scufl2.ucfpackage.UCFPackage.ResourceEntry;
public class RDFXMLDeserializer {
private final UCFPackage ucfPackage;
private WorkflowBundle workflowBundle;
private JAXBContext jaxbContext;
private Unmarshaller unmarshaller;
private Scufl2Tools scufl2Tools = new Scufl2Tools();
private URITools uriTools = new URITools();
private Workflow currentWorkflow;
private uk.org.taverna.scufl2.api.core.Processor currentProcessor;
private URI currentBase;
private uk.org.taverna.scufl2.api.dispatchstack.DispatchStack currentStack;
public RDFXMLDeserializer(UCFPackage ucfPackage) {
this.ucfPackage = ucfPackage;
try {
jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
unmarshaller = jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw new IllegalStateException(
"Can't create JAXBContext/unmarshaller", e);
}
}
@SuppressWarnings("unchecked")
public WorkflowBundle readWorkflowBundle(URI suggestedLocation)
throws IOException, ReaderException {
location = suggestedLocation;
if (location == null) {
location = URI.create("");
} else {
if (!location.getRawPath().endsWith("/")) {
if (location.getQuery() != null
|| location.getFragment() != null) {
// Ouch.. Perhaps some silly website with ?bundleId=15 ?
// We'll better conserve that somehow.
// Let's do the jar: trick and hope it works. Have to escape
// evil chars.
location = URI.create("jar:"
+ location.toASCIIString().replace("?", "%63")
.replace("#", "#35") + "!/");
} else {
// Simple, pretend we're one level down inside the ZIP file
// as a directory
location = location.resolve(location.getRawPath() + "/");
}
}
}
String workflowBundlePath = findWorkflowBundlePath();
InputStream bundleStream = ucfPackage
.getResourceAsInputStream(workflowBundlePath);
JAXBElement<WorkflowBundleDocument> elem;
try {
elem = (JAXBElement<WorkflowBundleDocument>) unmarshaller
.unmarshal(bundleStream);
} catch (JAXBException e) {
throw new ReaderException("Can't parse workflow bundle document "
+ workflowBundlePath, e);
}
WorkflowBundleDocument workflowBundleDocument = elem.getValue();
URI base = location.resolve(workflowBundlePath);
if (workflowBundleDocument.getBase() != null) {
base = location.resolve(workflowBundleDocument.getBase());
}
if (workflowBundleDocument.getAny().size() != 1) {
throw new ReaderException(
"Invalid WorkflowBundleDocument, expected only one <WorkflowBundle>");
}
uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle wb = (uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle) workflowBundleDocument
.getAny().get(0);
parseWorkflowBundle(wb, base);
scufl2Tools.setParents(workflowBundle);
return workflowBundle;
}
protected void parseWorkflowBundle(
uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle wb, URI base)
throws ReaderException, IOException {
workflowBundle = new WorkflowBundle();
workflowBundle.setResources(ucfPackage);
if (wb.getName() != null) {
workflowBundle.setName(wb.getName());
}
if (wb.getSameBaseAs() != null
&& wb.getSameBaseAs().getResource() != null) {
workflowBundle.setSameBaseAs(base.resolve(wb.getSameBaseAs()
.getResource()));
}
mapBean(base.resolve(wb.getAbout()), workflowBundle);
for (uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle.Workflow wfEntry : wb
.getWorkflow()) {
URI wfUri = base.resolve(wfEntry.getWorkflow().getAbout());
String resource = wfEntry.getWorkflow().getSeeAlso().getResource();
URI source = uriTools
.relativePath(location, base.resolve(resource));
readWorkflow(wfUri, source);
}
for (uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle.Profile pfEntry : wb
.getProfile()) {
URI wfUri = base.resolve(pfEntry.getProfile().getAbout());
String resource = pfEntry.getProfile().getSeeAlso().getResource();
URI source = uriTools
.relativePath(location, base.resolve(resource));
readProfile(wfUri, source);
}
if (wb.getMainWorkflow() != null
&& wb.getMainWorkflow().getResource() != null) {
URI mainWfUri = base.resolve(wb.getMainWorkflow().getResource());
Workflow mainWorkflow = (Workflow) resolveBeanUri(mainWfUri);
if (mainWorkflow == null) {
throw new ReaderException("Unknown main workflow " + mainWfUri
+ ", got" + uriToBean.keySet());
}
workflowBundle.setMainWorkflow(mainWorkflow);
}
if (wb.getMainProfile() != null
&& wb.getMainProfile().getResource() != null) {
URI profileUri = base.resolve(wb.getMainProfile().getResource());
uk.org.taverna.scufl2.api.profiles.Profile mainWorkflow = (uk.org.taverna.scufl2.api.profiles.Profile) resolveBeanUri(profileUri);
workflowBundle.setMainProfile(mainWorkflow);
}
}
protected WorkflowBean resolveBeanUri(URI uri) {
WorkflowBean workflowBean = uriToBean.get(uri);
if (workflowBean != null) {
return workflowBean;
}
return uriTools.resolveUri(uri, workflowBundle);
}
protected void readProfile(URI profileUri, URI source)
throws ReaderException {
if (source.isAbsolute()) {
throw new ReaderException("Can't read external profile source "
+ source);
}
uk.org.taverna.scufl2.api.profiles.Profile p = new uk.org.taverna.scufl2.api.profiles.Profile();
p.setParent(workflowBundle);
mapBean(profileUri, p);
}
protected void readWorkflow(URI wfUri, URI source) throws ReaderException,
IOException {
if (source.isAbsolute()) {
throw new ReaderException("Can't read external workflow source "
+ source);
}
InputStream bundleStream = ucfPackage.getResourceAsInputStream(source
.getPath());
JAXBElement<WorkflowDocument> elem;
try {
elem = (JAXBElement<WorkflowDocument>) unmarshaller
.unmarshal(bundleStream);
} catch (JAXBException e) {
throw new ReaderException(
"Can't parse workflow document " + source, e);
}
URI base = location.resolve(source);
if (elem.getValue().getBase() != null) {
base = base.resolve(elem.getValue().getBase());
}
if (elem.getValue().getAny().size() != 1) {
throw new ReaderException("Expects only a <Workflow> element in "
+ source);
}
uk.org.taverna.scufl2.rdfxml.jaxb.Workflow workflow = (uk.org.taverna.scufl2.rdfxml.jaxb.Workflow) elem
.getValue().getAny().get(0);
currentBase = base;
parseWorkflow(workflow, wfUri);
}
protected void parseWorkflow(
uk.org.taverna.scufl2.rdfxml.jaxb.Workflow workflow, URI wfUri) {
Workflow wf = new Workflow();
wf.setParent(workflowBundle);
if (workflow.getAbout() != null) {
mapBean(currentBase.resolve(workflow.getAbout()), wf);
// TODO: Compare resolved URI with desired wfUri
} else {
mapBean(wfUri, wf);
}
currentWorkflow = wf;
if (workflow.getName() != null) {
wf.setName(workflow.getName());
}
if (workflow.getWorkflowIdentifier() != null
&& workflow.getWorkflowIdentifier().getResource() != null) {
wf.setWorkflowIdentifier(currentBase.resolve(workflow
.getWorkflowIdentifier().getResource()));
}
for (InputWorkflowPort inputWorkflowPort : workflow
.getInputWorkflowPort()) {
parseInputWorkflowPort(inputWorkflowPort.getInputWorkflowPort());
}
for (OutputWorkflowPort outputWorkflowPort : workflow
.getOutputWorkflowPort()) {
parseOutputWorkflowPort(outputWorkflowPort.getOutputWorkflowPort());
}
for (Processor processor : workflow.getProcessor()) {
parseProcessor(processor.getProcessor());
}
for (DataLinkEntry dataLinkEntry : workflow.getDatalink()) {
parseDataLink(dataLinkEntry.getDataLink());
}
for (Control c : workflow.getControl()) {
parseControlLink(c.getBlocking());
}
}
protected void parseProcessor(
uk.org.taverna.scufl2.rdfxml.jaxb.Processor processor) {
uk.org.taverna.scufl2.api.core.Processor p = new uk.org.taverna.scufl2.api.core.Processor();
currentProcessor = p;
p.setParent(currentWorkflow);
mapBean(currentBase.resolve(processor.getAbout()), p);
if (processor.getName() != null) {
p.setName(processor.getName());
}
for (InputProcessorPort inputProcessorPort : processor
.getInputProcessorPort()) {
processorInputProcessorPort(inputProcessorPort
.getInputProcessorPort());
}
for (OutputProcessorPort outputProcessorPort : processor
.getOutputProcessorPort()) {
processorOutputProcessorPort(outputProcessorPort
.getOutputProcessorPort());
}
if (processor.getDispatchStack() != null) {
parseDispatchStack(processor.getDispatchStack().getDispatchStack());
}
if (processor.getIterationStrategyStack() != null) {
parseIterationStrategyStack(processor.getIterationStrategyStack()
.getIterationStrategyStack());
}
}
protected void parseDispatchStack(DispatchStack original) {
uk.org.taverna.scufl2.api.dispatchstack.DispatchStack stack = new uk.org.taverna.scufl2.api.dispatchstack.DispatchStack();
if (original.getType() != null) {
stack.setType(currentBase.resolve(original.getType().getResource()));
}
stack.setParent(currentProcessor);
mapBean(currentBase.resolve(original.getAbout()), stack);
currentStack = stack;
if (original.getDispatchStackLayers() != null) {
for (DispatchStackLayer dispatchStackLayer : original.getDispatchStackLayers().getDispatchStackLayer()) {
parseDispatchStackLayer(dispatchStackLayer);
}
}
}
protected void parseDispatchStackLayer(DispatchStackLayer original) {
uk.org.taverna.scufl2.api.dispatchstack.DispatchStackLayer layer = new uk.org.taverna.scufl2.api.dispatchstack.DispatchStackLayer();
layer.setConfigurableType(currentBase.resolve(original.getType().getResource()));
mapBean(currentBase.resolve(original.getAbout()), layer);
}
protected void parseIterationStrategyStack(
IterationStrategyStack iterationStrategyStack) {
// TODO Auto-generated method stub
}
protected void processorOutputProcessorPort(
uk.org.taverna.scufl2.rdfxml.jaxb.OutputProcessorPort original) {
uk.org.taverna.scufl2.api.port.OutputProcessorPort port = new uk.org.taverna.scufl2.api.port.OutputProcessorPort();
port.setName(original.getName());
if (original.getPortDepth() != null) {
port.setDepth(original.getPortDepth().getValue());
}
if (original.getGranularPortDepth() != null) {
port.setGranularDepth(original.getGranularPortDepth().getValue());
}
port.setParent(currentProcessor);
mapBean(currentBase.resolve(original.getAbout()), port);
}
protected void processorInputProcessorPort(
uk.org.taverna.scufl2.rdfxml.jaxb.InputProcessorPort original) {
uk.org.taverna.scufl2.api.port.InputProcessorPort port = new uk.org.taverna.scufl2.api.port.InputProcessorPort();
port.setName(original.getName());
if (original.getPortDepth() != null) {
port.setDepth(original.getPortDepth().getValue());
}
port.setParent(currentProcessor);
mapBean(currentBase.resolve(original.getAbout()), port);
}
protected void parseDataLink(DataLink original) {
URI fromUri = currentBase.resolve(original.getReceiveFrom()
.getResource());
URI toUri = currentBase.resolve(original.getSendTo().getResource());
WorkflowBean from = resolveBeanUri(fromUri);
WorkflowBean to = resolveBeanUri(toUri);
uk.org.taverna.scufl2.api.core.DataLink link = new uk.org.taverna.scufl2.api.core.DataLink();
link.setReceivesFrom((SenderPort) from);
link.setSendsTo((ReceiverPort) to);
if (original.getMergePosition() != null) {
link.setMergePosition(original.getMergePosition().getValue());
}
link.setParent(currentWorkflow);
mapBean(currentBase.resolve(original.getAbout()), link);
}
protected void parseControlLink(Blocking original) {
URI blockUri = currentBase.resolve(original.getBlock()
.getResource());
URI untilFinishedUri = currentBase.resolve(original.getUntilFinished().getResource());
WorkflowBean block = resolveBeanUri(blockUri);
WorkflowBean untilFinished = resolveBeanUri(untilFinishedUri);
BlockingControlLink blocking = new BlockingControlLink();
blocking.setBlock((uk.org.taverna.scufl2.api.core.Processor) block);
blocking.setUntilFinished((uk.org.taverna.scufl2.api.core.Processor) untilFinished);
blocking.setParent(currentWorkflow);
mapBean(currentBase.resolve(original.getAbout()), blocking);
}
protected void parseOutputWorkflowPort(
uk.org.taverna.scufl2.rdfxml.jaxb.OutputWorkflowPort original) {
uk.org.taverna.scufl2.api.port.OutputWorkflowPort port = new uk.org.taverna.scufl2.api.port.OutputWorkflowPort();
port.setName(original.getName());
port.setParent(currentWorkflow);
mapBean(currentBase.resolve(original.getAbout()), port);
}
protected void parseInputWorkflowPort(
uk.org.taverna.scufl2.rdfxml.jaxb.InputWorkflowPort original) {
uk.org.taverna.scufl2.api.port.InputWorkflowPort port = new uk.org.taverna.scufl2.api.port.InputWorkflowPort();
port.setName(original.getName());
if (original.getPortDepth() != null) {
port.setDepth(original.getPortDepth().getValue());
}
port.setParent(currentWorkflow);
mapBean(currentBase.resolve(original.getAbout()), port);
}
protected Map<URI, WorkflowBean> uriToBean = new HashMap<URI, WorkflowBean>();
protected Map<WorkflowBean, URI> beanToUri = new HashMap<WorkflowBean, URI>();
private URI location;
protected void mapBean(URI uri, WorkflowBean bean) {
uriToBean.put(uri, bean);
beanToUri.put(bean, uri);
}
protected String findWorkflowBundlePath() {
if (APPLICATION_VND_TAVERNA_SCUFL2_WORKFLOW_BUNDLE.equals(ucfPackage
.getPackageMediaType())) {
for (ResourceEntry potentialRoot : ucfPackage.getRootFiles()) {
if (APPLICATION_RDF_XML.equals(potentialRoot.getMediaType())) {
return potentialRoot.getPath();
}
}
}
return RDFXMLWriter.WORKFLOW_BUNDLE_RDF;
}
}
| scufl2-rdfxml/src/main/java/uk/org/taverna/scufl2/rdfxml/RDFXMLDeserializer.java | package uk.org.taverna.scufl2.rdfxml;
import static uk.org.taverna.scufl2.rdfxml.RDFXMLReader.APPLICATION_RDF_XML;
import static uk.org.taverna.scufl2.rdfxml.RDFXMLReader.APPLICATION_VND_TAVERNA_SCUFL2_WORKFLOW_BUNDLE;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import uk.org.taverna.scufl2.api.common.Scufl2Tools;
import uk.org.taverna.scufl2.api.common.URITools;
import uk.org.taverna.scufl2.api.common.WorkflowBean;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.core.BlockingControlLink;
import uk.org.taverna.scufl2.api.core.Workflow;
import uk.org.taverna.scufl2.api.io.ReaderException;
import uk.org.taverna.scufl2.api.port.ReceiverPort;
import uk.org.taverna.scufl2.api.port.SenderPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Blocking;
import uk.org.taverna.scufl2.rdfxml.jaxb.Control;
import uk.org.taverna.scufl2.rdfxml.jaxb.DataLink;
import uk.org.taverna.scufl2.rdfxml.jaxb.DataLinkEntry;
import uk.org.taverna.scufl2.rdfxml.jaxb.DispatchStack;
import uk.org.taverna.scufl2.rdfxml.jaxb.DispatchStackLayer;
import uk.org.taverna.scufl2.rdfxml.jaxb.IterationStrategyStack;
import uk.org.taverna.scufl2.rdfxml.jaxb.ObjectFactory;
import uk.org.taverna.scufl2.rdfxml.jaxb.Processor.InputProcessorPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Processor.OutputProcessorPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Workflow.InputWorkflowPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Workflow.OutputWorkflowPort;
import uk.org.taverna.scufl2.rdfxml.jaxb.Workflow.Processor;
import uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundleDocument;
import uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowDocument;
import uk.org.taverna.scufl2.ucfpackage.UCFPackage;
import uk.org.taverna.scufl2.ucfpackage.UCFPackage.ResourceEntry;
public class RDFXMLDeserializer {
private final UCFPackage ucfPackage;
private WorkflowBundle workflowBundle;
private JAXBContext jaxbContext;
private Unmarshaller unmarshaller;
private Scufl2Tools scufl2Tools = new Scufl2Tools();
private URITools uriTools = new URITools();
private Workflow currentWorkflow;
private uk.org.taverna.scufl2.api.core.Processor currentProcessor;
private URI currentBase;
private uk.org.taverna.scufl2.api.dispatchstack.DispatchStack currentStack;
public RDFXMLDeserializer(UCFPackage ucfPackage) {
this.ucfPackage = ucfPackage;
try {
jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
unmarshaller = jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw new IllegalStateException(
"Can't create JAXBContext/unmarshaller", e);
}
}
@SuppressWarnings("unchecked")
public WorkflowBundle readWorkflowBundle(URI suggestedLocation)
throws IOException, ReaderException {
location = suggestedLocation;
if (location == null) {
location = URI.create("");
} else {
if (!location.getRawPath().endsWith("/")) {
if (location.getQuery() != null
|| location.getFragment() != null) {
// Ouch.. Perhaps some silly website with ?bundleId=15 ?
// We'll better conserve that somehow.
// Let's do the jar: trick and hope it works. Have to escape
// evil chars.
location = URI.create("jar:"
+ location.toASCIIString().replace("?", "%63")
.replace("#", "#35") + "!/");
} else {
// Simple, pretend we're one level down inside the ZIP file
// as a directory
location = location.resolve(location.getRawPath() + "/");
}
}
}
String workflowBundlePath = findWorkflowBundlePath();
InputStream bundleStream = ucfPackage
.getResourceAsInputStream(workflowBundlePath);
JAXBElement<WorkflowBundleDocument> elem;
try {
elem = (JAXBElement<WorkflowBundleDocument>) unmarshaller
.unmarshal(bundleStream);
} catch (JAXBException e) {
throw new ReaderException("Can't parse workflow bundle document "
+ workflowBundlePath, e);
}
WorkflowBundleDocument workflowBundleDocument = elem.getValue();
URI base = location.resolve(workflowBundlePath);
if (workflowBundleDocument.getBase() != null) {
base = location.resolve(workflowBundleDocument.getBase());
}
if (workflowBundleDocument.getAny().size() != 1) {
throw new ReaderException(
"Invalid WorkflowBundleDocument, expected only one <WorkflowBundle>");
}
uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle wb = (uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle) workflowBundleDocument
.getAny().get(0);
parseWorkflowBundle(wb, base);
scufl2Tools.setParents(workflowBundle);
return workflowBundle;
}
protected void parseWorkflowBundle(
uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle wb, URI base)
throws ReaderException, IOException {
workflowBundle = new WorkflowBundle();
workflowBundle.setResources(ucfPackage);
if (wb.getName() != null) {
workflowBundle.setName(wb.getName());
}
if (wb.getSameBaseAs() != null
&& wb.getSameBaseAs().getResource() != null) {
workflowBundle.setSameBaseAs(base.resolve(wb.getSameBaseAs()
.getResource()));
}
mapBean(base.resolve(wb.getAbout()), workflowBundle);
for (uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle.Workflow wfEntry : wb
.getWorkflow()) {
URI wfUri = base.resolve(wfEntry.getWorkflow().getAbout());
String resource = wfEntry.getWorkflow().getSeeAlso().getResource();
URI source = uriTools
.relativePath(location, base.resolve(resource));
readWorkflow(wfUri, source);
}
for (uk.org.taverna.scufl2.rdfxml.jaxb.WorkflowBundle.Profile pfEntry : wb
.getProfile()) {
URI wfUri = base.resolve(pfEntry.getProfile().getAbout());
String resource = pfEntry.getProfile().getSeeAlso().getResource();
URI source = uriTools
.relativePath(location, base.resolve(resource));
readProfile(wfUri, source);
}
if (wb.getMainWorkflow() != null
&& wb.getMainWorkflow().getResource() != null) {
URI mainWfUri = base.resolve(wb.getMainWorkflow().getResource());
Workflow mainWorkflow = (Workflow) resolveBeanUri(mainWfUri);
if (mainWorkflow == null) {
throw new ReaderException("Unknown main workflow " + mainWfUri
+ ", got" + uriToBean.keySet());
}
workflowBundle.setMainWorkflow(mainWorkflow);
}
if (wb.getMainProfile() != null
&& wb.getMainProfile().getResource() != null) {
URI profileUri = base.resolve(wb.getMainProfile().getResource());
uk.org.taverna.scufl2.api.profiles.Profile mainWorkflow = (uk.org.taverna.scufl2.api.profiles.Profile) resolveBeanUri(profileUri);
workflowBundle.setMainProfile(mainWorkflow);
}
}
protected WorkflowBean resolveBeanUri(URI uri) {
WorkflowBean workflowBean = uriToBean.get(uri);
if (workflowBean != null) {
return workflowBean;
}
return uriTools.resolveUri(uri, workflowBundle);
}
protected void readProfile(URI profileUri, URI source)
throws ReaderException {
if (source.isAbsolute()) {
throw new ReaderException("Can't read external profile source "
+ source);
}
uk.org.taverna.scufl2.api.profiles.Profile p = new uk.org.taverna.scufl2.api.profiles.Profile();
p.setParent(workflowBundle);
mapBean(profileUri, p);
}
protected void readWorkflow(URI wfUri, URI source) throws ReaderException,
IOException {
if (source.isAbsolute()) {
throw new ReaderException("Can't read external workflow source "
+ source);
}
InputStream bundleStream = ucfPackage.getResourceAsInputStream(source
.getPath());
JAXBElement<WorkflowDocument> elem;
try {
elem = (JAXBElement<WorkflowDocument>) unmarshaller
.unmarshal(bundleStream);
} catch (JAXBException e) {
throw new ReaderException(
"Can't parse workflow document " + source, e);
}
URI base = location.resolve(source);
if (elem.getValue().getBase() != null) {
base = base.resolve(elem.getValue().getBase());
}
if (elem.getValue().getAny().size() != 1) {
throw new ReaderException("Expects only a <Workflow> element in "
+ source);
}
uk.org.taverna.scufl2.rdfxml.jaxb.Workflow workflow = (uk.org.taverna.scufl2.rdfxml.jaxb.Workflow) elem
.getValue().getAny().get(0);
currentBase = base;
parseWorkflow(workflow, wfUri);
}
protected void parseWorkflow(
uk.org.taverna.scufl2.rdfxml.jaxb.Workflow workflow, URI wfUri) {
Workflow wf = new Workflow();
wf.setParent(workflowBundle);
if (workflow.getAbout() != null) {
mapBean(currentBase.resolve(workflow.getAbout()), wf);
// TODO: Compare resolved URI with desired wfUri
} else {
mapBean(wfUri, wf);
}
currentWorkflow = wf;
if (workflow.getName() != null) {
wf.setName(workflow.getName());
}
if (workflow.getWorkflowIdentifier() != null
&& workflow.getWorkflowIdentifier().getResource() != null) {
wf.setWorkflowIdentifier(currentBase.resolve(workflow
.getWorkflowIdentifier().getResource()));
}
for (InputWorkflowPort inputWorkflowPort : workflow
.getInputWorkflowPort()) {
parseInputWorkflowPort(inputWorkflowPort.getInputWorkflowPort());
}
for (OutputWorkflowPort outputWorkflowPort : workflow
.getOutputWorkflowPort()) {
parseOutputWorkflowPort(outputWorkflowPort.getOutputWorkflowPort());
}
for (Processor processor : workflow.getProcessor()) {
parseProcessor(processor.getProcessor());
}
for (DataLinkEntry dataLinkEntry : workflow.getDatalink()) {
parseDataLink(dataLinkEntry.getDataLink());
}
for (Control c : workflow.getControl()) {
parseControlLink(c.getBlocking());
}
}
protected void parseProcessor(
uk.org.taverna.scufl2.rdfxml.jaxb.Processor processor) {
uk.org.taverna.scufl2.api.core.Processor p = new uk.org.taverna.scufl2.api.core.Processor();
currentProcessor = p;
p.setParent(currentWorkflow);
mapBean(currentBase.resolve(processor.getAbout()), p);
if (processor.getName() != null) {
p.setName(processor.getName());
}
for (InputProcessorPort inputProcessorPort : processor
.getInputProcessorPort()) {
processorInputProcessorPort(inputProcessorPort
.getInputProcessorPort());
}
for (OutputProcessorPort outputProcessorPort : processor
.getOutputProcessorPort()) {
processorOutputProcessorPort(outputProcessorPort
.getOutputProcessorPort());
}
if (processor.getDispatchStack() != null) {
parseDispatchStack(processor.getDispatchStack().getDispatchStack());
}
if (processor.getIterationStrategyStack() != null) {
parseIterationStrategyStack(processor.getIterationStrategyStack()
.getIterationStrategyStack());
}
}
protected void parseDispatchStack(DispatchStack original) {
uk.org.taverna.scufl2.api.dispatchstack.DispatchStack stack = new uk.org.taverna.scufl2.api.dispatchstack.DispatchStack();
if (original.getType() != null) {
stack.setType(currentBase.resolve(original.getType().getResource()));
}
stack.setParent(currentProcessor);
currentStack = stack;
if (original.getDispatchStackLayers() != null) {
for (DispatchStackLayer dispatchStackLayer : original.getDispatchStackLayers().getDispatchStackLayer()) {
parseDispatchStackLayer(dispatchStackLayer);
}
}
}
protected void parseDispatchStackLayer(DispatchStackLayer dispatchStackLayer) {
// TODO Auto-generated method stub
}
protected void parseIterationStrategyStack(
IterationStrategyStack iterationStrategyStack) {
// TODO Auto-generated method stub
}
protected void processorOutputProcessorPort(
uk.org.taverna.scufl2.rdfxml.jaxb.OutputProcessorPort original) {
uk.org.taverna.scufl2.api.port.OutputProcessorPort port = new uk.org.taverna.scufl2.api.port.OutputProcessorPort();
port.setName(original.getName());
if (original.getPortDepth() != null) {
port.setDepth(original.getPortDepth().getValue());
}
if (original.getGranularPortDepth() != null) {
port.setGranularDepth(original.getGranularPortDepth().getValue());
}
port.setParent(currentProcessor);
mapBean(currentBase.resolve(original.getAbout()), port);
}
protected void processorInputProcessorPort(
uk.org.taverna.scufl2.rdfxml.jaxb.InputProcessorPort original) {
uk.org.taverna.scufl2.api.port.InputProcessorPort port = new uk.org.taverna.scufl2.api.port.InputProcessorPort();
port.setName(original.getName());
if (original.getPortDepth() != null) {
port.setDepth(original.getPortDepth().getValue());
}
port.setParent(currentProcessor);
mapBean(currentBase.resolve(original.getAbout()), port);
}
protected void parseDataLink(DataLink original) {
URI fromUri = currentBase.resolve(original.getReceiveFrom()
.getResource());
URI toUri = currentBase.resolve(original.getSendTo().getResource());
WorkflowBean from = resolveBeanUri(fromUri);
WorkflowBean to = resolveBeanUri(toUri);
uk.org.taverna.scufl2.api.core.DataLink link = new uk.org.taverna.scufl2.api.core.DataLink();
link.setReceivesFrom((SenderPort) from);
link.setSendsTo((ReceiverPort) to);
if (original.getMergePosition() != null) {
link.setMergePosition(original.getMergePosition().getValue());
}
link.setParent(currentWorkflow);
mapBean(currentBase.resolve(original.getAbout()), link);
}
protected void parseControlLink(Blocking original) {
URI blockUri = currentBase.resolve(original.getBlock()
.getResource());
URI untilFinishedUri = currentBase.resolve(original.getUntilFinished().getResource());
WorkflowBean block = resolveBeanUri(blockUri);
WorkflowBean untilFinished = resolveBeanUri(untilFinishedUri);
BlockingControlLink blocking = new BlockingControlLink();
blocking.setBlock((uk.org.taverna.scufl2.api.core.Processor) block);
blocking.setUntilFinished((uk.org.taverna.scufl2.api.core.Processor) untilFinished);
blocking.setParent(currentWorkflow);
mapBean(currentBase.resolve(original.getAbout()), blocking);
}
protected void parseOutputWorkflowPort(
uk.org.taverna.scufl2.rdfxml.jaxb.OutputWorkflowPort original) {
uk.org.taverna.scufl2.api.port.OutputWorkflowPort port = new uk.org.taverna.scufl2.api.port.OutputWorkflowPort();
port.setName(original.getName());
port.setParent(currentWorkflow);
mapBean(currentBase.resolve(original.getAbout()), port);
}
protected void parseInputWorkflowPort(
uk.org.taverna.scufl2.rdfxml.jaxb.InputWorkflowPort original) {
uk.org.taverna.scufl2.api.port.InputWorkflowPort port = new uk.org.taverna.scufl2.api.port.InputWorkflowPort();
port.setName(original.getName());
if (original.getPortDepth() != null) {
port.setDepth(original.getPortDepth().getValue());
}
port.setParent(currentWorkflow);
mapBean(currentBase.resolve(original.getAbout()), port);
}
protected Map<URI, WorkflowBean> uriToBean = new HashMap<URI, WorkflowBean>();
protected Map<WorkflowBean, URI> beanToUri = new HashMap<WorkflowBean, URI>();
private URI location;
protected void mapBean(URI uri, WorkflowBean bean) {
uriToBean.put(uri, bean);
beanToUri.put(bean, uri);
}
protected String findWorkflowBundlePath() {
if (APPLICATION_VND_TAVERNA_SCUFL2_WORKFLOW_BUNDLE.equals(ucfPackage
.getPackageMediaType())) {
for (ResourceEntry potentialRoot : ucfPackage.getRootFiles()) {
if (APPLICATION_RDF_XML.equals(potentialRoot.getMediaType())) {
return potentialRoot.getPath();
}
}
}
return RDFXMLWriter.WORKFLOW_BUNDLE_RDF;
}
}
| Parse dispatch stack layers
| scufl2-rdfxml/src/main/java/uk/org/taverna/scufl2/rdfxml/RDFXMLDeserializer.java | Parse dispatch stack layers | <ide><path>cufl2-rdfxml/src/main/java/uk/org/taverna/scufl2/rdfxml/RDFXMLDeserializer.java
<ide> stack.setType(currentBase.resolve(original.getType().getResource()));
<ide> }
<ide> stack.setParent(currentProcessor);
<add> mapBean(currentBase.resolve(original.getAbout()), stack);
<ide> currentStack = stack;
<ide> if (original.getDispatchStackLayers() != null) {
<ide> for (DispatchStackLayer dispatchStackLayer : original.getDispatchStackLayers().getDispatchStackLayer()) {
<ide> parseDispatchStackLayer(dispatchStackLayer);
<ide> }
<ide> }
<del>
<del>
<del> }
<del>
<del> protected void parseDispatchStackLayer(DispatchStackLayer dispatchStackLayer) {
<del> // TODO Auto-generated method stub
<del>
<add> }
<add>
<add> protected void parseDispatchStackLayer(DispatchStackLayer original) {
<add> uk.org.taverna.scufl2.api.dispatchstack.DispatchStackLayer layer = new uk.org.taverna.scufl2.api.dispatchstack.DispatchStackLayer();
<add> layer.setConfigurableType(currentBase.resolve(original.getType().getResource()));
<add> mapBean(currentBase.resolve(original.getAbout()), layer);
<ide> }
<ide>
<ide> protected void parseIterationStrategyStack( |
|
Java | apache-2.0 | f3130e115a58a9df22a4c192c7e71e00c80ac0e6 | 0 | werkt/bazel,twitter-forks/bazel,bazelbuild/bazel,akira-baruah/bazel,dslomov/bazel-windows,aehlig/bazel,davidzchen/bazel,cushon/bazel,twitter-forks/bazel,ulfjack/bazel,perezd/bazel,safarmer/bazel,aehlig/bazel,akira-baruah/bazel,davidzchen/bazel,werkt/bazel,akira-baruah/bazel,dropbox/bazel,meteorcloudy/bazel,akira-baruah/bazel,davidzchen/bazel,cushon/bazel,dslomov/bazel,safarmer/bazel,katre/bazel,dropbox/bazel,akira-baruah/bazel,dslomov/bazel-windows,aehlig/bazel,dslomov/bazel-windows,davidzchen/bazel,safarmer/bazel,meteorcloudy/bazel,cushon/bazel,werkt/bazel,katre/bazel,perezd/bazel,perezd/bazel,twitter-forks/bazel,dslomov/bazel,ulfjack/bazel,dslomov/bazel-windows,werkt/bazel,akira-baruah/bazel,aehlig/bazel,dslomov/bazel-windows,ulfjack/bazel,aehlig/bazel,perezd/bazel,safarmer/bazel,aehlig/bazel,bazelbuild/bazel,dropbox/bazel,dropbox/bazel,ButterflyNetwork/bazel,dslomov/bazel,perezd/bazel,ulfjack/bazel,meteorcloudy/bazel,dslomov/bazel-windows,davidzchen/bazel,werkt/bazel,ButterflyNetwork/bazel,meteorcloudy/bazel,bazelbuild/bazel,dropbox/bazel,katre/bazel,cushon/bazel,twitter-forks/bazel,perezd/bazel,ButterflyNetwork/bazel,perezd/bazel,bazelbuild/bazel,katre/bazel,meteorcloudy/bazel,ulfjack/bazel,davidzchen/bazel,aehlig/bazel,bazelbuild/bazel,dslomov/bazel,davidzchen/bazel,dropbox/bazel,katre/bazel,meteorcloudy/bazel,werkt/bazel,ButterflyNetwork/bazel,twitter-forks/bazel,ButterflyNetwork/bazel,dslomov/bazel,safarmer/bazel,dslomov/bazel,twitter-forks/bazel,ulfjack/bazel,bazelbuild/bazel,twitter-forks/bazel,ButterflyNetwork/bazel,ulfjack/bazel,cushon/bazel,katre/bazel,meteorcloudy/bazel,safarmer/bazel,cushon/bazel,dslomov/bazel | // Copyright 2014 The Bazel Authors. 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.google.devtools.build.lib.skyframe;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.Actions.GeneratingActions;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.BasicActionLookupValue;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.VisibleForSerialization;
import com.google.devtools.build.skyframe.SkyKey;
import java.util.ArrayList;
import javax.annotation.Nullable;
/** A non-rule configured target in the context of a Skyframe graph. */
@Immutable
@ThreadSafe
@AutoCodec(memoization = AutoCodec.Memoization.START_MEMOIZING)
@VisibleForTesting
public final class NonRuleConfiguredTargetValue extends BasicActionLookupValue
implements ConfiguredTargetValue {
// These variables are only non-final because they may be clear()ed to save memory.
// configuredTarget is null only after it is cleared.
@Nullable private ConfiguredTarget configuredTarget;
// May be null either after clearing or because transitive packages are not tracked.
@Nullable private NestedSet<Package> transitivePackagesForPackageRootResolution;
@AutoCodec.Instantiator
@VisibleForSerialization
NonRuleConfiguredTargetValue(
ArrayList<ActionAnalysisMetadata> actions,
ImmutableMap<Artifact, Integer> generatingActionIndex,
ConfiguredTarget configuredTarget) {
super(actions, generatingActionIndex, /*removeActionsAfterEvaluation=*/ false);
this.configuredTarget = configuredTarget;
// Transitive packages are not serialized.
this.transitivePackagesForPackageRootResolution = null;
}
NonRuleConfiguredTargetValue(
ConfiguredTarget configuredTarget,
GeneratingActions generatingActions,
@Nullable NestedSet<Package> transitivePackagesForPackageRootResolution,
boolean removeActionsAfterEvaluation) {
super(generatingActions, removeActionsAfterEvaluation);
this.configuredTarget = Preconditions.checkNotNull(configuredTarget, generatingActions);
this.transitivePackagesForPackageRootResolution = transitivePackagesForPackageRootResolution;
}
@VisibleForTesting
@Override
public ConfiguredTarget getConfiguredTarget() {
Preconditions.checkNotNull(configuredTarget);
return configuredTarget;
}
@VisibleForTesting
@Override
public ArrayList<ActionAnalysisMetadata> getActions() {
Preconditions.checkNotNull(configuredTarget, this);
return actions;
}
@Override
public NestedSet<Package> getTransitivePackagesForPackageRootResolution() {
return Preconditions.checkNotNull(transitivePackagesForPackageRootResolution);
}
@Override
public void clear(boolean clearEverything) {
Preconditions.checkNotNull(configuredTarget);
Preconditions.checkNotNull(transitivePackagesForPackageRootResolution);
if (clearEverything) {
configuredTarget = null;
}
transitivePackagesForPackageRootResolution = null;
}
/**
* Returns a label of NonRuleConfiguredTargetValue.
*/
@ThreadSafe
static Label extractLabel(SkyKey value) {
Object valueName = value.argument();
Preconditions.checkState(valueName instanceof ConfiguredTargetKey, valueName);
return ((ConfiguredTargetKey) valueName).getLabel();
}
@Override
public String toString() {
return getStringHelper().add("configuredTarget", configuredTarget).toString();
}
}
| src/main/java/com/google/devtools/build/lib/skyframe/NonRuleConfiguredTargetValue.java | // Copyright 2014 The Bazel Authors. 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.google.devtools.build.lib.skyframe;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.Actions.GeneratingActions;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.BasicActionLookupValue;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.VisibleForSerialization;
import com.google.devtools.build.skyframe.SkyKey;
import java.util.ArrayList;
import javax.annotation.Nullable;
/**
* A configured target in the context of a Skyframe graph.
*/
@Immutable
@ThreadSafe
@AutoCodec
@VisibleForTesting
public final class NonRuleConfiguredTargetValue
extends BasicActionLookupValue implements ConfiguredTargetValue {
// These variables are only non-final because they may be clear()ed to save memory.
// configuredTarget is null only after it is cleared.
@Nullable private ConfiguredTarget configuredTarget;
// May be null either after clearing or because transitive packages are not tracked.
@Nullable private NestedSet<Package> transitivePackagesForPackageRootResolution;
@AutoCodec.Instantiator
@VisibleForSerialization
NonRuleConfiguredTargetValue(
ArrayList<ActionAnalysisMetadata> actions,
ImmutableMap<Artifact, Integer> generatingActionIndex,
ConfiguredTarget configuredTarget) {
super(actions, generatingActionIndex, /*removeActionsAfterEvaluation=*/ false);
this.configuredTarget = configuredTarget;
// Transitive packages are not serialized.
this.transitivePackagesForPackageRootResolution = null;
}
NonRuleConfiguredTargetValue(
ConfiguredTarget configuredTarget,
GeneratingActions generatingActions,
@Nullable NestedSet<Package> transitivePackagesForPackageRootResolution,
boolean removeActionsAfterEvaluation) {
super(generatingActions, removeActionsAfterEvaluation);
this.configuredTarget = Preconditions.checkNotNull(configuredTarget, generatingActions);
this.transitivePackagesForPackageRootResolution = transitivePackagesForPackageRootResolution;
}
@VisibleForTesting
@Override
public ConfiguredTarget getConfiguredTarget() {
Preconditions.checkNotNull(configuredTarget);
return configuredTarget;
}
@VisibleForTesting
@Override
public ArrayList<ActionAnalysisMetadata> getActions() {
Preconditions.checkNotNull(configuredTarget, this);
return actions;
}
@Override
public NestedSet<Package> getTransitivePackagesForPackageRootResolution() {
return Preconditions.checkNotNull(transitivePackagesForPackageRootResolution);
}
@Override
public void clear(boolean clearEverything) {
Preconditions.checkNotNull(configuredTarget);
Preconditions.checkNotNull(transitivePackagesForPackageRootResolution);
if (clearEverything) {
configuredTarget = null;
}
transitivePackagesForPackageRootResolution = null;
}
/**
* Returns a label of NonRuleConfiguredTargetValue.
*/
@ThreadSafe
static Label extractLabel(SkyKey value) {
Object valueName = value.argument();
Preconditions.checkState(valueName instanceof ConfiguredTargetKey, valueName);
return ((ConfiguredTargetKey) valueName).getLabel();
}
@Override
public String toString() {
return getStringHelper().add("configuredTarget", configuredTarget).toString();
}
}
| Memoize non-rule configured targets. This is probably a good idea in general, but especially necessary because OutputFileConfiguredTarget (which is not a RuleConfiguredTarget) contains a reference to its generating configured target, so all the optimizations needed for RuleConfiguredTarget apply to OutputFileConfiguredTarget.
PiperOrigin-RevId: 189942424
| src/main/java/com/google/devtools/build/lib/skyframe/NonRuleConfiguredTargetValue.java | Memoize non-rule configured targets. This is probably a good idea in general, but especially necessary because OutputFileConfiguredTarget (which is not a RuleConfiguredTarget) contains a reference to its generating configured target, so all the optimizations needed for RuleConfiguredTarget apply to OutputFileConfiguredTarget. | <ide><path>rc/main/java/com/google/devtools/build/lib/skyframe/NonRuleConfiguredTargetValue.java
<ide> import java.util.ArrayList;
<ide> import javax.annotation.Nullable;
<ide>
<del>/**
<del> * A configured target in the context of a Skyframe graph.
<del> */
<add>/** A non-rule configured target in the context of a Skyframe graph. */
<ide> @Immutable
<ide> @ThreadSafe
<del>@AutoCodec
<add>@AutoCodec(memoization = AutoCodec.Memoization.START_MEMOIZING)
<ide> @VisibleForTesting
<del>public final class NonRuleConfiguredTargetValue
<del> extends BasicActionLookupValue implements ConfiguredTargetValue {
<add>public final class NonRuleConfiguredTargetValue extends BasicActionLookupValue
<add> implements ConfiguredTargetValue {
<ide>
<ide> // These variables are only non-final because they may be clear()ed to save memory.
<ide> // configuredTarget is null only after it is cleared. |
|
Java | bsd-3-clause | 19a969e9b688eb432b7bed335406c0a64a55f39f | 0 | aic-sri-international/aic-expresso,aic-sri-international/aic-expresso | package com.sri.ai.test.grinder.sgdpllt.theory.base;
import static com.sri.ai.expresso.helper.Expressions.parse;
import static com.sri.ai.grinder.helper.GrinderUtil.BOOLEAN_TYPE;
import static com.sri.ai.util.Util.map;
import static com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheoryTestingSupport.TESTING_CATEGORICAL_TYPE;
import static com.sri.ai.grinder.sgdpllt.theory.differencearithmetic.DifferenceArithmeticTheoryTestingSupport.TESTING_INTEGER_INTERVAL_TYPE;
import static com.sri.ai.grinder.sgdpllt.theory.linearrealarithmetic.LinearRealArithmeticTheoryTestingSupport.TESTING_REAL_INTERVAL_TYPE;
import java.util.Random;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.sri.ai.expresso.helper.Expressions;
import com.sri.ai.expresso.type.FunctionType;
import com.sri.ai.grinder.sgdpllt.api.Context;
import com.sri.ai.grinder.sgdpllt.api.StepSolver;
import com.sri.ai.grinder.sgdpllt.tester.TheoryTestingSupport;
import com.sri.ai.grinder.sgdpllt.theory.base.UnificationStepSolver;
import com.sri.ai.grinder.sgdpllt.theory.compound.CompoundTheory;
import com.sri.ai.grinder.sgdpllt.theory.differencearithmetic.DifferenceArithmeticTheory;
import com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheory;
import com.sri.ai.grinder.sgdpllt.theory.linearrealarithmetic.LinearRealArithmeticTheory;
import com.sri.ai.grinder.sgdpllt.theory.propositional.PropositionalTheory;
public class UnificationStepSolverTest {
private Random seededRandom = new Random(1);
@Test
public void propositionalTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new PropositionalTheory());
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("P", BOOLEAN_TYPE, "Q", BOOLEAN_TYPE, "R", BOOLEAN_TYPE,
"unary_prop/1", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE), "binary_prop/2", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(P)"));
StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(Q)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("P = Q"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P and not Q"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(true)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("P = unary_prop(Q)"), step.getSplitter());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P and Q and not unary_prop(Q) and unary_prop(P)"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P and Q and not unary_prop(Q) and unary_prop(P)"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
// Now test out individual branches
unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(parse("P = unary_prop(Q)"), step.getSplitter());
StepSolver<Boolean> falseItDependsSolver = step.getStepSolverForWhenSplitterIsFalse();
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).itDepends());
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).getValue());
StepSolver<Boolean> trueItDependsSolver = step.getStepSolverForWhenSplitterIsTrue();
localTestContext = rootContext.conjoin(parse("P"), rootContext);
step = trueItDependsSolver.step(localTestContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(parse("P = unary_prop(Q)"), step.getSplitter());
falseItDependsSolver = step.getStepSolverForWhenSplitterIsFalse();
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).itDepends());
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).getValue());
localTestContext = localTestContext.conjoin(parse("unary_prop(Q)"), localTestContext);
step = trueItDependsSolver.step(localTestContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(parse("unary_prop(P) = Q"), step.getSplitter());
falseItDependsSolver = step.getStepSolverForWhenSplitterIsFalse();
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).itDepends());
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).getValue());
localTestContext = localTestContext.conjoin(parse("unary_prop(P)"), localTestContext);
step = trueItDependsSolver.step(localTestContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(parse("unary_prop(P) = Q"), step.getSplitter());
falseItDependsSolver = step.getStepSolverForWhenSplitterIsFalse();
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).itDepends());
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).getValue());
localTestContext = localTestContext.conjoin(parse("Q"), localTestContext);
step = trueItDependsSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
}
@Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
@Test
public void advancedPropositionalTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new PropositionalTheory());
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("P", BOOLEAN_TYPE, "Q", BOOLEAN_TYPE, "R", BOOLEAN_TYPE,
"unary_prop/1", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE), "binary_prop/2", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P and Q and not unary_prop(true) and unary_prop(false)"), rootContext);
StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
}
@Test
public void equalityTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new EqualityTheory(true, true));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_CATEGORICAL_TYPE, "Y", TESTING_CATEGORICAL_TYPE, "Z", TESTING_CATEGORICAL_TYPE,
"unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
"binary_eq/2", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_eq(X)"), parse("unary_eq(X)"));
StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_eq(X)"), parse("unary_eq(Y)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("X = Y"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = a and Y = b"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_eq(X)"), parse("unary_eq(a)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = a"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = b"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_eq(X, unary_eq(X))"), parse("binary_eq(unary_eq(Y), Y)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("X = unary_eq(Y)"), step.getSplitter());
}
@Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
@Test
public void advancedEqualityTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new EqualityTheory(false, true));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_CATEGORICAL_TYPE, "Y", TESTING_CATEGORICAL_TYPE, "Z", TESTING_CATEGORICAL_TYPE,
"unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
"binary_eq/2", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("binary_eq(X, unary_eq(X))"), parse("binary_eq(unary_eq(Y), Y)"));
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = b and Y = a and unary_eq(Y) = b and unary_eq(X) = a"), rootContext);
StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = a and Y = a and unary_eq(Y) = b and unary_eq(X) = a"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = b and Y = a and unary_eq(a) = b and unary_eq(b) = a"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
}
@Test
public void differenceArithmeticTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new DifferenceArithmeticTheory(true, true));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("I", TESTING_INTEGER_INTERVAL_TYPE, "J", TESTING_INTEGER_INTERVAL_TYPE, "K", TESTING_INTEGER_INTERVAL_TYPE,
"unary_dar/1", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
"binary_dar/2", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(I)"));
StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(J)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("I = J"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0 and J = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(0)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_dar(I, unary_dar(I))"), parse("binary_dar(unary_dar(J), J)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("I = unary_dar(J)"), step.getSplitter());
}
@Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
@Test
public void advancedDifferenceArithmeticTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new DifferenceArithmeticTheory(true, true));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("I", TESTING_INTEGER_INTERVAL_TYPE, "J", TESTING_INTEGER_INTERVAL_TYPE, "K", TESTING_INTEGER_INTERVAL_TYPE,
"unary_dar/1", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
"binary_dar/2", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver =new UnificationStepSolver(parse("binary_dar(I, unary_dar(I))"), parse("binary_dar(unary_dar(J), J)"));
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0 and J = 1 and unary_dar(J) = 0 and unary_dar(I) = 1"), rootContext);
StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 1 and J = 1 and unary_dar(J) = 0 and unary_dar(I) = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0 and J = 1 and unary_dar(1) = 0 and unary_dar(0) = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
}
@Test
public void linearRealArithmeticTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new LinearRealArithmeticTheory(true, true));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_REAL_INTERVAL_TYPE, "Y", TESTING_REAL_INTERVAL_TYPE, "Z", TESTING_REAL_INTERVAL_TYPE,
"unary_lra/1", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE),
"binary_lra/2", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(X)"));
StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(Y)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("X = Y"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0 and Y = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(0)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_lra(X, unary_lra(X))"), parse("binary_lra(unary_lra(Y), Y)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("X = unary_lra(Y)"), step.getSplitter());
}
@Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
@Test
public void advancedLinearRealArithmeticTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new LinearRealArithmeticTheory(true, true));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_REAL_INTERVAL_TYPE, "Y", TESTING_REAL_INTERVAL_TYPE, "Z", TESTING_REAL_INTERVAL_TYPE,
"unary_lra/1", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE),
"binary_lra/2", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver =new UnificationStepSolver(parse("binary_lra(X, unary_lra(X))"), parse("binary_lra(unary_lra(Y), Y)"));
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0 and Y = 1 and unary_lra(Y) = 0 and unary_lra(X) = 1"), rootContext);
StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 1 and Y = 1 and unary_lra(Y) = 0 and unary_lra(X) = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0 and Y = 1 and unary_lra(1) = 0 and unary_lra(0) = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
}
@Test
public void compundTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true,
new CompoundTheory(
new EqualityTheory(false, true),
new DifferenceArithmeticTheory(false, true),
new LinearRealArithmeticTheory(false, true),
new PropositionalTheory()));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map(
"P", BOOLEAN_TYPE, "Q", BOOLEAN_TYPE, "R", BOOLEAN_TYPE,
"unary_prop/1", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE),
"binary_prop/2", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE),
"S", TESTING_CATEGORICAL_TYPE, "T", TESTING_CATEGORICAL_TYPE, "U", TESTING_CATEGORICAL_TYPE,
"unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
"binary_eq/2", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
"I", TESTING_INTEGER_INTERVAL_TYPE, "J", TESTING_INTEGER_INTERVAL_TYPE, "K", TESTING_INTEGER_INTERVAL_TYPE,
"unary_dar/1", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
"binary_dar/2", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
"X", TESTING_REAL_INTERVAL_TYPE, "Y", TESTING_REAL_INTERVAL_TYPE, "Z", TESTING_REAL_INTERVAL_TYPE,
"unary_lra/1", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE),
"binary_lra/2", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE)
));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(P)"));
StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(Q)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("P = Q"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P and not Q"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(true)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("P = unary_prop(Q)"), step.getSplitter());
//
//
unificationStepSolver = new UnificationStepSolver(parse("unary_eq(S)"), parse("unary_eq(S)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_eq(S)"), parse("unary_eq(T)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("S = T"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("S = a and T = b"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_eq(S)"), parse("unary_eq(a)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("S = a"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("S = b"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_eq(S, unary_eq(S))"), parse("binary_eq(unary_eq(T), T)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("S = unary_eq(T)"), step.getSplitter());
//
//
unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(I)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(J)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("I = J"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0 and J = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(0)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_dar(I, unary_dar(I))"), parse("binary_dar(unary_dar(J), J)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("I = unary_dar(J)"), step.getSplitter());
//
//
unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(X)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(Y)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("X = Y"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0 and Y = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(0)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 1"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_lra(X, unary_lra(X))"), parse("binary_lra(unary_lra(Y), Y)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("X = unary_lra(Y)"), step.getSplitter());
}
@Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
@Test
public void advancedCompositeTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true,
new CompoundTheory(
new EqualityTheory(false, true),
new DifferenceArithmeticTheory(false, true),
new LinearRealArithmeticTheory(false, true),
new PropositionalTheory()));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map(
"P", BOOLEAN_TYPE, "Q", BOOLEAN_TYPE, "R", BOOLEAN_TYPE,
"unary_prop/1", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE),
"binary_prop/2", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE),
"S", TESTING_CATEGORICAL_TYPE, "T", TESTING_CATEGORICAL_TYPE, "U", TESTING_CATEGORICAL_TYPE,
"unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
"binary_eq/2", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
"I", TESTING_INTEGER_INTERVAL_TYPE, "J", TESTING_INTEGER_INTERVAL_TYPE, "K", TESTING_INTEGER_INTERVAL_TYPE,
"unary_dar/1", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
"binary_dar/2", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
"X", TESTING_REAL_INTERVAL_TYPE, "Y", TESTING_REAL_INTERVAL_TYPE, "Z", TESTING_REAL_INTERVAL_TYPE,
"unary_lra/1", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE),
"binary_lra/2", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE)
));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P and Q and not unary_prop(Q) and unary_prop(P)"), rootContext);
StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P and Q and not unary_prop(Q) and unary_prop(P)"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
}
}
| src/test/java/com/sri/ai/test/grinder/sgdpllt/theory/base/UnificationStepSolverTest.java | package com.sri.ai.test.grinder.sgdpllt.theory.base;
import static com.sri.ai.expresso.helper.Expressions.parse;
import static com.sri.ai.grinder.helper.GrinderUtil.BOOLEAN_TYPE;
import static com.sri.ai.util.Util.map;
import static com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheoryTestingSupport.TESTING_CATEGORICAL_TYPE;
import java.util.Random;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.sri.ai.expresso.helper.Expressions;
import com.sri.ai.expresso.type.FunctionType;
import com.sri.ai.grinder.sgdpllt.api.Context;
import com.sri.ai.grinder.sgdpllt.api.StepSolver;
import com.sri.ai.grinder.sgdpllt.tester.TheoryTestingSupport;
import com.sri.ai.grinder.sgdpllt.theory.base.UnificationStepSolver;
import com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheory;
import com.sri.ai.grinder.sgdpllt.theory.propositional.PropositionalTheory;
public class UnificationStepSolverTest {
private Random seededRandom = new Random(1);
@Test
public void propositionalTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new PropositionalTheory());
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("P", BOOLEAN_TYPE, "Q", BOOLEAN_TYPE, "R", BOOLEAN_TYPE,
"unary_prop/1", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE), "binary_prop/2", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(P)"));
StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(Q)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("P = Q"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P and not Q"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(true)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("P = unary_prop(Q)"), step.getSplitter());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P and Q and not unary_prop(Q) and unary_prop(P)"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P and Q and not unary_prop(Q) and unary_prop(P)"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
// Now test out individual branches
unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(parse("P = unary_prop(Q)"), step.getSplitter());
StepSolver<Boolean> falseItDependsSolver = step.getStepSolverForWhenSplitterIsFalse();
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).itDepends());
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).getValue());
StepSolver<Boolean> trueItDependsSolver = step.getStepSolverForWhenSplitterIsTrue();
localTestContext = rootContext.conjoin(parse("P"), rootContext);
step = trueItDependsSolver.step(localTestContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(parse("P = unary_prop(Q)"), step.getSplitter());
falseItDependsSolver = step.getStepSolverForWhenSplitterIsFalse();
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).itDepends());
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).getValue());
localTestContext = localTestContext.conjoin(parse("unary_prop(Q)"), localTestContext);
step = trueItDependsSolver.step(localTestContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(parse("unary_prop(P) = Q"), step.getSplitter());
falseItDependsSolver = step.getStepSolverForWhenSplitterIsFalse();
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).itDepends());
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).getValue());
localTestContext = localTestContext.conjoin(parse("unary_prop(P)"), localTestContext);
step = trueItDependsSolver.step(localTestContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(parse("unary_prop(P) = Q"), step.getSplitter());
falseItDependsSolver = step.getStepSolverForWhenSplitterIsFalse();
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).itDepends());
Assert.assertEquals(false, falseItDependsSolver.step(rootContext).getValue());
localTestContext = localTestContext.conjoin(parse("Q"), localTestContext);
step = trueItDependsSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
}
@Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
@Test
public void advancedPropositionalTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new PropositionalTheory());
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("P", BOOLEAN_TYPE, "Q", BOOLEAN_TYPE, "R", BOOLEAN_TYPE,
"unary_prop/1", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE), "binary_prop/2", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P and Q and not unary_prop(true) and unary_prop(false)"), rootContext);
StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
}
@Test
public void equalityTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new EqualityTheory(false, true));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_CATEGORICAL_TYPE, "Y", TESTING_CATEGORICAL_TYPE, "Z", TESTING_CATEGORICAL_TYPE,
"unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
"binary_eq/2", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_eq(X)"), parse("unary_eq(X)"));
StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_eq(X)"), parse("unary_eq(Y)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("X = Y"), step.getSplitter());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = a and Y = b"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("unary_eq(X)"), parse("unary_eq(a)"));
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = a"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = b"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
unificationStepSolver = new UnificationStepSolver(parse("binary_eq(X, unary_eq(X))"), parse("binary_eq(unary_eq(Y), Y)"));
step = unificationStepSolver.step(rootContext);
Assert.assertEquals(true, step.itDepends());
Assert.assertEquals(Expressions.parse("X = unary_eq(Y)"), step.getSplitter());
}
@Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
@Test
public void advancedEqualityTest() {
TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new EqualityTheory(false, true));
// NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_CATEGORICAL_TYPE, "Y", TESTING_CATEGORICAL_TYPE, "Z", TESTING_CATEGORICAL_TYPE,
"unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
"binary_eq/2", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE)));
Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("binary_eq(X, unary_eq(X))"), parse("binary_eq(unary_eq(Y), Y)"));
Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = b and Y = a and unary_eq(Y) = b and unary_eq(X) = a"), rootContext);
StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(true, step.getValue());
localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = a and Y = a and unary_eq(Y) = b and unary_eq(X) = a"), rootContext);
step = unificationStepSolver.step(localTestContext);
Assert.assertEquals(false, step.itDepends());
Assert.assertEquals(false, step.getValue());
}
}
| Additional unification step solver tests. | src/test/java/com/sri/ai/test/grinder/sgdpllt/theory/base/UnificationStepSolverTest.java | Additional unification step solver tests. | <ide><path>rc/test/java/com/sri/ai/test/grinder/sgdpllt/theory/base/UnificationStepSolverTest.java
<ide> import static com.sri.ai.grinder.helper.GrinderUtil.BOOLEAN_TYPE;
<ide> import static com.sri.ai.util.Util.map;
<ide> import static com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheoryTestingSupport.TESTING_CATEGORICAL_TYPE;
<add>import static com.sri.ai.grinder.sgdpllt.theory.differencearithmetic.DifferenceArithmeticTheoryTestingSupport.TESTING_INTEGER_INTERVAL_TYPE;
<add>import static com.sri.ai.grinder.sgdpllt.theory.linearrealarithmetic.LinearRealArithmeticTheoryTestingSupport.TESTING_REAL_INTERVAL_TYPE;
<ide>
<ide> import java.util.Random;
<ide>
<ide> import com.sri.ai.grinder.sgdpllt.api.StepSolver;
<ide> import com.sri.ai.grinder.sgdpllt.tester.TheoryTestingSupport;
<ide> import com.sri.ai.grinder.sgdpllt.theory.base.UnificationStepSolver;
<add>import com.sri.ai.grinder.sgdpllt.theory.compound.CompoundTheory;
<add>import com.sri.ai.grinder.sgdpllt.theory.differencearithmetic.DifferenceArithmeticTheory;
<ide> import com.sri.ai.grinder.sgdpllt.theory.equality.EqualityTheory;
<add>import com.sri.ai.grinder.sgdpllt.theory.linearrealarithmetic.LinearRealArithmeticTheory;
<ide> import com.sri.ai.grinder.sgdpllt.theory.propositional.PropositionalTheory;
<ide>
<ide> public class UnificationStepSolverTest {
<ide>
<ide> @Test
<ide> public void equalityTest() {
<del> TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new EqualityTheory(false, true));
<add> TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new EqualityTheory(true, true));
<ide> // NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
<ide> theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_CATEGORICAL_TYPE, "Y", TESTING_CATEGORICAL_TYPE, "Z", TESTING_CATEGORICAL_TYPE,
<ide> "unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
<ide> step = unificationStepSolver.step(localTestContext);
<ide> Assert.assertEquals(false, step.itDepends());
<ide> Assert.assertEquals(false, step.getValue());
<add>
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = b and Y = a and unary_eq(a) = b and unary_eq(b) = a"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> }
<add>
<add> @Test
<add> public void differenceArithmeticTest() {
<add> TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new DifferenceArithmeticTheory(true, true));
<add> // NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
<add> theoryTestingSupport.setVariableNamesAndTypesForTesting(map("I", TESTING_INTEGER_INTERVAL_TYPE, "J", TESTING_INTEGER_INTERVAL_TYPE, "K", TESTING_INTEGER_INTERVAL_TYPE,
<add> "unary_dar/1", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
<add> "binary_dar/2", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE)));
<add> Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
<add>
<add> UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(I)"));
<add> StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(J)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("I = J"), step.getSplitter());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
<add> Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
<add>
<add> Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0 and J = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(0)"));
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("binary_dar(I, unary_dar(I))"), parse("binary_dar(unary_dar(J), J)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("I = unary_dar(J)"), step.getSplitter());
<add> }
<add>
<add> @Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
<add> @Test
<add> public void advancedDifferenceArithmeticTest() {
<add> TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new DifferenceArithmeticTheory(true, true));
<add> // NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
<add> theoryTestingSupport.setVariableNamesAndTypesForTesting(map("I", TESTING_INTEGER_INTERVAL_TYPE, "J", TESTING_INTEGER_INTERVAL_TYPE, "K", TESTING_INTEGER_INTERVAL_TYPE,
<add> "unary_dar/1", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
<add> "binary_dar/2", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE)));
<add> Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
<add>
<add> UnificationStepSolver unificationStepSolver =new UnificationStepSolver(parse("binary_dar(I, unary_dar(I))"), parse("binary_dar(unary_dar(J), J)"));
<add>
<add> Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0 and J = 1 and unary_dar(J) = 0 and unary_dar(I) = 1"), rootContext);
<add> StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 1 and J = 1 and unary_dar(J) = 0 and unary_dar(I) = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0 and J = 1 and unary_dar(1) = 0 and unary_dar(0) = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> }
<add>
<add> @Test
<add> public void linearRealArithmeticTest() {
<add> TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new LinearRealArithmeticTheory(true, true));
<add> // NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
<add> theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_REAL_INTERVAL_TYPE, "Y", TESTING_REAL_INTERVAL_TYPE, "Z", TESTING_REAL_INTERVAL_TYPE,
<add> "unary_lra/1", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE),
<add> "binary_lra/2", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE)));
<add> Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
<add>
<add> UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(X)"));
<add> StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(Y)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("X = Y"), step.getSplitter());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
<add> Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
<add>
<add> Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0 and Y = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(0)"));
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("binary_lra(X, unary_lra(X))"), parse("binary_lra(unary_lra(Y), Y)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("X = unary_lra(Y)"), step.getSplitter());
<add> }
<add>
<add> @Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
<add> @Test
<add> public void advancedLinearRealArithmeticTest() {
<add> TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true, new LinearRealArithmeticTheory(true, true));
<add> // NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
<add> theoryTestingSupport.setVariableNamesAndTypesForTesting(map("X", TESTING_REAL_INTERVAL_TYPE, "Y", TESTING_REAL_INTERVAL_TYPE, "Z", TESTING_REAL_INTERVAL_TYPE,
<add> "unary_lra/1", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE),
<add> "binary_lra/2", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE)));
<add> Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
<add>
<add> UnificationStepSolver unificationStepSolver =new UnificationStepSolver(parse("binary_lra(X, unary_lra(X))"), parse("binary_lra(unary_lra(Y), Y)"));
<add>
<add> Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0 and Y = 1 and unary_lra(Y) = 0 and unary_lra(X) = 1"), rootContext);
<add> StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 1 and Y = 1 and unary_lra(Y) = 0 and unary_lra(X) = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0 and Y = 1 and unary_lra(1) = 0 and unary_lra(0) = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> }
<add>
<add> @Test
<add> public void compundTest() {
<add> TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true,
<add> new CompoundTheory(
<add> new EqualityTheory(false, true),
<add> new DifferenceArithmeticTheory(false, true),
<add> new LinearRealArithmeticTheory(false, true),
<add> new PropositionalTheory()));
<add> // NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
<add> theoryTestingSupport.setVariableNamesAndTypesForTesting(map(
<add> "P", BOOLEAN_TYPE, "Q", BOOLEAN_TYPE, "R", BOOLEAN_TYPE,
<add> "unary_prop/1", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE),
<add> "binary_prop/2", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE),
<add> "S", TESTING_CATEGORICAL_TYPE, "T", TESTING_CATEGORICAL_TYPE, "U", TESTING_CATEGORICAL_TYPE,
<add> "unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
<add> "binary_eq/2", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
<add> "I", TESTING_INTEGER_INTERVAL_TYPE, "J", TESTING_INTEGER_INTERVAL_TYPE, "K", TESTING_INTEGER_INTERVAL_TYPE,
<add> "unary_dar/1", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
<add> "binary_dar/2", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
<add> "X", TESTING_REAL_INTERVAL_TYPE, "Y", TESTING_REAL_INTERVAL_TYPE, "Z", TESTING_REAL_INTERVAL_TYPE,
<add> "unary_lra/1", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE),
<add> "binary_lra/2", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE)
<add> ));
<add> Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
<add>
<add> UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(P)"));
<add> StepSolver.Step<Boolean> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(Q)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("P = Q"), step.getSplitter());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
<add> Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
<add>
<add> Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P and not Q"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_prop(P)"), parse("unary_prop(true)"));
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("P = unary_prop(Q)"), step.getSplitter());
<add>
<add> //
<add> //
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_eq(S)"), parse("unary_eq(S)"));
<add>
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_eq(S)"), parse("unary_eq(T)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("S = T"), step.getSplitter());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
<add> Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
<add>
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("S = a and T = b"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_eq(S)"), parse("unary_eq(a)"));
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("S = a"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("S = b"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("binary_eq(S, unary_eq(S))"), parse("binary_eq(unary_eq(T), T)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("S = unary_eq(T)"), step.getSplitter());
<add>
<add> //
<add> //
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(I)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(J)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("I = J"), step.getSplitter());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
<add> Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
<add>
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0 and J = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_dar(I)"), parse("unary_dar(0)"));
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 0"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("I = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("binary_dar(I, unary_dar(I))"), parse("binary_dar(unary_dar(J), J)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("I = unary_dar(J)"), step.getSplitter());
<add>
<add> //
<add> //
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(X)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(Y)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("X = Y"), step.getSplitter());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).itDepends());
<add> Assert.assertEquals(true, step.getStepSolverForWhenSplitterIsTrue().step(rootContext).getValue());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).itDepends());
<add> Assert.assertEquals(false, step.getStepSolverForWhenSplitterIsFalse().step(rootContext).getValue());
<add>
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0 and Y = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("unary_lra(X)"), parse("unary_lra(0)"));
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 0"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("X = 1"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<add>
<add> unificationStepSolver = new UnificationStepSolver(parse("binary_lra(X, unary_lra(X))"), parse("binary_lra(unary_lra(Y), Y)"));
<add> step = unificationStepSolver.step(rootContext);
<add> Assert.assertEquals(true, step.itDepends());
<add> Assert.assertEquals(Expressions.parse("X = unary_lra(Y)"), step.getSplitter());
<add> }
<add>
<add> @Ignore("TODO - context implementation currently does not support these more advanced/indirect comparisons")
<add> @Test
<add> public void advancedCompositeTest() {
<add> TheoryTestingSupport theoryTestingSupport = TheoryTestingSupport.make(seededRandom, true,
<add> new CompoundTheory(
<add> new EqualityTheory(false, true),
<add> new DifferenceArithmeticTheory(false, true),
<add> new LinearRealArithmeticTheory(false, true),
<add> new PropositionalTheory()));
<add> // NOTE: passing explicit FunctionTypes will prevent the general variables' argument types being randomly changed.
<add> theoryTestingSupport.setVariableNamesAndTypesForTesting(map(
<add> "P", BOOLEAN_TYPE, "Q", BOOLEAN_TYPE, "R", BOOLEAN_TYPE,
<add> "unary_prop/1", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE),
<add> "binary_prop/2", new FunctionType(BOOLEAN_TYPE, BOOLEAN_TYPE, BOOLEAN_TYPE),
<add> "S", TESTING_CATEGORICAL_TYPE, "T", TESTING_CATEGORICAL_TYPE, "U", TESTING_CATEGORICAL_TYPE,
<add> "unary_eq/1", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
<add> "binary_eq/2", new FunctionType(TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE, TESTING_CATEGORICAL_TYPE),
<add> "I", TESTING_INTEGER_INTERVAL_TYPE, "J", TESTING_INTEGER_INTERVAL_TYPE, "K", TESTING_INTEGER_INTERVAL_TYPE,
<add> "unary_dar/1", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
<add> "binary_dar/2", new FunctionType(TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE, TESTING_INTEGER_INTERVAL_TYPE),
<add> "X", TESTING_REAL_INTERVAL_TYPE, "Y", TESTING_REAL_INTERVAL_TYPE, "Z", TESTING_REAL_INTERVAL_TYPE,
<add> "unary_lra/1", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE),
<add> "binary_lra/2", new FunctionType(TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE, TESTING_REAL_INTERVAL_TYPE)
<add> ));
<add> Context rootContext = theoryTestingSupport.makeContextWithTestingInformation();
<add>
<add> UnificationStepSolver unificationStepSolver = new UnificationStepSolver(parse("binary_prop(P, unary_prop(P))"), parse("binary_prop(unary_prop(Q), Q)"));
<add>
<add> Context localTestContext = rootContext.conjoinWithConjunctiveClause(parse("not P and Q and not unary_prop(Q) and unary_prop(P)"), rootContext);
<add> StepSolver.Step<Boolean> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(true, step.getValue());
<add> localTestContext = rootContext.conjoinWithConjunctiveClause(parse("P and Q and not unary_prop(Q) and unary_prop(P)"), rootContext);
<add> step = unificationStepSolver.step(localTestContext);
<add> Assert.assertEquals(false, step.itDepends());
<add> Assert.assertEquals(false, step.getValue());
<ide> }
<ide> } |
|
JavaScript | mit | bd929bfa59c22a1dcb6de8cd53e7f86229815ec4 | 0 | emmettgarber/phase-0,emmettgarber/phase-0,emmettgarber/phase-0 |
var mouse = {
agility: 7,
stealth: 7,
intelligence: 7,
}
var fatty = {
agility: 2,
stealth: 14,
intelligence: 12
}
var agile = {
agility: 14,
stealth: 12,
intelligence: 2
}
var smarty = {
agility: 12,
stealth: 2,
intelligence: 14
}
function intro() {
console.log("You are Scooter the hungry mouse. Your mission, if you choose to accept it, is to get to the delicious cheese in pantry.");
console.log("Your task is no easy one however: Gilda the fat cat is in the bedroom, Tornado the fast cat is in the living,");
console.log("and Albert the cunning cat is in the kitchen. You must get by all three using either your agility, stealth or intelligence to get the cheese!");
console.log("Start your quest for delicious cheese by typing in Gilda(\"trait you want to use\") below where the Start Game line.")
console.log("")
}
function Gilda(trait) {
if (Math.ceil(mouse[trait] + Math.random(8)) >= Math.ceil(fatty[trait] + Math.random(5))) {
console.log("Scooter used his " + trait + " to get by Gilda. Now its time to get by Tornado. Enter Tornado(\"trait you want to use\") to move on!");
}
else {
console.log("Oh noooo!!! Gilda got Scooter. Gilda is like a smart, stealthy walrus try using agility to get by her next time.")
}
console.log("")
}
function Tornado(trait) {
if (Math.ceil(mouse[trait] + Math.random(8)) >= Math.ceil(agile[trait] + Math.random(5))) {
console.log("Scooter used his " + trait + " to get by Tornado. Now its time to get by Albert. Enter Albert(trait you want to use) to move on!");
}
else {
console.log("Oh noooo!!! Tornado got Scooter. Tornado is like a fast, stealthy commando try using intelligence to get by him next time.")
}
console.log("")
}
function Albert(trait) {
if (Math.ceil(mouse[trait] + Math.random(8)) >= Math.ceil(smarty[trait] + Math.random(5))) {
console.log("Scooter used his " + trait + " to get by Albert. You out-ran, out-smarted, and out-stealthed your opponents. Time to enjoy some sweet, sweet cheese!!");
}
else {
console.log("Oh noooo!!! Albert got Scooter. Albert is like a fast, smart bird of pray try using stealth to get by him next time.")
}
}
intro()
// Start Game
// Reflection
// What was the most difficult part of this challenge?
// I think just coming up with a concept of how to interact with the user
// What did you learn about creating objects and functions that interact with one another?
// There are lots of things you can do with objects, whether it is creating or calling on them. You definitely need to be careful with your flow control and how you access the values if they are being manipulated
// Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
// I learned about ceil and went back over random in this challenge.
// How can you access and manipulate properties of objects?
// You can use object. or object[] to access and manipulate properties. I used the bracket method in this challenge
| week-7/game.js |
var mouse = {
agility: 7,
stealth: 7,
intelligence: 7,
}
var fatty = {
agility: 2,
stealth: 14,
intelligence: 12
}
var agile = {
agility: 14,
stealth: 12,
intelligence: 2
}
var smarty = {
agility: 12,
stealth: 2,
intelligence: 14
}
function intro() {
console.log("You are Scooter the hungry mouse. Your mission, if you choose to accept it, is to get to the delicious cheese in pantry.");
console.log("Your task is no easy one however: Gilda the fat cat is in the bedroom, Tornado the fast cat is in the living,");
console.log("and Albert the cunning cat is in the kitchen. You must get by all three using either your agility, stealth or intelligence to get the cheese!");
console.log("Start your quest for delicious cheese by typing in Gilda(\"trait you want to use\") below where the Start Game line.")
console.log("")
}
function Gilda(trait) {
if (Math.ceil(mouse[trait] + Math.random(8)) >= Math.ceil(fatty[trait] + Math.random(5))) {
console.log("Scooter used his " + trait + " to get by Gilda. Now its time to get by Tornado. Enter Tornado(\"trait you want to use\") to move on!");
}
else {
console.log("Oh noooo!!! Gilda got Scooter. Gilda is like a smart, stealthy walrus try using agility to get by her next time.")
}
console.log("")
}
function Tornado(trait) {
if (Math.ceil(mouse[trait] + Math.random(8)) >= Math.ceil(agile[trait] + Math.random(5))) {
console.log("Scooter used his " + trait + " to get by Tornado. Now its time to get by Albert. Enter Albert(trait you want to use) to move on!");
}
else {
console.log("Oh noooo!!! Tornado got Scooter. Tornado is like a fast, stealthy commando try using intelligence to get by him next time.")
}
console.log("")
}
function Albert(trait) {
if (Math.ceil(mouse[trait] + Math.random(8)) >= Math.ceil(smarty[trait] + Math.random(5))) {
console.log("Scooter used his " + trait + " to get by Albert. You out-ran, out-smarted, and out-stealthed your opponents. Time to enjoy some sweet, sweet cheese!!");
}
else {
console.log("Oh noooo!!! Albert got Scooter. Albert is like a fast, smart bird of pray try using stealth to get by him next time.")
}
}
intro()
// Start Game
| Add reflection for game
| week-7/game.js | Add reflection for game | <ide><path>eek-7/game.js
<ide> }
<ide> intro()
<ide> // Start Game
<add>
<add>
<add>
<add>
<add>
<add>// Reflection
<add>// What was the most difficult part of this challenge?
<add>// I think just coming up with a concept of how to interact with the user
<add>// What did you learn about creating objects and functions that interact with one another?
<add>// There are lots of things you can do with objects, whether it is creating or calling on them. You definitely need to be careful with your flow control and how you access the values if they are being manipulated
<add>// Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
<add>// I learned about ceil and went back over random in this challenge.
<add>// How can you access and manipulate properties of objects?
<add>// You can use object. or object[] to access and manipulate properties. I used the bracket method in this challenge |
|
JavaScript | mit | eb74b5b6f0f83e8722389979e705e249b1f6497b | 0 | 10layer/jexpress,10layer/jexpress | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
name: String,
city: String,
address: String,
img: String,
description: String,
email: String,
sage_uid: String,
sage_product_id: String,
sage_taxtype_id: String,
sage_message: String,
datatill_group_id: Number,
bank_account: Number,
bank_code: String,
_deleted: { type: Boolean, default: false, index: true },
});
LocationSchema.set("_perms", {
admin: "crud",
user: "r",
all: "r"
});
module.exports = mongoose.model('Location', LocationSchema); | models/location_model.js | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
name: String,
city: String,
address: String,
img: String,
description: String,
email: String,
sage_uid: String,
sage_product_id: String,
sage_taxtype_id: String,
sage_message: String,
datatill_group_id: Number,
_deleted: { type: Boolean, default: false, index: true },
});
LocationSchema.set("_perms", {
admin: "crud",
user: "r",
all: "r"
});
module.exports = mongoose.model('Location', LocationSchema); | Bank account and code
| models/location_model.js | Bank account and code | <ide><path>odels/location_model.js
<ide> sage_taxtype_id: String,
<ide> sage_message: String,
<ide> datatill_group_id: Number,
<add> bank_account: Number,
<add> bank_code: String,
<ide> _deleted: { type: Boolean, default: false, index: true },
<ide> });
<ide> |
|
Java | apache-2.0 | eb59b297081e7945b116b1b1df18bbe09d26a27f | 0 | tkountis/hazelcast,emre-aydin/hazelcast,juanavelez/hazelcast,juanavelez/hazelcast,Donnerbart/hazelcast,emre-aydin/hazelcast,mdogan/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,tombujok/hazelcast,tkountis/hazelcast,tkountis/hazelcast,dbrimley/hazelcast,dsukhoroslov/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,emrahkocaman/hazelcast,lmjacksoniii/hazelcast,mesutcelik/hazelcast,tombujok/hazelcast,tufangorel/hazelcast,mdogan/hazelcast,dsukhoroslov/hazelcast,lmjacksoniii/hazelcast,Donnerbart/hazelcast,tufangorel/hazelcast,emrahkocaman/hazelcast,mdogan/hazelcast,Donnerbart/hazelcast | package com.hazelcast.instance;
import com.hazelcast.config.Config;
import com.hazelcast.internal.metrics.ProbeLevel;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link GroupProperty} and {@link GroupProperties} classes.
* <p/>
* Need to run with {@link HazelcastSerialClassRunner} due to tests with System environment variables.
*/
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class GroupPropertiesTest {
private final Config config = new Config();
private final GroupProperties defaultGroupProperties = new GroupProperties(config);
@Test
public void setProperty_ensureHighestPriorityOfConfig() {
config.setProperty(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE, "configValue");
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.setSystemProperty("systemValue");
GroupProperties groupProperties = new GroupProperties(config);
String loggingType = groupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.clearSystemProperty();
assertEquals("configValue", loggingType);
}
@Test
public void setProperty_ensureUsageOfSystemProperty() {
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.setSystemProperty("systemValue");
GroupProperties groupProperties = new GroupProperties(config);
String loggingType = groupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.clearSystemProperty();
assertEquals("systemValue", loggingType);
}
@Test
public void setProperty_ensureUsageOfSystemProperty_withNullConfig() {
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.setSystemProperty("systemValue");
GroupProperties groupProperties = new GroupProperties(null);
String loggingType = groupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.clearSystemProperty();
assertEquals("systemValue", loggingType);
}
@Test
public void setProperty_ensureUsageOfDefaultValue() {
String loggingType = defaultGroupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
assertEquals("128M", loggingType);
}
@Test
public void setProperty_ensureUsageOfDefaultValue_withNullConfig() {
GroupProperties groupProperties = new GroupProperties(null);
String loggingType = groupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
assertEquals("128M", loggingType);
}
@Test
public void setProperty_inheritDefaultValueOfParentProperty() {
String inputIOThreadCount = defaultGroupProperties.getString(GroupProperty.IO_INPUT_THREAD_COUNT);
assertEquals(GroupProperty.IO_THREAD_COUNT.getDefaultValue(), inputIOThreadCount);
}
@Test
public void setProperty_inheritActualValueOfParentProperty() {
config.setProperty(GroupProperty.IO_THREAD_COUNT, "1");
GroupProperties groupProperties = new GroupProperties(config);
String inputIOThreadCount = groupProperties.getString(GroupProperty.IO_INPUT_THREAD_COUNT);
assertEquals("1", inputIOThreadCount);
assertNotEquals(GroupProperty.IO_THREAD_COUNT.getDefaultValue(), inputIOThreadCount);
}
@Test
public void getSystemProperty() {
GroupProperty.APPLICATION_VALIDATION_TOKEN.setSystemProperty("token");
assertEquals("token", GroupProperty.APPLICATION_VALIDATION_TOKEN.getSystemProperty());
GroupProperty.APPLICATION_VALIDATION_TOKEN.clearSystemProperty();
}
@Test
public void getBoolean() {
boolean isHumanReadable = defaultGroupProperties.getBoolean(GroupProperty.PERFORMANCE_MONITOR_HUMAN_FRIENDLY_FORMAT);
assertTrue(isHumanReadable);
}
@Test
public void getInteger() {
int ioThreadCount = defaultGroupProperties.getInteger(GroupProperty.IO_THREAD_COUNT);
assertEquals(3, ioThreadCount);
}
@Test
public void getLong() {
long lockMaxLeaseTimeSeconds = defaultGroupProperties.getLong(GroupProperty.LOCK_MAX_LEASE_TIME_SECONDS);
assertEquals(Long.MAX_VALUE, lockMaxLeaseTimeSeconds);
}
@Test
public void getFloat() {
float maxFileSize = defaultGroupProperties.getFloat(GroupProperty.PERFORMANCE_MONITOR_MAX_ROLLED_FILE_SIZE_MB);
assertEquals(10, maxFileSize, 0.0001);
}
@Test
public void getTimeUnit() {
config.setProperty(GroupProperty.PARTITION_TABLE_SEND_INTERVAL, "300");
GroupProperties groupProperties = new GroupProperties(config);
assertEquals(300, groupProperties.getSeconds(GroupProperty.PARTITION_TABLE_SEND_INTERVAL));
}
@Test
public void getTimeUnit_default() {
long expectedSeconds = 15;
long intervalNanos = defaultGroupProperties.getNanos(GroupProperty.PARTITION_TABLE_SEND_INTERVAL);
long intervalMillis = defaultGroupProperties.getMillis(GroupProperty.PARTITION_TABLE_SEND_INTERVAL);
long intervalSeconds = defaultGroupProperties.getSeconds(GroupProperty.PARTITION_TABLE_SEND_INTERVAL);
assertEquals(TimeUnit.SECONDS.toNanos(expectedSeconds), intervalNanos);
assertEquals(TimeUnit.SECONDS.toMillis(expectedSeconds), intervalMillis);
assertEquals(expectedSeconds, intervalSeconds);
}
@Test(expected = IllegalArgumentException.class)
public void getTimeUnit_noTimeUnitProperty() {
defaultGroupProperties.getMillis(GroupProperty.APPLICATION_VALIDATION_TOKEN);
}
@Test
public void getEnum() {
config.setProperty(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.DEBUG.toString());
GroupProperties groupProperties = new GroupProperties(config);
ProbeLevel level = groupProperties.getEnum(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.class);
assertEquals(ProbeLevel.DEBUG, level);
}
@Test
public void getEnum_default() {
ProbeLevel level = defaultGroupProperties.getEnum(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.class);
assertEquals(ProbeLevel.MANDATORY, level);
}
@Test(expected = IllegalArgumentException.class)
public void getEnum_nonExistingEnum() {
config.setProperty(GroupProperty.PERFORMANCE_METRICS_LEVEL, "notExist");
GroupProperties groupProperties = new GroupProperties(config);
groupProperties.getEnum(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.class);
}
@Test
public void getEnum_ignoredName() {
config.setProperty(GroupProperty.PERFORMANCE_METRICS_LEVEL, "dEbUg");
GroupProperties groupProperties = new GroupProperties(config);
ProbeLevel level = groupProperties.getEnum(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.class);
assertEquals(ProbeLevel.DEBUG, level);
}
}
| hazelcast/src/test/java/com/hazelcast/instance/GroupPropertiesTest.java | package com.hazelcast.instance;
import com.hazelcast.config.Config;
import com.hazelcast.internal.metrics.ProbeLevel;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class GroupPropertiesTest {
private final Config config = new Config();
private final GroupProperties defaultGroupProperties = new GroupProperties(config);
@Test
public void setProperty_ensureHighestPriorityOfConfig() {
config.setProperty(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE, "configValue");
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.setSystemProperty("systemValue");
GroupProperties groupProperties = new GroupProperties(config);
String loggingType = groupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.clearSystemProperty();
assertEquals("configValue", loggingType);
}
@Test
public void setProperty_ensureUsageOfSystemProperty() {
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.setSystemProperty("systemValue");
GroupProperties groupProperties = new GroupProperties(config);
String loggingType = groupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.clearSystemProperty();
assertEquals("systemValue", loggingType);
}
@Test
public void setProperty_ensureUsageOfSystemProperty_withNullConfig() {
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.setSystemProperty("systemValue");
GroupProperties groupProperties = new GroupProperties(null);
String loggingType = groupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE.clearSystemProperty();
assertEquals("systemValue", loggingType);
}
@Test
public void setProperty_ensureUsageOfDefaultValue() {
String loggingType = defaultGroupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
assertEquals("128M", loggingType);
}
@Test
public void setProperty_ensureUsageOfDefaultValue_withNullConfig() {
GroupProperties groupProperties = new GroupProperties(null);
String loggingType = groupProperties.getString(GroupProperty.ELASTIC_MEMORY_TOTAL_SIZE);
assertEquals("128M", loggingType);
}
@Test
public void setProperty_inheritDefaultValueOfParentProperty() {
String inputIOThreadCount = defaultGroupProperties.getString(GroupProperty.IO_INPUT_THREAD_COUNT);
assertEquals(GroupProperty.IO_THREAD_COUNT.getDefaultValue(), inputIOThreadCount);
}
@Test
public void setProperty_inheritActualValueOfParentProperty() {
config.setProperty(GroupProperty.IO_THREAD_COUNT, "1");
GroupProperties groupProperties = new GroupProperties(config);
String inputIOThreadCount = groupProperties.getString(GroupProperty.IO_INPUT_THREAD_COUNT);
assertEquals("1", inputIOThreadCount);
assertNotEquals(GroupProperty.IO_THREAD_COUNT.getDefaultValue(), inputIOThreadCount);
}
@Test
public void getSystemProperty() {
GroupProperty.APPLICATION_VALIDATION_TOKEN.setSystemProperty("token");
assertEquals("token", GroupProperty.APPLICATION_VALIDATION_TOKEN.getSystemProperty());
GroupProperty.APPLICATION_VALIDATION_TOKEN.clearSystemProperty();
}
@Test
public void getBoolean() {
boolean isHumanReadable = defaultGroupProperties.getBoolean(GroupProperty.PERFORMANCE_MONITOR_HUMAN_FRIENDLY_FORMAT);
assertTrue(isHumanReadable);
}
@Test
public void getInteger() {
int ioThreadCount = defaultGroupProperties.getInteger(GroupProperty.IO_THREAD_COUNT);
assertEquals(3, ioThreadCount);
}
@Test
public void getLong() {
long lockMaxLeaseTimeSeconds = defaultGroupProperties.getLong(GroupProperty.LOCK_MAX_LEASE_TIME_SECONDS);
assertEquals(Long.MAX_VALUE, lockMaxLeaseTimeSeconds);
}
@Test
public void getFloat() {
float maxFileSize = defaultGroupProperties.getFloat(GroupProperty.PERFORMANCE_MONITOR_MAX_ROLLED_FILE_SIZE_MB);
assertEquals(10, maxFileSize, 0.0001);
}
@Test
public void getTimeUnit() {
config.setProperty(GroupProperty.PARTITION_TABLE_SEND_INTERVAL, "300");
GroupProperties groupProperties = new GroupProperties(config);
assertEquals(300, groupProperties.getSeconds(GroupProperty.PARTITION_TABLE_SEND_INTERVAL));
}
@Test
public void getTimeUnit_default() {
long expectedSeconds = 15;
long intervalNanos = defaultGroupProperties.getNanos(GroupProperty.PARTITION_TABLE_SEND_INTERVAL);
long intervalMillis = defaultGroupProperties.getMillis(GroupProperty.PARTITION_TABLE_SEND_INTERVAL);
long intervalSeconds = defaultGroupProperties.getSeconds(GroupProperty.PARTITION_TABLE_SEND_INTERVAL);
assertEquals(TimeUnit.SECONDS.toNanos(expectedSeconds), intervalNanos);
assertEquals(TimeUnit.SECONDS.toMillis(expectedSeconds), intervalMillis);
assertEquals(expectedSeconds, intervalSeconds);
}
@Test(expected = IllegalArgumentException.class)
public void getTimeUnit_noTimeUnitProperty() {
defaultGroupProperties.getMillis(GroupProperty.APPLICATION_VALIDATION_TOKEN);
}
@Test
public void getEnum() {
config.setProperty(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.DEBUG.toString());
GroupProperties groupProperties = new GroupProperties(config);
ProbeLevel level = groupProperties.getEnum(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.class);
assertEquals(ProbeLevel.DEBUG, level);
}
@Test
public void getEnum_default() {
ProbeLevel level = defaultGroupProperties.getEnum(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.class);
assertEquals(ProbeLevel.MANDATORY, level);
}
@Test(expected = IllegalArgumentException.class)
public void getEnum_nonExistingEnum() {
config.setProperty(GroupProperty.PERFORMANCE_METRICS_LEVEL, "notExist");
GroupProperties groupProperties = new GroupProperties(config);
groupProperties.getEnum(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.class);
}
@Test
public void getEnum_ignoredName() {
config.setProperty(GroupProperty.PERFORMANCE_METRICS_LEVEL, "dEbUg");
GroupProperties groupProperties = new GroupProperties(config);
ProbeLevel level = groupProperties.getEnum(GroupProperty.PERFORMANCE_METRICS_LEVEL, ProbeLevel.class);
assertEquals(ProbeLevel.DEBUG, level);
}
}
| Added JavaDoc to explain serial runner on GroupPropertiesTest.
| hazelcast/src/test/java/com/hazelcast/instance/GroupPropertiesTest.java | Added JavaDoc to explain serial runner on GroupPropertiesTest. | <ide><path>azelcast/src/test/java/com/hazelcast/instance/GroupPropertiesTest.java
<ide>
<ide> import com.hazelcast.config.Config;
<ide> import com.hazelcast.internal.metrics.ProbeLevel;
<del>import com.hazelcast.test.HazelcastParallelClassRunner;
<ide> import com.hazelcast.test.HazelcastSerialClassRunner;
<ide> import com.hazelcast.test.annotation.QuickTest;
<ide> import org.junit.Test;
<ide> import static org.junit.Assert.assertNotEquals;
<ide> import static org.junit.Assert.assertTrue;
<ide>
<add>/**
<add> * Tests for {@link GroupProperty} and {@link GroupProperties} classes.
<add> * <p/>
<add> * Need to run with {@link HazelcastSerialClassRunner} due to tests with System environment variables.
<add> */
<ide> @RunWith(HazelcastSerialClassRunner.class)
<ide> @Category(QuickTest.class)
<ide> public class GroupPropertiesTest { |
|
Java | mit | bef23548a5efdd3aaaba6ceeb92df93212e2c9b5 | 0 | vrk-kpa/xroad-catalog,vrk-kpa/xroad-catalog | /*
* Copyright 2014-2015 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 fi.vrk.xroad.catalog.lister;
import fi.vrk.xroad.xroad_catalog_lister.ListMembers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.ClassUtils;
import org.springframework.ws.client.core.WebServiceTemplate;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest(randomPort = true)
public class ApplicationTests {
private Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
@Value("${local.server.port}")
private int port = 0;
@Before
public void init() throws Exception {
marshaller.setPackagesToScan(ClassUtils.getPackageName(ListMembers.class));
marshaller.afterPropertiesSet();
}
@Test
public void testListServices() {
ListMembers request = new ListMembers();
assertNotNull(new WebServiceTemplate(marshaller).marshalSendAndReceive("http://localhost:"
+ port + "/ws", request));
}
}
| xroad-catalog-lister/src/test/java/fi/vrk/xroad/catalog/lister/ApplicationTests.java | /*
* Copyright 2014-2015 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 fi.vrk.xroad.catalog.lister;
import fi.vrk.xroad.xroad_catalog_lister.ListMembersRequest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.ClassUtils;
import org.springframework.ws.client.core.WebServiceTemplate;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest(randomPort = true)
public class ApplicationTests {
private Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
@Value("${local.server.port}")
private int port = 0;
@Before
public void init() throws Exception {
marshaller.setPackagesToScan(ClassUtils.getPackageName(ListMembersRequest.class));
marshaller.afterPropertiesSet();
}
@Test
public void testListServices() {
ListMembersRequest request = new ListMembersRequest();
assertNotNull(new WebServiceTemplate(marshaller).marshalSendAndReceive("http://localhost:"
+ port + "/ws", request));
}
}
| Fix for tests
| xroad-catalog-lister/src/test/java/fi/vrk/xroad/catalog/lister/ApplicationTests.java | Fix for tests | <ide><path>road-catalog-lister/src/test/java/fi/vrk/xroad/catalog/lister/ApplicationTests.java
<ide>
<ide> package fi.vrk.xroad.catalog.lister;
<ide>
<del>import fi.vrk.xroad.xroad_catalog_lister.ListMembersRequest;
<add>import fi.vrk.xroad.xroad_catalog_lister.ListMembers;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.junit.runner.RunWith;
<ide>
<ide> @Before
<ide> public void init() throws Exception {
<del> marshaller.setPackagesToScan(ClassUtils.getPackageName(ListMembersRequest.class));
<add> marshaller.setPackagesToScan(ClassUtils.getPackageName(ListMembers.class));
<ide> marshaller.afterPropertiesSet();
<ide> }
<ide>
<ide>
<ide> @Test
<ide> public void testListServices() {
<del> ListMembersRequest request = new ListMembersRequest();
<add> ListMembers request = new ListMembers();
<ide> assertNotNull(new WebServiceTemplate(marshaller).marshalSendAndReceive("http://localhost:"
<ide> + port + "/ws", request));
<ide> } |
|
JavaScript | apache-2.0 | ad1f6d39a5a5188655e2d9f15994cc64843fad7e | 0 | wayfair/tungstenjs,cgvarela/tungstenjs,wayfair/tungstenjs | /**
* Base Ampersand view for vdom- see class declaration for more information
*
* @author Matt DeGennaro <[email protected]>
*/
'use strict';
var _ = require('underscore');
var AmpersandView = require('ampersand-view');
var tungsten = require('../../src/tungsten');
var ViewWidget = require('./ampersand_view_widget');
var logger = require('../../src/utils/logger');
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
/**
* Provides generic reusable methods that child views can inherit from
*/
var BaseView = AmpersandView.extend({
tungstenView: true,
/*
* Default to an empty hash
*/
eventOptions: {},
/**
* Shared init logic
*/
initialize: function(options) {
if (!this.el) {
return false;
}
this.options = options || {};
// VTree is passable as an option if we are transitioning in from a different view
if (this.options.vtree) {
this.vtree = this.options.vtree;
}
// Template object
if (this.options.template) {
this.compiledTemplate = this.options.template;
}
// VTree is passable as an option if we are transitioning in from a different view
if (this.options.vtree) {
this.vtree = this.options.vtree;
}
// First-pass rendering context
if (this.options.context) {
this.context = this.options.context;
}
// Handle to the parent view
if (this.options.parentView) {
this.parentView = this.options.parentView;
}
/* develblock:start */
this.initDebug();
/* develblock:end */
var dataItem = this.serialize();
// Sanity check that template exists and has a toVdom method
if (this.compiledTemplate && this.compiledTemplate.toVdom) {
// Run attachView with this instance to attach childView widget points
this.compiledTemplate = this.compiledTemplate.attachView(this, ViewWidget);
if (this.options.dynamicInitialize) {
// If dynamicInitialize is set, empty this.el and replace it with the rendered template
while (this.el.firstChild) {
this.el.removeChild(this.el.firstChild);
}
var tagName = this.el.tagName;
this.vtree = tungsten.parseString('<' + tagName + '></' + tagName + '>');
this.render();
}
// If the deferRender option was set, it means a layout manager / a module will control when this view is rendered
if (!this.options.deferRender) {
var self = this;
self.vtree = self.vtree || self.compiledTemplate.toVdom(dataItem);
self.initializeRenderListener(dataItem);
if (this.options.dynamicInitialize) {
// If dynamicInitialize was set, render was already invoked, so childViews are attached
self.postInitialize();
} else {
setTimeout(function() {
self.attachChildViews();
self.postInitialize();
}, 1);
}
} else {
this.postInitialize();
}
} else {
this.initializeRenderListener(dataItem);
this.postInitialize();
}
},
debouncer: null,
initializeRenderListener: function(dataItem) {
// If this has a model and is the top level view, set up the listener for rendering
if (dataItem && (dataItem.tungstenModel || dataItem.tungstenCollection)) {
var runOnChange;
var self = this;
if (!this.parentView) {
runOnChange = _.bind(this.render, this);
} else if (!dataItem.parentProp && this.parentView.model !== dataItem) {
// If this model was not set up via relation, manually trigger an event on the parent's model to kick one off
runOnChange = function() {
// trigger event on parent to start a render
self.parentView.model.trigger('render');
};
}
if (runOnChange) {
this.listenTo(dataItem, 'all', function() {
// Since we're attaching a very naive listener, we may get many events in sequence, so we set a small debounce
clearTimeout(self.debouncer);
self.debouncer = setTimeout(runOnChange, 1);
});
}
}
},
/**
* This function is run once we are done initializing the view.
* Currently unimplemented. Child views should override this if they would like to use it.
*/
postInitialize: function() {},
/* develblock:start */
/**
* Bootstraps all debug functionality
*/
initDebug: function() {
var dataset = require('data-set');
var data = dataset(this.el);
data.view = this;
tungsten.debug.registry.register(this);
// Rebind events so that they can be tracked
this.delegateEvents();
// These methods are often invoked oddly, so ensure their context
_.bindAll(this, 'getEvents', 'getDebugName', 'getChildViews');
},
/**
* Get a list of all trackable functions for this view instance
* Ignores certain base and debugging functions
*
* @param {Object} trackedFunctions Object to track state
* @param {Function} getTrackableFunction Callback to get wrapper function
*
* @return {Array<Object>} List of trackable functions
*/
getFunctions: function(trackedFunctions, getTrackableFunction) {
// Debug functions shouldn't be debuggable
var blacklist = {
constructor: true,
initialize: true,
postInitialize: true,
compiledTemplate: true,
initDebug: true,
getFunctions: true,
getEvents: true,
getElTemplate: true,
getVdomTemplate: true,
getChildren: true,
getDebugName: true
};
var getFunctions = require('../shared/get_functions');
return getFunctions(trackedFunctions, getTrackableFunction, this, BaseView.prototype, blacklist);
},
/**
* Gets a JSON format version of the current state
*
* @return {Object|Array} Data of bound model or collection
*/
getState: function() {
var data = this.serialize();
if (data && typeof data.toJSON === 'function') {
data = data.toJSON();
}
return data;
},
/**
* Sets the state to the given data
* @param {Object|Array} data Object to set state to
*/
setState: function(data) {
var dataObj = this.serialize();
if (typeof dataObj.reset === 'function') {
dataObj.reset(data);
} else if (typeof dataObj.set === 'function') {
dataObj.set(data, {reset: true});
}
return data;
},
/**
* Return a list of DOM events
*
* @return {Array<Object>} List of bound DOM events
*/
getEvents: function() {
var events = _.result(this, 'events');
var eventKeys = _.keys(events);
var result = new Array(eventKeys.length);
for (var i = 0; i < eventKeys.length; i++) {
result[i] = {
selector: eventKeys[i],
name: events[eventKeys[i]],
fn: this[events[eventKeys[i]]]
};
}
return result;
},
/**
* Converts the current vtree to an HTML structure
*
* @return {string} HTML representation of VTree
*/
getVdomTemplate: function() {
var vtreeToRender = this.vtree;
if (!this.parentView) {
vtreeToRender = vtreeToRender.children;
}
return tungsten.debug.vtreeToString(vtreeToRender, true);
},
/**
* Compares the current VTree and DOM structure and returns a diff
*
* @return {string} Diff of VTree vs DOM
*/
getTemplateDiff: function() {
if (!this.parentView) {
var numChildren = Math.max(this.vtree.children.length, this.el.childNodes.length);
var output = '';
for (var i = 0; i < numChildren; i++) {
output += tungsten.debug.diffVtreeAndElem(this.vtree.children[i], this.el.childNodes[i]);
}
return output;
} else {
return tungsten.debug.diffVtreeAndElem(this.vtree, this.el);
}
},
/**
* Gets children of this object
*
* @return {Array} Whether this object has children
*/
getChildren: function() {
if (this.getChildViews.original) {
return this.getChildViews.original.call(this);
} else {
return this.getChildViews();
}
},
/**
* Debug name of this object, using declared debugName, falling back to cid
*
* @return {string} Debug name
*/
getDebugName: function() {
return this.debugName ? this.debugName + this.cid.replace('view', '') : this.cid;
},
/* develblock:end */
/**
* Lets the child view dictate what to pass into the template as context. If not overriden, then it will simply use the default
* model.attributes or collection.toJSON
*
* @return {Object} model.attributes or collection.toJSON()
*/
serialize: function() {
return this.model || this.collection || {};
},
/**
* Override of the base Backbone function
* @param {Object?} events Event object o bind to. Falls back to this.events
*/
delegateEvents: function(events) {
if (!this.el) {
return;
}
if (!(events || (events = _.result(this, 'events')))) {
return this;
}
// Unbind any current events
this.undelegateEvents();
// Get any options that may have been set
var eventOptions = _.result(this, 'eventOptions');
// Event / selector strings
var keys = _.keys(events);
var key;
// Create an array to hold the information to detach events
this.eventsToRemove = new Array(keys.length);
for (var i = keys.length; i--;) {
key = keys[i];
// Sanity check that value maps to a function
var method = events[key];
if (typeof method !== 'function') {
method = this[events[key]];
}
if (!method) {
throw new Error('Method "' + events[key] + '" does not exist');
}
var match = key.match(delegateEventSplitter);
var eventName = match[1],
selector = match[2];
method = _.bind(method, this);
// throws an error if invalid
this.eventsToRemove[i] = tungsten.bindEvent(this.el, eventName, selector, method, eventOptions[key]);
}
},
/**
* Override of the base Backbone function
*/
undelegateEvents: function() {
if (!this.el) {
return;
}
// Uses array created in delegateEvents to unbind events
if (this.eventsToRemove) {
for (var i = 0; i < this.eventsToRemove.length; i++) {
tungsten.unbindEvent(this.eventsToRemove[i]);
}
this.eventsToRemove = null;
}
},
/**
* Generic view rendering function that renders the view's compiled template using its model
* @return {Object} the view itself for chainability
*/
render: function() {
if (!this.compiledTemplate) {
return;
}
// let the view have a say in what context to pass to the template
// defaults to an empty object for context so that our view render won't fail
var serializedModel = this.context || this.serialize();
var initialTree = this.vtree || this.compiledTemplate.toVdom(this.serialize(), true);
this.vtree = tungsten.updateTree(this.el, initialTree, this.compiledTemplate.toVdom(serializedModel));
// Clear any passed context
this.context = null;
// good to know when the view is rendered
this.trigger('rendered');
this.postRender();
return this;
},
/**
* This function is run once we are done rendering the view.
* Currently unimplemented. Child views should override this if they would like to use it.
*/
postRender: function() {},
/**
* Updates the function with a new model and template
* @param {Object} newModel Model to update to
*/
update: function(newModel) {
// Track if anything has changed in order to trigger a render
if (newModel !== this.model) {
// If the model has changed, change listener to new model
this.stopListening(this.model);
this.model = newModel;
this.initializeRenderListener(newModel);
}
this.render();
},
/**
* Parse this.vtree for childViews
* This ensures DOM order and only gets the list on demand rather than each render cycle
* @return {Array<Object>} DOM order array of child views
*/
getChildViews: function() {
var childInstances = [];
var recurse = function(vnode) {
var child;
for (var i = 0; i < vnode.children.length; i++) {
child = vnode.children[i];
if (child.type === 'VirtualNode' && child.hasWidgets) {
recurse(child);
} else if (child.type === 'Widget' && child.view) {
childInstances.push(child.view);
}
}
};
recurse(this.vtree);
return childInstances;
},
/**
* Parse this.vtree for childViews and attach them to the DOM node
* Used during initialization where a render is unnecessary
*/
attachChildViews: function() {
var recurse = function(vnode, elem) {
if (!elem) {
return;
}
var child;
for (var i = 0; i < vnode.children.length; i++) {
child = vnode.children[i];
if (child.type === 'VirtualNode' && child.hasWidgets) {
recurse(child, elem.childNodes[i]);
} else if (child.type === 'Widget' && !child.view && typeof child.attach === 'function') {
child.attach(elem.childNodes[i]);
}
}
};
recurse(this.vtree, this.el);
},
/**
* Removes model listeners and DOM events from this and all child views
*/
destroy: function() {
clearTimeout(this.debouncer);
this.stopListening();
this.undelegateEvents();
var childInstances = this.getChildViews();
for (var i = 0; i < childInstances.length; i++) {
childInstances[i].destroy();
}
}
});
BaseView.extend = function(protoProps) {
/* develblock:start */
// Certain methods of BaseView should be unable to be overridden
var methods = ['initialize', 'render', 'delegateEvents', 'undelegateEvents'];
function wrapOverride(first, second) {
return function() {
first.apply(this, arguments);
second.apply(this, arguments);
};
}
for (var i = 0; i < methods.length; i++) {
if (protoProps[methods[i]]) {
var msg = 'Model.' + methods[i] + ' may not be overridden';
if (protoProps && protoProps.debugName) {
msg += ' for model "' + protoProps.debugName + '"';
}
logger.warn(msg);
// Replace attempted override with base version
protoProps[methods[i]] = wrapOverride(BaseView.prototype[methods[i]], protoProps[methods[i]]);
}
}
/* develblock:end */
return AmpersandView.extend.call(this, protoProps);
};
BaseView.tungstenView = true;
module.exports = BaseView;
| adaptors/ampersand/base_view.js | /**
* Base Ampersand view for vdom- see class declaration for more information
*
* @author Matt DeGennaro <[email protected]>
*/
'use strict';
var _ = require('underscore');
var AmpersandView = require('ampersand-view');
var tungsten = require('../../src/tungsten');
var ViewWidget = require('./ampersand_view_widget');
var logger = require('../../src/utils/logger');
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
/**
* Provides generic reusable methods that child views can inherit from
*/
var BaseView = AmpersandView.extend({
tungstenView: true,
/*
* Default to an empty hash
*/
eventOptions: {},
/**
* Shared init logic
*/
initialize: function(options) {
if (!this.el) {
return false;
}
this.options = options || {};
// VTree is passable as an option if we are transitioning in from a different view
if (this.options.vtree) {
this.vtree = this.options.vtree;
}
// Template object
if (this.options.template) {
this.compiledTemplate = this.options.template;
}
// VTree is passable as an option if we are transitioning in from a different view
if (this.options.vtree) {
this.vtree = this.options.vtree;
}
// First-pass rendering context
if (this.options.context) {
this.context = this.options.context;
}
// Handle to the parent view
if (this.options.parentView) {
this.parentView = this.options.parentView;
}
/* develblock:start */
this.initDebug();
/* develblock:end */
var dataItem = this.serialize();
// Sanity check that template exists and has a toVdom method
if (this.compiledTemplate && this.compiledTemplate.toVdom) {
// Run attachView with this instance to attach childView widget points
this.compiledTemplate = this.compiledTemplate.attachView(this, ViewWidget);
if (this.options.dynamicInitialize) {
// If dynamicInitialize is set, empty this.el and replace it with the rendered template
while (this.el.firstChild) {
this.el.removeChild(this.el.firstChild);
}
var tagName = this.el.tagName;
this.vtree = tungsten.parseString('<' + tagName + '></' + tagName + '>');
this.render();
}
// If the deferRender option was set, it means a layout manager / a module will control when this view is rendered
if (!this.options.deferRender) {
var self = this;
self.vtree = self.vtree || self.compiledTemplate.toVdom(dataItem);
self.initializeRenderListener(dataItem);
if (this.options.dynamicInitialize) {
// If dynamicInitialize was set, render was already invoked, so childViews are attached
self.postInitialize();
} else {
setTimeout(function() {
self.attachChildViews();
self.postInitialize();
}, 1);
}
} else {
this.postInitialize();
}
} else {
this.initializeRenderListener(dataItem);
this.postInitialize();
}
},
debouncer: null,
initializeRenderListener: function(dataItem) {
// If this has a model and is the top level view, set up the listener for rendering
if (dataItem && (dataItem.tungstenModel || dataItem.tungstenCollection)) {
var runOnChange;
var self = this;
if (!this.parentView) {
runOnChange = _.bind(this.render, this);
} else if (!dataItem.parentProp && this.parentView.model !== dataItem) {
// If this model was not set up via relation, manually trigger an event on the parent's model to kick one off
runOnChange = function() {
// trigger event on parent to start a render
self.parentView.model.trigger('render');
};
}
if (runOnChange) {
this.listenTo(dataItem, 'all', function() {
// Since we're attaching a very naive listener, we may get many events in sequence, so we set a small debounce
clearTimeout(self.debouncer);
self.debouncer = setTimeout(runOnChange, 1);
});
}
}
},
/**
* This function is run once we are done initializing the view.
* Currently unimplemented. Child views should override this if they would like to use it.
*/
postInitialize: function() {},
/* develblock:start */
/**
* Bootstraps all debug functionality
*/
initDebug: function() {
var dataset = require('data-set');
var data = dataset(this.el);
data.view = this;
tungsten.debug.registry.register(this);
// These methods are often invoked oddly, so ensure their context
_.bindAll(this, 'getEvents', 'getDebugName', 'getChildViews');
},
/**
* Get a list of all trackable functions for this view instance
* Ignores certain base and debugging functions
*
* @param {Object} trackedFunctions Object to track state
* @param {Function} getTrackableFunction Callback to get wrapper function
*
* @return {Array<Object>} List of trackable functions
*/
getFunctions: function(trackedFunctions, getTrackableFunction) {
// Debug functions shouldn't be debuggable
var blacklist = {
constructor: true,
initialize: true,
postInitialize: true,
compiledTemplate: true,
initDebug: true,
getFunctions: true,
getEvents: true,
getElTemplate: true,
getVdomTemplate: true,
getChildren: true,
getDebugName: true
};
var getFunctions = require('../shared/get_functions');
return getFunctions(trackedFunctions, getTrackableFunction, this, BaseView.prototype, blacklist);
},
/**
* Gets a JSON format version of the current state
*
* @return {Object|Array} Data of bound model or collection
*/
getState: function() {
var data = this.serialize();
if (data && typeof data.toJSON === 'function') {
data = data.toJSON();
}
return data;
},
/**
* Sets the state to the given data
* @param {Object|Array} data Object to set state to
*/
setState: function(data) {
var dataObj = this.serialize();
if (typeof dataObj.reset === 'function') {
dataObj.reset(data);
} else if (typeof dataObj.set === 'function') {
dataObj.set(data, {reset: true});
}
return data;
},
/**
* Return a list of DOM events
*
* @return {Array<Object>} List of bound DOM events
*/
getEvents: function() {
var events = _.result(this, 'events');
var eventKeys = _.keys(events);
var result = new Array(eventKeys.length);
for (var i = 0; i < eventKeys.length; i++) {
result[i] = {
selector: eventKeys[i],
name: events[eventKeys[i]],
fn: this[events[eventKeys[i]]]
};
}
return result;
},
/**
* Converts the current vtree to an HTML structure
*
* @return {string} HTML representation of VTree
*/
getVdomTemplate: function() {
var vtreeToRender = this.vtree;
if (!this.parentView) {
vtreeToRender = vtreeToRender.children;
}
return tungsten.debug.vtreeToString(vtreeToRender, true);
},
/**
* Compares the current VTree and DOM structure and returns a diff
*
* @return {string} Diff of VTree vs DOM
*/
getTemplateDiff: function() {
if (!this.parentView) {
var numChildren = Math.max(this.vtree.children.length, this.el.childNodes.length);
var output = '';
for (var i = 0; i < numChildren; i++) {
output += tungsten.debug.diffVtreeAndElem(this.vtree.children[i], this.el.childNodes[i]);
}
return output;
} else {
return tungsten.debug.diffVtreeAndElem(this.vtree, this.el);
}
},
/**
* Gets children of this object
*
* @return {Array} Whether this object has children
*/
getChildren: function() {
if (this.getChildViews.original) {
return this.getChildViews.original.call(this);
} else {
return this.getChildViews();
}
},
/**
* Debug name of this object, using declared debugName, falling back to cid
*
* @return {string} Debug name
*/
getDebugName: function() {
return this.debugName ? this.debugName + this.cid.replace('view', '') : this.cid;
},
/* develblock:end */
/**
* Lets the child view dictate what to pass into the template as context. If not overriden, then it will simply use the default
* model.attributes or collection.toJSON
*
* @return {Object} model.attributes or collection.toJSON()
*/
serialize: function() {
return this.model || this.collection || {};
},
/**
* Override of the base Backbone function
* @param {Object?} events Event object o bind to. Falls back to this.events
*/
delegateEvents: function(events) {
if (!this.el) {
return;
}
if (!(events || (events = _.result(this, 'events')))) {
return this;
}
// Unbind any current events
this.undelegateEvents();
// Get any options that may have been set
var eventOptions = _.result(this, 'eventOptions');
// Event / selector strings
var keys = _.keys(events);
var key;
// Create an array to hold the information to detach events
this.eventsToRemove = new Array(keys.length);
for (var i = keys.length; i--;) {
key = keys[i];
// Sanity check that value maps to a function
var method = events[key];
if (typeof method !== 'function') {
method = this[events[key]];
}
if (!method) {
throw new Error('Method "' + events[key] + '" does not exist');
}
var match = key.match(delegateEventSplitter);
var eventName = match[1],
selector = match[2];
method = _.bind(method, this);
// throws an error if invalid
this.eventsToRemove[i] = tungsten.bindEvent(this.el, eventName, selector, method, eventOptions[key]);
}
},
/**
* Override of the base Backbone function
*/
undelegateEvents: function() {
if (!this.el) {
return;
}
// Uses array created in delegateEvents to unbind events
if (this.eventsToRemove) {
for (var i = 0; i < this.eventsToRemove.length; i++) {
tungsten.unbindEvent(this.eventsToRemove[i]);
}
this.eventsToRemove = null;
}
},
/**
* Generic view rendering function that renders the view's compiled template using its model
* @return {Object} the view itself for chainability
*/
render: function() {
if (!this.compiledTemplate) {
return;
}
// let the view have a say in what context to pass to the template
// defaults to an empty object for context so that our view render won't fail
var serializedModel = this.context || this.serialize();
var initialTree = this.vtree || this.compiledTemplate.toVdom(this.serialize(), true);
this.vtree = tungsten.updateTree(this.el, initialTree, this.compiledTemplate.toVdom(serializedModel));
// Clear any passed context
this.context = null;
// good to know when the view is rendered
this.trigger('rendered');
this.postRender();
return this;
},
/**
* This function is run once we are done rendering the view.
* Currently unimplemented. Child views should override this if they would like to use it.
*/
postRender: function() {},
/**
* Updates the function with a new model and template
* @param {Object} newModel Model to update to
*/
update: function(newModel) {
// Track if anything has changed in order to trigger a render
if (newModel !== this.model) {
// If the model has changed, change listener to new model
this.stopListening(this.model);
this.model = newModel;
this.initializeRenderListener(newModel);
}
this.render();
},
/**
* Parse this.vtree for childViews
* This ensures DOM order and only gets the list on demand rather than each render cycle
* @return {Array<Object>} DOM order array of child views
*/
getChildViews: function() {
var childInstances = [];
var recurse = function(vnode) {
var child;
for (var i = 0; i < vnode.children.length; i++) {
child = vnode.children[i];
if (child.type === 'VirtualNode' && child.hasWidgets) {
recurse(child);
} else if (child.type === 'Widget' && child.view) {
childInstances.push(child.view);
}
}
};
recurse(this.vtree);
return childInstances;
},
/**
* Parse this.vtree for childViews and attach them to the DOM node
* Used during initialization where a render is unnecessary
*/
attachChildViews: function() {
var recurse = function(vnode, elem) {
if (!elem) {
return;
}
var child;
for (var i = 0; i < vnode.children.length; i++) {
child = vnode.children[i];
if (child.type === 'VirtualNode' && child.hasWidgets) {
recurse(child, elem.childNodes[i]);
} else if (child.type === 'Widget' && !child.view && typeof child.attach === 'function') {
child.attach(elem.childNodes[i]);
}
}
};
recurse(this.vtree, this.el);
},
/**
* Removes model listeners and DOM events from this and all child views
*/
destroy: function() {
clearTimeout(this.debouncer);
this.stopListening();
this.undelegateEvents();
var childInstances = this.getChildViews();
for (var i = 0; i < childInstances.length; i++) {
childInstances[i].destroy();
}
}
});
BaseView.extend = function(protoProps) {
/* develblock:start */
// Certain methods of BaseView should be unable to be overridden
var methods = ['initialize', 'render', 'delegateEvents', 'undelegateEvents'];
function wrapOverride(first, second) {
return function() {
first.apply(this, arguments);
second.apply(this, arguments);
};
}
for (var i = 0; i < methods.length; i++) {
if (protoProps[methods[i]]) {
var msg = 'Model.' + methods[i] + ' may not be overridden';
if (protoProps && protoProps.debugName) {
msg += ' for model "' + protoProps.debugName + '"';
}
logger.warn(msg);
// Replace attempted override with base version
protoProps[methods[i]] = wrapOverride(BaseView.prototype[methods[i]], protoProps[methods[i]]);
}
}
/* develblock:end */
return AmpersandView.extend.call(this, protoProps);
};
BaseView.tungstenView = true;
module.exports = BaseView;
| Fix for Ampersand view method tracking
| adaptors/ampersand/base_view.js | Fix for Ampersand view method tracking | <ide><path>daptors/ampersand/base_view.js
<ide> var data = dataset(this.el);
<ide> data.view = this;
<ide> tungsten.debug.registry.register(this);
<add> // Rebind events so that they can be tracked
<add> this.delegateEvents();
<ide> // These methods are often invoked oddly, so ensure their context
<ide> _.bindAll(this, 'getEvents', 'getDebugName', 'getChildViews');
<ide> }, |
|
Java | mit | 4ede0fe53dd1b6b1c12d746b706e56aaad2de0c0 | 0 | bcgit/bc-java,bcgit/bc-java,bcgit/bc-java | package org.bouncycastle.asn1.eac;
import java.math.BigInteger;
import java.util.Enumeration;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.util.Arrays;
/**
* an Iso7816ECDSAPublicKeyStructure structure.
* <pre>
* Certificate Holder Authorization ::= SEQUENCE {
* ASN1TaggedObject primeModulusP; // OPTIONAL
* ASN1TaggedObject firstCoefA; // OPTIONAL
* ASN1TaggedObject secondCoefB; // OPTIONAL
* ASN1TaggedObject basePointG; // OPTIONAL
* ASN1TaggedObject orderOfBasePointR; // OPTIONAL
* ASN1TaggedObject publicPointY; //REQUIRED
* ASN1TaggedObject cofactorF; // OPTIONAL
* }
* </pre>
*/
public class ECDSAPublicKey
extends PublicKeyDataObject
{
private ASN1ObjectIdentifier usage;
private BigInteger primeModulusP; // OPTIONAL
private BigInteger firstCoefA; // OPTIONAL
private BigInteger secondCoefB; // OPTIONAL
private byte[] basePointG; // OPTIONAL
private BigInteger orderOfBasePointR; // OPTIONAL
private byte[] publicPointY; //REQUIRED
private BigInteger cofactorF; // OPTIONAL
private int options;
private static final int P = 0x01;
private static final int A = 0x02;
private static final int B = 0x04;
private static final int G = 0x08;
private static final int R = 0x10;
private static final int Y = 0x20;
private static final int F = 0x40;
ECDSAPublicKey(ASN1Sequence seq)
throws IllegalArgumentException
{
Enumeration en = seq.getObjects();
this.usage = ASN1ObjectIdentifier.getInstance(en.nextElement());
options = 0;
while (en.hasMoreElements())
{
Object obj = en.nextElement();
if (obj instanceof ASN1TaggedObject)
{
ASN1TaggedObject to = (ASN1TaggedObject)obj;
switch (to.getTagNo())
{
case 0x1:
setPrimeModulusP(UnsignedInteger.getInstance(to).getValue());
break;
case 0x2:
setFirstCoefA(UnsignedInteger.getInstance(to).getValue());
break;
case 0x3:
setSecondCoefB(UnsignedInteger.getInstance(to).getValue());
break;
case 0x4:
setBasePointG(ASN1OctetString.getInstance(to, false));
break;
case 0x5:
setOrderOfBasePointR(UnsignedInteger.getInstance(to).getValue());
break;
case 0x6:
setPublicPointY(ASN1OctetString.getInstance(to, false));
break;
case 0x7:
setCofactorF(UnsignedInteger.getInstance(to).getValue());
break;
default:
options = 0;
throw new IllegalArgumentException("Unknown Object Identifier!");
}
}
else
{
throw new IllegalArgumentException("Unknown Object Identifier!");
}
}
if (options != 0x20 && options != 0x7F)
{
throw new IllegalArgumentException("All options must be either present or absent!");
}
}
public ECDSAPublicKey(ASN1ObjectIdentifier usage, byte[] ppY)
throws IllegalArgumentException
{
this.usage = usage;
setPublicPointY(new DEROctetString(ppY));
}
public ECDSAPublicKey(ASN1ObjectIdentifier usage, BigInteger p, BigInteger a, BigInteger b, byte[] basePoint, BigInteger order, byte[] publicPoint, int cofactor)
{
this.usage = usage;
setPrimeModulusP(p);
setFirstCoefA(a);
setSecondCoefB(b);
setBasePointG(new DEROctetString(basePoint));
setOrderOfBasePointR(order);
setPublicPointY(new DEROctetString(publicPoint));
setCofactorF(BigInteger.valueOf(cofactor));
}
public ASN1ObjectIdentifier getUsage()
{
return usage;
}
public byte[] getBasePointG()
{
if ((options & G) != 0)
{
return Arrays.clone(basePointG);
}
else
{
return null;
}
}
private void setBasePointG(ASN1OctetString basePointG)
throws IllegalArgumentException
{
if ((options & G) == 0)
{
options |= G;
this.basePointG = basePointG.getOctets();
}
else
{
throw new IllegalArgumentException("Base Point G already set");
}
}
public BigInteger getCofactorF()
{
if ((options & F) != 0)
{
return cofactorF;
}
else
{
return null;
}
}
private void setCofactorF(BigInteger cofactorF)
throws IllegalArgumentException
{
if ((options & F) == 0)
{
options |= F;
this.cofactorF = cofactorF;
}
else
{
throw new IllegalArgumentException("Cofactor F already set");
}
}
public BigInteger getFirstCoefA()
{
if ((options & A) != 0)
{
return firstCoefA;
}
else
{
return null;
}
}
private void setFirstCoefA(BigInteger firstCoefA)
throws IllegalArgumentException
{
if ((options & A) == 0)
{
options |= A;
this.firstCoefA = firstCoefA;
}
else
{
throw new IllegalArgumentException("First Coef A already set");
}
}
public BigInteger getOrderOfBasePointR()
{
if ((options & R) != 0)
{
return orderOfBasePointR;
}
else
{
return null;
}
}
private void setOrderOfBasePointR(BigInteger orderOfBasePointR)
throws IllegalArgumentException
{
if ((options & R) == 0)
{
options |= R;
this.orderOfBasePointR = orderOfBasePointR;
}
else
{
throw new IllegalArgumentException("Order of base point R already set");
}
}
public BigInteger getPrimeModulusP()
{
if ((options & P) != 0)
{
return primeModulusP;
}
else
{
return null;
}
}
private void setPrimeModulusP(BigInteger primeModulusP)
{
if ((options & P) == 0)
{
options |= P;
this.primeModulusP = primeModulusP;
}
else
{
throw new IllegalArgumentException("Prime Modulus P already set");
}
}
public byte[] getPublicPointY()
{
if ((options & Y) != 0)
{
return Arrays.clone(publicPointY);
}
else
{
return null;
}
}
private void setPublicPointY(ASN1OctetString publicPointY)
throws IllegalArgumentException
{
if ((options & Y) == 0)
{
options |= Y;
this.publicPointY = publicPointY.getOctets();
}
else
{
throw new IllegalArgumentException("Public Point Y already set");
}
}
public BigInteger getSecondCoefB()
{
if ((options & B) != 0)
{
return secondCoefB;
}
else
{
return null;
}
}
private void setSecondCoefB(BigInteger secondCoefB)
throws IllegalArgumentException
{
if ((options & B) == 0)
{
options |= B;
this.secondCoefB = secondCoefB;
}
else
{
throw new IllegalArgumentException("Second Coef B already set");
}
}
public boolean hasParameters()
{
return primeModulusP != null;
}
public ASN1EncodableVector getASN1EncodableVector(ASN1ObjectIdentifier oid, boolean publicPointOnly)
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(oid);
if (!publicPointOnly)
{
v.add(new UnsignedInteger(0x01, getPrimeModulusP()));
v.add(new UnsignedInteger(0x02, getFirstCoefA()));
v.add(new UnsignedInteger(0x03, getSecondCoefB()));
v.add(new DERTaggedObject(false, 0x04, new DEROctetString(getBasePointG())));
v.add(new UnsignedInteger(0x05, getOrderOfBasePointR()));
}
v.add(new DERTaggedObject(false, 0x06, new DEROctetString(getPublicPointY())));
if (!publicPointOnly)
{
v.add(new UnsignedInteger(0x07, getCofactorF()));
}
return v;
}
public ASN1Primitive toASN1Primitive()
{
return new DERSequence(getASN1EncodableVector(usage, !hasParameters()));
}
}
| core/src/main/java/org/bouncycastle/asn1/eac/ECDSAPublicKey.java | package org.bouncycastle.asn1.eac;
import java.math.BigInteger;
import java.util.Enumeration;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.util.Arrays;
/**
* an Iso7816ECDSAPublicKeyStructure structure.
* <pre>
* Certificate Holder Authorization ::= SEQUENCE {
* ASN1TaggedObject primeModulusP; // OPTIONAL
* ASN1TaggedObject firstCoefA; // OPTIONAL
* ASN1TaggedObject secondCoefB; // OPTIONAL
* ASN1TaggedObject basePointG; // OPTIONAL
* ASN1TaggedObject orderOfBasePointR; // OPTIONAL
* ASN1TaggedObject publicPointY; //REQUIRED
* ASN1TaggedObject cofactorF; // OPTIONAL
* }
* </pre>
*/
public class ECDSAPublicKey
extends PublicKeyDataObject
{
private ASN1ObjectIdentifier usage;
private BigInteger primeModulusP; // OPTIONAL
private BigInteger firstCoefA; // OPTIONAL
private BigInteger secondCoefB; // OPTIONAL
private byte[] basePointG; // OPTIONAL
private BigInteger orderOfBasePointR; // OPTIONAL
private byte[] publicPointY; //REQUIRED
private BigInteger cofactorF; // OPTIONAL
private int options;
private static final int P = 0x01;
private static final int A = 0x02;
private static final int B = 0x04;
private static final int G = 0x08;
private static final int R = 0x10;
private static final int Y = 0x20;
private static final int F = 0x40;
ECDSAPublicKey(ASN1Sequence seq)
throws IllegalArgumentException
{
Enumeration en = seq.getObjects();
this.usage = ASN1ObjectIdentifier.getInstance(en.nextElement());
options = 0;
while (en.hasMoreElements())
{
Object obj = en.nextElement();
if (obj instanceof ASN1TaggedObject)
{
ASN1TaggedObject to = (ASN1TaggedObject)obj;
switch (to.getTagNo())
{
case 0x1:
setPrimeModulusP(UnsignedInteger.getInstance(to).getValue());
break;
case 0x2:
setFirstCoefA(UnsignedInteger.getInstance(to).getValue());
break;
case 0x3:
setSecondCoefB(UnsignedInteger.getInstance(to).getValue());
break;
case 0x4:
setBasePointG(ASN1OctetString.getInstance(to, false));
break;
case 0x5:
setOrderOfBasePointR(UnsignedInteger.getInstance(to).getValue());
break;
case 0x6:
setPublicPointY(ASN1OctetString.getInstance(to, false));
break;
case 0x7:
setCofactorF(UnsignedInteger.getInstance(to).getValue());
break;
default:
options = 0;
throw new IllegalArgumentException("Unknown Object Identifier!");
}
}
else
{
throw new IllegalArgumentException("Unknown Object Identifier!");
}
}
if (options != 0x20 && options != 0x7F)
{
throw new IllegalArgumentException("All options must be either present or absent!");
}
}
public ECDSAPublicKey(ASN1ObjectIdentifier usage, byte[] ppY)
throws IllegalArgumentException
{
this.usage = usage;
setPublicPointY(new DEROctetString(ppY));
}
public ECDSAPublicKey(ASN1ObjectIdentifier usage, BigInteger p, BigInteger a, BigInteger b, byte[] basePoint, BigInteger order, byte[] publicPoint, int cofactor)
{
this.usage = usage;
setPrimeModulusP(p);
setFirstCoefA(a);
setSecondCoefB(b);
setBasePointG(new DEROctetString(basePoint));
setOrderOfBasePointR(order);
setPublicPointY(new DEROctetString(publicPoint));
setCofactorF(BigInteger.valueOf(cofactor));
}
public ASN1ObjectIdentifier getUsage()
{
return usage;
}
public byte[] getBasePointG()
{
if ((options & G) != 0)
{
return Arrays.clone(basePointG);
}
else
{
return null;
}
}
private void setBasePointG(ASN1OctetString basePointG)
throws IllegalArgumentException
{
if ((options & G) == 0)
{
options |= G;
this.basePointG = basePointG.getOctets();
}
else
{
throw new IllegalArgumentException("Base Point G already set");
}
}
public BigInteger getCofactorF()
{
if ((options & F) != 0)
{
return cofactorF;
}
else
{
return null;
}
}
private void setCofactorF(BigInteger cofactorF)
throws IllegalArgumentException
{
if ((options & F) == 0)
{
options |= F;
this.cofactorF = cofactorF;
}
else
{
throw new IllegalArgumentException("Cofactor F already set");
}
}
public BigInteger getFirstCoefA()
{
if ((options & A) != 0)
{
return firstCoefA;
}
else
{
return null;
}
}
private void setFirstCoefA(BigInteger firstCoefA)
throws IllegalArgumentException
{
if ((options & A) == 0)
{
options |= A;
this.firstCoefA = firstCoefA;
}
else
{
throw new IllegalArgumentException("First Coef A already set");
}
}
public BigInteger getOrderOfBasePointR()
{
if ((options & R) != 0)
{
return orderOfBasePointR;
}
else
{
return null;
}
}
private void setOrderOfBasePointR(BigInteger orderOfBasePointR)
throws IllegalArgumentException
{
if ((options & R) == 0)
{
options |= R;
this.orderOfBasePointR = orderOfBasePointR;
}
else
{
throw new IllegalArgumentException("Order of base point R already set");
}
}
public BigInteger getPrimeModulusP()
{
if ((options & P) != 0)
{
return primeModulusP;
}
else
{
return null;
}
}
private void setPrimeModulusP(BigInteger primeModulusP)
{
if ((options & P) == 0)
{
options |= P;
this.primeModulusP = primeModulusP;
}
else
{
throw new IllegalArgumentException("Prime Modulus P already set");
}
}
public byte[] getPublicPointY()
{
if ((options & Y) != 0)
{
return Arrays.clone(publicPointY);
}
else
{
return null;
}
}
private void setPublicPointY(ASN1OctetString publicPointY)
throws IllegalArgumentException
{
if ((options & Y) == 0)
{
options |= Y;
this.publicPointY = publicPointY.getOctets();
}
else
{
throw new IllegalArgumentException("Public Point Y already set");
}
}
public BigInteger getSecondCoefB()
{
if ((options & B) != 0)
{
return secondCoefB;
}
else
{
return null;
}
}
private void setSecondCoefB(BigInteger secondCoefB)
throws IllegalArgumentException
{
if ((options & B) == 0)
{
options |= B;
this.secondCoefB = secondCoefB;
}
else
{
throw new IllegalArgumentException("Second Coef B already set");
}
}
public boolean hasParameters()
{
return primeModulusP != null;
}
public ASN1EncodableVector getASN1EncodableVector(ASN1ObjectIdentifier oid, boolean publicPointOnly)
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(oid);
if (!publicPointOnly)
{
v.add(new UnsignedInteger(0x01, getPrimeModulusP()));
v.add(new UnsignedInteger(0x02, getFirstCoefA()));
v.add(new UnsignedInteger(0x03, getSecondCoefB()));
v.add(new DERTaggedObject(false, 0x04, new DEROctetString(getBasePointG())));
v.add(new UnsignedInteger(0x05, getOrderOfBasePointR()));
}
v.add(new DERTaggedObject(false, 0x06, new DEROctetString(getPublicPointY())));
if (!publicPointOnly)
{
v.add(new UnsignedInteger(0x07, getCofactorF()));
}
return v;
}
public ASN1Primitive toASN1Primitive()
{
return new DERSequence(getASN1EncodableVector(usage, false));
}
}
| BJA-645 removed hard coded boolean
| core/src/main/java/org/bouncycastle/asn1/eac/ECDSAPublicKey.java | BJA-645 removed hard coded boolean | <ide><path>ore/src/main/java/org/bouncycastle/asn1/eac/ECDSAPublicKey.java
<ide>
<ide> public ASN1Primitive toASN1Primitive()
<ide> {
<del> return new DERSequence(getASN1EncodableVector(usage, false));
<add> return new DERSequence(getASN1EncodableVector(usage, !hasParameters()));
<ide> }
<ide> } |
|
Java | bsd-3-clause | dc47405d3d524388be6271ace16ecb98f69d8d9f | 0 | lukehutch/gribbit-rox,lukehutch/gribbit-rox | package com.flat502.rox.processing;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
// import sun.security.tools.keytool.CertAndKeyGen;
// import sun.security.x509.X500Name;
import com.flat502.rox.log.Log;
import com.flat502.rox.log.LogFactory;
//@SuppressWarnings("restriction")
public class SSLConfiguration {
public static enum ClientAuth {
NONE, REQUEST, REQUIRE
};
private static Log log = LogFactory.getLog(SSLConfiguration.class);
/**
* A regular expression that matches only cipher suites that allow for anonymous key exchange.
*/
public static final String ANON_CIPHER_SUITES = "_DH_anon_(?i)";
/**
* A regular expression that matches all cipher suites.
*/
public static final String ALL_CIPHER_SUITES = ".*";
/**
* A regular expression that matches all protocols.
*/
public static final String ALL_PROTOCOLS = ".*";
/**
* A regular expression that matches all TLS protocols.
*/
public static final String TLS_PROTOCOLS = "^TLS";
// The pattern used to select cipher suites
private Pattern cipherSuitePattern;
private Pattern protocolPattern;
// Default to 10 seconds
private int handshakeTimeout = 10000;
private KeyStore keyStore;
private KeyStore trustStore;
private String keyStorePassphrase;
private SecureRandom rng;
private ClientAuth clientAuth = ClientAuth.NONE;
private PrivateKey explicitPrivateKey;
private X509Certificate[] explicitCertChain;
private String keystoreName;
private String truststoreName;
private SSLContext explicitContext;
public SSLConfiguration() {
this.setCipherSuitePattern(ALL_CIPHER_SUITES);
this.setProtocolPattern(ALL_PROTOCOLS);
}
public SSLConfiguration(SSLContext context) {
this();
this.explicitContext = context;
}
public SSLConfiguration(Properties props) throws GeneralSecurityException, IOException {
this();
String ks = getProperty(props, "javax.net.ssl.keyStore", null);
String ksp = getProperty(props, "javax.net.ssl.keyStorePassword", null);
String kst = getProperty(props, "javax.net.ssl.keyStoreType", "JKS");
if (ks != null && ksp != null && kst != null) {
this.setKeyStore(ks, ksp, ksp, kst);
}
String ts = getProperty(props, "javax.net.ssl.trustStore", null);
String tsp = getProperty(props, "javax.net.ssl.trustStorePassword", null);
String tst = getProperty(props, "javax.net.ssl.trustStoreType", "JKS");
if (ts != null && tsp != null && tst != null) {
this.setTrustStore(ts, tsp, tst);
}
}
public SSLConfiguration(KeyStore keyStore, String keyStorePassphrase, KeyStore trustStore) {
this();
this.keyStore = keyStore;
this.keyStorePassphrase = keyStorePassphrase;
this.trustStore = trustStore;
}
public SSLConfiguration(String keyStorePath, String keyStorePassphrase, String keyStoreType,
String trustStorePath, String trustStorePassphrase, String trustStoreType)
throws GeneralSecurityException, IOException {
this();
this.setKeyStore(keyStorePath, keyStorePassphrase, keyStorePassphrase, keyStoreType);
this.setTrustStore(keyStorePath, trustStorePassphrase, trustStoreType);
}
private static final Provider PROVIDER = new BouncyCastleProvider();
// TODO: For letsencrypt cert generation using BouncyCastle, see:
// https://www.mayrhofer.eu.org/create-x509-certs-in-java
public static SSLConfiguration createSelfSignedCertificate() throws Exception {
if (log.logInfo()) {
log.info("Generating self-signed SSL key pair");
}
String domain = "localhost";
SecureRandom random = new SecureRandom();
final KeyPair keyPair;
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(/* bits = */1024, random);
keyPair = keyGen.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
// Should not reach here, every Java implementation must have RSA key pair generator
throw new RuntimeException(e);
}
// // To encode the private key into KEY format:
// ByteBuffer keyByteBuf = ByteBuffer.allocate(1024);
// keyByteBuf.put("-----BEGIN PRIVATE KEY-----\n".getBytes("ASCII"));
// keyByteBuf.put(Base64.getEncoder().encode(key.getEncoded()));
// keyByteBuf.put("\n-----END PRIVATE KEY-----\n".getBytes("ASCII"));
// Prepare the information required for generating an X.509 certificate
X500Name owner = new X500Name("CN=" + domain);
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random),
new Date(), new Date(System.currentTimeMillis() + 10L * 365 * 24 * 60 * 60 * 1000), owner,
keyPair.getPublic());
// Sign a certificate using the private key
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
X509CertificateHolder certHolder = builder.build(signer);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
cert.verify(keyPair.getPublic());
// // To encode the certificate into CRT format:
// ByteBuffer crtByteBuf = ByteBuffer.allocate(1024);
// crtByteBuf.put("-----BEGIN CERTIFICATE-----\n".getBytes("ASCII"));
// crtByteBuf.put(Base64.getEncoder().encode(cert.getEncoded()));
// crtByteBuf.put("\n-----END CERTIFICATE-----\n".getBytes("ASCII"));
// CertificateFactory cf = CertificateFactory.getInstance("X.509");
// // To load a CRT format cert back in:
// ByteArrayInputStream crtStream = new ByteArrayInputStream(Arrays.copyOf(crtByteBuf.array(),
// crtByteBuf.position()));
// X509Certificate caCert = (X509Certificate) cf.generateCertificate(crtStream);
SSLConfiguration cfg = new SSLConfiguration();
cfg.addTrustedEntity(cert);
cfg.addIdentity(keyPair.getPrivate(), new X509Certificate[] { cert });
return cfg;
}
public void setRandomNumberGenerator(SecureRandom rng) {
this.rng = rng;
}
/**
* Configure a timeout value for SSL handshaking.
* <p>
* If the remote server is not SSL enabled then it falls to some sort of timeout to determine this, since a
* non-SSL server is waiting for a request from a client, which is in turn waiting for an SSL handshake to be
* initiated by the server.
* <p>
* This method controls the length of that timeout.
* <p>
* This timeout defaults to 10 seconds.
* <p>
* The new timeout affects only connections initiated subsequent to the completion of this method call.
*
* @param timeout
* The timeout (in milliseconds). A value of 0 indicates no timeout should be enforced (not
* recommended).
* @throws IllegalArgumentException
* If the timeout provided is negative.
*/
public void setHandshakeTimeout(int timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("timeout is negative");
}
this.handshakeTimeout = timeout;
}
public int getHandshakeTimeout() {
return this.handshakeTimeout;
}
/**
* Set the regular expression used to select the SSL cipher suites to use during SSL handshaking.
*
* @param cipherSuitePattern
* A regular expression for selecting the set of SSL cipher suites. A <code>null</code> value will
* treated as matching <i>all</i> cipher suites.
* @see #ALL_CIPHER_SUITES
* @see #ANON_CIPHER_SUITES
*/
public void setCipherSuitePattern(String cipherSuitePattern) {
if (cipherSuitePattern == null) {
cipherSuitePattern = ALL_CIPHER_SUITES;
}
synchronized (this) {
this.cipherSuitePattern = Pattern.compile(cipherSuitePattern);
}
}
/**
* Set the regular expression used to select the SSL protocol suites to use during SSL handshaking.
*
* @param protocolPattern
* A regular expression for selecting the set of SSL protocols. A <code>null</code> value will
* treated as matching <i>all</i> protocols.
* @see #ALL_PROTOCOLS
* @see #TLS_PROTOCOLS
*/
public void setProtocolPattern(String protocolPattern) {
if (protocolPattern == null) {
protocolPattern = ALL_PROTOCOLS;
}
synchronized (this) {
this.protocolPattern = Pattern.compile(protocolPattern);
}
}
public void addTrustedEntities(Collection<X509Certificate> certs) throws GeneralSecurityException, IOException {
for (X509Certificate certificate : certs) {
this.addTrustedEntity(certificate);
}
}
public void addTrustedEntity(X509Certificate cert) throws GeneralSecurityException, IOException {
if (this.trustStore == null) {
this.trustStore = SSLConfiguration.initKeyStore();
}
String alias = cert.getSubjectX500Principal().getName() + ":" + cert.getSerialNumber();
this.trustStore.setCertificateEntry(alias, cert);
this.setTrustStore(this.trustStore);
}
public void addIdentity(PrivateKey privateKey, X509Certificate[] chain) throws GeneralSecurityException,
IOException {
if (this.keyStore == null) {
this.keyStore = SSLConfiguration.initKeyStore();
}
String alias = privateKey.getAlgorithm() + ":" + privateKey.hashCode();
this.keyStore.setKeyEntry(alias, privateKey, "".toCharArray(), chain);
this.setKeyStore(this.keyStore, "");
this.explicitPrivateKey = privateKey;
this.explicitCertChain = chain;
}
public void setClientAuthentication(ClientAuth auth) {
this.clientAuth = auth;
}
public ClientAuth getClientAuthentication() {
return this.clientAuth;
}
// Convenience method
public void setKeyStore(String storeFile, String keyStorePassphrase, String entryPassphrase, String storeType)
throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance(storeType);
ks.load(new FileInputStream(storeFile),
keyStorePassphrase == null ? null : keyStorePassphrase.toCharArray());
this.setKeyStore(ks, entryPassphrase);
this.keystoreName = storeFile;
this.keyStorePassphrase = keyStorePassphrase;
}
// Keystore.load must have been called.
public void setKeyStore(KeyStore ks, String passphrase) throws GeneralSecurityException {
this.keyStore = ks;
this.keyStorePassphrase = passphrase;
}
// Convenience method
public void setTrustStore(String storeFile, String passphrase, String storeType)
throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance(storeType);
ks.load(new FileInputStream(storeFile), passphrase == null ? null : passphrase.toCharArray());
this.setTrustStore(ks);
this.truststoreName = storeFile;
}
public void setTrustStore(KeyStore ts) throws GeneralSecurityException {
this.trustStore = ts;
}
public SSLContext createContext() throws GeneralSecurityException {
if (this.explicitContext != null) {
return this.explicitContext;
}
KeyManager[] km = null;
if (this.keyStore != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(this.keyStore, this.keyStorePassphrase == null ? null : this.keyStorePassphrase.toCharArray());
km = kmf.getKeyManagers();
}
TrustManager[] tm = null;
if (this.trustStore != null) {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(this.trustStore);
tm = tmf.getTrustManagers();
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(km, tm, this.rng);
return sslContext;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" client auth=" + this.clientAuth);
sb.append("\n handshake timeout=" + this.handshakeTimeout + "ms");
if (this.explicitPrivateKey != null) {
sb.append("\n explicit identity(key)=" + this.explicitPrivateKey);
}
if (this.explicitCertChain != null) {
sb.append("\n explicit identity(certs)=" + Arrays.toString(this.explicitCertChain));
}
if (this.keystoreName != null) {
sb.append("\n keystore=" + keystoreName);
}
if (this.truststoreName != null) {
sb.append("\n truststore=" + truststoreName);
}
return sb.toString();
}
protected String[] selectCiphersuites(String[] supportedCipherSuites) {
synchronized (this) {
if (log.logTrace()) {
log.trace("Selecting cipher suites using pattern [" + this.cipherSuitePattern + "]");
}
List<String> ciphers = new ArrayList<>(supportedCipherSuites.length);
for (String supportedCipherSuite : supportedCipherSuites) {
if (this.cipherSuitePattern.matcher(supportedCipherSuite).find()) {
if (log.logTrace()) {
log.trace("Matched " + supportedCipherSuite);
}
ciphers.add(supportedCipherSuite);
}
}
return ciphers.toArray(new String[0]);
}
}
protected String[] selectProtocols(String[] supportedProtocols) {
synchronized (this) {
if (log.logTrace()) {
log.trace("Selecting protocols using pattern [" + this.protocolPattern + "]");
}
List<String> protocols = new ArrayList<>(supportedProtocols.length);
for (String supportedProtocol : supportedProtocols) {
if (this.protocolPattern.matcher(supportedProtocol).find()) {
if (log.logTrace()) {
log.trace("Matched " + supportedProtocol);
}
protocols.add(supportedProtocol);
}
}
return protocols.toArray(new String[0]);
}
}
//setProtocolPattern etc
//
private static KeyStore initKeyStore() throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
return ks;
}
private static String getProperty(Properties props, String name, String defVal) throws SSLException {
String v = props.getProperty(name, defVal);
if (v == null) {
log.warn("No value for property " + name);
}
return v;
}
}
| src/com/flat502/rox/processing/SSLConfiguration.java | package com.flat502.rox.processing;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
// import sun.security.tools.keytool.CertAndKeyGen;
// import sun.security.x509.X500Name;
import com.flat502.rox.log.Log;
import com.flat502.rox.log.LogFactory;
//@SuppressWarnings("restriction")
public class SSLConfiguration {
public static enum ClientAuth {
NONE, REQUEST, REQUIRE
};
private static Log log = LogFactory.getLog(SSLConfiguration.class);
/**
* A regular expression that matches only cipher suites that allow for anonymous key exchange.
*/
public static final String ANON_CIPHER_SUITES = "_DH_anon_(?i)";
/**
* A regular expression that matches all cipher suites.
*/
public static final String ALL_CIPHER_SUITES = ".*";
/**
* A regular expression that matches all protocols.
*/
public static final String ALL_PROTOCOLS = ".*";
/**
* A regular expression that matches all TLS protocols.
*/
public static final String TLS_PROTOCOLS = "^TLS";
// The pattern used to select cipher suites
private Pattern cipherSuitePattern;
private Pattern protocolPattern;
// Default to 10 seconds
private int handshakeTimeout = 10000;
private KeyStore keyStore;
private KeyStore trustStore;
private String keyStorePassphrase;
private SecureRandom rng;
private ClientAuth clientAuth = ClientAuth.NONE;
private PrivateKey explicitPrivateKey;
private X509Certificate[] explicitCertChain;
private String keystoreName;
private String truststoreName;
private SSLContext explicitContext;
public SSLConfiguration() {
this.setCipherSuitePattern(ALL_CIPHER_SUITES);
this.setProtocolPattern(ALL_PROTOCOLS);
}
public SSLConfiguration(SSLContext context) {
this();
this.explicitContext = context;
}
public SSLConfiguration(Properties props) throws GeneralSecurityException, IOException {
this();
String ks = getProperty(props, "javax.net.ssl.keyStore", null);
String ksp = getProperty(props, "javax.net.ssl.keyStorePassword", null);
String kst = getProperty(props, "javax.net.ssl.keyStoreType", "JKS");
if (ks != null && ksp != null && kst != null) {
this.setKeyStore(ks, ksp, ksp, kst);
}
String ts = getProperty(props, "javax.net.ssl.trustStore", null);
String tsp = getProperty(props, "javax.net.ssl.trustStorePassword", null);
String tst = getProperty(props, "javax.net.ssl.trustStoreType", "JKS");
if (ts != null && tsp != null && tst != null) {
this.setTrustStore(ts, tsp, tst);
}
}
public SSLConfiguration(KeyStore keyStore, String keyStorePassphrase, KeyStore trustStore) {
this();
this.keyStore = keyStore;
this.keyStorePassphrase = keyStorePassphrase;
this.trustStore = trustStore;
}
public SSLConfiguration(String keyStorePath, String keyStorePassphrase, String keyStoreType,
String trustStorePath, String trustStorePassphrase, String trustStoreType)
throws GeneralSecurityException, IOException {
this();
this.setKeyStore(keyStorePath, keyStorePassphrase, keyStorePassphrase, keyStoreType);
this.setTrustStore(keyStorePath, trustStorePassphrase, trustStoreType);
}
private static final Provider PROVIDER = new BouncyCastleProvider();
// TODO: For letsencrypt cert generation using BouncyCastle, see:
// https://www.mayrhofer.eu.org/create-x509-certs-in-java
public static SSLConfiguration createSelfSignedCertificate() throws Exception {
if (log.logInfo()) {
log.info("Generating self-signed SSL key pair");
}
String domain = "localhost";
SecureRandom random = new SecureRandom();
final KeyPair keyPair;
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(/* bits = */1024, random);
keyPair = keyGen.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
// Should not reach here, every Java implementation must have RSA key pair generator
throw new RuntimeException(e);
}
PrivateKey privateKey = keyPair.getPrivate();
// // To encode the private key into KEY format:
// ByteBuffer keyByteBuf = ByteBuffer.allocate(1024);
// keyByteBuf.put("-----BEGIN PRIVATE KEY-----\n".getBytes("ASCII"));
// keyByteBuf.put(Base64.getEncoder().encode(key.getEncoded()));
// keyByteBuf.put("\n-----END PRIVATE KEY-----\n".getBytes("ASCII"));
// Prepare the information required for generating an X.509 certificate
X500Name owner = new X500Name("CN=" + domain);
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random),
new Date(), new Date(System.currentTimeMillis() + 10L * 365 * 24 * 60 * 60 * 1000), owner,
keyPair.getPublic());
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(privateKey);
X509CertificateHolder certHolder = builder.build(signer);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
cert.verify(keyPair.getPublic());
// // To encode the certificate into CRT format:
// ByteBuffer crtByteBuf = ByteBuffer.allocate(1024);
// crtByteBuf.put("-----BEGIN CERTIFICATE-----\n".getBytes("ASCII"));
// crtByteBuf.put(Base64.getEncoder().encode(cert.getEncoded()));
// crtByteBuf.put("\n-----END CERTIFICATE-----\n".getBytes("ASCII"));
// CertificateFactory cf = CertificateFactory.getInstance("X.509");
// // To load a CRT format cert back in:
// ByteArrayInputStream crtStream = new ByteArrayInputStream(Arrays.copyOf(crtByteBuf.array(),
// crtByteBuf.position()));
// X509Certificate caCert = (X509Certificate) cf.generateCertificate(crtStream);
SSLConfiguration cfg = new SSLConfiguration();
cfg.addTrustedEntity(cert);
cfg.addIdentity(privateKey, new X509Certificate[] { cert });
return cfg;
}
public void setRandomNumberGenerator(SecureRandom rng) {
this.rng = rng;
}
/**
* Configure a timeout value for SSL handshaking.
* <p>
* If the remote server is not SSL enabled then it falls to some sort of timeout to determine this, since a
* non-SSL server is waiting for a request from a client, which is in turn waiting for an SSL handshake to be
* initiated by the server.
* <p>
* This method controls the length of that timeout.
* <p>
* This timeout defaults to 10 seconds.
* <p>
* The new timeout affects only connections initiated subsequent to the completion of this method call.
*
* @param timeout
* The timeout (in milliseconds). A value of 0 indicates no timeout should be enforced (not
* recommended).
* @throws IllegalArgumentException
* If the timeout provided is negative.
*/
public void setHandshakeTimeout(int timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("timeout is negative");
}
this.handshakeTimeout = timeout;
}
public int getHandshakeTimeout() {
return this.handshakeTimeout;
}
/**
* Set the regular expression used to select the SSL cipher suites to use during SSL handshaking.
*
* @param cipherSuitePattern
* A regular expression for selecting the set of SSL cipher suites. A <code>null</code> value will
* treated as matching <i>all</i> cipher suites.
* @see #ALL_CIPHER_SUITES
* @see #ANON_CIPHER_SUITES
*/
public void setCipherSuitePattern(String cipherSuitePattern) {
if (cipherSuitePattern == null) {
cipherSuitePattern = ALL_CIPHER_SUITES;
}
synchronized (this) {
this.cipherSuitePattern = Pattern.compile(cipherSuitePattern);
}
}
/**
* Set the regular expression used to select the SSL protocol suites to use during SSL handshaking.
*
* @param protocolPattern
* A regular expression for selecting the set of SSL protocols. A <code>null</code> value will
* treated as matching <i>all</i> protocols.
* @see #ALL_PROTOCOLS
* @see #TLS_PROTOCOLS
*/
public void setProtocolPattern(String protocolPattern) {
if (protocolPattern == null) {
protocolPattern = ALL_PROTOCOLS;
}
synchronized (this) {
this.protocolPattern = Pattern.compile(protocolPattern);
}
}
public void addTrustedEntities(Collection<X509Certificate> certs) throws GeneralSecurityException, IOException {
for (X509Certificate certificate : certs) {
this.addTrustedEntity(certificate);
}
}
public void addTrustedEntity(X509Certificate cert) throws GeneralSecurityException, IOException {
if (this.trustStore == null) {
this.trustStore = SSLConfiguration.initKeyStore();
}
String alias = cert.getSubjectX500Principal().getName() + ":" + cert.getSerialNumber();
this.trustStore.setCertificateEntry(alias, cert);
this.setTrustStore(this.trustStore);
}
public void addIdentity(PrivateKey privateKey, X509Certificate[] chain) throws GeneralSecurityException,
IOException {
if (this.keyStore == null) {
this.keyStore = SSLConfiguration.initKeyStore();
}
String alias = privateKey.getAlgorithm() + ":" + privateKey.hashCode();
this.keyStore.setKeyEntry(alias, privateKey, "".toCharArray(), chain);
this.setKeyStore(this.keyStore, "");
this.explicitPrivateKey = privateKey;
this.explicitCertChain = chain;
}
public void setClientAuthentication(ClientAuth auth) {
this.clientAuth = auth;
}
public ClientAuth getClientAuthentication() {
return this.clientAuth;
}
// Convenience method
public void setKeyStore(String storeFile, String keyStorePassphrase, String entryPassphrase, String storeType)
throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance(storeType);
ks.load(new FileInputStream(storeFile),
keyStorePassphrase == null ? null : keyStorePassphrase.toCharArray());
this.setKeyStore(ks, entryPassphrase);
this.keystoreName = storeFile;
this.keyStorePassphrase = keyStorePassphrase;
}
// Keystore.load must have been called.
public void setKeyStore(KeyStore ks, String passphrase) throws GeneralSecurityException {
this.keyStore = ks;
this.keyStorePassphrase = passphrase;
}
// Convenience method
public void setTrustStore(String storeFile, String passphrase, String storeType)
throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance(storeType);
ks.load(new FileInputStream(storeFile), passphrase == null ? null : passphrase.toCharArray());
this.setTrustStore(ks);
this.truststoreName = storeFile;
}
public void setTrustStore(KeyStore ts) throws GeneralSecurityException {
this.trustStore = ts;
}
public SSLContext createContext() throws GeneralSecurityException {
if (this.explicitContext != null) {
return this.explicitContext;
}
KeyManager[] km = null;
if (this.keyStore != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(this.keyStore, this.keyStorePassphrase == null ? null : this.keyStorePassphrase.toCharArray());
km = kmf.getKeyManagers();
}
TrustManager[] tm = null;
if (this.trustStore != null) {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(this.trustStore);
tm = tmf.getTrustManagers();
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(km, tm, this.rng);
return sslContext;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" client auth=" + this.clientAuth);
sb.append("\n handshake timeout=" + this.handshakeTimeout + "ms");
if (this.explicitPrivateKey != null) {
sb.append("\n explicit identity(key)=" + this.explicitPrivateKey);
}
if (this.explicitCertChain != null) {
sb.append("\n explicit identity(certs)=" + Arrays.toString(this.explicitCertChain));
}
if (this.keystoreName != null) {
sb.append("\n keystore=" + keystoreName);
}
if (this.truststoreName != null) {
sb.append("\n truststore=" + truststoreName);
}
return sb.toString();
}
protected String[] selectCiphersuites(String[] supportedCipherSuites) {
synchronized (this) {
if (log.logTrace()) {
log.trace("Selecting cipher suites using pattern [" + this.cipherSuitePattern + "]");
}
List<String> ciphers = new ArrayList<>(supportedCipherSuites.length);
for (String supportedCipherSuite : supportedCipherSuites) {
if (this.cipherSuitePattern.matcher(supportedCipherSuite).find()) {
if (log.logTrace()) {
log.trace("Matched " + supportedCipherSuite);
}
ciphers.add(supportedCipherSuite);
}
}
return ciphers.toArray(new String[0]);
}
}
protected String[] selectProtocols(String[] supportedProtocols) {
synchronized (this) {
if (log.logTrace()) {
log.trace("Selecting protocols using pattern [" + this.protocolPattern + "]");
}
List<String> protocols = new ArrayList<>(supportedProtocols.length);
for (String supportedProtocol : supportedProtocols) {
if (this.protocolPattern.matcher(supportedProtocol).find()) {
if (log.logTrace()) {
log.trace("Matched " + supportedProtocol);
}
protocols.add(supportedProtocol);
}
}
return protocols.toArray(new String[0]);
}
}
//setProtocolPattern etc
//
private static KeyStore initKeyStore() throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
return ks;
}
private static String getProperty(Properties props, String name, String defVal) throws SSLException {
String v = props.getProperty(name, defVal);
if (v == null) {
log.warn("No value for property " + name);
}
return v;
}
}
| Fix comment | src/com/flat502/rox/processing/SSLConfiguration.java | Fix comment | <ide><path>rc/com/flat502/rox/processing/SSLConfiguration.java
<ide> // Should not reach here, every Java implementation must have RSA key pair generator
<ide> throw new RuntimeException(e);
<ide> }
<del> PrivateKey privateKey = keyPair.getPrivate();
<ide>
<ide> // // To encode the private key into KEY format:
<ide> // ByteBuffer keyByteBuf = ByteBuffer.allocate(1024);
<ide> new Date(), new Date(System.currentTimeMillis() + 10L * 365 * 24 * 60 * 60 * 1000), owner,
<ide> keyPair.getPublic());
<ide>
<del> ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(privateKey);
<add> // Sign a certificate using the private key
<add> ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
<ide> X509CertificateHolder certHolder = builder.build(signer);
<ide> X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
<ide> cert.verify(keyPair.getPublic());
<ide> // crtByteBuf.put(Base64.getEncoder().encode(cert.getEncoded()));
<ide> // crtByteBuf.put("\n-----END CERTIFICATE-----\n".getBytes("ASCII"));
<ide> // CertificateFactory cf = CertificateFactory.getInstance("X.509");
<del>
<add>
<ide> // // To load a CRT format cert back in:
<ide> // ByteArrayInputStream crtStream = new ByteArrayInputStream(Arrays.copyOf(crtByteBuf.array(),
<ide> // crtByteBuf.position()));
<ide>
<ide> SSLConfiguration cfg = new SSLConfiguration();
<ide> cfg.addTrustedEntity(cert);
<del> cfg.addIdentity(privateKey, new X509Certificate[] { cert });
<add> cfg.addIdentity(keyPair.getPrivate(), new X509Certificate[] { cert });
<ide> return cfg;
<ide> }
<ide> |
|
Java | apache-2.0 | c59f6288bb531e5c75ae234a3e2b43589298535e | 0 | nolearning/learningAndroid | package com.learning.java;
import java.io.File;
import com.fasterxml.jackson.*;
import com.fasterxml.jackson.databind.*;
public class TestMain {
private static class Package {
private String name;
private String id;
public String publisher;
public String version;
public String grade;
public String subject;
public int fasciculeOrder;
public String fasciculeName;
public int limitedTime;
public String fullMark;
public int starred;
private Package[] childNodes;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Package[] getChildNodes() {
return childNodes;
}
public void setChildNodes(Package[] childNodes) {
this.childNodes = childNodes;
}
}
private class TestJackson {
private File jsonFile;
private ObjectMapper mapper;
public TestJackson(String file) {
jsonFile = new File(file);
mapper = new ObjectMapper();
}
public void readJSONByDataBinding() {
try {
Package p1 = mapper.readValue(jsonFile, Package.class);
mapper.createObjectNode();
System.out.println(p1.childNodes[1].childNodes[0].name);
} catch(Exception e) {
System.err.println(e);
}
}
public void readJSONbyTreeModel() {
try {
JsonNode rootNode = mapper.readValue(jsonFile, JsonNode.class);
System.out.println(rootNode.get("childNodes").asText());
} catch (Exception e) {
System.err.println(e);
}
}
}
public static void main(String[] args) {
TestMain tm = new TestMain();
TestJackson tj = tm.new TestJackson("package.json");
///tj.readJSONByDataBinding();
tj.readJSONbyTreeModel();
}
}
| TestJackson/src/com/learning/java/TestMain.java | package com.learning.java;
import java.io.File;
import com.fasterxml.jackson.*;
import com.fasterxml.jackson.databind.*;
public class TestMain {
private static class Package {
private String name;
private String id;
public String publisher;
public String version;
public String grade;
public String subject;
public int fasciculeOrder;
public String fasciculeName;
public int limitedTime;
public String fullMark;
public int starred;
private Package[] childNodes;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Package[] getChildNodes() {
return childNodes;
}
public void setChildNodes(Package[] childNodes) {
this.childNodes = childNodes;
}
}
private class TestJackson {
private File jsonFile;
private ObjectMapper mapper;
public TestJackson(String file) {
jsonFile = new File(file);
mapper = new ObjectMapper();
}
public void readJSONByDataBinding() {
try {
Package p1 = mapper.readValue(jsonFile, Package.class);
System.out.println(p1.childNodes[1].childNodes[0].name);
} catch(Exception e) {
System.err.println(e);
}
}
}
public static void main(String[] args) {
TestMain tm = new TestMain();
TestJackson tj = tm.new TestJackson("package.json");
tj.readJSONByDataBinding();
}
}
| commit for JsonTree model
| TestJackson/src/com/learning/java/TestMain.java | commit for JsonTree model | <ide><path>estJackson/src/com/learning/java/TestMain.java
<ide> public void readJSONByDataBinding() {
<ide> try {
<ide> Package p1 = mapper.readValue(jsonFile, Package.class);
<add> mapper.createObjectNode();
<ide> System.out.println(p1.childNodes[1].childNodes[0].name);
<ide> } catch(Exception e) {
<add> System.err.println(e);
<add> }
<add> }
<add>
<add> public void readJSONbyTreeModel() {
<add> try {
<add> JsonNode rootNode = mapper.readValue(jsonFile, JsonNode.class);
<add> System.out.println(rootNode.get("childNodes").asText());
<add> } catch (Exception e) {
<ide> System.err.println(e);
<ide> }
<ide> }
<ide> TestMain tm = new TestMain();
<ide>
<ide> TestJackson tj = tm.new TestJackson("package.json");
<del> tj.readJSONByDataBinding();
<add> ///tj.readJSONByDataBinding();
<add> tj.readJSONbyTreeModel();
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | e285b0bfafa2c6f86aa008c5ac0910f09bbc6b81 | 0 | life-beam/j2objc,bandcampdotcom/j2objc,mirego/j2objc,groschovskiy/j2objc,mirego/j2objc,bandcampdotcom/j2objc,lukhnos/j2objc,life-beam/j2objc,doppllib/j2objc,groschovskiy/j2objc,lukhnos/j2objc,life-beam/j2objc,bandcampdotcom/j2objc,groschovskiy/j2objc,mirego/j2objc,bandcampdotcom/j2objc,doppllib/j2objc,doppllib/j2objc,life-beam/j2objc,google/j2objc,doppllib/j2objc,life-beam/j2objc,bandcampdotcom/j2objc,mirego/j2objc,google/j2objc,doppllib/j2objc,google/j2objc,google/j2objc,mirego/j2objc,lukhnos/j2objc,mirego/j2objc,life-beam/j2objc,groschovskiy/j2objc,groschovskiy/j2objc,doppllib/j2objc,google/j2objc,lukhnos/j2objc,google/j2objc,groschovskiy/j2objc,lukhnos/j2objc,bandcampdotcom/j2objc,lukhnos/j2objc | /*
* Copyright 2011 Google 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.google.devtools.j2objc.util;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.ast.CompilationUnit;
import com.google.devtools.j2objc.types.NativeType;
import com.google.devtools.j2objc.types.PointerType;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.TypeMirror;
/**
* Singleton service for type/method/variable name support.
*
* @author Tom Ball
*/
public class NameTable {
private final TypeUtil typeUtil;
private final ElementUtil elementUtil;
private final CaptureInfo captureInfo;
private final Map<VariableElement, String> variableNames = new HashMap<>();
private final Map<ExecutableElement, String> methodSelectorCache = new HashMap<>();
public static final String INIT_NAME = "init";
public static final String RETAIN_METHOD = "retain";
public static final String RELEASE_METHOD = "release";
public static final String DEALLOC_METHOD = "dealloc";
public static final String FINALIZE_METHOD = "finalize";
// The JDT compiler requires package-info files be named as "package-info",
// but that's an illegal type to generate.
public static final String PACKAGE_INFO_CLASS_NAME = "package-info";
private static final String PACKAGE_INFO_OBJC_NAME = "package_info";
// The self name in Java is reserved in Objective-C, but functionized methods
// actually want the first parameter to be self. This is an internal name,
// converted to self during generation.
public static final String SELF_NAME = "$$self$$";
public static final String ID_TYPE = "id";
// This is syntactic sugar for blocks. All block are typed as ids, but we add a block_type typedef
// for source clarity.
public static final String BLOCK_TYPE = "block_type";
private static final Logger logger = Logger.getLogger(NameTable.class.getName());
/**
* The list of predefined types, common primitive typedefs, constants and
* variables.
*/
public static final Set<String> reservedNames = Sets.newHashSet(
// types
"id", "bool", "BOOL", "SEL", "IMP", "unichar",
// constants
"nil", "Nil", "YES", "NO", "TRUE", "FALSE",
// C99 keywords
"auto", "const", "entry", "extern", "goto", "inline", "register", "restrict", "signed",
"sizeof", "struct", "typedef", "union", "unsigned", "volatile",
// C++ keywords
"and", "and_eq", "asm", "bitand", "bitor", "compl", "const_cast", "delete", "dynamic_cast",
"explicit", "export", "friend", "mutable", "namespace", "not", "not_eq", "operator", "or",
"or_eq", "reinterpret_cast", "static_cast", "template", "typeid", "typename", "using",
"virtual", "wchar_t", "xor", "xor_eq",
// variables
"self", "isa",
// Definitions from standard C and Objective-C headers, not including
// typedefs and #defines that start with "_", nor #defines for
// functions. Some of these may seem very unlikely to be used in
// Java source, but if a name is legal some Java developer might very
// well use it.
// Definitions from stddef.h
"ptrdiff_t", "size_t", "wchar_t", "wint_t",
// Definitions from stdint.h
"int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t",
"int_least8_t", "int_least16_t", "int_least32_t", "int_least64_t",
"uint_least8_t", "uint_least16_t", "uint_least32_t", "uint_least64_t",
"int_fast8_t", "int_fast16_t", "int_fast32_t", "int_fast64_t",
"uint_fast8_t", "uint_fast16_t", "uint_fast32_t", "uint_fast64_t",
"intptr_t", "uintptr_t", "intmax_t", "uintmax_t",
"INT8_MAX", "INT16_MAX", "INT32_MAX", "INT64_MAX", "INT8_MIN", "INT16_MIN", "INT32_MIN",
"INT64_MIN", "UINT8_MAX", "UINT16_MAX", "UINT32_MAX", "UINT64_MAX", "INT_LEAST8_MIN",
"INT_LEAST16_MIN", "INT_LEAST32_MIN", "INT_LEAST64_MIN", "INT_LEAST8_MAX", "INT_LEAST16_MAX",
"INT_LEAST32_MAX", "INT_LEAST64_MAX", "INT_FAST8_MIN", "INT_FAST16_MIN", "INT_FAST32_MIN",
"INT_FAST64_MIN", "INT_FAST8_MAX", "INT_FAST16_MAX", "INT_FAST32_MAX", "INT_FAST64_MAX",
"UINT_FAST8_MAX", "UINT_FAST16_MAX", "UINT_FAST32_MAX", "UINT_FAST64_MAX", "INTPTR_MIN",
"INTPTR_MAX", "UINTPTR_MAX", "INTMAX_MIN", "INTMAX_MAX", "UINTMAX_MAX", "PTRDIFF_MIN",
"PTRDIFF_MAX", "SIZE_MAX", "WCHAR_MAX", "WCHAR_MIN", "WINT_MIN", "WINT_MAX",
"SIG_ATOMIC_MIN", "SIG_ATOMIC_MAX", "INT8_MAX", "INT16_MAX", "INT32_MAX", "INT64_MAX",
"UINT8_C", "UINT16_C", "UINT32_C", "UINT64_C", "INTMAX_C", "UINTMAX_C",
// Definitions from stdio.h
"va_list", "fpos_t", "FILE", "off_t", "ssize_t", "BUFSIZ", "EOF", "FOPEN_MAX",
"FILENAME_MAX", "R_OK", "SEEK_SET", "SEEK_CUR", "SEEK_END", "stdin", "STDIN_FILENO",
"stdout", "STDOUT_FILENO", "stderr", "STDERR_FILENO", "TMP_MAX", "W_OK", "X_OK",
"sys_errlist",
// Definitions from stdlib.h
"ct_rune_t", "rune_t", "div_t", "ldiv_t", "lldiv_t", "dev_t", "mode_t",
"NULL", "EXIT_FAILURE", "EXIT_SUCCESS", "RAND_MAX", "MB_CUR_MAX", "MB_CUR_MAX_L",
// Definitions from errno.h
"errno", "EPERM", "ENOENT", "ESRCH", "EINTR", "EIO", "ENXIO", "E2BIG", "ENOEXEC",
"EBADF", "ECHILD", "EDEADLK", "ENOMEM", "EACCES", "EFAULT", "ENOTBLK", "EBUSY",
"EEXIST", "EXDEV", "ENODEV", "ENOTDIR", "EISDIR", "EINVAL", "ENFILE", "EMFILE",
"ENOTTY", "ETXTBSY", "EFBIG", "ENOSPC", "ESPIPE", "EROFS", "EMLINK", "EPIPE",
"EDOM", "ERANGE", "EAGAIN", "EWOULDBLOCK", "EINPROGRESS", "EALREADY", "ENOTSOCK",
"EDESTADDRREQ", "EMSGSIZE", "EPROTOTYPE", "ENOPROTOOPT", "EPROTONOSUPPORT",
"ESOCKTNOSUPPORT", "ENOTSUP", "ENOTSUPP", "EPFNOSUPPORT", "EAFNOSUPPORT", "EADDRINUSE",
"EADDRNOTAVAIL", "ENETDOWN", "ENETUNREACH", "ENETRESET", "ECONNABORTED", "ECONNRESET",
"ENOBUFS", "EISCONN", "ENOTCONN", "ESHUTDOWN", "ETOOMANYREFS", "ETIMEDOUT", "ECONNREFUSED",
"ELOOP", "ENAMETOOLONG", "EHOSTDOWN", "EHOSTUNREACH", "ENOTEMPTY", "EPROCLIM", "EUSERS",
"EDQUOT", "ESTALE", "EREMOTE", "EBADRPC", "ERPCMISMATCH", "EPROGUNAVAIL", "EPROGMISMATCH",
"EPROCUNAVAIL", "ENOLCK", "ENOSYS", "EFTYPE", "EAUTH", "ENEEDAUTH", "EPWROFF", "EDEVERR",
"EOVERFLOW", "EBADEXEC", "EBADARCH", "ESHLIBVERS", "EBADMACHO", "ECANCELED", "EIDRM",
"ENOMSG", "ENOATTR", "EBADMSG", "EMULTIHOP", "ENODATA", "ENOLINK", "ENOSR", "ENOSTR",
"EPROTO", "ETIME", "ENOPOLICY", "ENOTRECOVERABLE", "EOWNERDEAD", "EQFULL", "EILSEQ",
"EOPNOTSUPP", "ELAST",
// Definitions from fcntl.h
"F_DUPFD", "F_GETFD", "F_SETFD", "F_GETFL", "F_SETFL", "F_GETOWN", "F_SETOWN",
"F_GETLK", "F_SETLK", "F_SETLKW", "FD_CLOEXEC", "F_RDLCK", "F_UNLCK", "F_WRLCK",
"SEEK_SET", "SEEK_CUR", "SEEK_END",
"O_RDONLY", "O_WRONLY", "O_RDWR", "O_ACCMODE", "O_NONBLOCK", "O_APPEND", "O_SYNC", "O_CREAT",
"O_TRUNC", "O_EXCL", "O_NOCTTY", "O_NOFOLLOW",
// Definitions from math.h
"DOMAIN", "HUGE", "INFINITY", "NAN", "OVERFLOW", "SING", "UNDERFLOW", "signgam",
// Definitions from mman.h
"MAP_FIXED", "MAP_PRIVATE", "MAP_SHARED", "MCL_CURRENT", "MCL_FUTURE", "MS_ASYNC",
"MS_INVALIDATE", "MS_SYNC", "PROT_EXEC", "PROT_NONE", "PROT_READ", "PROT_WRITE",
// Definitions from netdb.h
"AI_ADDRCONFIG", "AI_ALL", "AI_CANONNAME", "AI_NUMERICHOST", "AI_NUMERICSERV",
"AI_PASSIVE", "AI_V4MAPPED", "EAI_AGAIN", "EAI_BADFLAGS", "EAI_FAIL", "EAI_FAMILY",
"EAI_MEMORY", "EAI_NODATA", "EAI_NONAME", "EAI_OVERFLOW", "EAI_SERVICE", "EAI_SOCKTYPE",
"EAI_SYSTEM", "HOST_NOT_FOUND", "NI_NAMEREQD", "NI_NUMERICHOST", "NO_DATA",
"NO_RECOVERY", "TRY_AGAIN",
// Definitions from net/if.h
"IFF_LOOPBACK", "IFF_MULTICAST", "IFF_POINTTOPOINT", "IFF_UP", "SIOCGIFADDR",
"SIOCGIFBRDADDR", "SIOCGIFNETMASK", "SIOCGIFDSTADDR",
// Definitions from netinet/in.h, in6.h
"IPPROTO_IP", "IPPROTO_IPV6", "IPPROTO_TCP", "IPV6_MULTICAST_HOPS", "IPV6_MULTICAST_IF",
"IP_MULTICAST_LOOP", "IPV6_TCLASS", "MCAST_JOIN_GROUP", "MCAST_JOIN_GROUP",
// Definitions from socket.h
"AF_INET", "AF_INET6", "AF_UNIX", "AF_UNSPEC", "MSG_OOB", "MSG_PEEK", "SHUT_RD", "SHUT_RDWR",
"SHUT_WR", "SOCK_DGRAM", "SOCK_STREAM", "SOL_SOCKET", "SO_BINDTODEVICE", "SO_BROADCAST",
"SO_ERROR", "SO_KEEPALIVE", "SO_LINGER", "SOOOBINLINE", "SO_REUSEADDR", "SO_RCVBUF",
"SO_RCVTIMEO", "SO_SNDBUF", "TCP_NODELAY",
// Definitions from stat.h
"S_IFBLK", "S_IFCHR", "S_IFDIR", "S_IFIFO", "S_IFLNK", "S_IFMT", "S_IFREG", "S_IFSOCK",
// Definitions from sys/poll.h
"POLLERR", "POLLHUP", "POLLIN", "POLLOUT",
// Definitions from sys/syslimits.h
"ARG_MAX", "LINE_MAX", "MAX_INPUT", "NAME_MAX", "NZERO", "PATH_MAX",
// Definitions from limits.h, machine/limits.h
"CHAR_BIT", "CHAR_MAX", "CHAR_MIN", "INT_MAX", "INT_MIN", "LLONG_MAX", "LLONG_MIN",
"LONG_BIT", "LONG_MAX", "LONG_MIN", "MB_LEN_MAX", "OFF_MIN", "OFF_MAX",
"PTHREAD_DESTRUCTOR_ITERATIONS", "PTHREAD_KEYS_MAX", "PTHREAD_STACK_MIN", "QUAD_MAX",
"QUAD_MIN", "SCHAR_MAX", "SCHAR_MIN", "SHRT_MAX", "SHRT_MIN", "SIZE_T_MAX", "SSIZE_MAX",
"UCHAR_MAX", "UINT_MAX", "ULONG_MAX", "UQUAD_MAX", "USHRT_MAX", "UULONG_MAX", "WORD_BIT",
// Definitions from time.h
"daylight", "getdate_err", "tzname",
// Definitions from types.h
"S_IRGRP", "S_IROTH", "S_IRUSR", "S_IRWXG", "S_IRWXO", "S_IRWXU", "S_IWGRP", "S_IWOTH",
"S_IWUSR", "S_IXGRP", "S_IXOTH", "S_IXUSR",
// Definitions from unistd.h
"F_OK", "R_OK", "STDERR_FILENO", "STDIN_FILENO", "STDOUT_FILENO", "W_OK", "X_OK",
"_SC_PAGESIZE", "_SC_PAGE_SIZE", "optind", "opterr", "optopt", "optreset",
// Cocoa definitions from ConditionalMacros.h
"CFMSYSTEMCALLS", "CGLUESUPPORTED", "FUNCTION_PASCAL", "FUNCTION_DECLSPEC",
"FUNCTION_WIN32CC", "GENERATING68881", "GENERATING68K", "GENERATINGCFM", "GENERATINGPOWERPC",
"OLDROUTINELOCATIONS", "PRAGMA_ALIGN_SUPPORTED", "PRAGMA_ENUM_PACK", "PRAGMA_ENUM_ALWAYSINT",
"PRAGMA_ENUM_OPTIONS", "PRAGMA_IMPORT", "PRAGMA_IMPORT_SUPPORTED", "PRAGMA_ONCE",
"PRAGMA_STRUCT_ALIGN", "PRAGMA_STRUCT_PACK", "PRAGMA_STRUCT_PACKPUSH",
"TARGET_API_MAC_CARBON", "TARGET_API_MAC_OS8", "TARGET_API_MAC_OSX", "TARGET_CARBON",
"TYPE_BOOL", "TYPE_EXTENDED", "TYPE_LONGDOUBLE_IS_DOUBLE", "TYPE_LONGLONG",
"UNIVERSAL_INTERFACES_VERSION",
// Core Foundation definitions
"BIG_ENDIAN", "BYTE_ORDER", "LITTLE_ENDIAN", "PDP_ENDIAN",
// CoreServices definitions
"positiveInfinity", "negativeInfinity",
// Common preprocessor definitions.
"DEBUG", "NDEBUG",
// Foundation methods with conflicting return types
"scale",
// Syntactic sugar for Objective-C block types
"block_type");
private static final Set<String> badParameterNames = Sets.newHashSet(
// Objective-C type qualifier keywords.
"in", "out", "inout", "oneway", "bycopy", "byref");
/**
* List of NSObject message names. Java methods with one of these names are
* renamed to avoid unintentional overriding. Message names with trailing
* colons are not included since they can't be overridden. For example,
* "public boolean isEqual(Object o)" would be translated as
* "- (BOOL)isEqualWithObject:(NSObject *)o", not NSObject's "isEqual:".
*/
public static final List<String> nsObjectMessages = Lists.newArrayList(
"alloc", "attributeKeys", "autoContentAccessingProxy", "autorelease",
"classCode", "classDescription", "classForArchiver",
"classForKeyedArchiver", "classFallbacksForKeyedArchiver",
"classForPortCoder", "className", "copy", "dealloc", "description",
"hash", "init", "initialize", "isProxy", "load", "mutableCopy", "new",
"release", "retain", "retainCount", "scriptingProperties", "self",
"superclass", "toManyRelationshipKeys", "toOneRelationshipKeys",
"version");
/**
* Map of package names to their specified prefixes. Multiple packages
* can share a prefix; for example, the com.google.common packages in
* Guava could share a "GG" (Google Guava) or simply "Guava" prefix.
*/
private final PackagePrefixes prefixMap;
private final ImmutableMap<String, String> classMappings;
private final ImmutableMap<String, String> methodMappings;
public NameTable(TypeUtil typeUtil, CaptureInfo captureInfo, Options options) {
this.typeUtil = typeUtil;
this.elementUtil = typeUtil.elementUtil();
this.captureInfo = captureInfo;
prefixMap = options.getPackagePrefixes();
classMappings = options.getMappings().getClassMappings();
methodMappings = options.getMappings().getMethodMappings();
}
public void setVariableName(VariableElement var, String name) {
String previousName = variableNames.get(var);
if (previousName != null && !previousName.equals(name)) {
logger.fine(String.format("Changing previous rename for variable: %s. Was: %s, now: %s",
var.toString(), previousName, name));
}
variableNames.put(var, name);
}
/**
* Gets the variable name without any qualifying class name or other prefix
* or suffix attached.
*/
public String getVariableBaseName(VariableElement var) {
return getVarBaseName(var, ElementUtil.isGlobalVar(var));
}
/**
* Gets the name of the accessor method for a static variable.
*/
public String getStaticAccessorName(VariableElement var) {
return getVarBaseName(var, false);
}
private String getVarBaseName(VariableElement var, boolean allowReservedName) {
String name = variableNames.get(var);
if (name != null) {
return name;
}
name = ElementUtil.getName(var);
if (allowReservedName) {
return name;
}
name = maybeRenameVar(var, name);
return name.equals(SELF_NAME) ? "self" : name;
}
private static String maybeRenameVar(VariableElement var, String name) {
if (isReservedName(name)) {
name += '_';
} else if (ElementUtil.isParameter(var) && badParameterNames.contains(name)) {
name += "Arg";
}
return name;
}
/**
* Gets the variable or parameter name that should be used in a doc-comment.
* This may be wrong if a variable is renamed by a translation phase, but will
* handle all the reserved and bad parameter renamings correctly.
*/
public static String getDocCommentVariableName(VariableElement var) {
return maybeRenameVar(var, ElementUtil.getName(var));
}
/**
* Gets the non-qualified variable name, with underscore suffix.
*/
public String getVariableShortName(VariableElement var) {
String baseName = getVariableBaseName(var);
if (var.getKind().isField() && !ElementUtil.isGlobalVar(var)) {
return baseName + '_';
}
return baseName;
}
/**
* Gets the name of the variable as it is declared in ObjC, fully qualified.
*/
public String getVariableQualifiedName(VariableElement var) {
String shortName = getVariableShortName(var);
if (ElementUtil.isGlobalVar(var)) {
String className = getFullName(ElementUtil.getDeclaringClass(var));
if (ElementUtil.isEnumConstant(var)) {
// Enums are declared in an array, so we use a macro to shorten the
// array access expression.
return "JreEnum(" + className + ", " + shortName + ")";
}
return className + '_' + shortName;
}
return shortName;
}
/**
* Returns the name of an annotation property variable, extracted from its accessor element.
*/
public static String getAnnotationPropertyName(ExecutableElement element) {
return getMethodName(element);
}
/**
* Capitalize the first letter of a string.
*/
public static String capitalize(String s) {
return s.length() > 0 ? Character.toUpperCase(s.charAt(0)) + s.substring(1) : s;
}
/**
* Given a period-separated name, return as a camel-cased type name. For
* example, java.util.logging.Level is returned as JavaUtilLoggingLevel.
*/
public static String camelCaseQualifiedName(String fqn) {
StringBuilder sb = new StringBuilder();
for (String part : fqn.split("\\.")) {
sb.append(capitalize(part));
}
return sb.toString();
}
/**
* Given a path, return as a camel-cased name. Used, for example, in header guards.
*/
public static String camelCasePath(String fqn) {
StringBuilder sb = new StringBuilder();
for (String part : fqn.split(Pattern.quote(File.separator))) {
sb.append(capitalize(part));
}
return sb.toString();
}
private static final Pattern FAMILY_METHOD_REGEX =
Pattern.compile("^[_]*(new|copy|alloc|init|mutableCopy).*");
public static boolean needsObjcMethodFamilyNoneAttribute(String name) {
return FAMILY_METHOD_REGEX.matcher(name).matches();
}
private String getParameterTypeKeyword(TypeMirror type) {
int arrayDimensions = 0;
while (TypeUtil.isArray(type)) {
type = ((ArrayType) type).getComponentType();
arrayDimensions++;
}
String name;
if (type.getKind().isPrimitive()) {
name = TypeUtil.getName(type);
} else {
// For type variables, use the first bound for the parameter keyword.
List<? extends TypeMirror> bounds = typeUtil.getUpperBounds(type);
TypeElement elem = bounds.isEmpty()
? TypeUtil.NS_OBJECT : typeUtil.getObjcClass(bounds.get(0));
if (arrayDimensions == 0 && elem.equals(TypeUtil.NS_OBJECT)) {
// Special case: Non-array object types become "id".
return ID_TYPE;
}
name = getFullName(elem);
}
if (arrayDimensions > 0) {
name += "Array";
if (arrayDimensions > 1) {
name += arrayDimensions;
}
}
return name;
}
private String parameterKeyword(TypeMirror type) {
return "with" + capitalize(getParameterTypeKeyword(type));
}
private static final Pattern SELECTOR_VALIDATOR = Pattern.compile("\\w+|(\\w+\\:)+");
private static void validateMethodSelector(String selector) {
if (!SELECTOR_VALIDATOR.matcher(selector).matches()) {
ErrorUtil.error("Invalid method selector: " + selector);
}
}
public static String getMethodName(ExecutableElement method) {
if (ElementUtil.isConstructor(method)) {
return "init";
}
String name = ElementUtil.getName(method);
if (isReservedName(name)) {
name += "__";
}
return name;
}
private boolean appendParamKeyword(
StringBuilder sb, TypeMirror paramType, char delim, boolean first) {
String keyword = parameterKeyword(paramType);
if (first) {
keyword = capitalize(keyword);
}
sb.append(keyword).append(delim);
return false;
}
private String addParamNames(ExecutableElement method, String name, char delim) {
StringBuilder sb = new StringBuilder(name);
boolean first = true;
TypeElement declaringClass = ElementUtil.getDeclaringClass(method);
if (ElementUtil.isConstructor(method)) {
for (VariableElement param : captureInfo.getImplicitPrefixParams(declaringClass)) {
first = appendParamKeyword(sb, param.asType(), delim, first);
}
}
for (VariableElement param : method.getParameters()) {
first = appendParamKeyword(sb, param.asType(), delim, first);
}
if (ElementUtil.isConstructor(method)) {
for (VariableElement param : captureInfo.getImplicitPostfixParams(declaringClass)) {
first = appendParamKeyword(sb, param.asType(), delim, first);
}
}
return sb.toString();
}
public String getMethodSelector(ExecutableElement method) {
String selector = methodSelectorCache.get(method);
if (selector != null) {
return selector;
}
selector = getMethodSelectorInner(method);
methodSelectorCache.put(method, selector);
return selector;
}
private String getMethodSelectorInner(ExecutableElement method) {
String selector = ElementUtil.getSelector(method);
if (selector != null) {
return selector;
}
if (ElementUtil.isInstanceMethod(method)) {
method = getOriginalMethod(method);
}
selector = getRenamedMethodName(method);
return selectorForMethodName(method, selector != null ? selector : getMethodName(method));
}
private String getRenamedMethodName(ExecutableElement method) {
String selector = methodMappings.get(Mappings.getMethodKey(method, typeUtil));
if (selector != null) {
validateMethodSelector(selector);
return selector;
}
selector = getMethodNameFromAnnotation(method);
if (selector != null) {
return selector;
}
return null;
}
public String selectorForMethodName(ExecutableElement method, String name) {
if (name.contains(":")) {
return name;
}
return addParamNames(method, name, ':');
}
/**
* Returns a "Type_method" function name for static methods, such as from
* enum types. A combination of classname plus modified selector is
* guaranteed to be unique within the app.
*/
public String getFullFunctionName(ExecutableElement method) {
return getFullName(ElementUtil.getDeclaringClass(method)) + '_' + getFunctionName(method);
}
/**
* Increments and returns a generic argument, as needed by lambda wrapper blocks. Possible
* variable names range from 'a' to 'zz'. This only supports 676 arguments, but this more than the
* java limit of 255 / 254 parameters for static / non-static parameters, respectively.
*/
public static char[] incrementVariable(char[] var) {
if (var == null) {
return new char[] { 'a' };
}
if (var[var.length - 1]++ == 'z') {
if (var.length == 1) {
var = new char[2];
var[0] = 'a';
} else {
var[0]++;
}
var[1] = 'a';
}
return var;
}
/**
* Returns the name of the allocating constructor that returns a retained
* object. The name will take the form of "new_TypeName_ConstructorName".
*/
public String getAllocatingConstructorName(ExecutableElement method) {
return "new_" + getFullFunctionName(method);
}
/**
* Returns the name of the allocating constructor that returns a released
* object. The name will take the form of "create_TypeName_ConstructorName".
*/
public String getReleasingConstructorName(ExecutableElement method) {
return "create_" + getFullFunctionName(method);
}
/**
* Returns an appropriate name to use for this method as a function. This name
* is guaranteed to be unique within the declaring class, if no methods in the
* class have a renaming. The returned name should be given an appropriate
* prefix to avoid collisions with methods from other classes.
*/
public String getFunctionName(ExecutableElement method) {
String name = ElementUtil.getSelector(method);
if (name == null) {
name = getRenamedMethodName(method);
}
if (name != null) {
return name.replaceAll(":", "_");
} else {
return addParamNames(method, getMethodName(method), '_');
}
}
public static String getMethodNameFromAnnotation(ExecutableElement method) {
AnnotationMirror annotation = ElementUtil.getAnnotation(method, ObjectiveCName.class);
if (annotation != null) {
String value = (String) ElementUtil.getAnnotationValue(annotation, "value");
validateMethodSelector(value);
return value;
}
return null;
}
private ExecutableElement getOriginalMethod(ExecutableElement method) {
TypeElement declaringClass = ElementUtil.getDeclaringClass(method);
return getOriginalMethod(method, declaringClass, declaringClass);
}
/**
* Finds the original method element to use for generating a selector. The method returned is the
* first method found in the hierarchy while traversing in order of declared inheritance that
* doesn't override a method from a supertype. (ie. it is the first leaf node found in the tree of
* overriding methods)
*/
private ExecutableElement getOriginalMethod(
ExecutableElement topMethod, TypeElement declaringClass, TypeElement currentType) {
if (currentType == null) {
return null;
}
// TODO(tball): simplify to ElementUtil.getSuperclass() when javac update is complete.
TypeElement superclass = currentType.getKind().isInterface()
? typeUtil.getJavaObject() : ElementUtil.getSuperclass(currentType);
ExecutableElement original = getOriginalMethod(topMethod, declaringClass, superclass);
if (original != null) {
return original;
}
for (TypeMirror supertype : currentType.getInterfaces()) {
original = getOriginalMethod(topMethod, declaringClass, TypeUtil.asTypeElement(supertype));
if (original != null) {
return original;
}
}
if (declaringClass == currentType) {
return topMethod;
}
for (ExecutableElement candidate : ElementUtil.getMethods(currentType)) {
if (ElementUtil.isInstanceMethod(candidate)
&& elementUtil.overrides(topMethod, candidate, declaringClass)) {
return candidate;
}
}
return null;
}
/**
* Converts a Java type to an equivalent Objective-C type, returning "id" for an object type.
*/
public static String getPrimitiveObjCType(TypeMirror type) {
return TypeUtil.isVoid(type) ? "void"
: type.getKind().isPrimitive() ? "j" + TypeUtil.getName(type) : "id";
}
/**
* Convert a Java type to an equivalent Objective-C type with type variables
* resolved to their bounds.
*/
public String getObjCType(TypeMirror type) {
return getObjcTypeInner(type, null);
}
public String getObjCType(VariableElement var) {
return getObjcTypeInner(var.asType(), ElementUtil.getTypeQualifiers(var));
}
/**
* Convert a Java type into the equivalent JNI type.
*/
public String getJniType(TypeMirror type) {
if (TypeUtil.isPrimitiveOrVoid(type)) {
return getPrimitiveObjCType(type);
} else if (TypeUtil.isArray(type)) {
return "jarray";
} else if (typeUtil.isString(type)) {
return "jstring";
} else if (typeUtil.isClassType(type)) {
return "jclass";
}
return "jobject";
}
private String getObjcTypeInner(TypeMirror type, String qualifiers) {
String objcType;
if (type instanceof NativeType) {
objcType = ((NativeType) type).getName();
} else if (type instanceof PointerType) {
String pointeeQualifiers = null;
if (qualifiers != null) {
int idx = qualifiers.indexOf('*');
if (idx != -1) {
pointeeQualifiers = qualifiers.substring(0, idx);
qualifiers = qualifiers.substring(idx + 1);
}
}
objcType = getObjcTypeInner(((PointerType) type).getPointeeType(), pointeeQualifiers);
objcType = objcType.endsWith("*") ? objcType + "*" : objcType + " *";
} else if (TypeUtil.isPrimitiveOrVoid(type)) {
objcType = getPrimitiveObjCType(type);
} else {
objcType = constructObjcTypeFromBounds(type);
}
if (qualifiers != null) {
qualifiers = qualifiers.trim();
if (!qualifiers.isEmpty()) {
objcType += " " + qualifiers;
}
}
return objcType;
}
private String constructObjcTypeFromBounds(TypeMirror type) {
String classType = null;
List<String> interfaces = new ArrayList<>();
for (TypeElement bound : typeUtil.getObjcUpperBounds(type)) {
if (bound.getKind().isInterface()) {
interfaces.add(getFullName(bound));
} else {
assert classType == null : "Cannot have multiple class bounds";
classType = getFullName(bound);
}
}
String protocols = interfaces.isEmpty() ? "" : "<" + Joiner.on(", ").join(interfaces) + ">";
return classType == null ? ID_TYPE + protocols : classType + protocols + " *";
}
public static String getNativeEnumName(String typeName) {
return typeName + "_Enum";
}
/**
* Return the full name of a type, including its package. For outer types,
* is the type's full name; for example, java.lang.Object's full name is
* "JavaLangObject". For inner classes, the full name is their outer class'
* name plus the inner class name; for example, java.util.ArrayList.ListItr's
* name is "JavaUtilArrayList_ListItr".
*/
public String getFullName(TypeElement element) {
element = typeUtil.getObjcClass(element);
// Avoid package prefix renaming for package-info types, and use a valid ObjC name that doesn't
// have a dash character.
if (ElementUtil.isPackageInfo(element)) {
return camelCaseQualifiedName(ElementUtil.getName(ElementUtil.getPackage(element)))
+ PACKAGE_INFO_OBJC_NAME;
}
// Use ObjectiveCName annotation, if it exists.
AnnotationMirror annotation = ElementUtil.getAnnotation(element, ObjectiveCName.class);
if (annotation != null) {
return (String) ElementUtil.getAnnotationValue(annotation, "value");
}
TypeElement outerClass = ElementUtil.getDeclaringClass(element);
if (outerClass != null) {
return getFullName(outerClass) + '_' + getTypeSubName(element);
}
// Use mapping file entry, if it exists.
String mappedName = classMappings.get(ElementUtil.getQualifiedName(element));
if (mappedName != null) {
return mappedName;
}
// Use camel-cased package+class name.
return getPrefix(ElementUtil.getPackage(element)) + getTypeSubName(element);
}
private String getTypeSubName(TypeElement element) {
if (ElementUtil.isLambda(element)) {
return ElementUtil.getName(element);
} else if (ElementUtil.isLocal(element)) {
String binaryName = elementUtil.getBinaryName(element);
int innerClassIndex = ElementUtil.isAnonymous(element)
? binaryName.length() : binaryName.lastIndexOf(ElementUtil.getName(element));
while (innerClassIndex > 0 && binaryName.charAt(innerClassIndex - 1) != '$') {
--innerClassIndex;
}
return binaryName.substring(innerClassIndex);
}
return ElementUtil.getName(element).replace('$', '_');
}
private static boolean isReservedName(String name) {
return reservedNames.contains(name) || nsObjectMessages.contains(name);
}
public static String getMainTypeFullName(CompilationUnit unit) {
PackageElement pkgElement = unit.getPackage().getPackageElement();
return unit.getEnv().nameTable().getPrefix(pkgElement) + unit.getMainTypeName();
}
public String getPrefix(PackageElement packageElement) {
return prefixMap.getPrefix(packageElement);
}
}
| translator/src/main/java/com/google/devtools/j2objc/util/NameTable.java | /*
* Copyright 2011 Google 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.google.devtools.j2objc.util;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.ast.CompilationUnit;
import com.google.devtools.j2objc.types.NativeType;
import com.google.devtools.j2objc.types.PointerType;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.TypeMirror;
/**
* Singleton service for type/method/variable name support.
*
* @author Tom Ball
*/
public class NameTable {
private final TypeUtil typeUtil;
private final ElementUtil elementUtil;
private final CaptureInfo captureInfo;
private final Map<VariableElement, String> variableNames = new HashMap<>();
public static final String INIT_NAME = "init";
public static final String RETAIN_METHOD = "retain";
public static final String RELEASE_METHOD = "release";
public static final String DEALLOC_METHOD = "dealloc";
public static final String FINALIZE_METHOD = "finalize";
// The JDT compiler requires package-info files be named as "package-info",
// but that's an illegal type to generate.
public static final String PACKAGE_INFO_CLASS_NAME = "package-info";
private static final String PACKAGE_INFO_OBJC_NAME = "package_info";
// The self name in Java is reserved in Objective-C, but functionized methods
// actually want the first parameter to be self. This is an internal name,
// converted to self during generation.
public static final String SELF_NAME = "$$self$$";
public static final String ID_TYPE = "id";
// This is syntactic sugar for blocks. All block are typed as ids, but we add a block_type typedef
// for source clarity.
public static final String BLOCK_TYPE = "block_type";
private static final Logger logger = Logger.getLogger(NameTable.class.getName());
/**
* The list of predefined types, common primitive typedefs, constants and
* variables.
*/
public static final Set<String> reservedNames = Sets.newHashSet(
// types
"id", "bool", "BOOL", "SEL", "IMP", "unichar",
// constants
"nil", "Nil", "YES", "NO", "TRUE", "FALSE",
// C99 keywords
"auto", "const", "entry", "extern", "goto", "inline", "register", "restrict", "signed",
"sizeof", "struct", "typedef", "union", "unsigned", "volatile",
// C++ keywords
"and", "and_eq", "asm", "bitand", "bitor", "compl", "const_cast", "delete", "dynamic_cast",
"explicit", "export", "friend", "mutable", "namespace", "not", "not_eq", "operator", "or",
"or_eq", "reinterpret_cast", "static_cast", "template", "typeid", "typename", "using",
"virtual", "wchar_t", "xor", "xor_eq",
// variables
"self", "isa",
// Definitions from standard C and Objective-C headers, not including
// typedefs and #defines that start with "_", nor #defines for
// functions. Some of these may seem very unlikely to be used in
// Java source, but if a name is legal some Java developer might very
// well use it.
// Definitions from stddef.h
"ptrdiff_t", "size_t", "wchar_t", "wint_t",
// Definitions from stdint.h
"int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t",
"int_least8_t", "int_least16_t", "int_least32_t", "int_least64_t",
"uint_least8_t", "uint_least16_t", "uint_least32_t", "uint_least64_t",
"int_fast8_t", "int_fast16_t", "int_fast32_t", "int_fast64_t",
"uint_fast8_t", "uint_fast16_t", "uint_fast32_t", "uint_fast64_t",
"intptr_t", "uintptr_t", "intmax_t", "uintmax_t",
"INT8_MAX", "INT16_MAX", "INT32_MAX", "INT64_MAX", "INT8_MIN", "INT16_MIN", "INT32_MIN",
"INT64_MIN", "UINT8_MAX", "UINT16_MAX", "UINT32_MAX", "UINT64_MAX", "INT_LEAST8_MIN",
"INT_LEAST16_MIN", "INT_LEAST32_MIN", "INT_LEAST64_MIN", "INT_LEAST8_MAX", "INT_LEAST16_MAX",
"INT_LEAST32_MAX", "INT_LEAST64_MAX", "INT_FAST8_MIN", "INT_FAST16_MIN", "INT_FAST32_MIN",
"INT_FAST64_MIN", "INT_FAST8_MAX", "INT_FAST16_MAX", "INT_FAST32_MAX", "INT_FAST64_MAX",
"UINT_FAST8_MAX", "UINT_FAST16_MAX", "UINT_FAST32_MAX", "UINT_FAST64_MAX", "INTPTR_MIN",
"INTPTR_MAX", "UINTPTR_MAX", "INTMAX_MIN", "INTMAX_MAX", "UINTMAX_MAX", "PTRDIFF_MIN",
"PTRDIFF_MAX", "SIZE_MAX", "WCHAR_MAX", "WCHAR_MIN", "WINT_MIN", "WINT_MAX",
"SIG_ATOMIC_MIN", "SIG_ATOMIC_MAX", "INT8_MAX", "INT16_MAX", "INT32_MAX", "INT64_MAX",
"UINT8_C", "UINT16_C", "UINT32_C", "UINT64_C", "INTMAX_C", "UINTMAX_C",
// Definitions from stdio.h
"va_list", "fpos_t", "FILE", "off_t", "ssize_t", "BUFSIZ", "EOF", "FOPEN_MAX",
"FILENAME_MAX", "R_OK", "SEEK_SET", "SEEK_CUR", "SEEK_END", "stdin", "STDIN_FILENO",
"stdout", "STDOUT_FILENO", "stderr", "STDERR_FILENO", "TMP_MAX", "W_OK", "X_OK",
"sys_errlist",
// Definitions from stdlib.h
"ct_rune_t", "rune_t", "div_t", "ldiv_t", "lldiv_t", "dev_t", "mode_t",
"NULL", "EXIT_FAILURE", "EXIT_SUCCESS", "RAND_MAX", "MB_CUR_MAX", "MB_CUR_MAX_L",
// Definitions from errno.h
"errno", "EPERM", "ENOENT", "ESRCH", "EINTR", "EIO", "ENXIO", "E2BIG", "ENOEXEC",
"EBADF", "ECHILD", "EDEADLK", "ENOMEM", "EACCES", "EFAULT", "ENOTBLK", "EBUSY",
"EEXIST", "EXDEV", "ENODEV", "ENOTDIR", "EISDIR", "EINVAL", "ENFILE", "EMFILE",
"ENOTTY", "ETXTBSY", "EFBIG", "ENOSPC", "ESPIPE", "EROFS", "EMLINK", "EPIPE",
"EDOM", "ERANGE", "EAGAIN", "EWOULDBLOCK", "EINPROGRESS", "EALREADY", "ENOTSOCK",
"EDESTADDRREQ", "EMSGSIZE", "EPROTOTYPE", "ENOPROTOOPT", "EPROTONOSUPPORT",
"ESOCKTNOSUPPORT", "ENOTSUP", "ENOTSUPP", "EPFNOSUPPORT", "EAFNOSUPPORT", "EADDRINUSE",
"EADDRNOTAVAIL", "ENETDOWN", "ENETUNREACH", "ENETRESET", "ECONNABORTED", "ECONNRESET",
"ENOBUFS", "EISCONN", "ENOTCONN", "ESHUTDOWN", "ETOOMANYREFS", "ETIMEDOUT", "ECONNREFUSED",
"ELOOP", "ENAMETOOLONG", "EHOSTDOWN", "EHOSTUNREACH", "ENOTEMPTY", "EPROCLIM", "EUSERS",
"EDQUOT", "ESTALE", "EREMOTE", "EBADRPC", "ERPCMISMATCH", "EPROGUNAVAIL", "EPROGMISMATCH",
"EPROCUNAVAIL", "ENOLCK", "ENOSYS", "EFTYPE", "EAUTH", "ENEEDAUTH", "EPWROFF", "EDEVERR",
"EOVERFLOW", "EBADEXEC", "EBADARCH", "ESHLIBVERS", "EBADMACHO", "ECANCELED", "EIDRM",
"ENOMSG", "ENOATTR", "EBADMSG", "EMULTIHOP", "ENODATA", "ENOLINK", "ENOSR", "ENOSTR",
"EPROTO", "ETIME", "ENOPOLICY", "ENOTRECOVERABLE", "EOWNERDEAD", "EQFULL", "EILSEQ",
"EOPNOTSUPP", "ELAST",
// Definitions from fcntl.h
"F_DUPFD", "F_GETFD", "F_SETFD", "F_GETFL", "F_SETFL", "F_GETOWN", "F_SETOWN",
"F_GETLK", "F_SETLK", "F_SETLKW", "FD_CLOEXEC", "F_RDLCK", "F_UNLCK", "F_WRLCK",
"SEEK_SET", "SEEK_CUR", "SEEK_END",
"O_RDONLY", "O_WRONLY", "O_RDWR", "O_ACCMODE", "O_NONBLOCK", "O_APPEND", "O_SYNC", "O_CREAT",
"O_TRUNC", "O_EXCL", "O_NOCTTY", "O_NOFOLLOW",
// Definitions from math.h
"DOMAIN", "HUGE", "INFINITY", "NAN", "OVERFLOW", "SING", "UNDERFLOW", "signgam",
// Definitions from mman.h
"MAP_FIXED", "MAP_PRIVATE", "MAP_SHARED", "MCL_CURRENT", "MCL_FUTURE", "MS_ASYNC",
"MS_INVALIDATE", "MS_SYNC", "PROT_EXEC", "PROT_NONE", "PROT_READ", "PROT_WRITE",
// Definitions from netdb.h
"AI_ADDRCONFIG", "AI_ALL", "AI_CANONNAME", "AI_NUMERICHOST", "AI_NUMERICSERV",
"AI_PASSIVE", "AI_V4MAPPED", "EAI_AGAIN", "EAI_BADFLAGS", "EAI_FAIL", "EAI_FAMILY",
"EAI_MEMORY", "EAI_NODATA", "EAI_NONAME", "EAI_OVERFLOW", "EAI_SERVICE", "EAI_SOCKTYPE",
"EAI_SYSTEM", "HOST_NOT_FOUND", "NI_NAMEREQD", "NI_NUMERICHOST", "NO_DATA",
"NO_RECOVERY", "TRY_AGAIN",
// Definitions from net/if.h
"IFF_LOOPBACK", "IFF_MULTICAST", "IFF_POINTTOPOINT", "IFF_UP", "SIOCGIFADDR",
"SIOCGIFBRDADDR", "SIOCGIFNETMASK", "SIOCGIFDSTADDR",
// Definitions from netinet/in.h, in6.h
"IPPROTO_IP", "IPPROTO_IPV6", "IPPROTO_TCP", "IPV6_MULTICAST_HOPS", "IPV6_MULTICAST_IF",
"IP_MULTICAST_LOOP", "IPV6_TCLASS", "MCAST_JOIN_GROUP", "MCAST_JOIN_GROUP",
// Definitions from socket.h
"AF_INET", "AF_INET6", "AF_UNIX", "AF_UNSPEC", "MSG_OOB", "MSG_PEEK", "SHUT_RD", "SHUT_RDWR",
"SHUT_WR", "SOCK_DGRAM", "SOCK_STREAM", "SOL_SOCKET", "SO_BINDTODEVICE", "SO_BROADCAST",
"SO_ERROR", "SO_KEEPALIVE", "SO_LINGER", "SOOOBINLINE", "SO_REUSEADDR", "SO_RCVBUF",
"SO_RCVTIMEO", "SO_SNDBUF", "TCP_NODELAY",
// Definitions from stat.h
"S_IFBLK", "S_IFCHR", "S_IFDIR", "S_IFIFO", "S_IFLNK", "S_IFMT", "S_IFREG", "S_IFSOCK",
// Definitions from sys/poll.h
"POLLERR", "POLLHUP", "POLLIN", "POLLOUT",
// Definitions from sys/syslimits.h
"ARG_MAX", "LINE_MAX", "MAX_INPUT", "NAME_MAX", "NZERO", "PATH_MAX",
// Definitions from limits.h, machine/limits.h
"CHAR_BIT", "CHAR_MAX", "CHAR_MIN", "INT_MAX", "INT_MIN", "LLONG_MAX", "LLONG_MIN",
"LONG_BIT", "LONG_MAX", "LONG_MIN", "MB_LEN_MAX", "OFF_MIN", "OFF_MAX",
"PTHREAD_DESTRUCTOR_ITERATIONS", "PTHREAD_KEYS_MAX", "PTHREAD_STACK_MIN", "QUAD_MAX",
"QUAD_MIN", "SCHAR_MAX", "SCHAR_MIN", "SHRT_MAX", "SHRT_MIN", "SIZE_T_MAX", "SSIZE_MAX",
"UCHAR_MAX", "UINT_MAX", "ULONG_MAX", "UQUAD_MAX", "USHRT_MAX", "UULONG_MAX", "WORD_BIT",
// Definitions from time.h
"daylight", "getdate_err", "tzname",
// Definitions from types.h
"S_IRGRP", "S_IROTH", "S_IRUSR", "S_IRWXG", "S_IRWXO", "S_IRWXU", "S_IWGRP", "S_IWOTH",
"S_IWUSR", "S_IXGRP", "S_IXOTH", "S_IXUSR",
// Definitions from unistd.h
"F_OK", "R_OK", "STDERR_FILENO", "STDIN_FILENO", "STDOUT_FILENO", "W_OK", "X_OK",
"_SC_PAGESIZE", "_SC_PAGE_SIZE", "optind", "opterr", "optopt", "optreset",
// Cocoa definitions from ConditionalMacros.h
"CFMSYSTEMCALLS", "CGLUESUPPORTED", "FUNCTION_PASCAL", "FUNCTION_DECLSPEC",
"FUNCTION_WIN32CC", "GENERATING68881", "GENERATING68K", "GENERATINGCFM", "GENERATINGPOWERPC",
"OLDROUTINELOCATIONS", "PRAGMA_ALIGN_SUPPORTED", "PRAGMA_ENUM_PACK", "PRAGMA_ENUM_ALWAYSINT",
"PRAGMA_ENUM_OPTIONS", "PRAGMA_IMPORT", "PRAGMA_IMPORT_SUPPORTED", "PRAGMA_ONCE",
"PRAGMA_STRUCT_ALIGN", "PRAGMA_STRUCT_PACK", "PRAGMA_STRUCT_PACKPUSH",
"TARGET_API_MAC_CARBON", "TARGET_API_MAC_OS8", "TARGET_API_MAC_OSX", "TARGET_CARBON",
"TYPE_BOOL", "TYPE_EXTENDED", "TYPE_LONGDOUBLE_IS_DOUBLE", "TYPE_LONGLONG",
"UNIVERSAL_INTERFACES_VERSION",
// Core Foundation definitions
"BIG_ENDIAN", "BYTE_ORDER", "LITTLE_ENDIAN", "PDP_ENDIAN",
// CoreServices definitions
"positiveInfinity", "negativeInfinity",
// Common preprocessor definitions.
"DEBUG", "NDEBUG",
// Foundation methods with conflicting return types
"scale",
// Syntactic sugar for Objective-C block types
"block_type");
private static final Set<String> badParameterNames = Sets.newHashSet(
// Objective-C type qualifier keywords.
"in", "out", "inout", "oneway", "bycopy", "byref");
/**
* List of NSObject message names. Java methods with one of these names are
* renamed to avoid unintentional overriding. Message names with trailing
* colons are not included since they can't be overridden. For example,
* "public boolean isEqual(Object o)" would be translated as
* "- (BOOL)isEqualWithObject:(NSObject *)o", not NSObject's "isEqual:".
*/
public static final List<String> nsObjectMessages = Lists.newArrayList(
"alloc", "attributeKeys", "autoContentAccessingProxy", "autorelease",
"classCode", "classDescription", "classForArchiver",
"classForKeyedArchiver", "classFallbacksForKeyedArchiver",
"classForPortCoder", "className", "copy", "dealloc", "description",
"hash", "init", "initialize", "isProxy", "load", "mutableCopy", "new",
"release", "retain", "retainCount", "scriptingProperties", "self",
"superclass", "toManyRelationshipKeys", "toOneRelationshipKeys",
"version");
/**
* Map of package names to their specified prefixes. Multiple packages
* can share a prefix; for example, the com.google.common packages in
* Guava could share a "GG" (Google Guava) or simply "Guava" prefix.
*/
private final PackagePrefixes prefixMap;
private final ImmutableMap<String, String> classMappings;
private final ImmutableMap<String, String> methodMappings;
public NameTable(TypeUtil typeUtil, CaptureInfo captureInfo, Options options) {
this.typeUtil = typeUtil;
this.elementUtil = typeUtil.elementUtil();
this.captureInfo = captureInfo;
prefixMap = options.getPackagePrefixes();
classMappings = options.getMappings().getClassMappings();
methodMappings = options.getMappings().getMethodMappings();
}
public void setVariableName(VariableElement var, String name) {
String previousName = variableNames.get(var);
if (previousName != null && !previousName.equals(name)) {
logger.fine(String.format("Changing previous rename for variable: %s. Was: %s, now: %s",
var.toString(), previousName, name));
}
variableNames.put(var, name);
}
/**
* Gets the variable name without any qualifying class name or other prefix
* or suffix attached.
*/
public String getVariableBaseName(VariableElement var) {
return getVarBaseName(var, ElementUtil.isGlobalVar(var));
}
/**
* Gets the name of the accessor method for a static variable.
*/
public String getStaticAccessorName(VariableElement var) {
return getVarBaseName(var, false);
}
private String getVarBaseName(VariableElement var, boolean allowReservedName) {
String name = variableNames.get(var);
if (name != null) {
return name;
}
name = ElementUtil.getName(var);
if (allowReservedName) {
return name;
}
name = maybeRenameVar(var, name);
return name.equals(SELF_NAME) ? "self" : name;
}
private static String maybeRenameVar(VariableElement var, String name) {
if (isReservedName(name)) {
name += '_';
} else if (ElementUtil.isParameter(var) && badParameterNames.contains(name)) {
name += "Arg";
}
return name;
}
/**
* Gets the variable or parameter name that should be used in a doc-comment.
* This may be wrong if a variable is renamed by a translation phase, but will
* handle all the reserved and bad parameter renamings correctly.
*/
public static String getDocCommentVariableName(VariableElement var) {
return maybeRenameVar(var, ElementUtil.getName(var));
}
/**
* Gets the non-qualified variable name, with underscore suffix.
*/
public String getVariableShortName(VariableElement var) {
String baseName = getVariableBaseName(var);
if (var.getKind().isField() && !ElementUtil.isGlobalVar(var)) {
return baseName + '_';
}
return baseName;
}
/**
* Gets the name of the variable as it is declared in ObjC, fully qualified.
*/
public String getVariableQualifiedName(VariableElement var) {
String shortName = getVariableShortName(var);
if (ElementUtil.isGlobalVar(var)) {
String className = getFullName(ElementUtil.getDeclaringClass(var));
if (ElementUtil.isEnumConstant(var)) {
// Enums are declared in an array, so we use a macro to shorten the
// array access expression.
return "JreEnum(" + className + ", " + shortName + ")";
}
return className + '_' + shortName;
}
return shortName;
}
/**
* Returns the name of an annotation property variable, extracted from its accessor element.
*/
public static String getAnnotationPropertyName(ExecutableElement element) {
return getMethodName(element);
}
/**
* Capitalize the first letter of a string.
*/
public static String capitalize(String s) {
return s.length() > 0 ? Character.toUpperCase(s.charAt(0)) + s.substring(1) : s;
}
/**
* Given a period-separated name, return as a camel-cased type name. For
* example, java.util.logging.Level is returned as JavaUtilLoggingLevel.
*/
public static String camelCaseQualifiedName(String fqn) {
StringBuilder sb = new StringBuilder();
for (String part : fqn.split("\\.")) {
sb.append(capitalize(part));
}
return sb.toString();
}
/**
* Given a path, return as a camel-cased name. Used, for example, in header guards.
*/
public static String camelCasePath(String fqn) {
StringBuilder sb = new StringBuilder();
for (String part : fqn.split(Pattern.quote(File.separator))) {
sb.append(capitalize(part));
}
return sb.toString();
}
private static final Pattern FAMILY_METHOD_REGEX =
Pattern.compile("^[_]*(new|copy|alloc|init|mutableCopy).*");
public static boolean needsObjcMethodFamilyNoneAttribute(String name) {
return FAMILY_METHOD_REGEX.matcher(name).matches();
}
private String getParameterTypeKeyword(TypeMirror type) {
int arrayDimensions = 0;
while (TypeUtil.isArray(type)) {
type = ((ArrayType) type).getComponentType();
arrayDimensions++;
}
String name;
if (type.getKind().isPrimitive()) {
name = TypeUtil.getName(type);
} else {
// For type variables, use the first bound for the parameter keyword.
List<? extends TypeMirror> bounds = typeUtil.getUpperBounds(type);
TypeElement elem = bounds.isEmpty()
? TypeUtil.NS_OBJECT : typeUtil.getObjcClass(bounds.get(0));
if (arrayDimensions == 0 && elem.equals(TypeUtil.NS_OBJECT)) {
// Special case: Non-array object types become "id".
return ID_TYPE;
}
name = getFullName(elem);
}
if (arrayDimensions > 0) {
name += "Array";
if (arrayDimensions > 1) {
name += arrayDimensions;
}
}
return name;
}
private String parameterKeyword(TypeMirror type) {
return "with" + capitalize(getParameterTypeKeyword(type));
}
private static final Pattern SELECTOR_VALIDATOR = Pattern.compile("\\w+|(\\w+\\:)+");
private static void validateMethodSelector(String selector) {
if (!SELECTOR_VALIDATOR.matcher(selector).matches()) {
ErrorUtil.error("Invalid method selector: " + selector);
}
}
public static String getMethodName(ExecutableElement method) {
if (ElementUtil.isConstructor(method)) {
return "init";
}
String name = ElementUtil.getName(method);
if (isReservedName(name)) {
name += "__";
}
return name;
}
private boolean appendParamKeyword(
StringBuilder sb, TypeMirror paramType, char delim, boolean first) {
String keyword = parameterKeyword(paramType);
if (first) {
keyword = capitalize(keyword);
}
sb.append(keyword).append(delim);
return false;
}
private String addParamNames(ExecutableElement method, String name, char delim) {
StringBuilder sb = new StringBuilder(name);
boolean first = true;
TypeElement declaringClass = ElementUtil.getDeclaringClass(method);
if (ElementUtil.isConstructor(method)) {
for (VariableElement param : captureInfo.getImplicitPrefixParams(declaringClass)) {
first = appendParamKeyword(sb, param.asType(), delim, first);
}
}
for (VariableElement param : method.getParameters()) {
first = appendParamKeyword(sb, param.asType(), delim, first);
}
if (ElementUtil.isConstructor(method)) {
for (VariableElement param : captureInfo.getImplicitPostfixParams(declaringClass)) {
first = appendParamKeyword(sb, param.asType(), delim, first);
}
}
return sb.toString();
}
public String getMethodSelector(ExecutableElement method) {
String selector = ElementUtil.getSelector(method);
if (selector != null) {
return selector;
}
if (ElementUtil.isInstanceMethod(method)) {
method = getOriginalMethod(method);
}
selector = getRenamedMethodName(method);
return selectorForMethodName(method, selector != null ? selector : getMethodName(method));
}
private String getRenamedMethodName(ExecutableElement method) {
String selector = methodMappings.get(Mappings.getMethodKey(method, typeUtil));
if (selector != null) {
validateMethodSelector(selector);
return selector;
}
selector = getMethodNameFromAnnotation(method);
if (selector != null) {
return selector;
}
return null;
}
public String selectorForMethodName(ExecutableElement method, String name) {
if (name.contains(":")) {
return name;
}
return addParamNames(method, name, ':');
}
/**
* Returns a "Type_method" function name for static methods, such as from
* enum types. A combination of classname plus modified selector is
* guaranteed to be unique within the app.
*/
public String getFullFunctionName(ExecutableElement method) {
return getFullName(ElementUtil.getDeclaringClass(method)) + '_' + getFunctionName(method);
}
/**
* Increments and returns a generic argument, as needed by lambda wrapper blocks. Possible
* variable names range from 'a' to 'zz'. This only supports 676 arguments, but this more than the
* java limit of 255 / 254 parameters for static / non-static parameters, respectively.
*/
public static char[] incrementVariable(char[] var) {
if (var == null) {
return new char[] { 'a' };
}
if (var[var.length - 1]++ == 'z') {
if (var.length == 1) {
var = new char[2];
var[0] = 'a';
} else {
var[0]++;
}
var[1] = 'a';
}
return var;
}
/**
* Returns the name of the allocating constructor that returns a retained
* object. The name will take the form of "new_TypeName_ConstructorName".
*/
public String getAllocatingConstructorName(ExecutableElement method) {
return "new_" + getFullFunctionName(method);
}
/**
* Returns the name of the allocating constructor that returns a released
* object. The name will take the form of "create_TypeName_ConstructorName".
*/
public String getReleasingConstructorName(ExecutableElement method) {
return "create_" + getFullFunctionName(method);
}
/**
* Returns an appropriate name to use for this method as a function. This name
* is guaranteed to be unique within the declaring class, if no methods in the
* class have a renaming. The returned name should be given an appropriate
* prefix to avoid collisions with methods from other classes.
*/
public String getFunctionName(ExecutableElement method) {
String name = ElementUtil.getSelector(method);
if (name == null) {
name = getRenamedMethodName(method);
}
if (name != null) {
return name.replaceAll(":", "_");
} else {
return addParamNames(method, getMethodName(method), '_');
}
}
public static String getMethodNameFromAnnotation(ExecutableElement method) {
AnnotationMirror annotation = ElementUtil.getAnnotation(method, ObjectiveCName.class);
if (annotation != null) {
String value = (String) ElementUtil.getAnnotationValue(annotation, "value");
validateMethodSelector(value);
return value;
}
return null;
}
private ExecutableElement getOriginalMethod(ExecutableElement method) {
TypeElement declaringClass = ElementUtil.getDeclaringClass(method);
return getOriginalMethod(method, declaringClass, declaringClass);
}
/**
* Finds the original method element to use for generating a selector. The method returned is the
* first method found in the hierarchy while traversing in order of declared inheritance that
* doesn't override a method from a supertype. (ie. it is the first leaf node found in the tree of
* overriding methods)
*/
private ExecutableElement getOriginalMethod(
ExecutableElement topMethod, TypeElement declaringClass, TypeElement currentType) {
if (currentType == null) {
return null;
}
// TODO(tball): simplify to ElementUtil.getSuperclass() when javac update is complete.
TypeElement superclass = currentType.getKind().isInterface()
? typeUtil.getJavaObject() : ElementUtil.getSuperclass(currentType);
ExecutableElement original = getOriginalMethod(topMethod, declaringClass, superclass);
if (original != null) {
return original;
}
for (TypeMirror supertype : currentType.getInterfaces()) {
original = getOriginalMethod(topMethod, declaringClass, TypeUtil.asTypeElement(supertype));
if (original != null) {
return original;
}
}
if (declaringClass == currentType) {
return topMethod;
}
for (ExecutableElement candidate : ElementUtil.getMethods(currentType)) {
if (ElementUtil.isInstanceMethod(candidate)
&& elementUtil.overrides(topMethod, candidate, declaringClass)) {
return candidate;
}
}
return null;
}
/**
* Converts a Java type to an equivalent Objective-C type, returning "id" for an object type.
*/
public static String getPrimitiveObjCType(TypeMirror type) {
return TypeUtil.isVoid(type) ? "void"
: type.getKind().isPrimitive() ? "j" + TypeUtil.getName(type) : "id";
}
/**
* Convert a Java type to an equivalent Objective-C type with type variables
* resolved to their bounds.
*/
public String getObjCType(TypeMirror type) {
return getObjcTypeInner(type, null);
}
public String getObjCType(VariableElement var) {
return getObjcTypeInner(var.asType(), ElementUtil.getTypeQualifiers(var));
}
/**
* Convert a Java type into the equivalent JNI type.
*/
public String getJniType(TypeMirror type) {
if (TypeUtil.isPrimitiveOrVoid(type)) {
return getPrimitiveObjCType(type);
} else if (TypeUtil.isArray(type)) {
return "jarray";
} else if (typeUtil.isString(type)) {
return "jstring";
} else if (typeUtil.isClassType(type)) {
return "jclass";
}
return "jobject";
}
private String getObjcTypeInner(TypeMirror type, String qualifiers) {
String objcType;
if (type instanceof NativeType) {
objcType = ((NativeType) type).getName();
} else if (type instanceof PointerType) {
String pointeeQualifiers = null;
if (qualifiers != null) {
int idx = qualifiers.indexOf('*');
if (idx != -1) {
pointeeQualifiers = qualifiers.substring(0, idx);
qualifiers = qualifiers.substring(idx + 1);
}
}
objcType = getObjcTypeInner(((PointerType) type).getPointeeType(), pointeeQualifiers);
objcType = objcType.endsWith("*") ? objcType + "*" : objcType + " *";
} else if (TypeUtil.isPrimitiveOrVoid(type)) {
objcType = getPrimitiveObjCType(type);
} else {
objcType = constructObjcTypeFromBounds(type);
}
if (qualifiers != null) {
qualifiers = qualifiers.trim();
if (!qualifiers.isEmpty()) {
objcType += " " + qualifiers;
}
}
return objcType;
}
private String constructObjcTypeFromBounds(TypeMirror type) {
String classType = null;
List<String> interfaces = new ArrayList<>();
for (TypeElement bound : typeUtil.getObjcUpperBounds(type)) {
if (bound.getKind().isInterface()) {
interfaces.add(getFullName(bound));
} else {
assert classType == null : "Cannot have multiple class bounds";
classType = getFullName(bound);
}
}
String protocols = interfaces.isEmpty() ? "" : "<" + Joiner.on(", ").join(interfaces) + ">";
return classType == null ? ID_TYPE + protocols : classType + protocols + " *";
}
public static String getNativeEnumName(String typeName) {
return typeName + "_Enum";
}
/**
* Return the full name of a type, including its package. For outer types,
* is the type's full name; for example, java.lang.Object's full name is
* "JavaLangObject". For inner classes, the full name is their outer class'
* name plus the inner class name; for example, java.util.ArrayList.ListItr's
* name is "JavaUtilArrayList_ListItr".
*/
public String getFullName(TypeElement element) {
element = typeUtil.getObjcClass(element);
// Avoid package prefix renaming for package-info types, and use a valid ObjC name that doesn't
// have a dash character.
if (ElementUtil.isPackageInfo(element)) {
return camelCaseQualifiedName(ElementUtil.getName(ElementUtil.getPackage(element)))
+ PACKAGE_INFO_OBJC_NAME;
}
// Use ObjectiveCName annotation, if it exists.
AnnotationMirror annotation = ElementUtil.getAnnotation(element, ObjectiveCName.class);
if (annotation != null) {
return (String) ElementUtil.getAnnotationValue(annotation, "value");
}
TypeElement outerClass = ElementUtil.getDeclaringClass(element);
if (outerClass != null) {
return getFullName(outerClass) + '_' + getTypeSubName(element);
}
// Use mapping file entry, if it exists.
String mappedName = classMappings.get(ElementUtil.getQualifiedName(element));
if (mappedName != null) {
return mappedName;
}
// Use camel-cased package+class name.
return getPrefix(ElementUtil.getPackage(element)) + getTypeSubName(element);
}
private String getTypeSubName(TypeElement element) {
if (ElementUtil.isLambda(element)) {
return ElementUtil.getName(element);
} else if (ElementUtil.isLocal(element)) {
String binaryName = elementUtil.getBinaryName(element);
int innerClassIndex = ElementUtil.isAnonymous(element)
? binaryName.length() : binaryName.lastIndexOf(ElementUtil.getName(element));
while (innerClassIndex > 0 && binaryName.charAt(innerClassIndex - 1) != '$') {
--innerClassIndex;
}
return binaryName.substring(innerClassIndex);
}
return ElementUtil.getName(element).replace('$', '_');
}
private static boolean isReservedName(String name) {
return reservedNames.contains(name) || nsObjectMessages.contains(name);
}
public static String getMainTypeFullName(CompilationUnit unit) {
PackageElement pkgElement = unit.getPackage().getPackageElement();
return unit.getEnv().nameTable().getPrefix(pkgElement) + unit.getMainTypeName();
}
public String getPrefix(PackageElement packageElement) {
return prefixMap.getPrefix(packageElement);
}
}
| Cache method selectors
Method NameTable.getOriginalMethod() is one of the top methods in the translator's profile. This CL has 7-8% improvement on our Guava benchmark.
Change on 2017/01/27 by zgao <[email protected]>
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=145795279
| translator/src/main/java/com/google/devtools/j2objc/util/NameTable.java | Cache method selectors | <ide><path>ranslator/src/main/java/com/google/devtools/j2objc/util/NameTable.java
<ide> private final ElementUtil elementUtil;
<ide> private final CaptureInfo captureInfo;
<ide> private final Map<VariableElement, String> variableNames = new HashMap<>();
<add> private final Map<ExecutableElement, String> methodSelectorCache = new HashMap<>();
<ide>
<ide> public static final String INIT_NAME = "init";
<ide> public static final String RETAIN_METHOD = "retain";
<ide> }
<ide>
<ide> public String getMethodSelector(ExecutableElement method) {
<add> String selector = methodSelectorCache.get(method);
<add> if (selector != null) {
<add> return selector;
<add> }
<add> selector = getMethodSelectorInner(method);
<add> methodSelectorCache.put(method, selector);
<add> return selector;
<add> }
<add>
<add> private String getMethodSelectorInner(ExecutableElement method) {
<ide> String selector = ElementUtil.getSelector(method);
<ide> if (selector != null) {
<ide> return selector; |
|
JavaScript | mit | 31adbe9759c6a9d268763b7147f7680c5fee8119 | 0 | nicolasbeauvais/Walrus,nicolasbeauvais/Walrus,nicolasbeauvais/Walrus |
/**
* Walrus Framework
* File maintained by: Nicolas Beauvais (E-Wok)
* Created: 07:51 21/01/14.
*/
if (!window.jQuery) {
throw new Error('jQuery is needed to run Walrus.js');
}
var Walrus = {};
(function (Walrus) {
// walrus is a ninja
'use strict';
Walrus.config = {};
/**
* Walrus.js constructor.
*
* attributes:
*
* ajaxNavigation: true|false
* lazyLoad: true|false
*
* @param {Object} config
*/
Walrus.init = function (config) {
// default config
if (!config.ajaxNavigation) {config.ajaxNavigation = false; }
if (!config.pageContainer) {config.pageContainer = 'container'; }
if (!config.lazyLoad) {config.lazyLoad = false; }
Walrus.config = config;
if (Walrus.config.ajaxNavigation) { Walrus.ajaxNavigationInit(); }
Walrus.bootstrap();
};
Walrus.bootstrap = function () {
if (Walrus.config.lazyLoad) { Walrus.checkLazy(); }
};
Walrus.ajaxNavigationInit = function () {
$(document).click(Walrus.catchLinks);
$(window).on("popstate", function (event) {
if (event.originalEvent.state !== null) {
Walrus.ajaxNavigation(event, location.href, true);
}
});
};
/**
* Catch all clicked link.
*/
Walrus.catchLinks = function (event) {
var elem, $link, href;
elem = event.target;
if (elem.tagName !== 'A') {
$link = $(elem).parents('a:first');
} else {
$link = $(elem);
}
if ($link[0] === undefined) { return; }
href = $link.attr('href');
if (Walrus.isntExternal(href)) {
Walrus.ajaxNavigation(event, href);
event.stopPropagation();
event.preventDefault();
} else { return; }
};
/**
* Check if an url belongs to the current website.
*
* @param url
* @returns {boolean}
*/
Walrus.isntExternal = function (url) {
var local = location.href.replace(/^((https?:)?\/\/)?(www\.)?(\.)?/gi, '').split('/')[0];
url = url.replace(/^((https?:)?\/\/)?(www\.)?(\.)?/gi, '').split('/')[0];
return local === (url === '' ? local : url);
};
/**
* Handle the AJAX navigation.
*
* @param event
* @param url
*/
Walrus.ajaxNavigation = function (event, url, back) {
$.ajax({
url: url,
dataType: 'html',
async: false
}).done(function (data) {
var id,
$data,
$dataContainer,
$currentContainer;
id = Walrus.config.pageContainer;
$data = $('<div></div>').html(data);
$dataContainer = $data.find('#' + id);
$currentContainer = $('#' + id);
if ($dataContainer.length === 1 && $currentContainer.length === 1) {
if (!back) { history.pushState({url: url}, '', url); }
$currentContainer.html($dataContainer.html());
document.title = $data.find('title:first').text();
} else {
console.log('bad content');
}
$(document).trigger('pageLoaded');
Walrus.bootstrap();
event.preventDefault();
});
};
Walrus.checkLazy = function checkLazy() {
var $nodes;
// @TODO: find y data
$nodes = $(document).find('[data-lazyload]');
$nodes.each(function () {
$(this).load($(this).data('lazyload'));
});
};
}(Walrus));
/** @TODO:
* 2. lazyload
* 3. compile
* 4. long polling
* 5. breadcrumb
*/
| www/assets/javascript/Walrus.js |
/**
* Walrus Framework
* File maintained by: Nicolas Beauvais (E-Wok)
* Created: 07:51 21/01/14.
*/
if (!window.jQuery) {
throw new Error('jQuery is needed to run Walrus.js');
}
var Walrus = {};
(function (Walrus) {
// walrus is a ninja
'use strict';
Walrus.config = {};
/**
* Walrus.js constructor.
*
* attributes:
*
* ajaxNavigation: true|false
* lazyLoad: true|false
*
* @param {Object} config
*/
Walrus.init = function (config) {
// default config
if (!config.ajaxNavigation) {config.ajaxNavigation = false; }
if (!config.pageContainer) {config.pageContainer = 'container'; }
if (!config.lazyLoad) {config.lazyLoad = false; }
Walrus.config = config;
if (Walrus.config.ajaxNavigation) { Walrus.ajaxNavigationInit(); }
Walrus.bootstrap();
};
Walrus.bootstrap = function () {
if (Walrus.config.lazyLoad) { Walrus.checkLazy(); }
};
Walrus.ajaxNavigationInit = function () {
$(document).click(Walrus.catchLinks);
$(window).on("popstate", function (event) {
if (event.originalEvent.state !== null) {
Walrus.ajaxNavigation(event, location.href, true);
}
});
};
/**
* Catch all clicked link.
*/
Walrus.catchLinks = function (event) {
var elem, $link, href;
elem = event.target;
if (elem.tagName !== 'A') {
$link = $(elem).parents('a:first');
} else {
$link = $(elem);
}
if ($link[0] === undefined) { return; }
href = $link.attr('href');
if (Walrus.isntExternal(href)) {
Walrus.ajaxNavigation(event, href);
event.stopPropagation();
event.preventDefault();
} else { return; }
};
/**
* Check if an url belongs to the current website.
*
* @param url
* @returns {boolean}
*/
Walrus.isntExternal = function (url) {
var local = location.href.replace(/^((https?:)?\/\/)?(www\.)?(\.)?/gi, '').split('/')[0];
url = url.replace(/^((https?:)?\/\/)?(www\.)?(\.)?/gi, '').split('/')[0];
return local === (url === '' ? local : url);
};
/**
* Handle the AJAX navigation.
*
* @param event
* @param url
*/
Walrus.ajaxNavigation = function (event, url, back) {
$.ajax({
url: url,
dataType: 'html',
async: false
}).done(function (data) {
var id,
$data,
$dataContainer,
$currentContainer;
id = Walrus.config.pageContainer;
$data = $('<div></div>').html(data);
$dataContainer = $data.find('#' + id);
$currentContainer = $('#' + id);
if ($dataContainer.length === 1 && $currentContainer.length === 1) {
if (!back) { history.pushState({url: url}, '', url); }
$currentContainer.html($dataContainer.html());
document.title = $data.find('title:first').text();
} else {
console.log('bad content');
}
$(document).trigger('pageLoaded');
Walrus.bootstrap();
event.preventDefault();
});
};
Walrus.checkLazy = function checkLazy() {
var $nodes;
// @TODO: find y data
$nodes = $(document).find('[data-lazyload]');
$nodes.each(function () {
console.log($(this)[0]);
});
};
}(Walrus));
/** @TODO:
* 2. lazyload
* 3. compile
* 4. long polling
* 5. breadcrumb
*/
| Walrus.js: lazyload (jQuery version)
| www/assets/javascript/Walrus.js | Walrus.js: lazyload (jQuery version) | <ide><path>ww/assets/javascript/Walrus.js
<ide> // @TODO: find y data
<ide> $nodes = $(document).find('[data-lazyload]');
<ide> $nodes.each(function () {
<del> console.log($(this)[0]);
<add> $(this).load($(this).data('lazyload'));
<ide> });
<ide> };
<ide> |
|
Java | bsd-3-clause | 09797356a07c04c2e177ca443acf83c091568122 | 0 | slothspot/scala,shimib/scala,jvican/scala,felixmulder/scala,martijnhoekstra/scala,shimib/scala,lrytz/scala,jvican/scala,martijnhoekstra/scala,martijnhoekstra/scala,felixmulder/scala,felixmulder/scala,scala/scala,jvican/scala,slothspot/scala,slothspot/scala,lrytz/scala,jvican/scala,scala/scala,felixmulder/scala,shimib/scala,slothspot/scala,shimib/scala,lrytz/scala,slothspot/scala,scala/scala,martijnhoekstra/scala,martijnhoekstra/scala,jvican/scala,jvican/scala,shimib/scala,lrytz/scala,scala/scala,felixmulder/scala,jvican/scala,slothspot/scala,lrytz/scala,scala/scala,martijnhoekstra/scala,felixmulder/scala,slothspot/scala,lrytz/scala,felixmulder/scala,shimib/scala,scala/scala | /* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
\* */
// $OldId: ExpandMixins.java,v 1.24 2002/11/11 16:08:50 schinz Exp $
// $Id$
package scalac.transformer;
import scalac.*;
import scalac.util.*;
import scalac.ast.*;
import scalac.symtab.*;
import java.util.*;
import java.util.Arrays;
import Tree.*;
/**
* A transformer to expand mixins using code copying. We assume that
* links to outer classes have been made explicit by a previous phase.
*
* @author Michel Schinz
* @version 1.0
*/
// TODO do not copy hidden members which are not accessible via
// "super".
// TODO also substitute type parameters of classes in which the mixin
// is nested, if any. Do the same for the substitution of symbols in
// ThisTypes.
public class ExpandMixins extends Transformer {
// Mapping from (class) symbols to their definition.
protected final Map/*<Symbol,Tree>*/ classDefs;
protected final Definitions defs;
protected final AddInterfacesPhase addInterfaces;
public ExpandMixins(Global global, ExpandMixinsPhase descr) {
super(global);
defs = global.definitions;
classDefs = descr.classDefs;
addInterfaces = global.PHASE.ADDINTERFACES;
}
public void apply() {
ClassDefCollector collector = new ClassDefCollector(classDefs);
for (int i = 0; i < global.units.length; i++) {
Unit unit = global.units[i];
for (int j = 0; j < unit.body.length; ++j)
collector.traverse(unit.body[j]);
}
super.apply();
}
protected void typeSubst(Type type, ArrayList f, ArrayList a) {
switch (type) {
case TypeRef(Type pre, Symbol sym, Type[] args): {
Symbol s = addInterfaces.getClassSymbol(sym);
f.addAll(Arrays.asList(s.typeParams()));
a.addAll(Arrays.asList(args));
typeSubst(pre, f, a);
} break;
default:
; // nothing to do
}
}
protected Object[] typeSubst(Type type) {
ArrayList/*<Symbol[]>*/ f = new ArrayList();
ArrayList/*<Type[]>*/ a = new ArrayList();
typeSubst(type, f, a);
return new Object[] {
f.toArray(new Symbol[f.size()]), a.toArray(new Type[a.size()])
};
}
protected void getArgsSection(Tree tree, List s) {
switch(tree) {
case Apply(Tree fun, Tree[] args):
getArgsSection(fun, s);
s.add(args);
break;
default:
; // nothing to do
}
}
protected Tree[][] getArgsSection(Tree tree) {
List s = new ArrayList();
getArgsSection(tree, s);
return (Tree[][])s.toArray(new Tree[s.size()][]);
}
protected Map/*<Template,Template>*/ expansions = new HashMap();
protected Template getMixinExpandedTemplate(Template tree, Symbol owner) {
if (! expansions.containsKey(tree))
expansions.put(tree, expandMixins(tree, owner));
return (Template)expansions.get(tree);
}
protected Template expandMixins(Template tree, final Symbol owner) {
Type templType = owner.info();
List/*<Tree>*/ newBody = new ArrayList();
Scope newMembers = new Scope();
Symbol newTemplSymbol = tree.symbol().cloneSymbol();
// Start by copying the statement sequence.
Tree[] body = tree.body;
for (int i = 0; i < body.length; ++i) {
Tree stat = body[i];
newBody.add(transform(stat));
if (stat.definesSymbol()) {
Symbol sym = stat.symbol();
newMembers.enterOrOverload(sym);
}
}
Type[] baseTypes = owner.parents();
global.log("baseTypes for " + Debug.show(owner)
+ " = <" + ArrayApply.toString(baseTypes) + ">");
// Then go over the mixins and mix them in.
SymbolCloner symbolCloner =
new SymbolCloner(global.freshNameCreator);
for (int bcIndex = tree.parents.length - 1; bcIndex > 0; --bcIndex) {
SymbolSubstTypeMap typeCloner = new SymbolSubstTypeMap();
Tree bc = tree.parents[bcIndex];
final Symbol bcSym = baseTypes[bcIndex].symbol();
symbolCloner.owners.put(bcSym, owner);
symbolCloner.owners.put(bcSym.constructor(), owner);
if ((bcSym.flags & Modifiers.INTERFACE) != 0)
continue;
assert classDefs.containsKey(bcSym) : bcSym;
ClassDef bcDef = (ClassDef)classDefs.get(bcSym);
// Create substitution for mixin's type parameters.
Object[] ts = typeSubst(baseTypes[bcIndex]);
assert ts.length == 2;
final Symbol[] tpFormals = (Symbol[])ts[0];
final Type[] tpActuals = (Type[])ts[1];
assert tpFormals.length == tpActuals.length;
Type.Map typeMap = new Type.Map() {
public Type apply(Type t) {
Type t1 = t.asSeenFrom(owner.thisType(), bcSym);
Type t2 = t1.subst(tpFormals, tpActuals);
return t2;
}
};
typeCloner.insertType(tpFormals, tpActuals);
// Create private fields for mixin's value parameters.
Tree[][] actuals = getArgsSection(bc);
assert bcDef.vparams.length == actuals.length;
for (int s = 0; s < bcDef.vparams.length; ++s) {
ValDef[] sectionF = bcDef.vparams[s];
Tree[] sectionA = actuals[s];
assert sectionF.length == sectionA.length;
for (int p = 0; p < sectionF.length; ++p) {
// We do not need to copy the actual parameters,
// since they are removed from their original
// location anyway.
ValDef formal = sectionF[p];
Tree actual = sectionA[p];
Symbol memberSymbol =
symbolCloner.cloneSymbol(formal.symbol(), true);
Type memberType = typeMap.apply(formal.tpe.type());
memberSymbol.updateInfo(memberType);
Tree memberDef = gen.ValDef(memberSymbol, actual);
newBody.add(memberDef);
typeCloner.insertSymbol(formal.symbol(), memberSymbol);
}
}
Template mixin = getMixinExpandedTemplate(bcDef.impl, bcSym);
Type bcType = mixin.type();
Tree[] mixinBody = mixin.body;
Map newNames = new HashMap();
// Pass 1: compute members to rename.
for (int m = 0; m < mixinBody.length; ++m) {
Tree member = mixinBody[m];
if (!member.definesSymbol()) continue;
Symbol symbol = member.symbol();
Name newName = (Name)newNames.get(symbol.name);
boolean shadowed = newName == null &&
newMembers.lookup(symbol.name) != Symbol.NONE;
if (shadowed && symbol.isDeferred()) continue;
Symbol clone = symbolCloner.cloneSymbol(symbol, shadowed);
if (newName != null)
clone.name = newName;
else
newNames.put(symbol.name, clone.name);
typeCloner.insertSymbol(symbol, clone);
newMembers.enterOrOverload(clone);
}
// Pass 2: copy members
TreeSymbolCloner treeSymbolCloner =
new TreeSymbolCloner(symbolCloner);
TreeCloner treeCloner = new TreeCloner(
global, symbolCloner.clones, typeCloner);
for (int m = 0; m < mixinBody.length; ++m) {
Tree member = mixinBody[m];
if (symbolCloner.clones.containsKey(member.symbol())) {
treeSymbolCloner.traverse(member);
newBody.add(treeCloner.transform(member));
}
}
}
// Modify mixin base classes to refer to interfaces instead of
// real classes.
Type[] newBaseTypes = new Type[baseTypes.length];
Tree[] newBaseClasses = new Tree[tree.parents.length];
newBaseTypes[0] = baseTypes[0];
newBaseClasses[0] = tree.parents[0];
for (int i = 1; i < baseTypes.length; ++i) {
switch (baseTypes[i]) {
case TypeRef(Type pre, Symbol sym, Type[] args): {
if (!Modifiers.Helper.isInterface(sym.flags))
sym = addInterfaces.getInterfaceSymbol(sym);
newBaseClasses[i] =
gen.mkParentConstr(tree.pos, new Type.TypeRef(pre, sym, args));
newBaseTypes[i] = new Type.TypeRef(pre, sym, args);
} break;
default:
throw global.fail("invalid base class type", baseTypes[i]);
}
}
Tree[] fixedBody = (Tree[])newBody.toArray(new Tree[newBody.size()]);
SuperFixer superFixer = new SuperFixer(
global, owner, symbolCloner.clones);
for (int i = 0; i < body.length; ++i) {
fixedBody[i] = superFixer.transform(fixedBody[i]);
}
Template newTree = make.Template(tree.pos, newBaseClasses, fixedBody);
newTree.setSymbol(newTemplSymbol);
newTree.setType(Type.compoundType(newBaseTypes, newMembers, owner));
return newTree;
}
public Tree transform(Tree tree) {
switch (tree) {
case ClassDef(_,
_,
TypeDef[] tparams,
ValDef[][] vparams,
Tree tpe,
Template impl):
Symbol sym = tree.symbol();
if (Modifiers.Helper.isInterface(sym.flags))
return super.transform(tree);
else {
global.log("expanding " + Debug.show(tree.symbol()));
Tree.ClassDef newClass = (Tree.ClassDef)
copy.ClassDef(tree,
sym,
super.transform(tparams),
super.transform(vparams),
super.transform(tpe),
getMixinExpandedTemplate(impl, sym));
newClass.symbol().updateInfo(newClass.impl.type);
return newClass;
}
default:
return super.transform(tree);
}
}
//########################################################################
// Return a hash table associating class definitions to (class) symbols.
protected static class ClassDefCollector extends Traverser {
private Map map;
public ClassDefCollector(Map map) {
this.map = map;
}
public void traverse(Tree tree) {
switch(tree) {
case ClassDef(_, _, _, _, _, _):
map.put(tree.symbol(), tree);
break;
default:
; // nothing to do
}
super.traverse(tree);
}
}
//########################################################################
// Private Class - MyTreeCloner
private static class SuperFixer extends Transformer {
private final Symbol clasz;
private final Map/*<Symbol,Symbol>*/ symbols;
public SuperFixer(Global global, Symbol clasz, Map symbols) {
super(global);
this.clasz = clasz;
this.symbols = symbols;
}
public Tree transform(Tree tree) {
switch (tree) {
case Select(Super(Tree qualifier), _):
Symbol symbol = (Symbol)symbols.get(tree.symbol());
if (symbol != null) {
Tree self = gen.This(((Select)tree).qualifier.pos, clasz);
return gen.Select(tree.pos, self, symbol);
}
}
return super.transform(tree);
}
}
//########################################################################
}
| sources/scalac/transformer/ExpandMixins.java | /* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
\* */
// $OldId: ExpandMixins.java,v 1.24 2002/11/11 16:08:50 schinz Exp $
// $Id$
package scalac.transformer;
import scalac.*;
import scalac.util.*;
import scalac.ast.*;
import scalac.symtab.*;
import java.util.*;
import java.util.Arrays;
import Tree.*;
/**
* A transformer to expand mixins using code copying. We assume that
* links to outer classes have been made explicit by a previous phase.
*
* @author Michel Schinz
* @version 1.0
*/
// TODO do not copy hidden members which are not accessible via
// "super".
// TODO also substitute type parameters of classes in which the mixin
// is nested, if any. Do the same for the substitution of symbols in
// ThisTypes.
public class ExpandMixins extends Transformer {
// Mapping from (class) symbols to their definition.
protected final Map/*<Symbol,Tree>*/ classDefs;
protected final Definitions defs;
protected final AddInterfacesPhase addInterfaces;
public ExpandMixins(Global global, ExpandMixinsPhase descr) {
super(global);
defs = global.definitions;
classDefs = descr.classDefs;
addInterfaces = global.PHASE.ADDINTERFACES;
}
public void apply() {
ClassDefCollector collector = new ClassDefCollector(classDefs);
for (int i = 0; i < global.units.length; i++) {
Unit unit = global.units[i];
for (int j = 0; j < unit.body.length; ++j)
collector.traverse(unit.body[j]);
}
super.apply();
}
protected void typeSubst(Type type, ArrayList f, ArrayList a) {
switch (type) {
case TypeRef(Type pre, Symbol sym, Type[] args): {
Symbol s = addInterfaces.getClassSymbol(sym);
f.addAll(Arrays.asList(s.typeParams()));
a.addAll(Arrays.asList(args));
typeSubst(pre, f, a);
} break;
default:
; // nothing to do
}
}
protected Object[] typeSubst(Type type) {
ArrayList/*<Symbol[]>*/ f = new ArrayList();
ArrayList/*<Type[]>*/ a = new ArrayList();
typeSubst(type, f, a);
return new Object[] {
f.toArray(new Symbol[f.size()]), a.toArray(new Type[a.size()])
};
}
protected void getArgsSection(Tree tree, List s) {
switch(tree) {
case Apply(Tree fun, Tree[] args):
getArgsSection(fun, s);
s.add(args);
break;
default:
; // nothing to do
}
}
protected Tree[][] getArgsSection(Tree tree) {
List s = new ArrayList();
getArgsSection(tree, s);
return (Tree[][])s.toArray(new Tree[s.size()][]);
}
protected Map/*<Template,Template>*/ expansions = new HashMap();
protected Template getMixinExpandedTemplate(Template tree, Symbol owner) {
if (! expansions.containsKey(tree))
expansions.put(tree, expandMixins(tree, owner));
return (Template)expansions.get(tree);
}
protected Template expandMixins(Template tree, final Symbol owner) {
Type templType = owner.info();
List/*<Tree>*/ newBody = new ArrayList();
Scope newMembers = new Scope();
Symbol newTemplSymbol = tree.symbol().cloneSymbol();
// Start by copying the statement sequence.
Tree[] body = tree.body;
for (int i = 0; i < body.length; ++i) {
Tree stat = body[i];
newBody.add(transform(stat));
if (stat.definesSymbol()) {
Symbol sym = stat.symbol();
newMembers.enterOrOverload(sym);
}
}
Type[] baseTypes = owner.parents();
global.log("baseTypes for " + Debug.show(owner)
+ " = <" + ArrayApply.toString(baseTypes) + ">");
// Then go over the mixins and mix them in.
for (int bcIndex = tree.parents.length - 1; bcIndex > 0; --bcIndex) {
SymbolCloner symbolCloner =
new SymbolCloner(global.freshNameCreator);
SymbolSubstTypeMap typeCloner = new SymbolSubstTypeMap();
Tree bc = tree.parents[bcIndex];
final Symbol bcSym = baseTypes[bcIndex].symbol();
symbolCloner.owners.put(bcSym, owner);
symbolCloner.owners.put(bcSym.constructor(), owner);
if ((bcSym.flags & Modifiers.INTERFACE) != 0)
continue;
assert classDefs.containsKey(bcSym) : bcSym;
ClassDef bcDef = (ClassDef)classDefs.get(bcSym);
// Create substitution for mixin's type parameters.
Object[] ts = typeSubst(baseTypes[bcIndex]);
assert ts.length == 2;
final Symbol[] tpFormals = (Symbol[])ts[0];
final Type[] tpActuals = (Type[])ts[1];
assert tpFormals.length == tpActuals.length;
Type.Map typeMap = new Type.Map() {
public Type apply(Type t) {
Type t1 = t.asSeenFrom(owner.thisType(), bcSym);
Type t2 = t1.subst(tpFormals, tpActuals);
return t2;
}
};
typeCloner.insertType(tpFormals, tpActuals);
// Create private fields for mixin's value parameters.
Tree[][] actuals = getArgsSection(bc);
assert bcDef.vparams.length == actuals.length;
for (int s = 0; s < bcDef.vparams.length; ++s) {
ValDef[] sectionF = bcDef.vparams[s];
Tree[] sectionA = actuals[s];
assert sectionF.length == sectionA.length;
for (int p = 0; p < sectionF.length; ++p) {
// We do not need to copy the actual parameters,
// since they are removed from their original
// location anyway.
ValDef formal = sectionF[p];
Tree actual = sectionA[p];
Symbol memberSymbol =
symbolCloner.cloneSymbol(formal.symbol(), true);
Type memberType = typeMap.apply(formal.tpe.type());
memberSymbol.updateInfo(memberType);
Tree memberDef = gen.ValDef(memberSymbol, actual);
newBody.add(memberDef);
typeCloner.insertSymbol(formal.symbol(), memberSymbol);
}
}
Template mixin = getMixinExpandedTemplate(bcDef.impl, bcSym);
Type bcType = mixin.type();
Tree[] mixinBody = mixin.body;
Map newNames = new HashMap();
// Pass 1: compute members to rename.
for (int m = 0; m < mixinBody.length; ++m) {
Tree member = mixinBody[m];
if (!member.definesSymbol()) continue;
Symbol symbol = member.symbol();
Name newName = (Name)newNames.get(symbol.name);
boolean shadowed = newName == null &&
newMembers.lookup(symbol.name) != Symbol.NONE;
if (shadowed && symbol.isDeferred()) continue;
Symbol clone = symbolCloner.cloneSymbol(symbol, shadowed);
if (newName != null)
clone.name = newName;
else
newNames.put(symbol.name, clone.name);
typeCloner.insertSymbol(symbol, clone);
newMembers.enterOrOverload(clone);
}
// Pass 2: copy members
TreeSymbolCloner treeSymbolCloner =
new TreeSymbolCloner(symbolCloner);
TreeCloner treeCloner = new MyTreeCloner(
global, symbolCloner.clones, typeCloner, owner);
for (int m = 0; m < mixinBody.length; ++m) {
Tree member = mixinBody[m];
if (symbolCloner.clones.containsKey(member.symbol())) {
treeSymbolCloner.traverse(member);
newBody.add(treeCloner.transform(member));
}
}
}
// Modify mixin base classes to refer to interfaces instead of
// real classes.
Type[] newBaseTypes = new Type[baseTypes.length];
Tree[] newBaseClasses = new Tree[tree.parents.length];
newBaseTypes[0] = baseTypes[0];
newBaseClasses[0] = tree.parents[0];
for (int i = 1; i < baseTypes.length; ++i) {
switch (baseTypes[i]) {
case TypeRef(Type pre, Symbol sym, Type[] args): {
if (!Modifiers.Helper.isInterface(sym.flags))
sym = addInterfaces.getInterfaceSymbol(sym);
newBaseClasses[i] =
gen.mkParentConstr(tree.pos, new Type.TypeRef(pre, sym, args));
newBaseTypes[i] = new Type.TypeRef(pre, sym, args);
} break;
default:
throw global.fail("invalid base class type", baseTypes[i]);
}
}
Tree[] fixedBody = (Tree[])newBody.toArray(new Tree[newBody.size()]);
Template newTree = make.Template(tree.pos, newBaseClasses, fixedBody);
newTree.setSymbol(newTemplSymbol);
newTree.setType(Type.compoundType(newBaseTypes, newMembers, owner));
return newTree;
}
public Tree transform(Tree tree) {
switch (tree) {
case ClassDef(_,
_,
TypeDef[] tparams,
ValDef[][] vparams,
Tree tpe,
Template impl):
Symbol sym = tree.symbol();
if (Modifiers.Helper.isInterface(sym.flags))
return super.transform(tree);
else {
global.log("expanding " + Debug.show(tree.symbol()));
Tree.ClassDef newClass = (Tree.ClassDef)
copy.ClassDef(tree,
sym,
super.transform(tparams),
super.transform(vparams),
super.transform(tpe),
getMixinExpandedTemplate(impl, sym));
newClass.symbol().updateInfo(newClass.impl.type);
return newClass;
}
default:
return super.transform(tree);
}
}
//########################################################################
// Return a hash table associating class definitions to (class) symbols.
protected static class ClassDefCollector extends Traverser {
private Map map;
public ClassDefCollector(Map map) {
this.map = map;
}
public void traverse(Tree tree) {
switch(tree) {
case ClassDef(_, _, _, _, _, _):
map.put(tree.symbol(), tree);
break;
default:
; // nothing to do
}
super.traverse(tree);
}
}
//########################################################################
// Private Class - MyTreeCloner
private static class MyTreeCloner extends TreeCloner {
private final Symbol clasz;
public MyTreeCloner(Global global, Map symbols, Type.Map types,
Symbol clasz)
{
super(global, symbols, types);
this.clasz = clasz;
}
public Tree transform(Tree tree) {
switch (tree) {
case Super(Tree qualifier):
return gen.This(tree.pos, clasz);
default:
return super.transform(tree);
}
}
}
//########################################################################
}
| - Replaced subclass of TreeCloner by SuperFixer
| sources/scalac/transformer/ExpandMixins.java | - Replaced subclass of TreeCloner by SuperFixer | <ide><path>ources/scalac/transformer/ExpandMixins.java
<ide> + " = <" + ArrayApply.toString(baseTypes) + ">");
<ide>
<ide> // Then go over the mixins and mix them in.
<add> SymbolCloner symbolCloner =
<add> new SymbolCloner(global.freshNameCreator);
<ide> for (int bcIndex = tree.parents.length - 1; bcIndex > 0; --bcIndex) {
<del> SymbolCloner symbolCloner =
<del> new SymbolCloner(global.freshNameCreator);
<ide> SymbolSubstTypeMap typeCloner = new SymbolSubstTypeMap();
<ide> Tree bc = tree.parents[bcIndex];
<ide>
<ide> // Pass 2: copy members
<ide> TreeSymbolCloner treeSymbolCloner =
<ide> new TreeSymbolCloner(symbolCloner);
<del> TreeCloner treeCloner = new MyTreeCloner(
<del> global, symbolCloner.clones, typeCloner, owner);
<add> TreeCloner treeCloner = new TreeCloner(
<add> global, symbolCloner.clones, typeCloner);
<ide> for (int m = 0; m < mixinBody.length; ++m) {
<ide> Tree member = mixinBody[m];
<ide> if (symbolCloner.clones.containsKey(member.symbol())) {
<ide> }
<ide>
<ide> Tree[] fixedBody = (Tree[])newBody.toArray(new Tree[newBody.size()]);
<add> SuperFixer superFixer = new SuperFixer(
<add> global, owner, symbolCloner.clones);
<add> for (int i = 0; i < body.length; ++i) {
<add> fixedBody[i] = superFixer.transform(fixedBody[i]);
<add> }
<ide> Template newTree = make.Template(tree.pos, newBaseClasses, fixedBody);
<ide> newTree.setSymbol(newTemplSymbol);
<ide> newTree.setType(Type.compoundType(newBaseTypes, newMembers, owner));
<ide> //########################################################################
<ide> // Private Class - MyTreeCloner
<ide>
<del> private static class MyTreeCloner extends TreeCloner {
<add> private static class SuperFixer extends Transformer {
<ide>
<ide> private final Symbol clasz;
<del>
<del> public MyTreeCloner(Global global, Map symbols, Type.Map types,
<del> Symbol clasz)
<del> {
<del> super(global, symbols, types);
<add> private final Map/*<Symbol,Symbol>*/ symbols;
<add>
<add> public SuperFixer(Global global, Symbol clasz, Map symbols) {
<add> super(global);
<ide> this.clasz = clasz;
<add> this.symbols = symbols;
<ide> }
<ide>
<ide> public Tree transform(Tree tree) {
<ide> switch (tree) {
<del> case Super(Tree qualifier):
<del> return gen.This(tree.pos, clasz);
<del> default:
<del> return super.transform(tree);
<del> }
<add> case Select(Super(Tree qualifier), _):
<add> Symbol symbol = (Symbol)symbols.get(tree.symbol());
<add> if (symbol != null) {
<add> Tree self = gen.This(((Select)tree).qualifier.pos, clasz);
<add> return gen.Select(tree.pos, self, symbol);
<add> }
<add> }
<add> return super.transform(tree);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 4cce9b5b978006f1d6a8f075f05f6c60f428de8c | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchdefinition;
import com.yahoo.searchlib.rankingexpression.Reference;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* Utility methods for query, document and constant rank feature names
*
* @author bratseth
*/
public class FeatureNames {
private static final Pattern identifierRegexp = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_-]*");
public static Reference asConstantFeature(String constantName) {
return Reference.simple("constant", quoteIfNecessary(constantName));
}
public static Reference asAttributeFeature(String attributeName) {
return Reference.simple("attribute", attributeName);
}
public static Reference asQueryFeature(String propertyName) {
return Reference.simple("query", quoteIfNecessary(propertyName));
}
/** Returns true if the given reference is an attribute, constant or query feature */
public static boolean isSimpleFeature(Reference reference) {
if ( ! reference.isSimple()) return false;
String name = reference.name();
return name.equals("attribute") || name.equals("constant") || name.equals("query");
}
/** Returns true if this is a constant */
public static boolean isConstantFeature(Reference reference) {
if ( ! isSimpleFeature(reference)) return false;
return reference.name().equals("constant");
}
/**
* Returns the single argument of the given feature name, without any quotes,
* or empty if it is not a valid query, attribute or constant feature name
*/
public static Optional<String> argumentOf(String feature) {
Optional<Reference> reference = Reference.simple(feature);
if ( ! reference.isPresent()) return Optional.empty();
if ( ! ( reference.get().name().equals("attribute") ||
reference.get().name().equals("constant") ||
reference.get().name().equals("query")))
return Optional.empty();
return Optional.of(reference.get().arguments().expressions().get(0).toString());
}
private static String quoteIfNecessary(String s) {
if (identifierRegexp.matcher(s).matches())
return s;
else
return "\"" + s + "\"";
}
}
| config-model/src/main/java/com/yahoo/searchdefinition/FeatureNames.java | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchdefinition;
import com.yahoo.searchlib.rankingexpression.Reference;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* Utility methods for query, document and constant rank feature names
*
* @author bratseth
*/
public class FeatureNames {
private static final Pattern identifierRegexp = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_-]*");
public static Reference asConstantFeature(String constantName) {
return Reference.simple("constant", quoteIfNecessary(constantName));
}
public static Reference asAttributeFeature(String attributeName) {
return Reference.simple("attribute", quoteIfNecessary(attributeName));
}
public static Reference asQueryFeature(String propertyName) {
return Reference.simple("query", quoteIfNecessary(propertyName));
}
/** Returns true if the given reference is an attribute, constant or query feature */
public static boolean isSimpleFeature(Reference reference) {
if ( ! reference.isSimple()) return false;
String name = reference.name();
return name.equals("attribute") || name.equals("constant") || name.equals("query");
}
/** Returns true if this is a constant */
public static boolean isConstantFeature(Reference reference) {
if ( ! isSimpleFeature(reference)) return false;
return reference.name().equals("constant");
}
/**
* Returns the single argument of the given feature name, without any quotes,
* or empty if it is not a valid query, attribute or constant feature name
*/
public static Optional<String> argumentOf(String feature) {
Optional<Reference> reference = Reference.simple(feature);
if ( ! reference.isPresent()) return Optional.empty();
if ( ! ( reference.get().name().equals("attribute") ||
reference.get().name().equals("constant") ||
reference.get().name().equals("query")))
return Optional.empty();
return Optional.of(reference.get().arguments().expressions().get(0).toString());
}
private static String quoteIfNecessary(String s) {
if (identifierRegexp.matcher(s).matches())
return s;
else
return "\"" + s + "\"";
}
}
| Attributes must be identifiers so no need for extra regex check for them.
| config-model/src/main/java/com/yahoo/searchdefinition/FeatureNames.java | Attributes must be identifiers so no need for extra regex check for them. | <ide><path>onfig-model/src/main/java/com/yahoo/searchdefinition/FeatureNames.java
<ide> }
<ide>
<ide> public static Reference asAttributeFeature(String attributeName) {
<del> return Reference.simple("attribute", quoteIfNecessary(attributeName));
<add> return Reference.simple("attribute", attributeName);
<ide> }
<ide>
<ide> public static Reference asQueryFeature(String propertyName) { |
|
Java | mit | 72baf6a12a2949c558873788275628976ed13626 | 0 | dennis-park/springies | package springies;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import jboxGlue.WorldManager;
import jgame.platform.JGEngine;
import listeners.JGameActionListener;
import masses.Mass;
import springs.Spring;
import walls.Wall;
import Parsers.ModelParser;
import Parsers.XMLParserCaller;
@SuppressWarnings("serial")
public class Springies extends JGEngine {
public ArrayList<Assembly> mAssemblyList;
private Wall[] mWallArray;
private EnvironmentManager mEnvironmentManager;
private JGameActionListener mActionListener;
private final int FPS = 40;
private final int FRAME_SKIP = 2;
public Springies () {
// set the window size
int height = 480;
double aspect = 16.0 / 9.0;
initEngineComponent((int) (height * aspect), height);
mAssemblyList = new ArrayList<Assembly>();
}
@Override
public void initCanvas ()
{
setCanvasSettings(1, // width of the canvas in tiles
1, // height of the canvas in tiles
displayWidth(), // width of one tile
displayHeight(), // height of one tile
null,// foreground colour -> use default colour white
null,// background colour -> use default colour black
null); // standard font -> use default font
}
@Override
public void initGame () {
setFrameRate(FPS, FRAME_SKIP);
WorldManager.initWorld(this);
mAssemblyList = new ArrayList<Assembly>();
// makeAssembly();
String environment_filename = "assets/environment.xml";
loadAssemblyFromFile(new File("assets/example.xml"));
//mEnvironmentManager = new EnvironmentManager(this);
mEnvironmentManager = new EnvironmentManager(this, environment_filename);
mActionListener = new JGameActionListener(this, mEnvironmentManager);
}
private ModelParser makeModelFromXML (String filename) {
XMLParserCaller caller = new XMLParserCaller();
ModelParser parser = new ModelParser(this);
try {
caller.call(filename, parser);
}
catch (Exception e) {
System.out.println("Error: Unable to parse XML file");
e.printStackTrace();
System.exit(1);
}
return parser;
}
@Override
/**
* In each frame, Springies will check all the user input events and perform actions accordingly.
* It will also iterate through all the masses and apply the Forces acting upon the masses at the
* moment. Then the JBox world will take 1 time step and update JGame accordingly.
*
*/
public void doFrame ()
{
doListenerEvents();
// update game objects
if (!mAssemblyList.isEmpty()) {
mEnvironmentManager.doForces();
WorldManager.getWorld().step(1f, 1);
moveObjects();
checkCollision(1 + 2, 1);
}
}
// This is a helper method to call the built in JEngine listeners. This way
// we don't have to worry about coordinates, etc. This method will send the lastKeyPressed
// and the mouseEvents to the Listener class and the Listener class will perform
// the appropriate actions
private void doListenerEvents () {
int last_key = getLastKey();
clearLastKey(); // last key has to be cleared every time
mActionListener.doKeyEvent(last_key);
mActionListener
.doMouseEvent(getMouseButton(1), getMouseButton(3), getMouseX(), getMouseY());
}
public Wall[] getWalls () {
return mWallArray;
}
public void makeAssembly () {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("XML documents", "xml");
chooser.setFileFilter(filter);
int returnVal = chooser.showDialog(null, "Load new Assembly file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
this.loadAssemblyFromFile(file);
}
}
public void loadAssemblyFromFile (File file) {
if (file != null) {
try {
ModelParser factory = makeModelFromXML(file.getAbsolutePath());
Assembly a = new Assembly();
for (Mass mass : factory.getMasses()) {
a.add(mass);
}
for (Spring spring : factory.getSprings()) {
a.add(spring);
}
mAssemblyList.add(a);
mEnvironmentManager.updateCOM(a);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private void removeAllObjects() {
for (Assembly a : mAssemblyList) {
for (Mass mass : a.getMassList()) {
removeObject(mass);
}
for (Spring spring : a.getSpringList()) {
removeObject(spring);
}
}
}
public void clearLoadedAssemblies () {
removeAllObjects();
mAssemblyList.clear();
}
public ArrayList<Assembly> getAssemblyList() {
return mAssemblyList;
}
}
| src/springies/Springies.java | package springies;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import jboxGlue.WorldManager;
import jgame.platform.JGEngine;
import listeners.JGameActionListener;
import masses.Mass;
import springs.Spring;
import walls.Wall;
import Parsers.ModelParser;
import Parsers.XMLParserCaller;
@SuppressWarnings("serial")
public class Springies extends JGEngine {
public ArrayList<Assembly> mAssemblyList;
private Wall[] mWallArray;
private EnvironmentManager mEnvironmentManager;
private JGameActionListener mActionListener;
private final int FPS = 40;
private final int FRAME_SKIP = 2;
public Springies () {
// set the window size
int height = 480;
double aspect = 16.0 / 9.0;
initEngineComponent((int) (height * aspect), height);
mAssemblyList = new ArrayList<Assembly>();
}
@Override
public void initCanvas ()
{
setCanvasSettings(1, // width of the canvas in tiles
1, // height of the canvas in tiles
displayWidth(), // width of one tile
displayHeight(), // height of one tile
null,// foreground colour -> use default colour white
null,// background colour -> use default colour black
null); // standard font -> use default font
}
@Override
public void initGame () {
setFrameRate(FPS, FRAME_SKIP);
WorldManager.initWorld(this);
mAssemblyList = new ArrayList<Assembly>();
// makeAssembly();
String environment_filename = "assets/environment.xml";
loadAssemblyFromFile(new File("assets/example.xml"));
//mEnvironmentManager = new EnvironmentManager(this);
mEnvironmentManager = new EnvironmentManager(this, environment_filename);
mActionListener = new JGameActionListener(this, mEnvironmentManager);
}
private void testAssembly() {
String model_filename = "assets/lamp.xml";
String model_filename2 = "assets/daintywalker.xml";
makeModelFromXML(model_filename);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
makeModelFromXML(model_filename2);
}
private ModelParser makeModelFromXML (String filename) {
XMLParserCaller caller = new XMLParserCaller();
ModelParser parser = new ModelParser(this);
try {
caller.call(filename, parser);
}
catch (Exception e) {
System.out.println("Error: Unable to parse XML file");
e.printStackTrace();
System.exit(1);
}
return parser;
}
@Override
/**
* In each frame, Springies will check all the user input events and perform actions accordingly.
* It will also iterate through all the masses and apply the Forces acting upon the masses at the
* moment. Then the JBox world will take 1 time step and update JGame accordingly.
*
*/
public void doFrame ()
{
doListenerEvents();
// update game objects
if (!mAssemblyList.isEmpty()) {
mEnvironmentManager.doForces();
WorldManager.getWorld().step(1f, 1);
moveObjects();
checkCollision(1 + 2, 1);
}
}
// This is a helper method to call the built in JEngine listeners. This way
// we don't have to worry about coordinates, etc. This method will send the lastKeyPressed
// and the mouseEvents to the Listener class and the Listener class will perform
// the appropriate actions
private void doListenerEvents () {
int last_key = getLastKey();
clearLastKey(); // last key has to be cleared every time
mActionListener.doKeyEvent(last_key);
mActionListener
.doMouseEvent(getMouseButton(1), getMouseButton(3), getMouseX(), getMouseY());
}
public Wall[] getWalls () {
return mWallArray;
}
public void makeAssembly () {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("XML documents", "xml");
chooser.setFileFilter(filter);
int returnVal = chooser.showDialog(null, "Load new Assembly file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
this.loadAssemblyFromFile(file);
}
}
public void loadAssemblyFromFile (File file) {
if (file != null) {
try {
ModelParser factory = makeModelFromXML(file.getAbsolutePath());
Assembly a = new Assembly();
for (Mass mass : factory.getMasses()) {
a.add(mass);
}
for (Spring spring : factory.getSprings()) {
a.add(spring);
}
mAssemblyList.add(a);
mEnvironmentManager.updateCOM(a);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private void removeAllObjects() {
for (Assembly a : mAssemblyList) {
for (Mass mass : a.getMassList()) {
removeObject(mass);
}
for (Spring spring : a.getSpringList()) {
removeObject(spring);
}
}
}
public void clearLoadedAssemblies () {
removeAllObjects();
mAssemblyList.clear();
}
public ArrayList<Assembly> getAssemblyList() {
return mAssemblyList;
}
}
| cleaned up tester methods
| src/springies/Springies.java | cleaned up tester methods | <ide><path>rc/springies/Springies.java
<ide> //mEnvironmentManager = new EnvironmentManager(this);
<ide> mEnvironmentManager = new EnvironmentManager(this, environment_filename);
<ide> mActionListener = new JGameActionListener(this, mEnvironmentManager);
<del> }
<del>
<del> private void testAssembly() {
<del> String model_filename = "assets/lamp.xml";
<del> String model_filename2 = "assets/daintywalker.xml";
<del> makeModelFromXML(model_filename);
<del> try {
<del> Thread.sleep(1000);
<del> }
<del> catch (InterruptedException e) {
<del> e.printStackTrace();
<del> }
<del> makeModelFromXML(model_filename2);
<ide> }
<ide>
<ide> private ModelParser makeModelFromXML (String filename) { |
|
Java | apache-2.0 | 9bb670a0de193a8e3141d15447a5dea811f0c992 | 0 | roboconf/roboconf-platform,vincent-zurczak/roboconf-platform,gibello/roboconf,vincent-zurczak/roboconf-platform,diarraa/roboconf-platform,vincent-zurczak/roboconf-platform,roboconf/roboconf-platform,gibello/roboconf,gibello/roboconf,roboconf/roboconf-platform,diarraa/roboconf-platform,diarraa/roboconf-platform | /**
* Copyright 2014-2015 Linagora, Université Joseph Fourier, Floralis
*
* The present code is developed in the scope of the joint LINAGORA -
* Université Joseph Fourier - Floralis research program and is designated
* as a "Result" pursuant to the terms and conditions of the LINAGORA
* - Université Joseph Fourier - Floralis research program. Each copyright
* holder of Results enumerated here above fully & independently holds complete
* ownership of the complete Intellectual Property rights applicable to the whole
* of said Results, and may freely exploit it in any manner which does not infringe
* the moral rights of the other copyright holders.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.roboconf.integration.tests;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
import java.util.List;
import javax.inject.Inject;
import net.roboconf.agent.AgentMessagingInterface;
import net.roboconf.core.internal.tests.TestApplication;
import net.roboconf.core.model.beans.Instance.InstanceStatus;
import net.roboconf.dm.management.ManagedApplication;
import net.roboconf.dm.management.Manager;
import net.roboconf.integration.probes.AbstractTest;
import net.roboconf.integration.probes.DmTest;
import net.roboconf.integration.tests.internal.RoboconfPaxRunner;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
/**
* Checks delayed initialization.
* <p>
* Configure an agent correctly and the DM incorrectly.<br />
* Wait a little bit and reconfigure the DM with the right messaging
* credentials. Make sure the agent's model is initialized correctly.
* </p>
*
* @author Vincent Zurczak - Linagora
*/
@RunWith( RoboconfPaxRunner.class )
@ExamReactorStrategy( PerMethod.class )
public class AgentWithDelayedInitializationTest extends DmTest {
@Inject
protected Manager manager;
//@Inject
//protected AgentMessagingInterface agentItf;
@Inject
public BundleContext ctx;
@ProbeBuilder
public TestProbeBuilder probeConfiguration( TestProbeBuilder probe ) {
// We need to specify the classes we need
// and that come from external modules.
probe.addTest( AbstractTest.class );
probe.addTest( DmTest.class );
probe.addTest( TestApplication.class );
return probe;
}
@Override
@Configuration
public Option[] config() {
List<Option> options = getBaseOptions();
// Add a valid configuration for the agent
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"message-server-ip",
"localhost" ));
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"message-server-username",
"guest" ));
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"message-server-password",
"guest" ));
TestApplication app = new TestApplication();
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"application-name",
app.getName()));
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"root-instance-name",
app.getMySqlVm().getName()));
// Add an invalid configuration for the DM
options.add( editConfigurationFilePut(
"etc/net.roboconf.dm.configuration.cfg",
"message-server-username",
"invalid" ));
// Deploy the agent's bundles
options.add( mavenBundle()
.groupId( "net.roboconf" )
.artifactId( "roboconf-plugin-api" )
.version( getRoboconfVersion())
.start());
options.add( mavenBundle()
.groupId( "net.roboconf" )
.artifactId( "roboconf-agent" )
.version( getRoboconfVersion())
.start());
options.add( mavenBundle()
.groupId( "net.roboconf" )
.artifactId( "roboconf-agent-default" )
.version( getRoboconfVersion())
.start());
return options.toArray( new Option[ options.size()]);
}
@Override
@Test
public void run() throws Exception {
// FIXME: keep it until we guarantee the build works.
// This information will help to debug build failures on Travis CI.
for( Bundle b : this.ctx.getBundles()) {
System.out.println( b.getSymbolicName());
}
// Update the manager.
this.manager.setConfigurationDirectoryLocation( newFolder().getAbsolutePath());
this.manager.reconfigure();
// Make like if the DM had already deployed an application's part
TestApplication app = new TestApplication();
ManagedApplication ma = new ManagedApplication( app, null );
this.manager.getAppNameToManagedApplication().put( app.getName(), ma );
// Check the DM
Assert.assertEquals( InstanceStatus.NOT_DEPLOYED, app.getMySqlVm().getStatus());
Assert.assertNotNull( this.manager.getMessagingClient());
Assert.assertFalse( this.manager.getMessagingClient().isConnected());
// FIXME: just for debug
ServiceReference sr = this.ctx.getServiceReference( AgentMessagingInterface.class );
Assert.assertNotNull( sr );
AgentMessagingInterface agentItf = (AgentMessagingInterface) this.ctx.getService( sr );
Assert.assertNotNull( "The previous assignation sometimes fail.", agentItf );
// Check the agent
Assert.assertEquals( app.getName(), agentItf.getApplicationName());
Assert.assertNull( agentItf.getRootInstance());
Assert.assertNotNull( agentItf.getMessagingClient());
Assert.assertTrue( agentItf.getMessagingClient().isConnected());
// Both cannot communicate.
// Let's wait a little bit and let's reconfigure the DM with the right credentials.
this.manager.setMessageServerUsername( "guest" );
this.manager.reconfigure();
// Manager#reconfigure() reloads all the applications from its configuration.
// Since we loaded one in-memory, we must restore it ourselves.
this.manager.getAppNameToManagedApplication().put( app.getName(), ma );
// Force the agent to send a heart beat message.
agentItf.forceHeartbeatSending();
Thread.sleep( 400 );
// The agent should now be configured.
Assert.assertEquals( app.getName(), agentItf.getApplicationName());
Assert.assertNotNull( agentItf.getMessagingClient());
Assert.assertTrue( agentItf.getMessagingClient().isConnected());
Assert.assertNotNull( agentItf.getRootInstance());
Assert.assertEquals( app.getMySqlVm(), agentItf.getRootInstance());
// And the DM should have considered the root instance as started.
Assert.assertEquals( InstanceStatus.DEPLOYED_STARTED, app.getMySqlVm().getStatus());
}
}
| miscellaneous/roboconf-integration-tests/src/test/java/net/roboconf/integration/tests/AgentWithDelayedInitializationTest.java | /**
* Copyright 2014-2015 Linagora, Université Joseph Fourier, Floralis
*
* The present code is developed in the scope of the joint LINAGORA -
* Université Joseph Fourier - Floralis research program and is designated
* as a "Result" pursuant to the terms and conditions of the LINAGORA
* - Université Joseph Fourier - Floralis research program. Each copyright
* holder of Results enumerated here above fully & independently holds complete
* ownership of the complete Intellectual Property rights applicable to the whole
* of said Results, and may freely exploit it in any manner which does not infringe
* the moral rights of the other copyright holders.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.roboconf.integration.tests;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
import java.util.List;
import javax.inject.Inject;
import net.roboconf.agent.AgentMessagingInterface;
import net.roboconf.core.internal.tests.TestApplication;
import net.roboconf.core.model.beans.Instance.InstanceStatus;
import net.roboconf.dm.management.ManagedApplication;
import net.roboconf.dm.management.Manager;
import net.roboconf.integration.probes.AbstractTest;
import net.roboconf.integration.probes.DmTest;
import net.roboconf.integration.tests.internal.RoboconfPaxRunner;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.ProbeBuilder;
import org.ops4j.pax.exam.TestProbeBuilder;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
/**
* Checks delayed initialization.
* <p>
* Configure an agent correctly and the DM incorrectly.<br />
* Wait a little bit and reconfigure the DM with the right messaging
* credentials. Make sure the agent's model is initialized correctly.
* </p>
*
* @author Vincent Zurczak - Linagora
*/
@RunWith( RoboconfPaxRunner.class )
@ExamReactorStrategy( PerMethod.class )
public class AgentWithDelayedInitializationTest extends DmTest {
@Inject
protected Manager manager;
@Inject
protected AgentMessagingInterface agentItf;
@Inject
public BundleContext ctx;
@ProbeBuilder
public TestProbeBuilder probeConfiguration( TestProbeBuilder probe ) {
// We need to specify the classes we need
// and that come from external modules.
probe.addTest( AbstractTest.class );
probe.addTest( DmTest.class );
probe.addTest( TestApplication.class );
return probe;
}
@Override
@Configuration
public Option[] config() {
List<Option> options = getBaseOptions();
// Add a valid configuration for the agent
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"message-server-ip",
"localhost" ));
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"message-server-username",
"guest" ));
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"message-server-password",
"guest" ));
TestApplication app = new TestApplication();
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"application-name",
app.getName()));
options.add( editConfigurationFilePut(
"etc/net.roboconf.agent.configuration.cfg",
"root-instance-name",
app.getMySqlVm().getName()));
// Add an invalid configuration for the DM
options.add( editConfigurationFilePut(
"etc/net.roboconf.dm.configuration.cfg",
"message-server-username",
"invalid" ));
// Deploy the agent's bundles
options.add( mavenBundle()
.groupId( "net.roboconf" )
.artifactId( "roboconf-plugin-api" )
.version( getRoboconfVersion())
.start());
options.add( mavenBundle()
.groupId( "net.roboconf" )
.artifactId( "roboconf-agent" )
.version( getRoboconfVersion())
.start());
options.add( mavenBundle()
.groupId( "net.roboconf" )
.artifactId( "roboconf-agent-default" )
.version( getRoboconfVersion())
.start());
return options.toArray( new Option[ options.size()]);
}
@Override
@Test
public void run() throws Exception {
// FIXME: keep it until we guarantee the build works.
// This information will help to debug build failures on Travis CI.
for( Bundle b : this.ctx.getBundles())
System.out.println( b.getSymbolicName());
// Update the manager.
this.manager.setConfigurationDirectoryLocation( newFolder().getAbsolutePath());
this.manager.reconfigure();
// Make like if the DM had already deployed an application's part
TestApplication app = new TestApplication();
ManagedApplication ma = new ManagedApplication( app, null );
this.manager.getAppNameToManagedApplication().put( app.getName(), ma );
// Check the DM
Assert.assertEquals( InstanceStatus.NOT_DEPLOYED, app.getMySqlVm().getStatus());
Assert.assertNotNull( this.manager.getMessagingClient());
Assert.assertFalse( this.manager.getMessagingClient().isConnected());
// Check the agent
Assert.assertEquals( app.getName(), this.agentItf.getApplicationName());
Assert.assertNull( this.agentItf.getRootInstance());
Assert.assertNotNull( this.agentItf.getMessagingClient());
Assert.assertTrue( this.agentItf.getMessagingClient().isConnected());
// Both cannot communicate.
// Let's wait a little bit and let's reconfigure the DM with the right credentials.
this.manager.setMessageServerUsername( "guest" );
this.manager.reconfigure();
// Manager#reconfigure() reloads all the applications from its configuration.
// Since we loaded one in-memory, we must restore it ourselves.
this.manager.getAppNameToManagedApplication().put( app.getName(), ma );
// Force the agent to send a heart beat message.
this.agentItf.forceHeartbeatSending();
Thread.sleep( 400 );
// The agent should now be configured.
Assert.assertEquals( app.getName(), this.agentItf.getApplicationName());
Assert.assertNotNull( this.agentItf.getMessagingClient());
Assert.assertTrue( this.agentItf.getMessagingClient().isConnected());
Assert.assertNotNull( this.agentItf.getRootInstance());
Assert.assertEquals( app.getMySqlVm(), this.agentItf.getRootInstance());
// And the DM should have considered the root instance as started.
Assert.assertEquals( InstanceStatus.DEPLOYED_STARTED, app.getMySqlVm().getStatus());
}
}
| Try to understand why this test sometimes work and sometimes not | miscellaneous/roboconf-integration-tests/src/test/java/net/roboconf/integration/tests/AgentWithDelayedInitializationTest.java | Try to understand why this test sometimes work and sometimes not | <ide><path>iscellaneous/roboconf-integration-tests/src/test/java/net/roboconf/integration/tests/AgentWithDelayedInitializationTest.java
<ide> import org.ops4j.pax.exam.spi.reactors.PerMethod;
<ide> import org.osgi.framework.Bundle;
<ide> import org.osgi.framework.BundleContext;
<add>import org.osgi.framework.ServiceReference;
<ide>
<ide> /**
<ide> * Checks delayed initialization.
<ide> @Inject
<ide> protected Manager manager;
<ide>
<del> @Inject
<del> protected AgentMessagingInterface agentItf;
<add> //@Inject
<add> //protected AgentMessagingInterface agentItf;
<ide>
<ide> @Inject
<ide> public BundleContext ctx;
<ide>
<ide> // FIXME: keep it until we guarantee the build works.
<ide> // This information will help to debug build failures on Travis CI.
<del> for( Bundle b : this.ctx.getBundles())
<add> for( Bundle b : this.ctx.getBundles()) {
<ide> System.out.println( b.getSymbolicName());
<add> }
<ide>
<ide> // Update the manager.
<ide> this.manager.setConfigurationDirectoryLocation( newFolder().getAbsolutePath());
<ide> Assert.assertNotNull( this.manager.getMessagingClient());
<ide> Assert.assertFalse( this.manager.getMessagingClient().isConnected());
<ide>
<add> // FIXME: just for debug
<add> ServiceReference sr = this.ctx.getServiceReference( AgentMessagingInterface.class );
<add> Assert.assertNotNull( sr );
<add> AgentMessagingInterface agentItf = (AgentMessagingInterface) this.ctx.getService( sr );
<add> Assert.assertNotNull( "The previous assignation sometimes fail.", agentItf );
<add>
<ide> // Check the agent
<del> Assert.assertEquals( app.getName(), this.agentItf.getApplicationName());
<del> Assert.assertNull( this.agentItf.getRootInstance());
<del> Assert.assertNotNull( this.agentItf.getMessagingClient());
<del> Assert.assertTrue( this.agentItf.getMessagingClient().isConnected());
<add> Assert.assertEquals( app.getName(), agentItf.getApplicationName());
<add> Assert.assertNull( agentItf.getRootInstance());
<add> Assert.assertNotNull( agentItf.getMessagingClient());
<add> Assert.assertTrue( agentItf.getMessagingClient().isConnected());
<ide>
<ide> // Both cannot communicate.
<ide> // Let's wait a little bit and let's reconfigure the DM with the right credentials.
<ide> this.manager.getAppNameToManagedApplication().put( app.getName(), ma );
<ide>
<ide> // Force the agent to send a heart beat message.
<del> this.agentItf.forceHeartbeatSending();
<add> agentItf.forceHeartbeatSending();
<ide> Thread.sleep( 400 );
<ide>
<ide> // The agent should now be configured.
<del> Assert.assertEquals( app.getName(), this.agentItf.getApplicationName());
<del> Assert.assertNotNull( this.agentItf.getMessagingClient());
<del> Assert.assertTrue( this.agentItf.getMessagingClient().isConnected());
<del> Assert.assertNotNull( this.agentItf.getRootInstance());
<del> Assert.assertEquals( app.getMySqlVm(), this.agentItf.getRootInstance());
<add> Assert.assertEquals( app.getName(), agentItf.getApplicationName());
<add> Assert.assertNotNull( agentItf.getMessagingClient());
<add> Assert.assertTrue( agentItf.getMessagingClient().isConnected());
<add> Assert.assertNotNull( agentItf.getRootInstance());
<add> Assert.assertEquals( app.getMySqlVm(), agentItf.getRootInstance());
<ide>
<ide> // And the DM should have considered the root instance as started.
<ide> Assert.assertEquals( InstanceStatus.DEPLOYED_STARTED, app.getMySqlVm().getStatus()); |
|
Java | epl-1.0 | 498059d6a45a8a41a5e1498d63ea118d63331903 | 0 | rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse | package com.redhat.ceylon.eclipse.imp.editorActionContributions;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.search.ui.ISearchPage;
import org.eclipse.search.ui.ISearchPageContainer;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
public class CeylonSearchDialogPage extends DialogPage
implements ISearchPage/*, IReplacePage*/ {
private String searchString="";
private boolean caseSensitive = false;
private boolean references = true;
private boolean declarations = true;
private ISearchPageContainer container;
public CeylonSearchDialogPage() {
super("Ceylon Search");
}
@Override
public void createControl(Composite parent) {
Composite result = new Composite(parent, SWT.NONE);
setControl(result);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
result.setLayout(layout);
Label title = new Label(result, SWT.RIGHT);
title.setText("Search string");
GridData gd = new GridData();
gd.horizontalSpan=2;
title.setLayoutData(gd);
final Combo text = new Combo(result, 0);
text.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
text.setText(searchString);
text.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent event) {
searchString = text.getText();
}
});
final Button caseSense = new Button(result, SWT.CHECK);
caseSense.setText("Case sensitive");
caseSense.setSelection(caseSensitive);
caseSense.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent event) {
caseSensitive = !caseSensitive;
}
@Override
public void widgetDefaultSelected(SelectionEvent event) {}
});
Group sub = new Group(result, SWT.SHADOW_ETCHED_IN);
sub.setText("Search For");
GridLayout sgl = new GridLayout();
sgl.numColumns = 2;
sub.setLayout(sgl);
final Button refs = new Button(sub, SWT.CHECK);
refs.setText("References");
refs.setSelection(references);
refs.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent event) {
references = !references;
}
@Override
public void widgetDefaultSelected(SelectionEvent event) {}
});
final Button decs = new Button(sub, SWT.CHECK);
decs.setText("Declarations");
decs.setSelection(declarations);
decs.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent event) {
declarations = !declarations;
}
@Override
public void widgetDefaultSelected(SelectionEvent event) {}
});
}
@Override
public boolean performAction() {
int scope = container.getSelectedScope();
String[] projectNames;
switch (scope) {
case ISearchPageContainer.WORKSPACE_SCOPE:
MessageDialog.openError(getShell(), "Ceylon Search Error", "Please select a project to search");
return false;
case ISearchPageContainer.SELECTED_PROJECTS_SCOPE:
projectNames = container.getSelectedProjectNames();
break;
case ISearchPageContainer.SELECTION_SCOPE:
projectNames = new String[] { getProject(container.getActiveEditorInput()).getName() };
break;
default:
MessageDialog.openError(getShell(), "Ceylon Search Error", "Unsupported scope");
return false;
}
NewSearchUI.runQueryInBackground(new CeylonSearchQuery(
searchString, projectNames, references, declarations,
caseSensitive));
return true;
}
public static IProject getProject(IEditorInput editor) {
return ((IFileEditorInput) editor).getFile().getProject();
}
/*@Override
public boolean performReplace() {
// TODO Auto-generated method stub
return true;
}*/
@Override
public void setContainer(ISearchPageContainer container) {
this.container = container;
}
}
| plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/imp/editorActionContributions/CeylonSearchDialogPage.java | package com.redhat.ceylon.eclipse.imp.editorActionContributions;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.search.ui.ISearchPage;
import org.eclipse.search.ui.ISearchPageContainer;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
public class CeylonSearchDialogPage extends DialogPage
implements ISearchPage/*, IReplacePage*/ {
private String searchString="";
private boolean caseSensitive = false;
private boolean references = true;
private boolean declarations = true;
private ISearchPageContainer container;
public CeylonSearchDialogPage() {
super("Ceylon Search");
}
@Override
public void createControl(Composite parent) {
Composite result = new Composite(parent, SWT.NONE);
setControl(result);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
result.setLayout(layout);
Label title = new Label(result, SWT.RIGHT);
title.setText("Search string");
GridData gd = new GridData();
gd.horizontalSpan=2;
title.setLayoutData(gd);
final Combo text = new Combo(result, 0);
text.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
text.setText(searchString);
text.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent event) {
searchString = text.getText();
}
});
final Button caseSense = new Button(result, SWT.CHECK);
caseSense.setText("Case sensitive");
caseSense.setSelection(caseSensitive);
caseSense.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent event) {
caseSensitive = !caseSensitive;
}
@Override
public void widgetDefaultSelected(SelectionEvent event) {}
});
Group sub = new Group(result, SWT.SHADOW_ETCHED_IN);
sub.setText("Search For");
GridLayout sgl = new GridLayout();
sgl.numColumns = 2;
sub.setLayout(sgl);
final Button refs = new Button(sub, SWT.CHECK);
refs.setText("References");
refs.setSelection(references);
refs.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent event) {
references = !references;
}
@Override
public void widgetDefaultSelected(SelectionEvent event) {}
});
final Button decs = new Button(sub, SWT.CHECK);
decs.setText("Declarations");
decs.setSelection(declarations);
decs.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent event) {
declarations = !declarations;
}
@Override
public void widgetDefaultSelected(SelectionEvent event) {}
});
}
@Override
public boolean performAction() {
int scope = container.getSelectedScope();
String[] projectNames;
switch (scope) {
case ISearchPageContainer.WORKSPACE_SCOPE:
throw new RuntimeException();
case ISearchPageContainer.SELECTED_PROJECTS_SCOPE:
projectNames = container.getSelectedProjectNames();
break;
case ISearchPageContainer.SELECTION_SCOPE:
projectNames = new String[] { getProject(container.getActiveEditorInput()).getName() };
break;
default:
throw new RuntimeException();
}
NewSearchUI.runQueryInBackground(new CeylonSearchQuery(
searchString, projectNames, references, declarations,
caseSensitive));
return true;
}
public static IProject getProject(IEditorInput editor) {
return ((IFileEditorInput) editor).getFile().getProject();
}
/*@Override
public boolean performReplace() {
// TODO Auto-generated method stub
return true;
}*/
@Override
public void setContainer(ISearchPageContainer container) {
this.container = container;
}
}
| dialogs | plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/imp/editorActionContributions/CeylonSearchDialogPage.java | dialogs | <ide><path>lugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/imp/editorActionContributions/CeylonSearchDialogPage.java
<ide>
<ide> import org.eclipse.core.resources.IProject;
<ide> import org.eclipse.jface.dialogs.DialogPage;
<add>import org.eclipse.jface.dialogs.MessageDialog;
<ide> import org.eclipse.search.ui.ISearchPage;
<ide> import org.eclipse.search.ui.ISearchPageContainer;
<ide> import org.eclipse.search.ui.NewSearchUI;
<ide> String[] projectNames;
<ide> switch (scope) {
<ide> case ISearchPageContainer.WORKSPACE_SCOPE:
<del> throw new RuntimeException();
<add> MessageDialog.openError(getShell(), "Ceylon Search Error", "Please select a project to search");
<add> return false;
<ide> case ISearchPageContainer.SELECTED_PROJECTS_SCOPE:
<ide> projectNames = container.getSelectedProjectNames();
<ide> break;
<ide> projectNames = new String[] { getProject(container.getActiveEditorInput()).getName() };
<ide> break;
<ide> default:
<del> throw new RuntimeException();
<add> MessageDialog.openError(getShell(), "Ceylon Search Error", "Unsupported scope");
<add> return false;
<ide> }
<ide>
<ide> NewSearchUI.runQueryInBackground(new CeylonSearchQuery( |
|
Java | mit | error: pathspec 'src/test/java/hudson/plugins/warnings/parser/PREfastParserTest.java' did not match any file(s) known to git
| 3546ade66cda0186fb648494072c5535aa1ca51e | 1 | amuniz/warnings-plugin,jenkinsci/warnings-plugin,SvenLuebke/warnings-plugin,SvenLuebke/warnings-plugin,recena/warnings-plugin,michelepagot/warnings-plugin,jenkinsci/warnings-plugin,michelepagot/warnings-plugin,amuniz/warnings-plugin,recena/warnings-plugin,amuniz/warnings-plugin,SvenLuebke/warnings-plugin,michelepagot/warnings-plugin,recena/warnings-plugin,jenkinsci/warnings-plugin | package hudson.plugins.warnings.parser;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import org.junit.Test;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.analysis.util.model.Priority;
/**
* Tests the class {@link PuppetLintParser}.
*
* @author Jan Vansteenkiste <[email protected]>
*/
public class PREfastParserTest extends ParserTester {
private static final String TYPE = new PuppetLintParser().getGroup();
/**
* Tests the Puppet-Lint parsing.
*
* @throws IOException
* in case of an error
*/
@Test
public void testParse() throws IOException {
Collection<FileAnnotation> results = createParser().parse(openFile());
Iterator<FileAnnotation> iterator = results.iterator();
FileAnnotation annotation = iterator.next();
checkLintWarning(annotation,
1, "failtest not in autoload module layout",
"failtest.pp", TYPE, "autoloader_layout", Priority.HIGH, "-");
annotation = iterator.next();
checkLintWarning(annotation,
3, "line has more than 80 characters",
"./modules/test/manifests/init.pp", TYPE, "80chars", Priority.NORMAL, "::test");
annotation = iterator.next();
checkLintWarning(annotation,
10, "line has more than 80 characters",
"./modules/test/manifests/sub/class/morefail.pp", TYPE, "80chars", Priority.NORMAL, "::test::sub::class");
}
/**
* Checks the properties of the specified warning.
*
* @param annotation
* the warning to check
* @param lineNumber
* the expected line number
* @param message
* the expected message
* @param fileName
* the expected filename
* @param type
* the expected type
* @param category
* the expected category
* @param priority
* the expected priority
* @param packageName
* the expected package name
*/
// CHECKSTYLE:OFF
private void checkLintWarning(final FileAnnotation annotation, final int lineNumber, final String message, final String fileName, final String type, final String category, final Priority priority, final String packageName) {
checkWarning(annotation, lineNumber, message, fileName, type, category, priority);
assertEquals("Wrong packageName detected.", packageName, annotation.getPackageName());
}
// CHECKSTYLE:ON
/**
* Creates the parser.
*
* @return the warnings parser
*/
protected AbstractWarningsParser createParser() {
return new PuppetLintParser();
}
@Override
protected String getWarningsFile() {
return "puppet-lint.txt";
}
}
| src/test/java/hudson/plugins/warnings/parser/PREfastParserTest.java | CC - Initial copy, template based on PuppetLintParserTest.java | src/test/java/hudson/plugins/warnings/parser/PREfastParserTest.java | CC - Initial copy, template based on PuppetLintParserTest.java | <ide><path>rc/test/java/hudson/plugins/warnings/parser/PREfastParserTest.java
<add>package hudson.plugins.warnings.parser;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.io.IOException;
<add>import java.util.Collection;
<add>import java.util.Iterator;
<add>
<add>import org.junit.Test;
<add>
<add>import hudson.plugins.analysis.util.model.FileAnnotation;
<add>import hudson.plugins.analysis.util.model.Priority;
<add>
<add>/**
<add> * Tests the class {@link PuppetLintParser}.
<add> *
<add> * @author Jan Vansteenkiste <[email protected]>
<add> */
<add>public class PREfastParserTest extends ParserTester {
<add> private static final String TYPE = new PuppetLintParser().getGroup();
<add>
<add> /**
<add> * Tests the Puppet-Lint parsing.
<add> *
<add> * @throws IOException
<add> * in case of an error
<add> */
<add> @Test
<add> public void testParse() throws IOException {
<add> Collection<FileAnnotation> results = createParser().parse(openFile());
<add> Iterator<FileAnnotation> iterator = results.iterator();
<add>
<add> FileAnnotation annotation = iterator.next();
<add> checkLintWarning(annotation,
<add> 1, "failtest not in autoload module layout",
<add> "failtest.pp", TYPE, "autoloader_layout", Priority.HIGH, "-");
<add>
<add> annotation = iterator.next();
<add> checkLintWarning(annotation,
<add> 3, "line has more than 80 characters",
<add> "./modules/test/manifests/init.pp", TYPE, "80chars", Priority.NORMAL, "::test");
<add>
<add> annotation = iterator.next();
<add> checkLintWarning(annotation,
<add> 10, "line has more than 80 characters",
<add> "./modules/test/manifests/sub/class/morefail.pp", TYPE, "80chars", Priority.NORMAL, "::test::sub::class");
<add> }
<add>
<add> /**
<add> * Checks the properties of the specified warning.
<add> *
<add> * @param annotation
<add> * the warning to check
<add> * @param lineNumber
<add> * the expected line number
<add> * @param message
<add> * the expected message
<add> * @param fileName
<add> * the expected filename
<add> * @param type
<add> * the expected type
<add> * @param category
<add> * the expected category
<add> * @param priority
<add> * the expected priority
<add> * @param packageName
<add> * the expected package name
<add> */
<add> // CHECKSTYLE:OFF
<add> private void checkLintWarning(final FileAnnotation annotation, final int lineNumber, final String message, final String fileName, final String type, final String category, final Priority priority, final String packageName) {
<add> checkWarning(annotation, lineNumber, message, fileName, type, category, priority);
<add> assertEquals("Wrong packageName detected.", packageName, annotation.getPackageName());
<add> }
<add> // CHECKSTYLE:ON
<add>
<add> /**
<add> * Creates the parser.
<add> *
<add> * @return the warnings parser
<add> */
<add> protected AbstractWarningsParser createParser() {
<add> return new PuppetLintParser();
<add> }
<add>
<add> @Override
<add> protected String getWarningsFile() {
<add> return "puppet-lint.txt";
<add> }
<add>} |
|
Java | apache-2.0 | 401f9782840ce7a5511377de1d60cfaa38373ef5 | 0 | blademainer/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,ernestp/consulo,asedunov/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,samthor/intellij-community,tmpgit/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,ernestp/consulo,mglukhikh/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,izonder/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,signed/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,signed/intellij-community,kool79/intellij-community,semonte/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,izonder/intellij-community,samthor/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,samthor/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,caot/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,signed/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,xfournet/intellij-community,samthor/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,FHannes/intellij-community,fitermay/intellij-community,hurricup/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,Distrotech/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,allotria/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,apixandru/intellij-community,semonte/intellij-community,supersven/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,adedayo/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,slisson/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,signed/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,adedayo/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,amith01994/intellij-community,diorcety/intellij-community,da1z/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,caot/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,muntasirsyed/intellij-community,holmes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,petteyg/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,retomerz/intellij-community,fnouama/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,gnuhub/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,caot/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,apixandru/intellij-community,holmes/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ryano144/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,slisson/intellij-community,samthor/intellij-community,allotria/intellij-community,kdwink/intellij-community,ernestp/consulo,akosyakov/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,izonder/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,asedunov/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,da1z/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,kool79/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,samthor/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,kool79/intellij-community,hurricup/intellij-community,hurricup/intellij-community,supersven/intellij-community,caot/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,semonte/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,blademainer/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,adedayo/intellij-community,FHannes/intellij-community,hurricup/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,holmes/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,semonte/intellij-community,jagguli/intellij-community,xfournet/intellij-community,apixandru/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,slisson/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,asedunov/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,robovm/robovm-studio,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,clumsy/intellij-community,jagguli/intellij-community,amith01994/intellij-community,robovm/robovm-studio,holmes/intellij-community,izonder/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,apixandru/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,xfournet/intellij-community,petteyg/intellij-community,diorcety/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,signed/intellij-community,Distrotech/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ibinti/intellij-community,diorcety/intellij-community,diorcety/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,allotria/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ibinti/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,allotria/intellij-community,gnuhub/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,kdwink/intellij-community,ryano144/intellij-community,ryano144/intellij-community,da1z/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,blademainer/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,consulo/consulo,ftomassetti/intellij-community,wreckJ/intellij-community,allotria/intellij-community,caot/intellij-community,caot/intellij-community,caot/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,semonte/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,kool79/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,signed/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,hurricup/intellij-community,adedayo/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,dslomov/intellij-community,holmes/intellij-community,hurricup/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,vladmm/intellij-community,apixandru/intellij-community,slisson/intellij-community,retomerz/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,xfournet/intellij-community,diorcety/intellij-community,retomerz/intellij-community,dslomov/intellij-community,amith01994/intellij-community,petteyg/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,jagguli/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,fnouama/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,signed/intellij-community,asedunov/intellij-community,consulo/consulo,pwoodworth/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,fnouama/intellij-community,signed/intellij-community,holmes/intellij-community,nicolargo/intellij-community,kool79/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,ryano144/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,supersven/intellij-community,signed/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,fitermay/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,ryano144/intellij-community,kool79/intellij-community,ryano144/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,caot/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,caot/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,kdwink/intellij-community,da1z/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ibinti/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,dslomov/intellij-community,retomerz/intellij-community,dslomov/intellij-community,izonder/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,signed/intellij-community,lucafavatella/intellij-community,consulo/consulo,tmpgit/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,kool79/intellij-community,samthor/intellij-community,FHannes/intellij-community,signed/intellij-community,diorcety/intellij-community,allotria/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,vladmm/intellij-community,allotria/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,FHannes/intellij-community,ibinti/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,semonte/intellij-community,petteyg/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,izonder/intellij-community,diorcety/intellij-community,slisson/intellij-community,izonder/intellij-community,amith01994/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,signed/intellij-community,jagguli/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,ibinti/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,holmes/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.jetbrains.plugins.groovy.lang.psi.impl.statements;
import com.intellij.lang.ASTNode;
import com.intellij.psi.*;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.TypeConversionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrConstructorInvocation;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrThisSuperReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyResolveResultImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrCallImpl;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;
import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodResolverProcessor;
/**
* User: Dmitry.Krasilschikov
* Date: 29.05.2007
*/
public class GrConstructorInvocationImpl extends GrCallImpl implements GrConstructorInvocation {
public GrConstructorInvocationImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(GroovyElementVisitor visitor) {
visitor.visitConstructorInvocation(this);
}
public String toString() {
return "Constructor invocation";
}
public boolean isSuperCall() {
return findChildByType(GroovyElementTypes.SUPER_REFERENCE_EXPRESSION) != null;
}
public boolean isThisCall() {
return findChildByType(GroovyElementTypes.THIS_REFERENCE_EXPRESSION) != null;
}
private static final TokenSet THIS_OR_SUPER_SET =
TokenSet.create(GroovyElementTypes.THIS_REFERENCE_EXPRESSION, GroovyElementTypes.SUPER_REFERENCE_EXPRESSION);
public GrThisSuperReferenceExpression getThisOrSuperKeyword() {
return (GrThisSuperReferenceExpression)findNotNullChildByType(THIS_OR_SUPER_SET);
}
@NotNull
public GroovyResolveResult[] multiResolve(boolean incompleteCode) {
PsiClass clazz = getDelegatedClass();
if (clazz != null) {
PsiType[] argTypes = PsiUtil.getArgumentTypes(getFirstChild(), false);
PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
PsiSubstitutor substitutor;
if (isThisCall()) {
substitutor = PsiSubstitutor.EMPTY;
} else {
PsiClass enclosing = PsiUtil.getContextClass(this);
assert enclosing != null;
substitutor = TypeConversionUtil.getSuperClassSubstitutor(clazz, enclosing, PsiSubstitutor.EMPTY);
}
PsiType thisType = factory.createType(clazz, substitutor);
MethodResolverProcessor processor = new MethodResolverProcessor(clazz.getName(), this, true, thisType, argTypes, PsiType.EMPTY_ARRAY,
incompleteCode, false);
final ResolveState state = ResolveState.initial().put(PsiSubstitutor.KEY, substitutor);
clazz.processDeclarations(processor, state, null, this);
ResolveUtil.processNonCodeMembers(thisType, processor, getThisOrSuperKeyword(), state);
return processor.getCandidates();
}
return GroovyResolveResult.EMPTY_ARRAY;
}
public GroovyResolveResult[] multiResolveClass() {
PsiClass aClass = getDelegatedClass();
if (aClass == null) return GroovyResolveResult.EMPTY_ARRAY;
return new GroovyResolveResult[]{new GroovyResolveResultImpl(aClass, this, null, PsiSubstitutor.EMPTY, true, true)};
}
public PsiMethod resolveMethod() {
return PsiImplUtil.extractUniqueElement(multiResolve(false));
}
@NotNull
@Override
public GroovyResolveResult advancedResolve() {
return PsiImplUtil.extractUniqueResult(multiResolve(false));
}
@Nullable
public PsiClass getDelegatedClass() {
PsiClass typeDefinition = PsiUtil.getContextClass(this);
if (typeDefinition != null) {
return isThisCall() ? typeDefinition : typeDefinition.getSuperClass();
}
return null;
}
@NotNull
public String getCanonicalText() {
return getText(); //TODO
}
@NotNull
@Override
public GroovyResolveResult[] getCallVariants(@Nullable GrExpression upToArgument) {
return multiResolve(true);
}
}
| plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrConstructorInvocationImpl.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.jetbrains.plugins.groovy.lang.psi.impl.statements;
import com.intellij.lang.ASTNode;
import com.intellij.psi.*;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.TypeConversionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrConstructorInvocation;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrThisSuperReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyResolveResultImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrCallImpl;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;
import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodResolverProcessor;
/**
* User: Dmitry.Krasilschikov
* Date: 29.05.2007
*/
public class GrConstructorInvocationImpl extends GrCallImpl implements GrConstructorInvocation {
public GrConstructorInvocationImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(GroovyElementVisitor visitor) {
visitor.visitConstructorInvocation(this);
}
public String toString() {
return "Constructor invocation";
}
public boolean isSuperCall() {
return findChildByType(GroovyElementTypes.SUPER_REFERENCE_EXPRESSION) != null;
}
public boolean isThisCall() {
return findChildByType(GroovyElementTypes.THIS_REFERENCE_EXPRESSION) != null;
}
private static final TokenSet THIS_OR_SUPER_SET =
TokenSet.create(GroovyElementTypes.THIS_REFERENCE_EXPRESSION, GroovyElementTypes.SUPER_REFERENCE_EXPRESSION);
public GrThisSuperReferenceExpression getThisOrSuperKeyword() {
return (GrThisSuperReferenceExpression)findNotNullChildByType(THIS_OR_SUPER_SET);
}
@NotNull
public GroovyResolveResult[] multiResolve(boolean incompleteCode) {
PsiClass clazz = getDelegatedClass();
if (clazz != null) {
PsiType[] argTypes = PsiUtil.getArgumentTypes(getFirstChild(), false);
PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
PsiSubstitutor substitutor;
if (isThisCall()) {
substitutor = PsiSubstitutor.EMPTY;
} else {
PsiClass enclosing = PsiUtil.getContextClass(this);
assert enclosing != null;
substitutor = TypeConversionUtil.getSuperClassSubstitutor(clazz, enclosing, PsiSubstitutor.EMPTY);
}
PsiType thisType = factory.createType(clazz, substitutor);
MethodResolverProcessor processor = new MethodResolverProcessor(clazz.getName(), this, true, thisType, argTypes, PsiType.EMPTY_ARRAY,
incompleteCode, false);
final ResolveState state = ResolveState.initial().put(PsiSubstitutor.KEY, substitutor);
clazz.processDeclarations(processor, state, null, this);
ResolveUtil.processNonCodeMembers(thisType, processor, getThisOrSuperKeyword(), state);
return processor.getCandidates();
}
return GroovyResolveResult.EMPTY_ARRAY;
}
public GroovyResolveResult[] multiResolveClass() {
return new GroovyResolveResult[]{new GroovyResolveResultImpl(getDelegatedClass(), this, null, PsiSubstitutor.EMPTY, true, true)};
}
public PsiMethod resolveMethod() {
return PsiImplUtil.extractUniqueElement(multiResolve(false));
}
@NotNull
@Override
public GroovyResolveResult advancedResolve() {
return PsiImplUtil.extractUniqueResult(multiResolve(false));
}
@Nullable
public PsiClass getDelegatedClass() {
PsiClass typeDefinition = PsiUtil.getContextClass(this);
if (typeDefinition != null) {
return isThisCall() ? typeDefinition : typeDefinition.getSuperClass();
}
return null;
}
@NotNull
public String getCanonicalText() {
return getText(); //TODO
}
@NotNull
@Override
public GroovyResolveResult[] getCallVariants(@Nullable GrExpression upToArgument) {
return multiResolve(true);
}
}
| EA-38182 - IAE: GroovyResolveResultImpl.<init>
| plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrConstructorInvocationImpl.java | EA-38182 - IAE: GroovyResolveResultImpl.<init> | <ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrConstructorInvocationImpl.java
<ide> }
<ide>
<ide> public GroovyResolveResult[] multiResolveClass() {
<del> return new GroovyResolveResult[]{new GroovyResolveResultImpl(getDelegatedClass(), this, null, PsiSubstitutor.EMPTY, true, true)};
<add> PsiClass aClass = getDelegatedClass();
<add> if (aClass == null) return GroovyResolveResult.EMPTY_ARRAY;
<add>
<add> return new GroovyResolveResult[]{new GroovyResolveResultImpl(aClass, this, null, PsiSubstitutor.EMPTY, true, true)};
<ide> }
<ide>
<ide> public PsiMethod resolveMethod() { |
|
Java | epl-1.0 | 2a171362e672ea489fa4a8c1ae1316892bbcc383 | 0 | shisoft/Nebuchadnezzar,shisoft/Nebuchadnezzar | package org.shisoft.neb;
import org.shisoft.neb.io.Reader;
import org.shisoft.neb.io.type_lengths;
import org.shisoft.neb.utils.Bindings;
import java.util.Arrays;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by shisoft on 16-4-11.
*/
public class Cleaner {
private Trunk trunk;
private long cellHeadLen = (long) Bindings.cellHeadLen.invoke();
private final ConcurrentSkipListMap<Long, Long> fragments = new ConcurrentSkipListMap<>();
public Cleaner(Trunk trunk) {
this.trunk = trunk;
}
public void addFragment (long startPos, long endPos) {
Segment seg = trunk.locateSegment(startPos);
seg.lockWrite();
try {
assert startPos >= seg.getBaseAddr() && endPos < seg.getBaseAddr() + Trunk.getSegSize();
seg.getFrags().add(startPos);
seg.incDeadObjectBytes((int) (endPos - startPos + 1));
trunk.putTombstone(startPos, endPos);
} finally {
seg.unlockWrite();
}
}
public void removeFragment (Segment seg, long startPos, int length) {
seg.lockWrite();
try {
assert startPos >= seg.getBaseAddr() && length + startPos - 1 < seg.getBaseAddr() + Trunk.getSegSize();
seg.getFrags().remove(startPos);
seg.decDeadObjectBytes(length);
//seg.appendTombstones(startPos);
} finally {
seg.unlockWrite();
}
}
private void checkTooManyRetry(String message, int retry) {
if (retry > 1000) {
System.out.println(message + " " + retry);
}
}
private boolean isInSegment(long addr, Segment segment) {
return addr >= segment.getBaseAddr() && addr < segment.getBaseAddr() + Trunk.getSegSize();
}
public void phaseOneCleanSegment(Segment segment) {
long pos = segment.getBaseAddr();
int retry = 0;
while (true) {
try {
if (segment.getFrags().isEmpty()) break;
segment.lockWrite();
Long fragLoc = segment.getFrags().ceiling(pos);
if (fragLoc == null) break;
if (!isInSegment(fragLoc, segment)) {
System.out.println("Frag out of segment range: " + segment.getBaseAddr() + " ~ " + (segment.getBaseAddr() + Trunk.getSegSize()) + ", " + fragLoc);
segment.getFrags().remove(fragLoc);
break;
}
if (Reader.readByte(fragLoc) == 2) {
int fragLen = Reader.readInt(fragLoc + type_lengths.byteLen);
long adjPos = fragLoc + fragLen;
if (adjPos >= segment.getBaseAddr() + Trunk.getSegSize() ||
adjPos >= trunk.getStoreAddress() + trunk.getSize() ||
adjPos < segment.getBaseAddr() ||
adjPos < trunk.getStoreAddress()) {
System.out.println("out of boundary in cleaner when reading frag");
break;
}
if (adjPos == segment.getCurrentLoc()) {
if (!segment.resetCurrentLoc(adjPos, fragLoc)) {
retry++;
checkTooManyRetry("Seg curr pos moved", retry);
} else {
removeFragment(segment, fragLoc, fragLen);
retry = 0;
}
} else {
if (Reader.readByte(adjPos) == 1) {
if (adjPos + cellHeadLen > segment.getBaseAddr() + Trunk.getSegSize() ||
adjPos + cellHeadLen >= trunk.getStoreAddress() + trunk.getSize() ||
adjPos < segment.getBaseAddr() ||
adjPos < trunk.getStoreAddress()) {
System.out.println("out of boundary in cleaner when reading cell");
break;
}
long cellHash = (long) Bindings.readCellHash.invoke(trunk, adjPos);
ReentrantReadWriteLock l = trunk.locateLock(cellHash);
segment.unlockWrite();
l.writeLock().lock();
try {
long cellAddr = trunk.getCellIndex().get(cellHash);
if (cellAddr > 0 && isInSegment(cellAddr, segment)) {
if (cellAddr == adjPos) {
int cellLen = (int) Bindings.readCellLength.invoke(trunk, adjPos);
cellLen += cellHeadLen;
trunk.copyMemoryForCleaner(adjPos, fragLoc, cellLen);
trunk.getCellIndex().put(cellHash, (long) fragLoc);
removeFragment(segment, fragLoc, fragLen);
addFragment(fragLoc + cellLen, adjPos + cellLen - 1);
pos = fragLoc + cellLen;
retry = 0;
} else {
retry++;
//checkTooManyRetry("Cell meta modified in frag adj", retry);
}
} else {
retry++;
//checkTooManyRetry("Cell cannot been found in frag adj", retry);
}
} finally {
l.writeLock().unlock();
}
} else if (Reader.readByte(adjPos) == 2) {
if (segment.getFrags().contains(adjPos)) {
int adjFragLen = Reader.readInt(adjPos + type_lengths.byteLen);
removeFragment(segment, fragLoc, fragLen);
removeFragment(segment, adjPos, adjFragLen);
addFragment(fragLoc, adjPos + adjFragLen - 1);
retry = 0;
} else {
retry++;
checkTooManyRetry("Adj frag does not on record", retry);
}
} else {
retry++;
// checkTooManyRetry("Adj pos cannot been recognized " + Reader.readByte(adjPos) + " " +
// pos + " " + segment.getCurrentLoc(), retry);
}
}
} else {
retry++;
checkTooManyRetry("Location is not a frag", retry);
}
} finally {
segment.unlockWrite();
}
}
}
public void phaseOneCleaning () {
Arrays.stream(trunk.getSegments())
.filter(seg -> seg.getFrags().size() > 0)
//.sorted((o1, o2) -> Integer.valueOf(o2.getDeadObjectBytes()).compareTo(o1.getDeadObjectBytes()))
//.limit((long) (Math.max(1, trunk.getSegments().length * 0.5)))
//.parallel()
.forEach(this::phaseOneCleanSegment);
}
public void phaseTwoCleaning () {
}
public void clean () {
phaseOneCleaning();
}
}
| src/java/org/shisoft/neb/Cleaner.java | package org.shisoft.neb;
import org.shisoft.neb.io.Reader;
import org.shisoft.neb.io.type_lengths;
import org.shisoft.neb.utils.Bindings;
import java.util.Arrays;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by shisoft on 16-4-11.
*/
public class Cleaner {
private Trunk trunk;
private long cellHeadLen = (long) Bindings.cellHeadLen.invoke();
private final ConcurrentSkipListMap<Long, Long> fragments = new ConcurrentSkipListMap<>();
public Cleaner(Trunk trunk) {
this.trunk = trunk;
}
public void addFragment (long startPos, long endPos) {
Segment seg = trunk.locateSegment(startPos);
seg.lockWrite();
try {
assert startPos >= seg.getBaseAddr() && endPos < seg.getBaseAddr() + Trunk.getSegSize();
seg.getFrags().add(startPos);
seg.incDeadObjectBytes((int) (endPos - startPos + 1));
trunk.putTombstone(startPos, endPos);
} finally {
seg.unlockWrite();
}
}
public void removeFragment (Segment seg, long startPos, int length) {
seg.lockWrite();
try {
assert startPos >= seg.getBaseAddr() && length + startPos - 1 < seg.getBaseAddr() + Trunk.getSegSize();
seg.getFrags().remove(startPos);
seg.decDeadObjectBytes(length);
//seg.appendTombstones(startPos);
} finally {
seg.unlockWrite();
}
}
private void checkTooManyRetry(String message, int retry) {
if (retry > 1000) {
System.out.println(message + " " + retry);
}
}
private boolean isInSegment(long addr, Segment segment) {
return addr >= segment.getBaseAddr() && addr < segment.getBaseAddr() + Trunk.getSegSize();
}
public void phaseOneCleanSegment(Segment segment) {
long pos = segment.getBaseAddr();
int retry = 0;
while (true) {
try {
if (segment.getFrags().isEmpty()) break;
segment.lockWrite();
Long fragLoc = segment.getFrags().ceiling(pos);
if (fragLoc == null) break;
if (!isInSegment(fragLoc, segment)) {
System.out.println("Frag out of segment range: " + segment.getBaseAddr() + " ~ " + (segment.getBaseAddr() + Trunk.getSegSize()) + ", " + fragLoc);
segment.getFrags().remove(fragLoc);
break;
}
if (Reader.readByte(fragLoc) == 2) {
int fragLen = Reader.readInt(fragLoc + type_lengths.byteLen);
long adjPos = fragLoc + fragLen;
if (adjPos >= segment.getBaseAddr() + Trunk.getSegSize() ||
adjPos >= trunk.getStoreAddress() + trunk.getSize() ||
adjPos < segment.getBaseAddr() ||
adjPos < trunk.getStoreAddress()) {
System.out.println("out of boundary in cleaner when reading frag");
break;
}
if (adjPos == segment.getCurrentLoc()) {
if (!segment.resetCurrentLoc(adjPos, fragLoc)) {
retry++;
checkTooManyRetry("Seg curr pos moved", retry);
} else {
removeFragment(segment, fragLoc, fragLen);
retry = 0;
}
} else {
if (Reader.readByte(adjPos) == 1) {
if (adjPos + cellHeadLen > segment.getBaseAddr() + Trunk.getSegSize() ||
adjPos + cellHeadLen >= trunk.getStoreAddress() + trunk.getSize() ||
adjPos < segment.getBaseAddr() ||
adjPos < trunk.getStoreAddress()) {
System.out.println("out of boundary in cleaner when reading cell");
break;
}
long cellHash = (long) Bindings.readCellHash.invoke(trunk, adjPos);
ReentrantReadWriteLock l = trunk.locateLock(cellHash);
segment.unlockWrite();
l.writeLock().lock();
try {
long cellAddr = trunk.getCellIndex().get(cellHash);
if (cellAddr > 0 && isInSegment(cellAddr, segment)) {
if (cellAddr == adjPos) {
int cellLen = (int) Bindings.readCellLength.invoke(trunk, adjPos);
cellLen += cellHeadLen;
trunk.copyMemoryForCleaner(adjPos, fragLoc, cellLen);
trunk.getCellIndex().put(cellHash, (long) fragLoc);
removeFragment(segment, fragLoc, fragLen);
addFragment(fragLoc + cellLen, adjPos + cellLen - 1);
pos = fragLoc + cellLen;
retry = 0;
} else {
retry++;
//checkTooManyRetry("Cell meta modified in frag adj", retry);
}
} else {
retry++;
//checkTooManyRetry("Cell cannot been found in frag adj", retry);
}
} finally {
l.writeLock().unlock();
}
} else if (Reader.readByte(adjPos) == 2) {
if (segment.getFrags().contains(adjPos)) {
int adjFragLen = Reader.readInt(adjPos + type_lengths.byteLen);
removeFragment(segment, fragLoc, fragLen);
removeFragment(segment, adjPos, adjFragLen);
addFragment(fragLoc, adjPos + adjFragLen - 1);
retry = 0;
} else {
retry++;
checkTooManyRetry("Adj frag does not on record", retry);
}
} else {
retry++;
// checkTooManyRetry("Adj pos cannot been recognized " + Reader.readByte(adjPos) + " " +
// pos + " " + segment.getCurrentLoc(), retry);
}
}
} else {
retry++;
checkTooManyRetry("Location is not a frag", retry);
}
} finally {
segment.unlockWrite();
}
}
}
public void phaseOneCleaning () {
Arrays.stream(trunk.getSegments())
.filter(seg -> seg.getFrags().size() > 0)
//.sorted((o1, o2) -> Integer.valueOf(o2.getDeadObjectBytes()).compareTo(o1.getDeadObjectBytes()))
//.limit((long) (Math.max(1, trunk.getSegments().length * 0.5)))
.parallel()
.forEach(this::phaseOneCleanSegment);
}
public void phaseTwoCleaning () {
}
public void clean () {
phaseOneCleaning();
}
}
| unparalleled test
| src/java/org/shisoft/neb/Cleaner.java | unparalleled test | <ide><path>rc/java/org/shisoft/neb/Cleaner.java
<ide> .filter(seg -> seg.getFrags().size() > 0)
<ide> //.sorted((o1, o2) -> Integer.valueOf(o2.getDeadObjectBytes()).compareTo(o1.getDeadObjectBytes()))
<ide> //.limit((long) (Math.max(1, trunk.getSegments().length * 0.5)))
<del> .parallel()
<add> //.parallel()
<ide> .forEach(this::phaseOneCleanSegment);
<ide> }
<ide> |
|
Java | apache-2.0 | b227182a5e521eaa667c3db8b0738923d0b13de4 | 0 | gbecares/bdt | /*
* Copyright (C) 2014 Stratio (http://stratio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.qa.utils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
public class ZookeeperSecUtils {
private final Logger logger = LoggerFactory.getLogger(ZookeeperSecUtils.class);
private static final String DEFAULT_ZK_HOSTS = "0.0.0.0:2181";
private static final String DEFAULT_ZK_SESSION_TIMEOUT = "30000";
private static final String DEFAULT_ZK_PRINCIPAL = "zookeeper/[email protected]";
private String zk_hosts;
private int timeout;
private ExponentialBackoffRetry retryPolicy;
private CuratorFramework curatorZkClient;
private Stat st;
public ZookeeperSecUtils() {
this.zk_hosts = System.getProperty("ZOOKEEPER_HOSTS", DEFAULT_ZK_HOSTS);
//this.principal = System.getProperty("ZOOKEEPER_PRINCIPAL", DEFAULT_ZK_PRINCIPAL);
this.timeout = Integer.parseInt(System.getProperty("ZOOKEEPER_SESSION_TIMEOUT", DEFAULT_ZK_SESSION_TIMEOUT));
this.retryPolicy = new ExponentialBackoffRetry(1000, 3);
this.curatorZkClient = CuratorFrameworkFactory.builder().connectString(this.zk_hosts).retryPolicy(this.retryPolicy).connectionTimeoutMs(this.timeout).build();
if ("true".equals(System.getProperty("SECURIZED_ZOOKEEPER", "true"))) {
System.setProperty("java.security.auth.login.config", System.getProperty("JAAS", "schemas/jaas.conf"));
System.setProperty("java.security.krb5.conf", System.getProperty("KRB5", "schemas/krb5.conf"));
}
}
public ZookeeperSecUtils(String hosts, int timeout) {
this.zk_hosts = hosts;
this.timeout = timeout;
//this.principal = principal;
this.retryPolicy = new ExponentialBackoffRetry(1000, 3);
this.curatorZkClient = CuratorFrameworkFactory.builder().connectString(this.zk_hosts).retryPolicy(this.retryPolicy).connectionTimeoutMs(this.timeout).build();
if ("true".equals(System.getProperty("SECURIZED_ZOOKEEPER", "true"))) {
System.setProperty("java.security.auth.login.config", System.getProperty("JAAS", "schemas/jaas.conf"));
System.setProperty("java.security.krb5.conf", System.getProperty("KRB5", "schemas/krb5.conf"));
}
}
public void connectZk() throws InterruptedException {
if (this.curatorZkClient.getState() != CuratorFrameworkState.STARTED) {
this.curatorZkClient.start();
this.curatorZkClient.blockUntilConnected();
}
}
public String zRead(String path) throws Exception {
logger.debug("Trying to read data at {}", path);
byte[] b;
String data;
this.st = new Stat();
b = this.curatorZkClient.getData().forPath(path);
if (b == null) {
data = "";
} else {
data = new String(b, StandardCharsets.UTF_8);
}
logger.debug("Requested path {} contains {}", path, data);
return data;
}
public void zCreate(String path, String document, boolean isEphemeral) throws Exception {
byte[] bDoc = document.getBytes(StandardCharsets.UTF_8);
if (isEphemeral) {
this.curatorZkClient.create().withMode(CreateMode.EPHEMERAL).forPath(path, bDoc);
} else {
this.curatorZkClient.create().withMode(CreateMode.PERSISTENT).forPath(path, bDoc);
}
}
public void zCreate(String path, boolean isEphemeral) throws Exception {
byte[] bDoc = "".getBytes(StandardCharsets.UTF_8);
if (isEphemeral) {
this.curatorZkClient.create().withMode(CreateMode.EPHEMERAL).forPath(path, bDoc);
} else {
this.curatorZkClient.create().withMode(CreateMode.PERSISTENT).forPath(path, bDoc);
}
}
public Boolean isConnected() {
return ((this.curatorZkClient != null) && (this.curatorZkClient.getZookeeperClient().isConnected()));
}
public Boolean exists(String path) throws Exception {
return this.curatorZkClient.checkExists().forPath(path) != null;
}
public void delete(String path) throws Exception {
this.curatorZkClient.delete().forPath(path);
}
public void disconnect() throws InterruptedException {
this.curatorZkClient.getZookeeperClient().close();
}
public void setZookeeperSecConnection(String hosts, int timeout) {
this.zk_hosts = hosts;
this.timeout = timeout;
}
}
| src/main/java/com/stratio/qa/utils/ZookeeperSecUtils.java | /*
* Copyright (C) 2014 Stratio (http://stratio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.qa.utils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
public class ZookeeperSecUtils {
private final Logger logger = LoggerFactory.getLogger(ZookeeperSecUtils.class);
private static final String DEFAULT_ZK_HOSTS = "0.0.0.0:2181";
private static final String DEFAULT_ZK_SESSION_TIMEOUT = "30000";
private static final String DEFAULT_ZK_PRINCIPAL = "zookeeper/[email protected]";
private String zk_hosts;
private int timeout;
private ExponentialBackoffRetry retryPolicy;
private CuratorFramework curatorZkClient;
private Stat st;
public ZookeeperSecUtils() {
this.zk_hosts = System.getProperty("ZOOKEEPER_HOSTS", DEFAULT_ZK_HOSTS);
//this.principal = System.getProperty("ZOOKEEPER_PRINCIPAL", DEFAULT_ZK_PRINCIPAL);
this.timeout = Integer.parseInt(System.getProperty("ZOOKEEPER_SESSION_TIMEOUT", DEFAULT_ZK_SESSION_TIMEOUT));
this.retryPolicy = new ExponentialBackoffRetry(1000, 3);
this.curatorZkClient = CuratorFrameworkFactory.builder().connectString(this.zk_hosts).retryPolicy(this.retryPolicy).connectionTimeoutMs(this.timeout).build();
if ("true".equals(System.getProperty("SECURIZED_ZOOKEEPER", "true"))) {
System.setProperty("java.security.auth.login.config", System.getProperty("JAAS", "schemas/jaas.conf"));
System.setProperty("java.security.krb5.conf", System.getProperty("KRB5", "schemas/krb5.conf"));
}
}
public ZookeeperSecUtils(String hosts, int timeout) {
this.zk_hosts = hosts;
this.timeout = timeout;
//this.principal = principal;
this.retryPolicy = new ExponentialBackoffRetry(1000, 3);
this.curatorZkClient = CuratorFrameworkFactory.builder().connectString(this.zk_hosts).retryPolicy(this.retryPolicy).connectionTimeoutMs(this.timeout).build();
if ("true".equals(System.getProperty("SECURIZED_ZOOKEEPER", "true"))) {
System.setProperty("java.security.auth.login.config", System.getProperty("JAAS", "/tmp/jaas.conf"));
System.setProperty("java.security.krb5.conf", System.getProperty("KRB5", "/tmp/krb5.conf"));
}
}
public void connectZk() throws InterruptedException {
if (this.curatorZkClient.getState() != CuratorFrameworkState.STARTED) {
this.curatorZkClient.start();
this.curatorZkClient.blockUntilConnected();
}
}
public String zRead(String path) throws Exception {
logger.debug("Trying to read data at {}", path);
byte[] b;
String data;
this.st = new Stat();
b = this.curatorZkClient.getData().forPath(path);
if (b == null) {
data = "";
} else {
data = new String(b, StandardCharsets.UTF_8);
}
logger.debug("Requested path {} contains {}", path, data);
return data;
}
public void zCreate(String path, String document, boolean isEphemeral) throws Exception {
byte[] bDoc = document.getBytes(StandardCharsets.UTF_8);
if (isEphemeral) {
this.curatorZkClient.create().withMode(CreateMode.EPHEMERAL).forPath(path, bDoc);
} else {
this.curatorZkClient.create().withMode(CreateMode.PERSISTENT).forPath(path, bDoc);
}
}
public void zCreate(String path, boolean isEphemeral) throws Exception {
byte[] bDoc = "".getBytes(StandardCharsets.UTF_8);
if (isEphemeral) {
this.curatorZkClient.create().withMode(CreateMode.EPHEMERAL).forPath(path, bDoc);
} else {
this.curatorZkClient.create().withMode(CreateMode.PERSISTENT).forPath(path, bDoc);
}
}
public Boolean isConnected() {
return ((this.curatorZkClient != null) && (this.curatorZkClient.getZookeeperClient().isConnected()));
}
public Boolean exists(String path) throws Exception {
return this.curatorZkClient.checkExists().forPath(path) != null;
}
public void delete(String path) throws Exception {
this.curatorZkClient.delete().forPath(path);
}
public void disconnect() throws InterruptedException {
this.curatorZkClient.getZookeeperClient().close();
}
public void setZookeeperSecConnection(String hosts, int timeout) {
this.zk_hosts = hosts;
this.timeout = timeout;
}
}
| [QA-369] fixing IT failure with securized zk
| src/main/java/com/stratio/qa/utils/ZookeeperSecUtils.java | [QA-369] fixing IT failure with securized zk | <ide><path>rc/main/java/com/stratio/qa/utils/ZookeeperSecUtils.java
<ide> this.curatorZkClient = CuratorFrameworkFactory.builder().connectString(this.zk_hosts).retryPolicy(this.retryPolicy).connectionTimeoutMs(this.timeout).build();
<ide>
<ide> if ("true".equals(System.getProperty("SECURIZED_ZOOKEEPER", "true"))) {
<del> System.setProperty("java.security.auth.login.config", System.getProperty("JAAS", "/tmp/jaas.conf"));
<del> System.setProperty("java.security.krb5.conf", System.getProperty("KRB5", "/tmp/krb5.conf"));
<add> System.setProperty("java.security.auth.login.config", System.getProperty("JAAS", "schemas/jaas.conf"));
<add> System.setProperty("java.security.krb5.conf", System.getProperty("KRB5", "schemas/krb5.conf"));
<ide> }
<ide> }
<ide> |
|
Java | lgpl-2.1 | 6e544de355b74e9f07c5c786a7632ae42505aed2 | 0 | pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 com.xpn.xwiki.web;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Date;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.util.Util;
/**
* <p>
* Action for serving skin files. It allows skins to be defined using XDocuments as skins, by letting files be placed as
* text fields in an XWiki.XWikiSkins object, or as attachments to the document, or as a file in the filesystem. If the
* file is not found in the current skin, then it is searched in its base skin, and eventually in the default base
* skins,
* </p>
* <p>
* This action indicates that the results should be publicly cacheable for 30 days.
* </p>
*
* @version $Id$
* @since 1.0
*/
public class SkinAction extends XWikiAction
{
/** Logging helper. */
private static final Logger LOGGER = LoggerFactory.getLogger(SkinAction.class);
/** Path delimiter. */
private static final String DELIMITER = "/";
/** The directory where the skins are placed in the webapp. */
private static final String SKINS_DIRECTORY = "skins";
/** The directory where resources are placed in the webapp. */
private static final String RESOURCES_DIRECTORY = "resources";
/** The encoding to use when reading text resources from the filesystem and when sending css/javascript responses. */
private static final String ENCODING = "UTF-8";
/**
* {@inheritDoc}
*
* @see XWikiAction#render(XWikiContext)
*/
@Override
public String render(XWikiContext context) throws XWikiException
{
try {
return render(context.getRequest().getPathInfo(), context);
} catch (IOException e) {
context.getResponse().setStatus(404);
return "docdoesnotexist";
}
}
public String render(String path, XWikiContext context) throws XWikiException, IOException
{
XWiki xwiki = context.getWiki();
// Since skin paths usually contain the name of skin document, it is likely that the context document belongs to
// the current skin.
XWikiDocument doc = context.getDoc();
// The base skin could be either a filesystem directory, or an xdocument.
String baseskin = xwiki.getBaseSkin(context, true);
XWikiDocument baseskindoc = xwiki.getDocument(baseskin, context);
// The default base skin is always a filesystem directory.
String defaultbaseskin = xwiki.getDefaultBaseSkin(context);
LOGGER.debug("document: [{}] ; baseskin: [{}] ; defaultbaseskin: [{}]",
new Object[] {doc.getDocumentReference(), baseskin, defaultbaseskin});
// Since we don't know exactly what does the URL point at, meaning that we don't know where the skin identifier
// ends and where the path to the file starts, we must try to split at every '/' character.
int idx = path.lastIndexOf(DELIMITER);
boolean found = false;
while (idx > 0) {
try {
String filename = Util.decodeURI(path.substring(idx + 1), context);
LOGGER.debug("Trying [{}]", filename);
// Try on the current skin document.
if (renderSkin(filename, doc, context)) {
found = true;
break;
}
// Try on the base skin document, if it is not the same as above.
if (!doc.getName().equals(baseskin)) {
if (renderSkin(filename, baseskindoc, context)) {
found = true;
break;
}
}
// Try on the default base skin, if it wasn't already tested above.
if (!(doc.getName().equals(defaultbaseskin) || baseskin.equals(defaultbaseskin))) {
// defaultbaseskin can only be on the filesystem, so don't try to use it as a
// skin document.
if (renderFileFromFilesystem(getSkinFilePath(filename, defaultbaseskin), context)) {
found = true;
break;
}
}
// Try in the resources directory.
if (renderFileFromFilesystem(getResourceFilePath(filename), context)) {
found = true;
break;
}
} catch (XWikiException ex) {
if (ex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {
// This means that the response couldn't be sent, although the file was
// successfully found. Signal this further, and stop trying to render.
throw ex;
}
LOGGER.debug(String.valueOf(idx), ex);
}
idx = path.lastIndexOf(DELIMITER, idx - 1);
}
if (!found) {
context.getResponse().setStatus(404);
return "docdoesnotexist";
}
return null;
}
/**
* Get the path for the given skin file in the given skin.
*
* @param filename Name of the file.
* @param skin Name of the skin to search in.
* @throws IOException if filename is invalid
*/
public String getSkinFilePath(String filename, String skin) throws IOException
{
String path =
URI.create(DELIMITER + SKINS_DIRECTORY + DELIMITER + skin + DELIMITER + filename).normalize().toString();
if (!path.startsWith(DELIMITER + SKINS_DIRECTORY)) {
LOGGER.warn("Illegal access, tried to use file [{}] as a skin. Possible break-in attempt!", path);
throw new IOException("Invalid filename: '" + filename + "' for skin '" + skin + "'");
}
return path;
}
/**
* Get the path for the given file in resources.
*
* @param filename Name of the file.
* @throws IOException if filename is invalid
*/
public String getResourceFilePath(String filename) throws IOException
{
String path = URI.create(DELIMITER + RESOURCES_DIRECTORY + DELIMITER + filename).normalize().toString();
if (!path.startsWith(DELIMITER + RESOURCES_DIRECTORY)) {
LOGGER.warn("Illegal access, tried to use file [{}] as a resource. Possible break-in attempt!", path);
throw new IOException("Invalid filename: '" + filename + "'");
}
return path;
}
/**
* Tries to serve a skin file using <tt>doc</tt> as a skin document. The file is searched in the following places:
* <ol>
* <li>As the content of a property with the same name as the requested filename, from an XWikiSkins object attached
* to the document.</li>
* <li>As the content of an attachment with the same name as the requested filename.</li>
* <li>As a file located on the filesystem, in the directory with the same name as the current document (in case the
* URL was actually pointing to <tt>/skins/directory/file</tt>).</li>
* </ol>
*
* @param filename The name of the skin file that should be rendered.
* @param doc The skin {@link XWikiDocument document}.
* @param context The current {@link XWikiContext request context}.
* @return <tt>true</tt> if the attachment was found and the content was successfully sent.
* @throws XWikiException If the attachment cannot be loaded.
* @throws IOException if the filename is invalid
*/
private boolean renderSkin(String filename, XWikiDocument doc, XWikiContext context) throws XWikiException,
IOException
{
LOGGER.debug("Rendering file [{}] within the [{}] document", filename, doc.getDocumentReference());
try {
if (doc.isNew()) {
LOGGER.debug("[{}] is not a document", doc.getDocumentReference().getName());
} else {
return renderFileFromObjectField(filename, doc, context)
|| renderFileFromAttachment(filename, doc, context)
|| (SKINS_DIRECTORY.equals(doc.getSpace()) && renderFileFromFilesystem(
getSkinFilePath(filename, doc.getName()), context));
}
} catch (IOException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response:", e);
}
return renderFileFromFilesystem(getSkinFilePath(filename, doc.getName()), context);
}
/**
* Tries to serve a file from the filesystem.
*
* @param path Path of the file that should be rendered.
* @param context The current {@link XWikiContext request context}.
* @return <tt>true</tt> if the file was found and its content was successfully sent.
* @throws XWikiException If the response cannot be sent.
*/
private boolean renderFileFromFilesystem(String path, XWikiContext context) throws XWikiException
{
LOGGER.debug("Rendering filesystem file from path [{}]", path);
XWikiResponse response = context.getResponse();
try {
byte[] data;
data = context.getWiki().getResourceContentAsBytes(path);
if (data != null && data.length > 0) {
String filename = path.substring(path.lastIndexOf("/") + 1, path.length());
String mimetype = context.getEngineContext().getMimeType(filename.toLowerCase());
Date modified = null;
if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) {
// Always force UTF-8, as this is the assumed encoding for text files.
String rawContent = new String(data, ENCODING);
byte[] newdata = context.getWiki().parseContent(rawContent, context).getBytes(ENCODING);
// If the content contained velocity code, then it should not be cached
if (Arrays.equals(newdata, data)) {
modified = context.getWiki().getResourceLastModificationDate(path);
} else {
modified = new Date();
data = newdata;
}
response.setCharacterEncoding(ENCODING);
} else {
modified = context.getWiki().getResourceLastModificationDate(path);
}
setupHeaders(response, mimetype, modified, data.length);
try {
response.getOutputStream().write(data);
} catch (IOException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e);
}
return true;
}
} catch (IOException ex) {
LOGGER.info("Skin file [{}] does not exist or cannot be accessed", path);
}
return false;
}
/**
* Tries to serve the content of an XWikiSkins object field as a skin file.
*
* @param filename The name of the skin file that should be rendered.
* @param doc The skin {@link XWikiDocument document}.
* @param context The current {@link XWikiContext request context}.
* @return <tt>true</tt> if the object exists, and the field is set to a non-empty value, and its content was
* successfully sent.
* @throws IOException If the response cannot be sent.
*/
public boolean renderFileFromObjectField(String filename, XWikiDocument doc, XWikiContext context)
throws IOException
{
LOGGER.debug("... as object property");
BaseObject object = doc.getObject("XWiki.XWikiSkins");
String content = null;
if (object != null) {
content = object.getStringValue(filename);
}
if (!StringUtils.isBlank(content)) {
XWiki xwiki = context.getWiki();
XWikiResponse response = context.getResponse();
String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase());
// Since object fields are read as unicode strings, the result does not depend on the wiki encoding. Force
// the output to UTF-8.
response.setCharacterEncoding(ENCODING);
if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) {
content = context.getWiki().parseContent(content, context);
}
byte[] data = content.getBytes(ENCODING);
setupHeaders(response, mimetype, doc.getDate(), data.length);
response.getOutputStream().write(data);
return true;
} else {
LOGGER.debug("Object field not found or empty");
}
return false;
}
/**
* Tries to serve the content of an attachment as a skin file.
*
* @param filename The name of the skin file that should be rendered.
* @param doc The skin {@link XWikiDocument document}.
* @param context The current {@link XWikiContext request context}.
* @return <tt>true</tt> if the attachment was found and its content was successfully sent.
* @throws IOException If the response cannot be sent.
* @throws XWikiException If the attachment cannot be loaded.
*/
public boolean renderFileFromAttachment(String filename, XWikiDocument doc, XWikiContext context)
throws IOException, XWikiException
{
LOGGER.debug("... as attachment");
XWikiAttachment attachment = doc.getAttachment(filename);
if (attachment != null) {
XWiki xwiki = context.getWiki();
XWikiResponse response = context.getResponse();
String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase());
if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) {
byte[] data = attachment.getContent(context);
// Always force UTF-8, as this is the assumed encoding for text files.
data = context.getWiki().parseContent(new String(data, ENCODING), context).getBytes(ENCODING);
response.setCharacterEncoding(ENCODING);
setupHeaders(response, mimetype, attachment.getDate(), data.length);
response.getOutputStream().write(data);
} else {
setupHeaders(response, mimetype, attachment.getDate(), attachment.getContentSize(context));
IOUtils.copy(attachment.getContentInputStream(context), response.getOutputStream());
}
return true;
} else {
LOGGER.debug("Attachment not found");
}
return false;
}
/**
* Checks if a mimetype indicates a javascript file.
*
* @param mimetype The mime type to check.
* @return <tt>true</tt> if the mime type represents a javascript file.
*/
public boolean isJavascriptMimeType(String mimetype)
{
boolean result =
"text/javascript".equalsIgnoreCase(mimetype) || "application/x-javascript".equalsIgnoreCase(mimetype)
|| "application/javascript".equalsIgnoreCase(mimetype);
result |= "application/ecmascript".equalsIgnoreCase(mimetype) || "text/ecmascript".equalsIgnoreCase(mimetype);
return result;
}
/**
* Checks if a mimetype indicates a CSS file.
*
* @param mimetype The mime type to check.
* @return <tt>true</tt> if the mime type represents a css file.
*/
public boolean isCssMimeType(String mimetype)
{
return "text/css".equalsIgnoreCase(mimetype);
}
/**
* Sets several headers to properly identify the response.
*
* @param response The servlet response object, where the headers should be set.
* @param mimetype The mimetype of the file. Used in the "Content-Type" header.
* @param lastChanged The date of the last change of the file. Used in the "Last-Modified" header.
* @param length The length of the content (in bytes). Used in the "Content-Length" header.
*/
protected void setupHeaders(XWikiResponse response, String mimetype, Date lastChanged, int length)
{
if (!StringUtils.isBlank(mimetype)) {
response.setContentType(mimetype);
} else {
response.setContentType("application/octet-stream");
}
response.setDateHeader("Last-Modified", lastChanged.getTime());
// Cache for one month (30 days)
response.setHeader("Cache-Control", "public");
response.setDateHeader("Expires", (new Date()).getTime() + 30 * 24 * 3600 * 1000L);
response.setContentLength(length);
}
}
| xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/SkinAction.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 com.xpn.xwiki.web;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Date;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.util.Util;
/**
* <p>
* Action for serving skin files. It allows skins to be defined using XDocuments as skins, by letting files be placed as
* text fields in an XWiki.XWikiSkins object, or as attachments to the document, or as a file in the filesystem. If the
* file is not found in the current skin, then it is searched in its base skin, and eventually in the default base
* skins,
* </p>
* <p>
* This action indicates that the results should be publicly cacheable for 30 days.
* </p>
*
* @version $Id$
* @since 1.0
*/
public class SkinAction extends XWikiAction
{
/** Logging helper. */
private static final Logger LOGGER = LoggerFactory.getLogger(SkinAction.class);
/** Path delimiter. */
private static final String DELIMITER = "/";
/** The directory where the skins are placed in the webapp. */
private static final String SKINS_DIRECTORY = "skins";
/** The directory where resources are placed in the webapp. */
private static final String RESOURCES_DIRECTORY = "resources";
/** The encoding to use when reading text resources from the filesystem and when sending css/javascript responses. */
private static final String ENCODING = "UTF-8";
/**
* {@inheritDoc}
*
* @see XWikiAction#render(XWikiContext)
*/
@Override
public String render(XWikiContext context) throws XWikiException
{
try {
return render(context.getRequest().getPathInfo(), context);
} catch (IOException e) {
context.getResponse().setStatus(404);
return "docdoesnotexist";
}
}
public String render(String path, XWikiContext context) throws XWikiException, IOException
{
XWiki xwiki = context.getWiki();
// Since skin paths usually contain the name of skin document, it is likely that the context document belongs to
// the current skin.
XWikiDocument doc = context.getDoc();
// The base skin could be either a filesystem directory, or an xdocument.
String baseskin = xwiki.getBaseSkin(context, true);
XWikiDocument baseskindoc = xwiki.getDocument(baseskin, context);
// The default base skin is always a filesystem directory.
String defaultbaseskin = xwiki.getDefaultBaseSkin(context);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("document: " + doc.getFullName() + " ; baseskin: " + baseskin + " ; defaultbaseskin: "
+ defaultbaseskin);
}
// Since we don't know exactly what does the URL point at, meaning that we don't know where the skin identifier
// ends and where the path to the file starts, we must try to split at every '/' character.
int idx = path.lastIndexOf(DELIMITER);
boolean found = false;
while (idx > 0) {
try {
String filename = Util.decodeURI(path.substring(idx + 1), context);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Trying '" + filename + "'");
}
// Try on the current skin document.
if (renderSkin(filename, doc, context)) {
found = true;
break;
}
// Try on the base skin document, if it is not the same as above.
if (!doc.getName().equals(baseskin)) {
if (renderSkin(filename, baseskindoc, context)) {
found = true;
break;
}
}
// Try on the default base skin, if it wasn't already tested above.
if (!(doc.getName().equals(defaultbaseskin) || baseskin.equals(defaultbaseskin))) {
// defaultbaseskin can only be on the filesystem, so don't try to use it as a
// skin document.
if (renderFileFromFilesystem(getSkinFilePath(filename, defaultbaseskin), context)) {
found = true;
break;
}
}
// Try in the resources directory.
if (renderFileFromFilesystem(getResourceFilePath(filename), context)) {
found = true;
break;
}
} catch (XWikiException ex) {
if (ex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {
// This means that the response couldn't be sent, although the file was
// successfully found. Signal this further, and stop trying to render.
throw ex;
}
LOGGER.debug(String.valueOf(idx), ex);
}
idx = path.lastIndexOf(DELIMITER, idx - 1);
}
if (!found) {
context.getResponse().setStatus(404);
return "docdoesnotexist";
}
return null;
}
/**
* Get the path for the given skin file in the given skin.
*
* @param filename Name of the file.
* @param skin Name of the skin to search in.
* @throws IOException if filename is invalid
*/
public String getSkinFilePath(String filename, String skin) throws IOException
{
String path =
URI.create(DELIMITER + SKINS_DIRECTORY + DELIMITER + skin + DELIMITER + filename).normalize().toString();
if (!path.startsWith(DELIMITER + SKINS_DIRECTORY)) {
LOGGER.warn("Illegal access, tried to use file [" + path + "] as a skin. Possible break-in attempt!");
throw new IOException("Invalid filename: '" + filename + "' for skin '" + skin + "'");
}
return path;
}
/**
* Get the path for the given file in resources.
*
* @param filename Name of the file.
* @throws IOException if filename is invalid
*/
public String getResourceFilePath(String filename) throws IOException
{
String path = URI.create(DELIMITER + RESOURCES_DIRECTORY + DELIMITER + filename).normalize().toString();
if (!path.startsWith(DELIMITER + RESOURCES_DIRECTORY)) {
LOGGER.warn("Illegal access, tried to use file [" + path + "] as a resource. Possible break-in attempt!");
throw new IOException("Invalid filename: '" + filename + "'");
}
return path;
}
/**
* Tries to serve a skin file using <tt>doc</tt> as a skin document. The file is searched in the following places:
* <ol>
* <li>As the content of a property with the same name as the requested filename, from an XWikiSkins object attached
* to the document.</li>
* <li>As the content of an attachment with the same name as the requested filename.</li>
* <li>As a file located on the filesystem, in the directory with the same name as the current document (in case the
* URL was actually pointing to <tt>/skins/directory/file</tt>).</li>
* </ol>
*
* @param filename The name of the skin file that should be rendered.
* @param doc The skin {@link XWikiDocument document}.
* @param context The current {@link XWikiContext request context}.
* @return <tt>true</tt> if the attachment was found and the content was successfully sent.
* @throws XWikiException If the attachment cannot be loaded.
* @throws IOException if the filename is invalid
*/
private boolean renderSkin(String filename, XWikiDocument doc, XWikiContext context) throws XWikiException,
IOException
{
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Rendering file '" + filename + "' within the '" + doc.getFullName() + "' document");
}
try {
if (doc.isNew()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(doc.getName() + " is not a document");
}
} else {
return renderFileFromObjectField(filename, doc, context)
|| renderFileFromAttachment(filename, doc, context)
|| (SKINS_DIRECTORY.equals(doc.getSpace()) && renderFileFromFilesystem(
getSkinFilePath(filename, doc.getName()), context));
}
} catch (IOException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response:", e);
}
return renderFileFromFilesystem(getSkinFilePath(filename, doc.getName()), context);
}
/**
* Tries to serve a file from the filesystem.
*
* @param path Path of the file that should be rendered.
* @param context The current {@link XWikiContext request context}.
* @return <tt>true</tt> if the file was found and its content was successfully sent.
* @throws XWikiException If the response cannot be sent.
*/
private boolean renderFileFromFilesystem(String path, XWikiContext context) throws XWikiException
{
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Rendering filesystem file from path [" + path + "]");
}
XWikiResponse response = context.getResponse();
try {
byte[] data;
data = context.getWiki().getResourceContentAsBytes(path);
if (data != null && data.length > 0) {
String filename = path.substring(path.lastIndexOf("/") + 1, path.length());
String mimetype = context.getEngineContext().getMimeType(filename.toLowerCase());
Date modified = null;
if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) {
// Always force UTF-8, as this is the assumed encoding for text files.
String rawContent = new String(data, ENCODING);
byte[] newdata = context.getWiki().parseContent(rawContent, context).getBytes(ENCODING);
// If the content contained velocity code, then it should not be cached
if (Arrays.equals(newdata, data)) {
modified = context.getWiki().getResourceLastModificationDate(path);
} else {
modified = new Date();
data = newdata;
}
response.setCharacterEncoding(ENCODING);
} else {
modified = context.getWiki().getResourceLastModificationDate(path);
}
setupHeaders(response, mimetype, modified, data.length);
try {
response.getOutputStream().write(data);
} catch (IOException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e);
}
return true;
}
} catch (IOException ex) {
LOGGER.info("Skin file '" + path + "' does not exist or cannot be accessed");
}
return false;
}
/**
* Tries to serve the content of an XWikiSkins object field as a skin file.
*
* @param filename The name of the skin file that should be rendered.
* @param doc The skin {@link XWikiDocument document}.
* @param context The current {@link XWikiContext request context}.
* @return <tt>true</tt> if the object exists, and the field is set to a non-empty value, and its content was
* successfully sent.
* @throws IOException If the response cannot be sent.
*/
public boolean renderFileFromObjectField(String filename, XWikiDocument doc, XWikiContext context)
throws IOException
{
LOGGER.debug("... as object property");
BaseObject object = doc.getObject("XWiki.XWikiSkins");
String content = null;
if (object != null) {
content = object.getStringValue(filename);
}
if (!StringUtils.isBlank(content)) {
XWiki xwiki = context.getWiki();
XWikiResponse response = context.getResponse();
String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase());
// Since object fields are read as unicode strings, the result does not depend on the wiki encoding. Force
// the output to UTF-8.
response.setCharacterEncoding(ENCODING);
if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) {
content = context.getWiki().parseContent(content, context);
}
byte[] data = content.getBytes(ENCODING);
setupHeaders(response, mimetype, doc.getDate(), data.length);
response.getOutputStream().write(data);
return true;
} else {
LOGGER.debug("Object field not found or empty");
}
return false;
}
/**
* Tries to serve the content of an attachment as a skin file.
*
* @param filename The name of the skin file that should be rendered.
* @param doc The skin {@link XWikiDocument document}.
* @param context The current {@link XWikiContext request context}.
* @return <tt>true</tt> if the attachment was found and its content was successfully sent.
* @throws IOException If the response cannot be sent.
* @throws XWikiException If the attachment cannot be loaded.
*/
public boolean renderFileFromAttachment(String filename, XWikiDocument doc, XWikiContext context)
throws IOException, XWikiException
{
LOGGER.debug("... as attachment");
XWikiAttachment attachment = doc.getAttachment(filename);
if (attachment != null) {
XWiki xwiki = context.getWiki();
XWikiResponse response = context.getResponse();
String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase());
if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) {
byte[] data = attachment.getContent(context);
// Always force UTF-8, as this is the assumed encoding for text files.
data = context.getWiki().parseContent(new String(data, ENCODING), context).getBytes(ENCODING);
response.setCharacterEncoding(ENCODING);
setupHeaders(response, mimetype, attachment.getDate(), data.length);
response.getOutputStream().write(data);
} else {
setupHeaders(response, mimetype, attachment.getDate(), attachment.getContentSize(context));
IOUtils.copy(attachment.getContentInputStream(context), response.getOutputStream());
}
return true;
} else {
LOGGER.debug("Attachment not found");
}
return false;
}
/**
* Checks if a mimetype indicates a javascript file.
*
* @param mimetype The mime type to check.
* @return <tt>true</tt> if the mime type represents a javascript file.
*/
public boolean isJavascriptMimeType(String mimetype)
{
boolean result =
"text/javascript".equalsIgnoreCase(mimetype) || "application/x-javascript".equalsIgnoreCase(mimetype)
|| "application/javascript".equalsIgnoreCase(mimetype);
result |= "application/ecmascript".equalsIgnoreCase(mimetype) || "text/ecmascript".equalsIgnoreCase(mimetype);
return result;
}
/**
* Checks if a mimetype indicates a CSS file.
*
* @param mimetype The mime type to check.
* @return <tt>true</tt> if the mime type represents a css file.
*/
public boolean isCssMimeType(String mimetype)
{
return "text/css".equalsIgnoreCase(mimetype);
}
/**
* Sets several headers to properly identify the response.
*
* @param response The servlet response object, where the headers should be set.
* @param mimetype The mimetype of the file. Used in the "Content-Type" header.
* @param lastChanged The date of the last change of the file. Used in the "Last-Modified" header.
* @param length The length of the content (in bytes). Used in the "Content-Length" header.
*/
protected void setupHeaders(XWikiResponse response, String mimetype, Date lastChanged, int length)
{
if (!StringUtils.isBlank(mimetype)) {
response.setContentType(mimetype);
} else {
response.setContentType("application/octet-stream");
}
response.setDateHeader("Last-Modified", lastChanged.getTime());
// Cache for one month (30 days)
response.setHeader("Cache-Control", "public");
response.setDateHeader("Expires", (new Date()).getTime() + 30 * 24 * 3600 * 1000L);
response.setContentLength(length);
}
}
| [cleanup] Improved logging code
| xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/SkinAction.java | [cleanup] Improved logging code | <ide><path>wiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/SkinAction.java
<ide> // The default base skin is always a filesystem directory.
<ide> String defaultbaseskin = xwiki.getDefaultBaseSkin(context);
<ide>
<del> if (LOGGER.isDebugEnabled()) {
<del> LOGGER.debug("document: " + doc.getFullName() + " ; baseskin: " + baseskin + " ; defaultbaseskin: "
<del> + defaultbaseskin);
<del> }
<add> LOGGER.debug("document: [{}] ; baseskin: [{}] ; defaultbaseskin: [{}]",
<add> new Object[] {doc.getDocumentReference(), baseskin, defaultbaseskin});
<ide>
<ide> // Since we don't know exactly what does the URL point at, meaning that we don't know where the skin identifier
<ide> // ends and where the path to the file starts, we must try to split at every '/' character.
<ide> while (idx > 0) {
<ide> try {
<ide> String filename = Util.decodeURI(path.substring(idx + 1), context);
<del> if (LOGGER.isDebugEnabled()) {
<del> LOGGER.debug("Trying '" + filename + "'");
<del> }
<add> LOGGER.debug("Trying [{}]", filename);
<ide>
<ide> // Try on the current skin document.
<ide> if (renderSkin(filename, doc, context)) {
<ide> String path =
<ide> URI.create(DELIMITER + SKINS_DIRECTORY + DELIMITER + skin + DELIMITER + filename).normalize().toString();
<ide> if (!path.startsWith(DELIMITER + SKINS_DIRECTORY)) {
<del> LOGGER.warn("Illegal access, tried to use file [" + path + "] as a skin. Possible break-in attempt!");
<add> LOGGER.warn("Illegal access, tried to use file [{}] as a skin. Possible break-in attempt!", path);
<ide> throw new IOException("Invalid filename: '" + filename + "' for skin '" + skin + "'");
<ide> }
<ide> return path;
<ide> {
<ide> String path = URI.create(DELIMITER + RESOURCES_DIRECTORY + DELIMITER + filename).normalize().toString();
<ide> if (!path.startsWith(DELIMITER + RESOURCES_DIRECTORY)) {
<del> LOGGER.warn("Illegal access, tried to use file [" + path + "] as a resource. Possible break-in attempt!");
<add> LOGGER.warn("Illegal access, tried to use file [{}] as a resource. Possible break-in attempt!", path);
<ide> throw new IOException("Invalid filename: '" + filename + "'");
<ide> }
<ide> return path;
<ide> private boolean renderSkin(String filename, XWikiDocument doc, XWikiContext context) throws XWikiException,
<ide> IOException
<ide> {
<del> if (LOGGER.isDebugEnabled()) {
<del> LOGGER.debug("Rendering file '" + filename + "' within the '" + doc.getFullName() + "' document");
<del> }
<add> LOGGER.debug("Rendering file [{}] within the [{}] document", filename, doc.getDocumentReference());
<ide> try {
<ide> if (doc.isNew()) {
<del> if (LOGGER.isDebugEnabled()) {
<del> LOGGER.debug(doc.getName() + " is not a document");
<del> }
<add> LOGGER.debug("[{}] is not a document", doc.getDocumentReference().getName());
<ide> } else {
<ide> return renderFileFromObjectField(filename, doc, context)
<ide> || renderFileFromAttachment(filename, doc, context)
<ide> */
<ide> private boolean renderFileFromFilesystem(String path, XWikiContext context) throws XWikiException
<ide> {
<del> if (LOGGER.isDebugEnabled()) {
<del> LOGGER.debug("Rendering filesystem file from path [" + path + "]");
<del> }
<add> LOGGER.debug("Rendering filesystem file from path [{}]", path);
<ide> XWikiResponse response = context.getResponse();
<ide> try {
<ide> byte[] data;
<ide> return true;
<ide> }
<ide> } catch (IOException ex) {
<del> LOGGER.info("Skin file '" + path + "' does not exist or cannot be accessed");
<add> LOGGER.info("Skin file [{}] does not exist or cannot be accessed", path);
<ide> }
<ide> return false;
<ide> } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.