diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRAXMLToSampleTab.java b/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRAXMLToSampleTab.java
index d42eb43d..3c431cdd 100644
--- a/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRAXMLToSampleTab.java
+++ b/src/main/java/uk/ac/ebi/fgpt/sampletab/sra/ENASRAXMLToSampleTab.java
@@ -1,377 +1,377 @@
package uk.ac.ebi.fgpt.sampletab.sra;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress2.magetab.exception.ParseException;
import uk.ac.ebi.arrayexpress2.magetab.validator.Validator;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.SampleData;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.msi.Database;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.msi.Organization;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.msi.Publication;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.msi.TermSource;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.scd.node.SampleNode;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.scd.node.attribute.CharacteristicAttribute;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.scd.node.attribute.CommentAttribute;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.scd.node.attribute.DatabaseAttribute;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.scd.node.attribute.OrganismAttribute;
import uk.ac.ebi.arrayexpress2.sampletab.datamodel.scd.node.attribute.UnitAttribute;
import uk.ac.ebi.arrayexpress2.sampletab.renderer.SampleTabWriter;
import uk.ac.ebi.arrayexpress2.sampletab.validator.SampleTabValidator;
import uk.ac.ebi.fgpt.sampletab.utils.ENAUtils;
import uk.ac.ebi.fgpt.sampletab.utils.XMLUtils;
public class ENASRAXMLToSampleTab {
// logging
private Logger log = LoggerFactory.getLogger(getClass());
//characteristics that we want to ignore
private static Collection<String> characteristicsIgnore;
static {
characteristicsIgnore = new TreeSet<String>();
characteristicsIgnore.add("ENA-SPOT-COUNT");
characteristicsIgnore.add("ENA-BASE-COUNT");
characteristicsIgnore.add("ENA-SUBMISSION-TOOL");
characteristicsIgnore = Collections.unmodifiableCollection(characteristicsIgnore);
}
public ENASRAXMLToSampleTab() {
}
public SampleData convert(String filename) throws IOException, ParseException, DocumentException {
return convert(new File(filename));
}
public SampleData convert(File infile) throws ParseException, IOException, DocumentException {
infile = infile.getAbsoluteFile();
if (infile.isDirectory()) {
infile = new File(infile, "study.xml");
log.info("Given a directly, looking for " + infile);
}
if (!infile.exists()) {
throw new IOException(infile + " does not exist");
}
Document studydoc;
studydoc = XMLUtils.getDocument(infile);
Element root = studydoc.getRootElement();
Element study = XMLUtils.getChildByName(root, "STUDY");
SampleData st = new SampleData();
// title
Element descriptor = XMLUtils.getChildByName(study, "DESCRIPTOR");
st.msi.submissionTitle = XMLUtils.getChildByName(descriptor, "STUDY_TITLE").getTextTrim();
st.msi.submissionIdentifier = "GEN-"+study.attributeValue("accession");
// description
String description = null;
if (descriptor != null) {
Element studyAbstract = XMLUtils.getChildByName(descriptor, "STUDY_ABSTRACT");
Element studyDescription = XMLUtils.getChildByName(descriptor, "STUDY_DESCRIPTION");
if (studyAbstract != null) {
description = studyAbstract.getTextTrim();
} else if (studyDescription != null) {
description = studyDescription.getTextTrim();
} else {
log.warn("no STUDY_ABSTRACT or STUDY_DESCRIPTION");
}
}
if (description != null) {
st.msi.submissionDescription = description;
}
// pubmed link
Set<Integer> pmids = new TreeSet<Integer>();
for (Element studyLinks : XMLUtils.getChildrenByName(study, "STUDY_LINKS")) {
for (Element studyLink : XMLUtils.getChildrenByName(studyLinks, "STUDY_LINK")) {
for (Element xrefLink : XMLUtils.getChildrenByName(studyLink, "XREF_LINK")) {
Element db = XMLUtils.getChildByName(xrefLink, "DB");
Element id = XMLUtils.getChildByName(xrefLink, "ID");
if (db.getTextTrim().equals("PUBMED")) {
try {
pmids.add(new Integer(id.getTextTrim()));
} catch (NumberFormatException e){
log.warn("Unable to parsed PubMedID "+id.getTextTrim());
}
}
}
}
}
for (Integer pmid : pmids) {
st.msi.publications.add(new Publication(""+pmid, null));
}
// database link
st.msi.databases.add(new Database("ENA SRA",
"http://www.ebi.ac.uk/ena/data/view/" + study.attributeValue("accession"),
study.attributeValue("accession")));
// organization
Element centerName = XMLUtils.getChildByName(descriptor, "CENTER_NAME");
Element centerTitle = XMLUtils.getChildByName(descriptor, "CENTER_TITLE");
Element centerProjectName = XMLUtils.getChildByName(descriptor, "CENTER_PROJECT_NAME");
if (centerName != null) {
st.msi.organizations.add(new Organization(centerName.getTextTrim(), null, null, null, "Submitter"));
} else if (centerTitle != null) {
st.msi.organizations.add(new Organization(centerTitle.getTextTrim(), null, null, null, "Submitter"));
} else if (study.attributeValue("center_name") != null) {
st.msi.organizations.add(new Organization(study.attributeValue("center_name"), null, null, null, "Submitter"));
} else if (centerProjectName != null) {
st.msi.organizations.add(new Organization(centerProjectName.getTextTrim(), null, null, null, "Submitter"));
} else {
throw new ParseException("Unable to find organization name.");
}
//ENA SRA does not have explicit term sources
TermSource ncbitaxonomy = new TermSource("NCBI Taxonomy", "http://www.ncbi.nlm.nih.gov/taxonomy/", null);
log.info("MSI section complete, starting SCD section.");
// start on the samples
Set<String> sampleSRAAccessions = ENAUtils.getSamplesForStudy(root);
if (sampleSRAAccessions.size()== 0){
throw new ParseException("Zero samples found.");
}
File indir = infile.getParentFile();
for (String sampleSRAAccession : sampleSRAAccessions) {
File sampleFile = new File(indir, sampleSRAAccession + ".xml");
Document sampledoc;
try {
sampledoc = XMLUtils.getDocument(sampleFile);
} catch (DocumentException e) {
// rethrow as a ParseException
throw new ParseException("Unable to parse XML document of sample " + sampleSRAAccession);
}
Element sampleroot = sampledoc.getRootElement();
Element sampleElement = XMLUtils.getChildByName(sampleroot, "SAMPLE");
Element sampleName = XMLUtils.getChildByName(sampleElement, "SAMPLE_NAME");
Element sampledescription = XMLUtils.getChildByName(sampleElement, "DESCRIPTION");
Element synonym = XMLUtils.getChildByName(sampleElement, "TITLE");
//sometimes the study is public but the samples are private
//check for that and skip sample
if (sampleElement == null){
continue;
}
// check that this actually is the sample we want
if (sampleElement.attributeValue("accession") != null
&& !sampleElement.attributeValue("accession").equals(sampleSRAAccession)) {
throw new ParseException("Accession in XML content does not match filename");
}
log.info("Processing sample " + sampleSRAAccession);
// create the actual sample node
SampleNode samplenode = new SampleNode();
samplenode.setNodeName(sampleSRAAccession);
samplenode.addAttribute(new DatabaseAttribute("ENA SRA",
sampleSRAAccession,
"http://www.ebi.ac.uk/ena/data/view/" + sampleSRAAccession));
// process any synonyms that may exist
if (sampleName != null) {
Element taxon = XMLUtils.getChildByName(sampleName, "TAXON_ID");
Element indivname = XMLUtils.getChildByName(sampleName, "INDIVIDUAL_NAME");
Element scientificname = XMLUtils.getChildByName(sampleName, "SCIENTIFIC_NAME");
Element commonname = XMLUtils.getChildByName(sampleName, "COMMON_NAME");
Element annonname = XMLUtils.getChildByName(sampleName, "ANONYMIZED_NAME");
// insert all synonyms at position zero so they display next to name
if (indivname != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", indivname.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
if (annonname != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", annonname.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
if (synonym != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", synonym.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
// now process organism
if (taxon != null) {
Integer taxid = new Integer(taxon.getTextTrim());
// TODO get taxon name from id
String taxName = null;
if (scientificname != null ){
taxName = scientificname.getTextTrim();
} else {
taxName = taxid.toString();
}
OrganismAttribute organismAttribute = null;
if (taxName != null && taxid != null) {
organismAttribute = new OrganismAttribute(taxName, st.msi.getOrAddTermSource(ncbitaxonomy), taxid);
} else if (taxName != null) {
organismAttribute = new OrganismAttribute(taxName);
}
if (organismAttribute != null) {
samplenode.addAttribute(organismAttribute);
}
}
}
if (sampledescription != null) {
// insert all synonyms at position zero so they display next to name
// do this after doing synonyms
if (sampledescription.attributeValue("alias") != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym",
sampledescription.attributeValue("alias"));
samplenode.addAttribute(synonymattrib, 0);
}
}
// finally, any other attributes ENA SRA provides
Element sampleAttributes = XMLUtils.getChildByName(sampleElement, "SAMPLE_ATTRIBUTES");
if (sampleAttributes != null) {
for (Element sampleAttribute : XMLUtils.getChildrenByName(sampleAttributes, "SAMPLE_ATTRIBUTE")) {
Element tag = XMLUtils.getChildByName(sampleAttribute, "TAG");
Element value = XMLUtils.getChildByName(sampleAttribute, "VALUE");
Element units = XMLUtils.getChildByName(sampleAttribute, "UNITS");
if (tag != null) {
String tagtext = tag.getTextTrim();
if (characteristicsIgnore.contains(tagtext)){
//skip this characteristic
log.debug("Skipping characteristic attribute "+tagtext);
continue;
}
String valuetext;
if (value == null) {
// some ENA SRA attributes are boolean
valuetext = tagtext;
} else {
valuetext = value.getTextTrim();
}
CharacteristicAttribute characteristicAttribute = new CharacteristicAttribute(tagtext,
valuetext);
- if (units != null) {
+ if (units != null && units.getTextTrim().length() > 0) {
log.info("Added unit "+units.getTextTrim());
characteristicAttribute.unit = new UnitAttribute();
characteristicAttribute.unit.setAttributeValue(units.getTextTrim());
}
samplenode.addAttribute(characteristicAttribute);
}
}
}
st.scd.addNode(samplenode);
}
log.info("Finished convert()");
return st;
}
public void convert(File file, Writer writer) throws IOException, ParseException, DocumentException {
log.debug("recieved xml, preparing to convert");
SampleData st = convert(file);
log.info("SampleTab converted, preparing to write");
Validator<SampleData> validator = new SampleTabValidator();
validator.validate(st);
SampleTabWriter sampletabwriter = new SampleTabWriter(writer);
sampletabwriter.write(st);
log.info("SampleTab written");
sampletabwriter.close();
}
public void convert(File studyFile, String outfilename) throws IOException, ParseException, DocumentException {
convert(studyFile, new File(outfilename));
}
public void convert(File studyFile, File sampletabFile) throws IOException, ParseException, DocumentException {
// create parent directories, if they dont exist
sampletabFile = sampletabFile.getAbsoluteFile();
if (sampletabFile.isDirectory()) {
sampletabFile = new File(sampletabFile, "sampletab.pre.txt");
}
if (!sampletabFile.getParentFile().exists()) {
sampletabFile.getParentFile().mkdirs();
}
convert(studyFile, new FileWriter(sampletabFile));
}
public void convert(String studyFilename, Writer writer) throws IOException, ParseException, DocumentException {
convert(new File(studyFilename), writer);
}
public void convert(String studyFilename, File sampletabFile) throws IOException, ParseException, DocumentException {
convert(studyFilename, new FileWriter(sampletabFile));
}
public void convert(String studyFilename, String sampletabFilename) throws IOException, ParseException, DocumentException {
convert(studyFilename, new File(sampletabFilename));
}
public static void main(String[] args) {
new ENASRAXMLToSampleTab().doMain(args);
}
public void doMain(String[] args) {
if (args.length < 2) {
System.out.println("Must provide an ENA SRA study filename and a SampleTab output filename.");
return;
}
String enasrafilename = args[0];
String sampleTabFilename = args[1];
ENASRAXMLToSampleTab converter = new ENASRAXMLToSampleTab();
try {
converter.convert(enasrafilename, sampleTabFilename);
} catch (ParseException e) {
System.out.println("Error converting " + enasrafilename + " to " + sampleTabFilename);
e.printStackTrace();
System.exit(2);
return;
} catch (IOException e) {
System.out.println("Error converting " + enasrafilename + " to " + sampleTabFilename);
e.printStackTrace();
System.exit(3);
return;
} catch (Exception e) {
System.out.println("Error converting " + enasrafilename + " to " + sampleTabFilename);
e.printStackTrace();
System.exit(4);
return;
}
}
}
| true | true | public SampleData convert(File infile) throws ParseException, IOException, DocumentException {
infile = infile.getAbsoluteFile();
if (infile.isDirectory()) {
infile = new File(infile, "study.xml");
log.info("Given a directly, looking for " + infile);
}
if (!infile.exists()) {
throw new IOException(infile + " does not exist");
}
Document studydoc;
studydoc = XMLUtils.getDocument(infile);
Element root = studydoc.getRootElement();
Element study = XMLUtils.getChildByName(root, "STUDY");
SampleData st = new SampleData();
// title
Element descriptor = XMLUtils.getChildByName(study, "DESCRIPTOR");
st.msi.submissionTitle = XMLUtils.getChildByName(descriptor, "STUDY_TITLE").getTextTrim();
st.msi.submissionIdentifier = "GEN-"+study.attributeValue("accession");
// description
String description = null;
if (descriptor != null) {
Element studyAbstract = XMLUtils.getChildByName(descriptor, "STUDY_ABSTRACT");
Element studyDescription = XMLUtils.getChildByName(descriptor, "STUDY_DESCRIPTION");
if (studyAbstract != null) {
description = studyAbstract.getTextTrim();
} else if (studyDescription != null) {
description = studyDescription.getTextTrim();
} else {
log.warn("no STUDY_ABSTRACT or STUDY_DESCRIPTION");
}
}
if (description != null) {
st.msi.submissionDescription = description;
}
// pubmed link
Set<Integer> pmids = new TreeSet<Integer>();
for (Element studyLinks : XMLUtils.getChildrenByName(study, "STUDY_LINKS")) {
for (Element studyLink : XMLUtils.getChildrenByName(studyLinks, "STUDY_LINK")) {
for (Element xrefLink : XMLUtils.getChildrenByName(studyLink, "XREF_LINK")) {
Element db = XMLUtils.getChildByName(xrefLink, "DB");
Element id = XMLUtils.getChildByName(xrefLink, "ID");
if (db.getTextTrim().equals("PUBMED")) {
try {
pmids.add(new Integer(id.getTextTrim()));
} catch (NumberFormatException e){
log.warn("Unable to parsed PubMedID "+id.getTextTrim());
}
}
}
}
}
for (Integer pmid : pmids) {
st.msi.publications.add(new Publication(""+pmid, null));
}
// database link
st.msi.databases.add(new Database("ENA SRA",
"http://www.ebi.ac.uk/ena/data/view/" + study.attributeValue("accession"),
study.attributeValue("accession")));
// organization
Element centerName = XMLUtils.getChildByName(descriptor, "CENTER_NAME");
Element centerTitle = XMLUtils.getChildByName(descriptor, "CENTER_TITLE");
Element centerProjectName = XMLUtils.getChildByName(descriptor, "CENTER_PROJECT_NAME");
if (centerName != null) {
st.msi.organizations.add(new Organization(centerName.getTextTrim(), null, null, null, "Submitter"));
} else if (centerTitle != null) {
st.msi.organizations.add(new Organization(centerTitle.getTextTrim(), null, null, null, "Submitter"));
} else if (study.attributeValue("center_name") != null) {
st.msi.organizations.add(new Organization(study.attributeValue("center_name"), null, null, null, "Submitter"));
} else if (centerProjectName != null) {
st.msi.organizations.add(new Organization(centerProjectName.getTextTrim(), null, null, null, "Submitter"));
} else {
throw new ParseException("Unable to find organization name.");
}
//ENA SRA does not have explicit term sources
TermSource ncbitaxonomy = new TermSource("NCBI Taxonomy", "http://www.ncbi.nlm.nih.gov/taxonomy/", null);
log.info("MSI section complete, starting SCD section.");
// start on the samples
Set<String> sampleSRAAccessions = ENAUtils.getSamplesForStudy(root);
if (sampleSRAAccessions.size()== 0){
throw new ParseException("Zero samples found.");
}
File indir = infile.getParentFile();
for (String sampleSRAAccession : sampleSRAAccessions) {
File sampleFile = new File(indir, sampleSRAAccession + ".xml");
Document sampledoc;
try {
sampledoc = XMLUtils.getDocument(sampleFile);
} catch (DocumentException e) {
// rethrow as a ParseException
throw new ParseException("Unable to parse XML document of sample " + sampleSRAAccession);
}
Element sampleroot = sampledoc.getRootElement();
Element sampleElement = XMLUtils.getChildByName(sampleroot, "SAMPLE");
Element sampleName = XMLUtils.getChildByName(sampleElement, "SAMPLE_NAME");
Element sampledescription = XMLUtils.getChildByName(sampleElement, "DESCRIPTION");
Element synonym = XMLUtils.getChildByName(sampleElement, "TITLE");
//sometimes the study is public but the samples are private
//check for that and skip sample
if (sampleElement == null){
continue;
}
// check that this actually is the sample we want
if (sampleElement.attributeValue("accession") != null
&& !sampleElement.attributeValue("accession").equals(sampleSRAAccession)) {
throw new ParseException("Accession in XML content does not match filename");
}
log.info("Processing sample " + sampleSRAAccession);
// create the actual sample node
SampleNode samplenode = new SampleNode();
samplenode.setNodeName(sampleSRAAccession);
samplenode.addAttribute(new DatabaseAttribute("ENA SRA",
sampleSRAAccession,
"http://www.ebi.ac.uk/ena/data/view/" + sampleSRAAccession));
// process any synonyms that may exist
if (sampleName != null) {
Element taxon = XMLUtils.getChildByName(sampleName, "TAXON_ID");
Element indivname = XMLUtils.getChildByName(sampleName, "INDIVIDUAL_NAME");
Element scientificname = XMLUtils.getChildByName(sampleName, "SCIENTIFIC_NAME");
Element commonname = XMLUtils.getChildByName(sampleName, "COMMON_NAME");
Element annonname = XMLUtils.getChildByName(sampleName, "ANONYMIZED_NAME");
// insert all synonyms at position zero so they display next to name
if (indivname != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", indivname.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
if (annonname != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", annonname.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
if (synonym != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", synonym.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
// now process organism
if (taxon != null) {
Integer taxid = new Integer(taxon.getTextTrim());
// TODO get taxon name from id
String taxName = null;
if (scientificname != null ){
taxName = scientificname.getTextTrim();
} else {
taxName = taxid.toString();
}
OrganismAttribute organismAttribute = null;
if (taxName != null && taxid != null) {
organismAttribute = new OrganismAttribute(taxName, st.msi.getOrAddTermSource(ncbitaxonomy), taxid);
} else if (taxName != null) {
organismAttribute = new OrganismAttribute(taxName);
}
if (organismAttribute != null) {
samplenode.addAttribute(organismAttribute);
}
}
}
if (sampledescription != null) {
// insert all synonyms at position zero so they display next to name
// do this after doing synonyms
if (sampledescription.attributeValue("alias") != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym",
sampledescription.attributeValue("alias"));
samplenode.addAttribute(synonymattrib, 0);
}
}
// finally, any other attributes ENA SRA provides
Element sampleAttributes = XMLUtils.getChildByName(sampleElement, "SAMPLE_ATTRIBUTES");
if (sampleAttributes != null) {
for (Element sampleAttribute : XMLUtils.getChildrenByName(sampleAttributes, "SAMPLE_ATTRIBUTE")) {
Element tag = XMLUtils.getChildByName(sampleAttribute, "TAG");
Element value = XMLUtils.getChildByName(sampleAttribute, "VALUE");
Element units = XMLUtils.getChildByName(sampleAttribute, "UNITS");
if (tag != null) {
String tagtext = tag.getTextTrim();
if (characteristicsIgnore.contains(tagtext)){
//skip this characteristic
log.debug("Skipping characteristic attribute "+tagtext);
continue;
}
String valuetext;
if (value == null) {
// some ENA SRA attributes are boolean
valuetext = tagtext;
} else {
valuetext = value.getTextTrim();
}
CharacteristicAttribute characteristicAttribute = new CharacteristicAttribute(tagtext,
valuetext);
if (units != null) {
log.info("Added unit "+units.getTextTrim());
characteristicAttribute.unit = new UnitAttribute();
characteristicAttribute.unit.setAttributeValue(units.getTextTrim());
}
samplenode.addAttribute(characteristicAttribute);
}
}
}
st.scd.addNode(samplenode);
}
log.info("Finished convert()");
return st;
}
| public SampleData convert(File infile) throws ParseException, IOException, DocumentException {
infile = infile.getAbsoluteFile();
if (infile.isDirectory()) {
infile = new File(infile, "study.xml");
log.info("Given a directly, looking for " + infile);
}
if (!infile.exists()) {
throw new IOException(infile + " does not exist");
}
Document studydoc;
studydoc = XMLUtils.getDocument(infile);
Element root = studydoc.getRootElement();
Element study = XMLUtils.getChildByName(root, "STUDY");
SampleData st = new SampleData();
// title
Element descriptor = XMLUtils.getChildByName(study, "DESCRIPTOR");
st.msi.submissionTitle = XMLUtils.getChildByName(descriptor, "STUDY_TITLE").getTextTrim();
st.msi.submissionIdentifier = "GEN-"+study.attributeValue("accession");
// description
String description = null;
if (descriptor != null) {
Element studyAbstract = XMLUtils.getChildByName(descriptor, "STUDY_ABSTRACT");
Element studyDescription = XMLUtils.getChildByName(descriptor, "STUDY_DESCRIPTION");
if (studyAbstract != null) {
description = studyAbstract.getTextTrim();
} else if (studyDescription != null) {
description = studyDescription.getTextTrim();
} else {
log.warn("no STUDY_ABSTRACT or STUDY_DESCRIPTION");
}
}
if (description != null) {
st.msi.submissionDescription = description;
}
// pubmed link
Set<Integer> pmids = new TreeSet<Integer>();
for (Element studyLinks : XMLUtils.getChildrenByName(study, "STUDY_LINKS")) {
for (Element studyLink : XMLUtils.getChildrenByName(studyLinks, "STUDY_LINK")) {
for (Element xrefLink : XMLUtils.getChildrenByName(studyLink, "XREF_LINK")) {
Element db = XMLUtils.getChildByName(xrefLink, "DB");
Element id = XMLUtils.getChildByName(xrefLink, "ID");
if (db.getTextTrim().equals("PUBMED")) {
try {
pmids.add(new Integer(id.getTextTrim()));
} catch (NumberFormatException e){
log.warn("Unable to parsed PubMedID "+id.getTextTrim());
}
}
}
}
}
for (Integer pmid : pmids) {
st.msi.publications.add(new Publication(""+pmid, null));
}
// database link
st.msi.databases.add(new Database("ENA SRA",
"http://www.ebi.ac.uk/ena/data/view/" + study.attributeValue("accession"),
study.attributeValue("accession")));
// organization
Element centerName = XMLUtils.getChildByName(descriptor, "CENTER_NAME");
Element centerTitle = XMLUtils.getChildByName(descriptor, "CENTER_TITLE");
Element centerProjectName = XMLUtils.getChildByName(descriptor, "CENTER_PROJECT_NAME");
if (centerName != null) {
st.msi.organizations.add(new Organization(centerName.getTextTrim(), null, null, null, "Submitter"));
} else if (centerTitle != null) {
st.msi.organizations.add(new Organization(centerTitle.getTextTrim(), null, null, null, "Submitter"));
} else if (study.attributeValue("center_name") != null) {
st.msi.organizations.add(new Organization(study.attributeValue("center_name"), null, null, null, "Submitter"));
} else if (centerProjectName != null) {
st.msi.organizations.add(new Organization(centerProjectName.getTextTrim(), null, null, null, "Submitter"));
} else {
throw new ParseException("Unable to find organization name.");
}
//ENA SRA does not have explicit term sources
TermSource ncbitaxonomy = new TermSource("NCBI Taxonomy", "http://www.ncbi.nlm.nih.gov/taxonomy/", null);
log.info("MSI section complete, starting SCD section.");
// start on the samples
Set<String> sampleSRAAccessions = ENAUtils.getSamplesForStudy(root);
if (sampleSRAAccessions.size()== 0){
throw new ParseException("Zero samples found.");
}
File indir = infile.getParentFile();
for (String sampleSRAAccession : sampleSRAAccessions) {
File sampleFile = new File(indir, sampleSRAAccession + ".xml");
Document sampledoc;
try {
sampledoc = XMLUtils.getDocument(sampleFile);
} catch (DocumentException e) {
// rethrow as a ParseException
throw new ParseException("Unable to parse XML document of sample " + sampleSRAAccession);
}
Element sampleroot = sampledoc.getRootElement();
Element sampleElement = XMLUtils.getChildByName(sampleroot, "SAMPLE");
Element sampleName = XMLUtils.getChildByName(sampleElement, "SAMPLE_NAME");
Element sampledescription = XMLUtils.getChildByName(sampleElement, "DESCRIPTION");
Element synonym = XMLUtils.getChildByName(sampleElement, "TITLE");
//sometimes the study is public but the samples are private
//check for that and skip sample
if (sampleElement == null){
continue;
}
// check that this actually is the sample we want
if (sampleElement.attributeValue("accession") != null
&& !sampleElement.attributeValue("accession").equals(sampleSRAAccession)) {
throw new ParseException("Accession in XML content does not match filename");
}
log.info("Processing sample " + sampleSRAAccession);
// create the actual sample node
SampleNode samplenode = new SampleNode();
samplenode.setNodeName(sampleSRAAccession);
samplenode.addAttribute(new DatabaseAttribute("ENA SRA",
sampleSRAAccession,
"http://www.ebi.ac.uk/ena/data/view/" + sampleSRAAccession));
// process any synonyms that may exist
if (sampleName != null) {
Element taxon = XMLUtils.getChildByName(sampleName, "TAXON_ID");
Element indivname = XMLUtils.getChildByName(sampleName, "INDIVIDUAL_NAME");
Element scientificname = XMLUtils.getChildByName(sampleName, "SCIENTIFIC_NAME");
Element commonname = XMLUtils.getChildByName(sampleName, "COMMON_NAME");
Element annonname = XMLUtils.getChildByName(sampleName, "ANONYMIZED_NAME");
// insert all synonyms at position zero so they display next to name
if (indivname != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", indivname.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
if (annonname != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", annonname.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
if (synonym != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym", synonym.getTextTrim());
samplenode.addAttribute(synonymattrib, 0);
}
// now process organism
if (taxon != null) {
Integer taxid = new Integer(taxon.getTextTrim());
// TODO get taxon name from id
String taxName = null;
if (scientificname != null ){
taxName = scientificname.getTextTrim();
} else {
taxName = taxid.toString();
}
OrganismAttribute organismAttribute = null;
if (taxName != null && taxid != null) {
organismAttribute = new OrganismAttribute(taxName, st.msi.getOrAddTermSource(ncbitaxonomy), taxid);
} else if (taxName != null) {
organismAttribute = new OrganismAttribute(taxName);
}
if (organismAttribute != null) {
samplenode.addAttribute(organismAttribute);
}
}
}
if (sampledescription != null) {
// insert all synonyms at position zero so they display next to name
// do this after doing synonyms
if (sampledescription.attributeValue("alias") != null) {
CommentAttribute synonymattrib = new CommentAttribute("Synonym",
sampledescription.attributeValue("alias"));
samplenode.addAttribute(synonymattrib, 0);
}
}
// finally, any other attributes ENA SRA provides
Element sampleAttributes = XMLUtils.getChildByName(sampleElement, "SAMPLE_ATTRIBUTES");
if (sampleAttributes != null) {
for (Element sampleAttribute : XMLUtils.getChildrenByName(sampleAttributes, "SAMPLE_ATTRIBUTE")) {
Element tag = XMLUtils.getChildByName(sampleAttribute, "TAG");
Element value = XMLUtils.getChildByName(sampleAttribute, "VALUE");
Element units = XMLUtils.getChildByName(sampleAttribute, "UNITS");
if (tag != null) {
String tagtext = tag.getTextTrim();
if (characteristicsIgnore.contains(tagtext)){
//skip this characteristic
log.debug("Skipping characteristic attribute "+tagtext);
continue;
}
String valuetext;
if (value == null) {
// some ENA SRA attributes are boolean
valuetext = tagtext;
} else {
valuetext = value.getTextTrim();
}
CharacteristicAttribute characteristicAttribute = new CharacteristicAttribute(tagtext,
valuetext);
if (units != null && units.getTextTrim().length() > 0) {
log.info("Added unit "+units.getTextTrim());
characteristicAttribute.unit = new UnitAttribute();
characteristicAttribute.unit.setAttributeValue(units.getTextTrim());
}
samplenode.addAttribute(characteristicAttribute);
}
}
}
st.scd.addNode(samplenode);
}
log.info("Finished convert()");
return st;
}
|
diff --git a/deegree-core/deegree-core-rendering-2d/src/main/java/org/deegree/rendering/r2d/context/RenderingInfo.java b/deegree-core/deegree-core-rendering-2d/src/main/java/org/deegree/rendering/r2d/context/RenderingInfo.java
index c1719c388c..dc9ab5e897 100644
--- a/deegree-core/deegree-core-rendering-2d/src/main/java/org/deegree/rendering/r2d/context/RenderingInfo.java
+++ b/deegree-core/deegree-core-rendering-2d/src/main/java/org/deegree/rendering/r2d/context/RenderingInfo.java
@@ -1,104 +1,106 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.rendering.r2d.context;
import java.awt.Color;
import org.deegree.geometry.Envelope;
/**
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class RenderingInfo {
private String format;
private int width, height;
private boolean transparent;
private Color bgcolor;
private Envelope envelope;
private double pixelSize;
public RenderingInfo( String format, int width, int height, boolean transparent, Color bgcolor, Envelope envelope,
double pixelSize ) {
this.format = format;
this.width = width;
this.height = height;
this.transparent = transparent;
this.bgcolor = bgcolor;
+ this.envelope = envelope;
+ this.pixelSize = pixelSize;
}
public void setFormat( String format ) {
this.format = format;
}
public String getFormat() {
return format;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public boolean getTransparent() {
return transparent;
}
public Color getBgColor() {
return bgcolor;
}
public Envelope getEnvelope() {
return envelope;
}
public double getPixelSize() {
return pixelSize;
}
}
| true | true | public RenderingInfo( String format, int width, int height, boolean transparent, Color bgcolor, Envelope envelope,
double pixelSize ) {
this.format = format;
this.width = width;
this.height = height;
this.transparent = transparent;
this.bgcolor = bgcolor;
}
| public RenderingInfo( String format, int width, int height, boolean transparent, Color bgcolor, Envelope envelope,
double pixelSize ) {
this.format = format;
this.width = width;
this.height = height;
this.transparent = transparent;
this.bgcolor = bgcolor;
this.envelope = envelope;
this.pixelSize = pixelSize;
}
|
diff --git a/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/project/E4NewProjectWizardPage.java b/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/project/E4NewProjectWizardPage.java
index 72ae3d44..9465cd4c 100644
--- a/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/project/E4NewProjectWizardPage.java
+++ b/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/project/E4NewProjectWizardPage.java
@@ -1,31 +1,32 @@
/*******************************************************************************
* Copyright (c) 2006, 2010 Soyatec(http://www.soyatec.com) 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:
* Soyatec - initial API and implementation
*******************************************************************************/
package org.eclipse.e4.internal.tools.wizards.project;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.pde.internal.ui.wizards.plugin.AbstractFieldData;
import org.eclipse.swt.widgets.Composite;
public class E4NewProjectWizardPage extends org.eclipse.pde.internal.ui.wizards.plugin.NewProjectCreationPage {
public E4NewProjectWizardPage(String pageName, AbstractFieldData data, boolean fragment, IStructuredSelection selection) {
super(pageName, data, fragment, selection);
}
@Override
public void createControl(Composite parent) {
super.createControl(parent);
fOSGIButton.setSelection(true);
+ fEclipseButton.setSelection(false);
fEclipseButton.setEnabled(false);
fEclipseCombo.setEnabled(false);
}
}
| true | true | public void createControl(Composite parent) {
super.createControl(parent);
fOSGIButton.setSelection(true);
fEclipseButton.setEnabled(false);
fEclipseCombo.setEnabled(false);
}
| public void createControl(Composite parent) {
super.createControl(parent);
fOSGIButton.setSelection(true);
fEclipseButton.setSelection(false);
fEclipseButton.setEnabled(false);
fEclipseCombo.setEnabled(false);
}
|
diff --git a/ActiveMtl/src/com/nurun/activemtl/ui/LoginActivity.java b/ActiveMtl/src/com/nurun/activemtl/ui/LoginActivity.java
index af432b0..b141ea7 100644
--- a/ActiveMtl/src/com/nurun/activemtl/ui/LoginActivity.java
+++ b/ActiveMtl/src/com/nurun/activemtl/ui/LoginActivity.java
@@ -1,184 +1,185 @@
package com.nurun.activemtl.ui;
import java.util.Arrays;
import java.util.List;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.Person;
import com.nurun.activemtl.PreferenceHelper;
import com.nurun.activemtl.R;
import com.nurun.activemtl.SocialMediaConnection;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
public class LoginActivity extends FragmentActivity {
private PlusClient mPlusClient;
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
protected ConnectionResult mConnectionResult;
private ProgressDialog mConnectionProgressDialog;
public static Intent newIntent(Context context) {
return new Intent(context, LoginActivity.class);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
Session session = Session.getActiveSession();
mPlusClient = new PlusClient.Builder(this, connectionCallback, connectionFailListener).setVisibleActivities("http://schemas.google.com/AddActivity",
"http://schemas.google.com/BuyActivity").build();
// Barre de progression à afficher si l'échec de connexion n'est pas
// résolu.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
if (mPlusClient.isConnected()) {
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
}
if (session != null && !session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
@Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == FragmentActivity.RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
} else {
ParseFacebookUtils.finishAuthentication(requestCode, responseCode, intent);
}
}
private void goToNextScreen() {
getFragmentManager().popBackStack();
setResult(200);
finish();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private ConnectionCallbacks connectionCallback = new ConnectionCallbacks() {
@Override
public void onDisconnected() {
}
@Override
public void onConnected(Bundle arg0) {
mConnectionProgressDialog.dismiss();
Person currentPerson = mPlusClient.getCurrentPerson();
PreferenceHelper.setSocialMediaConnection(LoginActivity.this, SocialMediaConnection.Google_plus);
PreferenceHelper.setUserId(LoginActivity.this, currentPerson.getId());
PreferenceHelper.setUserName(LoginActivity.this, currentPerson.getDisplayName());
goToNextScreen();
}
};
private OnConnectionFailedListener connectionFailListener = new OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(LoginActivity.this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
mConnectionResult = result;
}
};
public void onFacebookConnectionClicked() {
mConnectionProgressDialog.show();
List<String> permissions = Arrays.asList("basic_info", "user_about_me");
ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {
@Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d(getClass().getSimpleName(), "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d(getClass().getSimpleName(), "User signed up and logged in through Facebook!");
saveUserDatas(user);
} else {
Log.d(getClass().getSimpleName(), "User logged in through Facebook!");
saveUserDatas(user);
}
}
});
}
protected void saveUserDatas(ParseUser user) {
if (user != null) {
ParseFacebookUtils.link(user, this);
Request request = Request.newMeRequest(ParseFacebookUtils.getSession(), new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
PreferenceHelper.setUserId(LoginActivity.this, user.getId());
PreferenceHelper.setUserName(LoginActivity.this, user.getName());
+ PreferenceHelper.setSocialMediaConnection(LoginActivity.this, SocialMediaConnection.Facebook);
goToNextScreen();
} else if (response.getError() != null) {
if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
|| (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
Log.d(getClass().getSimpleName(), "The facebook session was invalidated.");
PreferenceHelper.clearUserInfos(getApplicationContext());
ParseUser.logOut();
} else {
Log.d(getClass().getSimpleName(), "Some other error: " + response.getError().getErrorMessage());
}
}
mConnectionProgressDialog.dismiss();
}
});
request.executeAsync();
}
}
public void onGooglePlusConnectionClicked() {
mConnectionProgressDialog.show();
if (mConnectionResult == null) {
mPlusClient.connect();
} else {
try {
mConnectionProgressDialog.show();
mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Nouvelle tentative de connexion
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
| true | true | protected void saveUserDatas(ParseUser user) {
if (user != null) {
ParseFacebookUtils.link(user, this);
Request request = Request.newMeRequest(ParseFacebookUtils.getSession(), new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
PreferenceHelper.setUserId(LoginActivity.this, user.getId());
PreferenceHelper.setUserName(LoginActivity.this, user.getName());
goToNextScreen();
} else if (response.getError() != null) {
if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
|| (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
Log.d(getClass().getSimpleName(), "The facebook session was invalidated.");
PreferenceHelper.clearUserInfos(getApplicationContext());
ParseUser.logOut();
} else {
Log.d(getClass().getSimpleName(), "Some other error: " + response.getError().getErrorMessage());
}
}
mConnectionProgressDialog.dismiss();
}
});
request.executeAsync();
}
}
| protected void saveUserDatas(ParseUser user) {
if (user != null) {
ParseFacebookUtils.link(user, this);
Request request = Request.newMeRequest(ParseFacebookUtils.getSession(), new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
PreferenceHelper.setUserId(LoginActivity.this, user.getId());
PreferenceHelper.setUserName(LoginActivity.this, user.getName());
PreferenceHelper.setSocialMediaConnection(LoginActivity.this, SocialMediaConnection.Facebook);
goToNextScreen();
} else if (response.getError() != null) {
if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
|| (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
Log.d(getClass().getSimpleName(), "The facebook session was invalidated.");
PreferenceHelper.clearUserInfos(getApplicationContext());
ParseUser.logOut();
} else {
Log.d(getClass().getSimpleName(), "Some other error: " + response.getError().getErrorMessage());
}
}
mConnectionProgressDialog.dismiss();
}
});
request.executeAsync();
}
}
|
diff --git a/csharp-squid/src/main/java/com/sonar/csharp/metric/CSharpCommentsAndNoSonarVisitor.java b/csharp-squid/src/main/java/com/sonar/csharp/metric/CSharpCommentsAndNoSonarVisitor.java
index b01b37ebc..7c8734347 100644
--- a/csharp-squid/src/main/java/com/sonar/csharp/metric/CSharpCommentsAndNoSonarVisitor.java
+++ b/csharp-squid/src/main/java/com/sonar/csharp/metric/CSharpCommentsAndNoSonarVisitor.java
@@ -1,104 +1,104 @@
/*
* Copyright (C) 2010 SonarSource SA
* All rights reserved
* mailto:contact AT sonarsource DOT com
*/
package com.sonar.csharp.metric;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
import org.sonar.squid.api.SourceFile;
import org.sonar.squid.recognizer.CodeRecognizer;
import org.sonar.squid.recognizer.ContainsDetector;
import org.sonar.squid.recognizer.Detector;
import org.sonar.squid.recognizer.EndWithDetector;
import org.sonar.squid.recognizer.KeywordsDetector;
import org.sonar.squid.recognizer.LanguageFootprint;
import com.sonar.csharp.api.CSharpKeyword;
import com.sonar.csharp.api.ast.CSharpAstVisitor;
import com.sonar.csharp.api.metric.CSharpMetric;
import com.sonar.sslr.api.AstAndTokenVisitor;
import com.sonar.sslr.api.AstNode;
import com.sonar.sslr.api.GenericTokenType;
import com.sonar.sslr.api.Token;
public class CSharpCommentsAndNoSonarVisitor extends CSharpAstVisitor implements AstAndTokenVisitor {
private static final String NOSONAR_TAG = "NOSONAR";
private int firstLineOfCodeIndex = -1;
/**
* {@inheritDoc}
*/
public void visitToken(Token token) {
if (firstLineOfCodeIndex == -1) {
if ( !token.getType().equals(GenericTokenType.UNKNOWN_CHAR)) {
firstLineOfCodeIndex = token.getLine();
}
}
}
@Override
public void leaveFile(AstNode astNode) {
SourceFile sourceFile = (SourceFile) peekSourceCode();
CodeRecognizer codeRecognizer = new CodeRecognizer(0.94, new CSharpFootprint());
for (Iterator<Token> iterator = getComments().iterator(); iterator.hasNext();) {
Token commentToken = (Token) iterator.next();
// if the comment is not located before the first code token, we consider this is a header of the file and ignore it
if (commentToken.getLine() >= firstLineOfCodeIndex) {
String comment = cleanComment(commentToken.getValue());
if (comment.length() == 0) {
sourceFile.add(CSharpMetric.COMMENT_BLANK_LINES, 1);
} else {
StringTokenizer tokenizer = new StringTokenizer(comment, "\n");
while (tokenizer.hasMoreElements()) {
String commentLine = tokenizer.nextToken().trim();
- if (commentLine.isEmpty()) {
+ if (commentLine.length() == 0) {
sourceFile.add(CSharpMetric.COMMENT_BLANK_LINES, 1);
} else if (codeRecognizer.isLineOfCode(commentLine)) {
sourceFile.add(CSharpMetric.COMMENTED_OUT_CODE_LINES, 1);
} else if (commentLine.indexOf(NOSONAR_TAG) != -1) {
sourceFile.addNoSonarTagLine(commentToken.getLine());
} else {
sourceFile.add(CSharpMetric.COMMENT_LINES, 1);
}
}
}
}
}
}
protected String cleanComment(String commentString) {
String comment = commentString.trim();
if (comment.startsWith("/") || comment.startsWith("\\") || comment.startsWith("*")) {
comment = cleanComment(comment.substring(1));
}
if (comment.endsWith("*/")) {
comment = comment.substring(0, comment.length() - 2).trim();
}
return comment;
}
class CSharpFootprint implements LanguageFootprint {
private final Set<Detector> detectors = new HashSet<Detector>();
@SuppressWarnings("all")
public CSharpFootprint() {
detectors.add(new EndWithDetector(0.95, '}', ';', '{'));
detectors.add(new KeywordsDetector(0.7, "||", "&&"));
detectors.add(new KeywordsDetector(0.3, CSharpKeyword.keywordValues()));
detectors.add(new ContainsDetector(0.95, "++", "for(", "if(", "while(", "catch(", "switch(", "try{", "else{"));
}
public Set<Detector> getDetectors() {
return detectors;
}
}
}
| true | true | public void leaveFile(AstNode astNode) {
SourceFile sourceFile = (SourceFile) peekSourceCode();
CodeRecognizer codeRecognizer = new CodeRecognizer(0.94, new CSharpFootprint());
for (Iterator<Token> iterator = getComments().iterator(); iterator.hasNext();) {
Token commentToken = (Token) iterator.next();
// if the comment is not located before the first code token, we consider this is a header of the file and ignore it
if (commentToken.getLine() >= firstLineOfCodeIndex) {
String comment = cleanComment(commentToken.getValue());
if (comment.length() == 0) {
sourceFile.add(CSharpMetric.COMMENT_BLANK_LINES, 1);
} else {
StringTokenizer tokenizer = new StringTokenizer(comment, "\n");
while (tokenizer.hasMoreElements()) {
String commentLine = tokenizer.nextToken().trim();
if (commentLine.isEmpty()) {
sourceFile.add(CSharpMetric.COMMENT_BLANK_LINES, 1);
} else if (codeRecognizer.isLineOfCode(commentLine)) {
sourceFile.add(CSharpMetric.COMMENTED_OUT_CODE_LINES, 1);
} else if (commentLine.indexOf(NOSONAR_TAG) != -1) {
sourceFile.addNoSonarTagLine(commentToken.getLine());
} else {
sourceFile.add(CSharpMetric.COMMENT_LINES, 1);
}
}
}
}
}
}
| public void leaveFile(AstNode astNode) {
SourceFile sourceFile = (SourceFile) peekSourceCode();
CodeRecognizer codeRecognizer = new CodeRecognizer(0.94, new CSharpFootprint());
for (Iterator<Token> iterator = getComments().iterator(); iterator.hasNext();) {
Token commentToken = (Token) iterator.next();
// if the comment is not located before the first code token, we consider this is a header of the file and ignore it
if (commentToken.getLine() >= firstLineOfCodeIndex) {
String comment = cleanComment(commentToken.getValue());
if (comment.length() == 0) {
sourceFile.add(CSharpMetric.COMMENT_BLANK_LINES, 1);
} else {
StringTokenizer tokenizer = new StringTokenizer(comment, "\n");
while (tokenizer.hasMoreElements()) {
String commentLine = tokenizer.nextToken().trim();
if (commentLine.length() == 0) {
sourceFile.add(CSharpMetric.COMMENT_BLANK_LINES, 1);
} else if (codeRecognizer.isLineOfCode(commentLine)) {
sourceFile.add(CSharpMetric.COMMENTED_OUT_CODE_LINES, 1);
} else if (commentLine.indexOf(NOSONAR_TAG) != -1) {
sourceFile.addNoSonarTagLine(commentToken.getLine());
} else {
sourceFile.add(CSharpMetric.COMMENT_LINES, 1);
}
}
}
}
}
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IFilterSelect.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IFilterSelect.java
index 9dec2496a..1a239e557 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IFilterSelect.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IFilterSelect.java
@@ -1,806 +1,807 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusListener;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.PopupListener;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Focusable;
import com.itmill.toolkit.terminal.gwt.client.ITooltip;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
/**
*
* TODO needs major refactoring (to be extensible etc)
*/
public class IFilterSelect extends Composite implements Paintable, Field,
KeyboardListener, ClickListener, FocusListener, Focusable {
public class FilterSelectSuggestion implements Suggestion, Command {
private final String key;
private final String caption;
private String iconUri;
public FilterSelectSuggestion(UIDL uidl) {
key = uidl.getStringAttribute("key");
caption = uidl.getStringAttribute("caption");
if (uidl.hasAttribute("icon")) {
iconUri = client.translateToolkitUri(uidl
.getStringAttribute("icon"));
}
}
public String getDisplayString() {
final StringBuffer sb = new StringBuffer();
if (iconUri != null) {
sb.append("<img src=\"");
sb.append(iconUri);
sb.append("\" alt=\"icon\" class=\"i-icon\" />");
}
sb.append(Util.escapeHTML(caption));
return sb.toString();
}
public String getReplacementString() {
return caption;
}
public int getOptionKey() {
return Integer.parseInt(key);
}
public String getIconUri() {
return iconUri;
}
public void execute() {
onSuggestionSelected(this);
}
}
/**
* @author mattitahvonen
*
*/
public class SuggestionPopup extends IToolkitOverlay implements
PositionCallback, PopupListener {
private static final int EXTRASPACE = 8;
private static final String Z_INDEX = "30000";
private final SuggestionMenu menu;
private final Element up = DOM.createDiv();
private final Element down = DOM.createDiv();
private final Element status = DOM.createDiv();
private boolean isPagingEnabled = true;
private long lastAutoClosed;
SuggestionPopup() {
super(true, false, true);
menu = new SuggestionMenu();
setWidget(menu);
setStyleName(CLASSNAME + "-suggestpopup");
DOM.setStyleAttribute(getElement(), "zIndex", Z_INDEX);
final Element root = getContainerElement();
DOM.setInnerHTML(up, "<span>Prev</span>");
DOM.sinkEvents(up, Event.ONCLICK);
DOM.setInnerHTML(down, "<span>Next</span>");
DOM.sinkEvents(down, Event.ONCLICK);
DOM.insertChild(root, up, 0);
DOM.appendChild(root, down);
DOM.appendChild(root, status);
DOM.setElementProperty(status, "className", CLASSNAME + "-status");
addPopupListener(this);
}
public void showSuggestions(Collection currentSuggestions,
int currentPage, int totalSuggestions) {
if (ApplicationConnection.isTestingMode()) {
// Add TT anchor point
DOM.setElementProperty(getElement(), "id", paintableId
+ "_OPTIONLIST");
}
menu.setSuggestions(currentSuggestions);
final int x = IFilterSelect.this.getAbsoluteLeft();
int y = tb.getAbsoluteTop();
y += tb.getOffsetHeight();
setPopupPosition(x, y);
final int first = currentPage * PAGELENTH
+ (nullSelectionAllowed && currentPage > 0 ? 0 : 1);
final int last = first + currentSuggestions.size() - 1;
final int matches = totalSuggestions
- (nullSelectionAllowed ? 1 : 0);
if (last > 0) {
// nullsel not counted, as requested by user
DOM.setInnerText(status, (matches == 0 ? 0 : first)
+ "-"
+ ("".equals(lastFilter) && nullSelectionAllowed
&& currentPage == 0 ? last - 1 : last) + "/"
+ matches);
} else {
DOM.setInnerText(status, "");
}
// We don't need to show arrows or statusbar if there is only one
// page
if (matches <= PAGELENTH) {
setPagingEnabled(false);
} else {
setPagingEnabled(true);
}
setPrevButtonActive(first > 1);
setNextButtonActive(last < matches);
// clear previously fixed width
menu.setWidth("");
DOM.setStyleAttribute(DOM.getFirstChild(menu.getElement()),
"width", "");
setPopupPositionAndShow(this);
}
private void setNextButtonActive(boolean b) {
if (b) {
DOM.sinkEvents(down, Event.ONCLICK);
DOM.setElementProperty(down, "className", CLASSNAME
+ "-nextpage");
} else {
DOM.sinkEvents(down, 0);
DOM.setElementProperty(down, "className", CLASSNAME
+ "-nextpage-off");
}
}
private void setPrevButtonActive(boolean b) {
if (b) {
DOM.sinkEvents(up, Event.ONCLICK);
DOM
.setElementProperty(up, "className", CLASSNAME
+ "-prevpage");
} else {
DOM.sinkEvents(up, 0);
DOM.setElementProperty(up, "className", CLASSNAME
+ "-prevpage-off");
}
}
public void selectNextItem() {
final MenuItem cur = menu.getSelectedItem();
final int index = 1 + menu.getItems().indexOf(cur);
if (menu.getItems().size() > index) {
final MenuItem newSelectedItem = (MenuItem) menu.getItems()
.get(index);
menu.selectItem(newSelectedItem);
tb.setText(newSelectedItem.getText());
tb.setSelectionRange(lastFilter.length(), newSelectedItem
.getText().length()
- lastFilter.length());
} else if (hasNextPage()) {
filterOptions(currentPage + 1, lastFilter);
}
}
public void selectPrevItem() {
final MenuItem cur = menu.getSelectedItem();
final int index = -1 + menu.getItems().indexOf(cur);
if (index > -1) {
final MenuItem newSelectedItem = (MenuItem) menu.getItems()
.get(index);
menu.selectItem(newSelectedItem);
tb.setText(newSelectedItem.getText());
tb.setSelectionRange(lastFilter.length(), newSelectedItem
.getText().length()
- lastFilter.length());
} else if (index == -1) {
if (currentPage > 0) {
filterOptions(currentPage - 1, lastFilter);
}
} else {
final MenuItem newSelectedItem = (MenuItem) menu.getItems()
.get(menu.getItems().size() - 1);
menu.selectItem(newSelectedItem);
tb.setText(newSelectedItem.getText());
tb.setSelectionRange(lastFilter.length(), newSelectedItem
.getText().length()
- lastFilter.length());
}
}
public void onBrowserEvent(Event event) {
final Element target = DOM.eventGetTarget(event);
if (DOM.compare(target, up)
|| DOM.compare(target, DOM.getChild(up, 0))) {
filterOptions(currentPage - 1, lastFilter);
} else if (DOM.compare(target, down)
|| DOM.compare(target, DOM.getChild(down, 0))) {
filterOptions(currentPage + 1, lastFilter);
}
tb.setFocus(true);
}
public void setPagingEnabled(boolean paging) {
if (isPagingEnabled == paging) {
return;
}
if (paging) {
DOM.setStyleAttribute(down, "display", "");
DOM.setStyleAttribute(up, "display", "");
DOM.setStyleAttribute(status, "display", "");
} else {
DOM.setStyleAttribute(down, "display", "none");
DOM.setStyleAttribute(up, "display", "none");
DOM.setStyleAttribute(status, "display", "none");
}
isPagingEnabled = paging;
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.PopupPanel$PositionCallback#setPosition
* (int, int)
*/
public void setPosition(int offsetWidth, int offsetHeight) {
int top = -1;
int left = -1;
// reset menu size and retrieve its "natural" size
menu.setHeight("");
if (currentPage > 0) {
// fix height to avoid height change when getting to last page
menu.fixHeightTo(PAGELENTH);
}
offsetHeight = getOffsetHeight();
final int desiredWidth = IFilterSelect.this.getOffsetWidth();
int naturalMenuWidth = DOM.getElementPropertyInt(DOM
.getFirstChild(menu.getElement()), "offsetWidth");
if (naturalMenuWidth < desiredWidth) {
menu.setWidth(desiredWidth + "px");
DOM.setStyleAttribute(DOM.getFirstChild(menu.getElement()),
"width", "100%");
naturalMenuWidth = desiredWidth;
}
if (Util.isIE()) {
DOM.setStyleAttribute(getElement(), "width", naturalMenuWidth
+ "px");
}
if (offsetHeight + getPopupTop() > Window.getClientHeight()
+ Window.getScrollTop()) {
// popup on top of input instead
top = getPopupTop() - offsetHeight
- IFilterSelect.this.getOffsetHeight();
if (top < 0) {
top = 0;
}
} else {
top = getPopupTop();
}
// fetch real width (mac FF bugs here due GWT popups overflow:auto )
offsetWidth = DOM.getElementPropertyInt(DOM.getFirstChild(menu
.getElement()), "offsetWidth");
if (offsetWidth + getPopupLeft() > Window.getClientWidth()
+ Window.getScrollLeft()) {
left = IFilterSelect.this.getAbsoluteLeft()
+ IFilterSelect.this.getOffsetWidth()
+ Window.getScrollLeft() - offsetWidth;
if (left < 0) {
left = 0;
}
} else {
left = getPopupLeft();
}
setPopupPosition(left, top);
}
/**
* @return true if popup was just closed
*/
public boolean isJustClosed() {
final long now = (new Date()).getTime();
return (lastAutoClosed > 0 && (now - lastAutoClosed) < 200);
}
public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
if (autoClosed) {
lastAutoClosed = (new Date()).getTime();
}
}
}
public class SuggestionMenu extends MenuBar {
SuggestionMenu() {
super(true);
setStyleName(CLASSNAME + "-suggestmenu");
}
/**
* Fixes menus height to use same space as full page would use. Needed
* to avoid height changes when quickly "scrolling" to last page
*/
public void fixHeightTo(int pagelenth) {
if (currentSuggestions.size() > 0) {
final int pixels = pagelenth * (getOffsetHeight() - 2)
/ currentSuggestions.size();
setHeight((pixels + 2) + "px");
}
}
public void setSuggestions(Collection suggestions) {
clearItems();
final Iterator it = suggestions.iterator();
while (it.hasNext()) {
final FilterSelectSuggestion s = (FilterSelectSuggestion) it
.next();
final MenuItem mi = new MenuItem(s.getDisplayString(), true, s);
this.addItem(mi);
if (s == currentSuggestion) {
selectItem(mi);
}
}
}
public void doSelectedItemAction() {
final MenuItem item = getSelectedItem();
final String enteredItemValue = tb.getText();
// check for exact match in menu
int p = getItems().size();
if (p > 0) {
for (int i = 0; i < p; i++) {
final MenuItem potentialExactMatch = (MenuItem) getItems()
.get(i);
if (potentialExactMatch.getText().equals(enteredItemValue)) {
selectItem(potentialExactMatch);
doItemAction(potentialExactMatch, true);
suggestionPopup.hide();
return;
}
}
}
if (allowNewItem) {
if (!enteredItemValue.equals(emptyText)) {
client.updateVariable(paintableId, "newitem",
enteredItemValue, immediate);
}
} else if (item != null
&& !"".equals(lastFilter)
&& item.getText().toLowerCase().startsWith(
lastFilter.toLowerCase())) {
doItemAction(item, true);
} else {
if (currentSuggestion != null) {
String text = currentSuggestion.getReplacementString();
tb.setText((text.equals("") ? emptyText : text));
// TODO add/remove class CLASSNAME_EMPTY
selectedOptionKey = currentSuggestion.key;
} else {
tb.setText(emptyText);
// TODO add class CLASSNAME_EMPTY
selectedOptionKey = null;
}
}
suggestionPopup.hide();
}
}
public static final int FILTERINGMODE_OFF = 0;
public static final int FILTERINGMODE_STARTSWITH = 1;
public static final int FILTERINGMODE_CONTAINS = 2;
private static final String CLASSNAME = "i-filterselect";
public static final int PAGELENTH = 10;
private final FlowPanel panel = new FlowPanel();
private final TextBox tb = new TextBox() {
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (client != null) {
client.handleTooltipEvent(event, IFilterSelect.this);
}
}
};
private final SuggestionPopup suggestionPopup = new SuggestionPopup();
private final HTML popupOpener = new HTML("");
private final Image selectedItemIcon = new Image();
private ApplicationConnection client;
private String paintableId;
private int currentPage;
private final Collection currentSuggestions = new ArrayList();
private boolean immediate;
private String selectedOptionKey;
private boolean filtering = false;
private String lastFilter = "";
private FilterSelectSuggestion currentSuggestion;
private int totalMatches;
private boolean allowNewItem;
private boolean nullSelectionAllowed;
private boolean enabled;
// shown in unfocused empty field, disappears on focus (e.g "Search here")
private String emptyText = "";
// Set true when popupopened has been clicked. Cleared on each UIDL-update.
// This handles the special case where are not filtering yet and the
// selected value has changed on the server-side. See #2119
private boolean popupOpenerClicked;
private static final String CLASSNAME_EMPTY = "empty";
private static final String ATTR_EMPTYTEXT = "emptytext";
public IFilterSelect() {
selectedItemIcon.setVisible(false);
panel.add(selectedItemIcon);
tb.sinkEvents(ITooltip.TOOLTIP_EVENTS);
panel.add(tb);
panel.add(popupOpener);
initWidget(panel);
setStyleName(CLASSNAME);
tb.addKeyboardListener(this);
tb.setStyleName(CLASSNAME + "-input");
tb.addFocusListener(this);
popupOpener.setStyleName(CLASSNAME + "-button");
popupOpener.addClickListener(this);
}
public boolean hasNextPage() {
if (totalMatches > (currentPage + 1) * PAGELENTH) {
return true;
} else {
return false;
}
}
public void filterOptions(int page) {
filterOptions(page, tb.getText());
}
public void filterOptions(int page, String filter) {
if (filter.equals(lastFilter) && currentPage == page) {
if (!suggestionPopup.isAttached()) {
suggestionPopup.showSuggestions(currentSuggestions,
currentPage, totalMatches);
}
return;
}
if (!filter.equals(lastFilter)) {
// we are on subsequent page and text has changed -> reset page
if ("".equals(filter)) {
// let server decide
page = -1;
} else {
page = 0;
}
}
filtering = true;
client.updateVariable(paintableId, "filter", filter, false);
client.updateVariable(paintableId, "page", page, true);
lastFilter = filter;
currentPage = page;
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
paintableId = uidl.getId();
this.client = client;
boolean readonly = uidl.hasAttribute("readonly");
boolean disabled = uidl.hasAttribute("disabled");
if (disabled || readonly) {
tb.setEnabled(false);
enabled = false;
} else {
tb.setEnabled(true);
enabled = true;
}
if (client.updateComponent(this, uidl, true)) {
return;
}
// not a FocusWidget -> needs own tabindex handling
if (uidl.hasAttribute("tabindex")) {
tb.setTabIndex(uidl.getIntAttribute("tabindex"));
}
immediate = uidl.hasAttribute("immediate");
nullSelectionAllowed = uidl.hasAttribute("nullselect");
currentPage = uidl.getIntVariable("page");
if (uidl.hasAttribute(ATTR_EMPTYTEXT)) {
// "emptytext" changed from server
emptyText = uidl.getStringAttribute(ATTR_EMPTYTEXT);
}
suggestionPopup.setPagingEnabled(true);
allowNewItem = uidl.hasAttribute("allownewitem");
currentSuggestions.clear();
final UIDL options = uidl.getChildUIDL(0);
totalMatches = uidl.getIntAttribute("totalMatches");
String captions = emptyText;
for (final Iterator i = options.getChildIterator(); i.hasNext();) {
final UIDL optionUidl = (UIDL) i.next();
final FilterSelectSuggestion suggestion = new FilterSelectSuggestion(
optionUidl);
currentSuggestions.add(suggestion);
if (optionUidl.hasAttribute("selected")) {
if (!filtering || popupOpenerClicked) {
tb.setText(suggestion.getReplacementString());
selectedOptionKey = "" + suggestion.getOptionKey();
}
currentSuggestion = suggestion;
+ setSelectedItemIcon(suggestion.getIconUri());
}
// Collect captions so we can calculate minimum width for textarea
if (captions.length() > 0) {
captions += "|";
}
captions += suggestion.getReplacementString();
}
if ((!filtering || popupOpenerClicked) && uidl.hasVariable("selected")
&& uidl.getStringArrayVariable("selected").length == 0) {
// select nulled
tb.setText(emptyText);
selectedOptionKey = null;
// TODO add class CLASSNAME_EMPTY
}
if (filtering
&& lastFilter.toLowerCase().equals(
uidl.getStringVariable("filter"))) {
suggestionPopup.showSuggestions(currentSuggestions, currentPage,
totalMatches);
filtering = false;
}
// Calculate minumum textarea width
final int minw = minWidth(captions);
final Element spacer = DOM.createDiv();
DOM.setStyleAttribute(spacer, "width", minw + "px");
DOM.setStyleAttribute(spacer, "height", "0");
DOM.setStyleAttribute(spacer, "overflow", "hidden");
DOM.appendChild(panel.getElement(), spacer);
popupOpenerClicked = false;
}
public void onSuggestionSelected(FilterSelectSuggestion suggestion) {
currentSuggestion = suggestion;
String newKey;
if (suggestion.key.equals("")) {
// "nullselection"
newKey = "";
} else {
// normal selection
newKey = String.valueOf(suggestion.getOptionKey());
}
String text = suggestion.getReplacementString();
tb.setText(text.equals("") ? emptyText : text);
// TODO add/remove class CLASSNAME_EMPTY
setSelectedItemIcon(suggestion.getIconUri());
if (!newKey.equals(selectedOptionKey)) {
selectedOptionKey = newKey;
client.updateVariable(paintableId, "selected",
new String[] { selectedOptionKey }, immediate);
// currentPage = -1; // forget the page
}
suggestionPopup.hide();
}
private void setSelectedItemIcon(String iconUri) {
if (iconUri == null) {
selectedItemIcon.setVisible(false);
} else {
selectedItemIcon.setUrl(iconUri);
selectedItemIcon.setVisible(true);
}
}
public void onKeyDown(Widget sender, char keyCode, int modifiers) {
if (enabled && suggestionPopup.isAttached()) {
switch (keyCode) {
case KeyboardListener.KEY_DOWN:
suggestionPopup.selectNextItem();
DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
break;
case KeyboardListener.KEY_UP:
suggestionPopup.selectPrevItem();
DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
break;
case KeyboardListener.KEY_PAGEDOWN:
if (hasNextPage()) {
filterOptions(currentPage + 1, lastFilter);
}
break;
case KeyboardListener.KEY_PAGEUP:
if (currentPage > 0) {
filterOptions(currentPage - 1, lastFilter);
}
break;
case KeyboardListener.KEY_ENTER:
case KeyboardListener.KEY_TAB:
suggestionPopup.menu.doSelectedItemAction();
break;
}
}
}
public void onKeyPress(Widget sender, char keyCode, int modifiers) {
}
public void onKeyUp(Widget sender, char keyCode, int modifiers) {
if (enabled) {
switch (keyCode) {
case KeyboardListener.KEY_ENTER:
case KeyboardListener.KEY_TAB:
case KeyboardListener.KEY_SHIFT:
case KeyboardListener.KEY_CTRL:
case KeyboardListener.KEY_ALT:
; // NOP
break;
case KeyboardListener.KEY_DOWN:
case KeyboardListener.KEY_UP:
case KeyboardListener.KEY_PAGEDOWN:
case KeyboardListener.KEY_PAGEUP:
if (suggestionPopup.isAttached()) {
break;
} else {
// open popup as from gadget
filterOptions(-1, "");
lastFilter = "";
tb.selectAll();
break;
}
case KeyboardListener.KEY_ESCAPE:
if (currentSuggestion != null) {
String text = currentSuggestion.getReplacementString();
tb.setText((text.equals("") ? emptyText : text));
// TODO add/remove class CLASSNAME_EMPTY
selectedOptionKey = currentSuggestion.key;
} else {
tb.setText(emptyText);
// TODO add class CLASSNAME_EMPTY
selectedOptionKey = null;
}
lastFilter = "";
suggestionPopup.hide();
break;
default:
filterOptions(currentPage);
break;
}
}
}
/**
* Listener for popupopener
*/
public void onClick(Widget sender) {
if (enabled) {
// ask suggestionPopup if it was just closed, we are using GWT
// Popup's
// auto close feature
if (!suggestionPopup.isJustClosed()) {
filterOptions(-1, "");
popupOpenerClicked = true;
lastFilter = "";
}
DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
tb.setFocus(true);
tb.selectAll();
}
}
/*
* Calculate minumum width for FilterSelect textarea
*/
private native int minWidth(String captions)
/*-{
if(!captions || captions.length <= 0)
return 0;
captions = captions.split("|");
var d = $wnd.document.createElement("div");
var html = "";
for(var i=0; i < captions.length; i++) {
html += "<div>" + captions[i] + "</div>";
// TODO apply same CSS classname as in suggestionmenu
}
d.style.position = "absolute";
d.style.top = "0";
d.style.left = "0";
d.style.visibility = "hidden";
d.innerHTML = html;
$wnd.document.body.appendChild(d);
var w = d.offsetWidth;
$wnd.document.body.removeChild(d);
return w;
}-*/;
public void onFocus(Widget sender) {
if (emptyText.equals(tb.getText())) {
tb.setText("");
// TODO remove class CLASSNAME_EMPTY
}
}
public void onLostFocus(Widget sender) {
if (!suggestionPopup.isAttached() || suggestionPopup.isJustClosed()) {
// typing so fast the popup was never opened, or it's just closed
suggestionPopup.menu.doSelectedItemAction();
}
if ("".equals(tb.getText())) {
tb.setText(emptyText);
// TODO add CLASSNAME_EMPTY
}
}
public void focus() {
tb.setFocus(true);
}
}
| true | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
paintableId = uidl.getId();
this.client = client;
boolean readonly = uidl.hasAttribute("readonly");
boolean disabled = uidl.hasAttribute("disabled");
if (disabled || readonly) {
tb.setEnabled(false);
enabled = false;
} else {
tb.setEnabled(true);
enabled = true;
}
if (client.updateComponent(this, uidl, true)) {
return;
}
// not a FocusWidget -> needs own tabindex handling
if (uidl.hasAttribute("tabindex")) {
tb.setTabIndex(uidl.getIntAttribute("tabindex"));
}
immediate = uidl.hasAttribute("immediate");
nullSelectionAllowed = uidl.hasAttribute("nullselect");
currentPage = uidl.getIntVariable("page");
if (uidl.hasAttribute(ATTR_EMPTYTEXT)) {
// "emptytext" changed from server
emptyText = uidl.getStringAttribute(ATTR_EMPTYTEXT);
}
suggestionPopup.setPagingEnabled(true);
allowNewItem = uidl.hasAttribute("allownewitem");
currentSuggestions.clear();
final UIDL options = uidl.getChildUIDL(0);
totalMatches = uidl.getIntAttribute("totalMatches");
String captions = emptyText;
for (final Iterator i = options.getChildIterator(); i.hasNext();) {
final UIDL optionUidl = (UIDL) i.next();
final FilterSelectSuggestion suggestion = new FilterSelectSuggestion(
optionUidl);
currentSuggestions.add(suggestion);
if (optionUidl.hasAttribute("selected")) {
if (!filtering || popupOpenerClicked) {
tb.setText(suggestion.getReplacementString());
selectedOptionKey = "" + suggestion.getOptionKey();
}
currentSuggestion = suggestion;
}
// Collect captions so we can calculate minimum width for textarea
if (captions.length() > 0) {
captions += "|";
}
captions += suggestion.getReplacementString();
}
if ((!filtering || popupOpenerClicked) && uidl.hasVariable("selected")
&& uidl.getStringArrayVariable("selected").length == 0) {
// select nulled
tb.setText(emptyText);
selectedOptionKey = null;
// TODO add class CLASSNAME_EMPTY
}
if (filtering
&& lastFilter.toLowerCase().equals(
uidl.getStringVariable("filter"))) {
suggestionPopup.showSuggestions(currentSuggestions, currentPage,
totalMatches);
filtering = false;
}
// Calculate minumum textarea width
final int minw = minWidth(captions);
final Element spacer = DOM.createDiv();
DOM.setStyleAttribute(spacer, "width", minw + "px");
DOM.setStyleAttribute(spacer, "height", "0");
DOM.setStyleAttribute(spacer, "overflow", "hidden");
DOM.appendChild(panel.getElement(), spacer);
popupOpenerClicked = false;
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
paintableId = uidl.getId();
this.client = client;
boolean readonly = uidl.hasAttribute("readonly");
boolean disabled = uidl.hasAttribute("disabled");
if (disabled || readonly) {
tb.setEnabled(false);
enabled = false;
} else {
tb.setEnabled(true);
enabled = true;
}
if (client.updateComponent(this, uidl, true)) {
return;
}
// not a FocusWidget -> needs own tabindex handling
if (uidl.hasAttribute("tabindex")) {
tb.setTabIndex(uidl.getIntAttribute("tabindex"));
}
immediate = uidl.hasAttribute("immediate");
nullSelectionAllowed = uidl.hasAttribute("nullselect");
currentPage = uidl.getIntVariable("page");
if (uidl.hasAttribute(ATTR_EMPTYTEXT)) {
// "emptytext" changed from server
emptyText = uidl.getStringAttribute(ATTR_EMPTYTEXT);
}
suggestionPopup.setPagingEnabled(true);
allowNewItem = uidl.hasAttribute("allownewitem");
currentSuggestions.clear();
final UIDL options = uidl.getChildUIDL(0);
totalMatches = uidl.getIntAttribute("totalMatches");
String captions = emptyText;
for (final Iterator i = options.getChildIterator(); i.hasNext();) {
final UIDL optionUidl = (UIDL) i.next();
final FilterSelectSuggestion suggestion = new FilterSelectSuggestion(
optionUidl);
currentSuggestions.add(suggestion);
if (optionUidl.hasAttribute("selected")) {
if (!filtering || popupOpenerClicked) {
tb.setText(suggestion.getReplacementString());
selectedOptionKey = "" + suggestion.getOptionKey();
}
currentSuggestion = suggestion;
setSelectedItemIcon(suggestion.getIconUri());
}
// Collect captions so we can calculate minimum width for textarea
if (captions.length() > 0) {
captions += "|";
}
captions += suggestion.getReplacementString();
}
if ((!filtering || popupOpenerClicked) && uidl.hasVariable("selected")
&& uidl.getStringArrayVariable("selected").length == 0) {
// select nulled
tb.setText(emptyText);
selectedOptionKey = null;
// TODO add class CLASSNAME_EMPTY
}
if (filtering
&& lastFilter.toLowerCase().equals(
uidl.getStringVariable("filter"))) {
suggestionPopup.showSuggestions(currentSuggestions, currentPage,
totalMatches);
filtering = false;
}
// Calculate minumum textarea width
final int minw = minWidth(captions);
final Element spacer = DOM.createDiv();
DOM.setStyleAttribute(spacer, "width", minw + "px");
DOM.setStyleAttribute(spacer, "height", "0");
DOM.setStyleAttribute(spacer, "overflow", "hidden");
DOM.appendChild(panel.getElement(), spacer);
popupOpenerClicked = false;
}
|
diff --git a/fap/app/tramitacion/TramiteBase.java b/fap/app/tramitacion/TramiteBase.java
index 61849d25..7c10a69f 100644
--- a/fap/app/tramitacion/TramiteBase.java
+++ b/fap/app/tramitacion/TramiteBase.java
@@ -1,504 +1,504 @@
package tramitacion;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityTransaction;
import org.joda.time.DateTime;
import config.InjectorConfig;
import controllers.fap.FirmaController;
import emails.Mails;
import enumerado.fap.gen.EstadosSolicitudEnum;
import messages.Messages;
import models.Aportacion;
import models.Documento;
import models.DocumentoExterno;
import models.Firma;
import models.Firmante;
import models.Firmantes;
import models.JustificanteRegistro;
import models.Registro;
import models.Solicitante;
import models.SolicitudGenerica;
import platino.DatosRegistro;
import play.db.jpa.JPA;
import play.libs.Crypto;
import play.modules.guice.InjectSupport;
import properties.FapProperties;
import reports.Report;
import services.FirmaService;
import services.GestorDocumentalService;
import services.GestorDocumentalServiceException;
import services.RegistroService;
import services.RegistroServiceException;
import services.TercerosService;
@InjectSupport
public abstract class TramiteBase {
@Inject
public static GestorDocumentalService gestorDocumentalService;
@Inject
public static RegistroService registroService;
@Inject
private static FirmaService firmaService;
public SolicitudGenerica solicitud;
public Registro registro;
public TramiteBase(SolicitudGenerica solicitud){
this.solicitud = solicitud;
this.registro = getRegistro();
inicializar();
}
/**
* Sobreescribir para inicializar la clase. Es invocado desde el constructor
*/
public void inicializar() {
}
public abstract Registro getRegistro();
public abstract String getTipoRegistro();
// Region Procedimientos y Funciones
public abstract String getBodyReport();
public abstract String getHeaderReport();
public abstract String getFooterReport();
public String getFooterEvaluacionReport() {
return getFooterReport();
}
public abstract String getMail(); // Cuando se registre un trámite
public abstract String getJustificanteRegistro();
/**
* Sobreescribir para asignar la descripción del justificante.
* @return
*/
public abstract String getDescripcionJustificante();
public abstract String getTipoTramite();
public SolicitudGenerica getSolicitud() {
return this.solicitud;
}
public abstract List<Documento> getDocumentos();
public abstract List<DocumentoExterno> getDocumentosExternos();
public void prepararFirmar(){
if(registro.fasesRegistro.borrador){
Messages.error("La solicitud ya está preparada");
}
validar();
eliminarBorrador();
eliminarOficial();
File borrador = generarBorrador();
File oficial = generarOficial();
almacenarEnGestorDocumental(borrador, oficial);
calcularFirmantes();
avanzarFaseBorrador();
}
public void validar(){
}
/**
* Nombre del fichero del justificante
* @return el nombre del fichero para el justificante
*/
public abstract String getPrefijoJustificantePdf();
public void eliminarBorrador(){
if(!Messages.hasErrors()){
// Borramos los documentos que se pudieron generar en una llamada previa al metodo, para no dejar basura en la BBDD
if ((registro.borrador != null) && (registro.borrador.uri != null)){
Documento borradorOld = registro.borrador;
registro.borrador = null;
registro.save();
try{
gestorDocumentalService.deleteDocumento(borradorOld);
}catch(Exception e){
play.Logger.error("Error eliminando borrador del gestor documental: "+e.getMessage());
};
}
}
}
public void eliminarOficial() {
if(!Messages.hasErrors()){
if((registro.oficial != null) && (registro.oficial.uri != null)){
Documento oficialOld = registro.oficial;
registro.oficial = null;
registro.save();
try {
gestorDocumentalService.deleteDocumento(oficialOld);
}catch(Exception e){
play.Logger.error("Error eliminando documento oficial del gestor documental: "+e.getMessage());
};
}
}
}
public File generarBorrador(){
File borrador = null;
borrador = new File (this.getBodyReport());
if(!Messages.hasErrors()){
try {
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
borrador = new Report(this.getBodyReport()).header(this.getHeaderReport()).footer(this.getFooterReport()).renderTmpFile(solicitud);
registro.borrador = new Documento();
registro.borrador.tipo = getTipoRegistro();
registro.save();
} catch (Exception ex2) {
Messages.error("Error generando el documento borrador");
play.Logger.error("Error generando el documento borrador: "+ex2.getMessage());
}
}
return borrador;
}
public File generarOficial(){
File oficial = null;
if(!Messages.hasErrors()){
try {
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
oficial = new Report(this.getBodyReport()).header(this.getHeaderReport()).registroSize().renderTmpFile(solicitud);
registro.oficial = new Documento();
registro.oficial.tipo = getTipoRegistro();
registro.save();
} catch (Exception ex2) {
Messages.error("Error generando el documento oficial");
play.Logger.error("Error generando el documento oficial: "+ex2.getMessage());
}
}
return oficial;
}
public void almacenarEnGestorDocumental(File borrador, File oficial){
if(!Messages.hasErrors()){
try {
gestorDocumentalService.saveDocumentoTemporal(registro.borrador, borrador);
gestorDocumentalService.saveDocumentoTemporal(registro.oficial, oficial);
}catch(Exception e){
Messages.error("Error almacenando documentos en el aed");
play.Logger.error("Error almacenando documentos en el aed: "+e.getMessage());
}
}
}
public void almacenarFirma(String firma, Documento documento, Firmante firmante) {
try {
gestorDocumentalService.agregarFirma(documento, new Firma(firma, firmante));
} catch (Exception e) {
Messages.error("Error guardando la firma del documento");
play.Logger.error("Error guardando la firma del documento: "+e.getMessage());
}
}
public void calcularFirmantes(){
if(!Messages.hasErrors()){
registro.firmantes = Firmantes.calcularFirmanteFromSolicitante(solicitud.solicitante);
registro.save();
}
}
public void avanzarFaseBorrador(){
if(!Messages.hasErrors()){
registro.fasesRegistro.borrador = true;
registro.save();
}
}
/**
* Reinicia las fases del registro y lo salva
*/
public void deshacer() {
registro.fasesRegistro.reiniciar();
registro.fasesRegistro.save();
}
public void firmar(String firma){
if(registro.fasesRegistro.borrador && !registro.fasesRegistro.firmada){
String identificadorFirmante = FirmaController.getIdentificacionFromFirma(firma);
if(registro.firmantes.containsFirmanteConIdentificador(identificadorFirmante) && !registro.firmantes.haFirmado(identificadorFirmante)){
Firmante firmante = firmaService.getFirmante(firma, registro.oficial);
for (Firmante firmanteAux: registro.firmantes.todos){
if (firmanteAux.idvalor.equals(identificadorFirmante)){
firmante.cardinalidad = firmanteAux.cardinalidad;
firmante.tipo = firmanteAux.tipo;
registro.firmantes.todos.remove(firmanteAux);
registro.firmantes.todos.add(firmante);
registro.save();
break;
}
}
firmante.fechaFirma = new DateTime();
almacenarFirma(firma, registro.oficial, firmante);
firmante.save();
if(hanFirmadoTodos()){
avanzarFaseFirmada();
}
} else if (registro.firmantes.haFirmado(identificadorFirmante)){
play.Logger.error("La solicitud ya ha sido firmada por ese certificado");
Messages.error("La solicitud ya ha sido firmada por ese certificado");
} else {
String firmantes="{";
for (Firmante firmante: registro.firmantes.todos){
firmantes+=firmante.toString()+" | ";
}
firmantes+="}";
play.Logger.error("El certificado <"+identificadorFirmante+"> no se corresponde con uno que debe firmar la solicitud: "+firmantes);
Messages.error("El certificado no se corresponde con uno que debe firmar la solicitud");
}
}
}
public void avanzarFaseFirmada(){
if(!Messages.hasErrors()){
registro.fasesRegistro.firmada = true;
registro.save();
}
}
public abstract void validarReglasConMensajes();
/**
* Sobreescribir para registrar el tipo de trámite específico
* @throws RegistroException
*/
public void registrar() throws RegistroServiceException {
EntityTransaction tx = JPA.em().getTransaction();
tx.commit();
//Registra la solicitud
if (!Messages.hasErrors()){
if (!registro.fasesRegistro.registro && registro.fasesRegistro.firmada) {
try {
tx.begin();
//Registra la solicitud
JustificanteRegistro justificante = registroService.registrarEntrada(this.solicitud.solicitante, registro.oficial, this.solicitud.expedientePlatino, null);
play.Logger.info("Se ha registrado la solicitud %s en platino (Algo relativo a ella)", solicitud.id);
tx.commit();
registro.refresh();
tx.begin();
//Almacena la información de registro
registro.informacionRegistro.setDataFromJustificante(justificante);
play.Logger.info("Almacenada la información del registro en la base de datos");
//Guarda el justificante en el AED
play.Logger.info("Se procede a guardar el justificante de la solicitud %s en el AED", solicitud.id);
Documento documento = registro.justificante;
documento.tipo = this.getJustificanteRegistro();
documento.descripcion = this.getDescripcionJustificante();
documento.save();
gestorDocumentalService.saveDocumentoTemporal(documento, justificante.getDocumento().contenido.getInputStream(), this.getNombreFicheroPdf());
play.Logger.info("Justificante Registro del trámite de '%s' almacenado en el AED", this.getTipoTramite());
registro.fasesRegistro.registro = true;
getRegistro().fasesRegistro.registro=true;
registro.fasesRegistro.save();
// Establecemos las fechas de registro para todos los documentos de la solicitud
List<Documento> documentos = new ArrayList<Documento>();
documentos.addAll(this.getDocumentos());
documentos.add(registro.justificante);
documentos.add(registro.oficial);
for (Documento doc: documentos) {
if (doc.fechaRegistro == null) {
doc.fechaRegistro = registro.informacionRegistro.fechaRegistro;
doc.save();
}
}
play.Logger.info("Fechas de registro establecidas a " + this.getRegistro().informacionRegistro.fechaRegistro);
tx.commit();
} catch (Exception e) {
Messages.error("Error al registrar de entrada la solicitud");
play.Logger.error("Error al registrar de entrada la solicitud: "+e.getMessage());
throw new RegistroServiceException("Error al obtener el justificante del registro de entrada");
}
} else {
play.Logger.info("El trámite de '%s' de la solicitud %s ya está registrada", this.getTipoTramite(), this.solicitud.id);
}
registro.refresh();
//Crea el expediente en el Gestor Documental
tx.begin();
crearExpediente();
tx.commit();
//Ahora el estado de la solicitud se cambia después de registrar.
//Clasifica los documentos en el AED
if (!registro.fasesRegistro.clasificarAed && registro.fasesRegistro.registro) {
//Clasifica los documentos sin registro
tx.begin();
List<Documento> documentos = new ArrayList<Documento>();
documentos.add(registro.justificante);
try {
gestorDocumentalService.clasificarDocumentos(this.solicitud, documentos);
} catch (GestorDocumentalServiceException e){
play.Logger.fatal("No se clasificaron algunos documentos sin registro: "+e.getMessage());
Messages.error("Algunos documentos sin registro del trámite de '" + this.getTipoTramite() + "' no pudieron ser clasificados correctamente");
throw new RegistroServiceException("Error al clasificar documentos sin registros");
}
if (!Messages.hasErrors()){
//Clasifica los documentos con registro de entrada
List<Documento> documentosRegistrados = new ArrayList<Documento>();
documentosRegistrados.addAll(this.getDocumentos());
documentosRegistrados.add(registro.oficial);
try {
gestorDocumentalService.clasificarDocumentos(this.solicitud, documentosRegistrados, registro.informacionRegistro);
registro.fasesRegistro.clasificarAed = true;
registro.fasesRegistro.save();
play.Logger.info("Se clasificaron todos los documentos del trámite de '%s'", this.getTipoTramite());
} catch (GestorDocumentalServiceException e){
play.Logger.fatal("No se clasificaron algunos documentos con registro de entrada: "+e.getMessage());
Messages.error("Algunos documentos con registro de entrada del trámite de '" + this.getTipoTramite() + "' no pudieron ser clasificados correctamente");
throw new RegistroServiceException("Error al clasificar documentos con registros");
}
}
tx.commit();
} else {
play.Logger.info("Ya están clasificados todos los documentos del trámite de '%s' de la solicitud %s", this.getTipoTramite(), this.solicitud.id);
}
registro.refresh();
//Añade los documentos a la lista de documentos de la solicitud
if (registro.fasesRegistro.clasificarAed){
tx.begin();
this.moverRegistradas();
for (Documento doc: this.getDocumentos()) {
if (!this.solicitud.documentacion.documentos.contains(doc))
this.solicitud.documentacion.documentos.add(doc);
}
this.prepararNuevo();
solicitud.save();
play.Logger.info("Los documentos del trámite de '%s' se movieron correctamente", this.getTipoTramite());
// Creamos el nuevo tercero, si no existe
if ((solicitud.solicitante.uriTerceros == null) || (solicitud.solicitante.uriTerceros.isEmpty())) {
try {
String tipoNumeroIdentificacion;
if (solicitud.solicitante.isPersonaFisica()){
tipoNumeroIdentificacion = solicitud.solicitante.fisica.nip.tipo;
} else {
tipoNumeroIdentificacion = "cif";
}
TercerosService tercerosService = InjectorConfig.getInjector().getInstance(TercerosService.class);
Solicitante existeTercero = tercerosService.buscarTercerosDetalladosByNumeroIdentificacion(solicitud.solicitante.getNumeroId(), tipoNumeroIdentificacion);
if (existeTercero == null){
String uriTercero = tercerosService.crearTerceroMinimal(solicitud.solicitante);
solicitud.solicitante.uriTerceros = uriTercero;
solicitud.save();
} else {
String uriTercero = existeTercero.uriTerceros;
solicitud.solicitante.uriTerceros = uriTercero;
solicitud.save();
play.Logger.warn("El Tercero ya existe en la BDD a Terceros de Platino: "+solicitud.solicitante.getNumeroId()+" - "+tipoNumeroIdentificacion+". Se ha seteado la uriTerceros a: "+uriTercero);
}
} catch (Exception e){
play.Logger.fatal("No se pudo crear el Tercero en Platino con id: "+solicitud.solicitante.getNumeroId()+" : "+e.getMessage());
}
}
try {
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
Mails.enviar(this.getMail(), solicitud);
} catch (Exception e){
play.Logger.error("Envío del Mail de registro del trámite fallido "+this.getMail()+": "+e.getMessage());
}
- play.Logger.info("Correo Registro del trámtite de '%s' enviado", this.getTipoTramite());
+ play.Logger.info("Correo Registro del trámite de '%s' enviado", this.getTipoTramite());
tx.commit();
}
}
tx.begin();
}
/**
* Mueve el trámite actual a la colección de trámites registrados
*/
public void moverRegistradas() {
}
/**
* Prepara un nuevo trámite y lo añade a la variable actual
*/
public void prepararNuevo() {
}
/**
* Obtiene el nombre del justificante del fichero pdf a partir del prefijo del justificante y
* del id de la solicitud más la extensión del fichero
* @return
*/
private final String getNombreFicheroPdf() {
return this.getPrefijoJustificantePdf() + this.solicitud.id + ".pdf";
}
/**
* Crea el expediente del Aed
*/
public abstract void crearExpedienteAed();
public void crearExpediente() throws RegistroServiceException{
if(!getRegistro().fasesRegistro.expedienteAed){
try {
gestorDocumentalService.crearExpediente(solicitud);
} catch (GestorDocumentalServiceException e) {
Messages.error("Error al crear el expediente");
play.Logger.error("Error al crear el expediente para la solicitud "+solicitud.id+": "+e);
throw new RegistroServiceException("Error al crear el expediente");
}
getRegistro().fasesRegistro.expedienteAed = true;
getRegistro().fasesRegistro.save();
}else{
play.Logger.info("El expediente del aed para la solicitud %s ya está creado", solicitud.id);
}
}
/**
* Crea el expediente en Platino
*/
public abstract void crearExpedientePlatino() throws RegistroServiceException;
public void cambiarEstadoSolicitud() {
solicitud.estado=EstadosSolicitudEnum.iniciada.name();
solicitud.save();
}
public File getDocumentoBorrador (){
try {
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
return new Report(getBodyReport()).header(getHeaderReport()).footer(getFooterEvaluacionReport()).registroSize().renderTmpFile(solicitud);
} catch (Exception e) {
play.Logger.error("Error generando el documento Solicitud para la Evaluación"+ e.getMessage());
return null;
}
}
public boolean hanFirmadoTodos(){
return registro.firmantes.hanFirmadoTodos();
}
}
| true | true | public void registrar() throws RegistroServiceException {
EntityTransaction tx = JPA.em().getTransaction();
tx.commit();
//Registra la solicitud
if (!Messages.hasErrors()){
if (!registro.fasesRegistro.registro && registro.fasesRegistro.firmada) {
try {
tx.begin();
//Registra la solicitud
JustificanteRegistro justificante = registroService.registrarEntrada(this.solicitud.solicitante, registro.oficial, this.solicitud.expedientePlatino, null);
play.Logger.info("Se ha registrado la solicitud %s en platino (Algo relativo a ella)", solicitud.id);
tx.commit();
registro.refresh();
tx.begin();
//Almacena la información de registro
registro.informacionRegistro.setDataFromJustificante(justificante);
play.Logger.info("Almacenada la información del registro en la base de datos");
//Guarda el justificante en el AED
play.Logger.info("Se procede a guardar el justificante de la solicitud %s en el AED", solicitud.id);
Documento documento = registro.justificante;
documento.tipo = this.getJustificanteRegistro();
documento.descripcion = this.getDescripcionJustificante();
documento.save();
gestorDocumentalService.saveDocumentoTemporal(documento, justificante.getDocumento().contenido.getInputStream(), this.getNombreFicheroPdf());
play.Logger.info("Justificante Registro del trámite de '%s' almacenado en el AED", this.getTipoTramite());
registro.fasesRegistro.registro = true;
getRegistro().fasesRegistro.registro=true;
registro.fasesRegistro.save();
// Establecemos las fechas de registro para todos los documentos de la solicitud
List<Documento> documentos = new ArrayList<Documento>();
documentos.addAll(this.getDocumentos());
documentos.add(registro.justificante);
documentos.add(registro.oficial);
for (Documento doc: documentos) {
if (doc.fechaRegistro == null) {
doc.fechaRegistro = registro.informacionRegistro.fechaRegistro;
doc.save();
}
}
play.Logger.info("Fechas de registro establecidas a " + this.getRegistro().informacionRegistro.fechaRegistro);
tx.commit();
} catch (Exception e) {
Messages.error("Error al registrar de entrada la solicitud");
play.Logger.error("Error al registrar de entrada la solicitud: "+e.getMessage());
throw new RegistroServiceException("Error al obtener el justificante del registro de entrada");
}
} else {
play.Logger.info("El trámite de '%s' de la solicitud %s ya está registrada", this.getTipoTramite(), this.solicitud.id);
}
registro.refresh();
//Crea el expediente en el Gestor Documental
tx.begin();
crearExpediente();
tx.commit();
//Ahora el estado de la solicitud se cambia después de registrar.
//Clasifica los documentos en el AED
if (!registro.fasesRegistro.clasificarAed && registro.fasesRegistro.registro) {
//Clasifica los documentos sin registro
tx.begin();
List<Documento> documentos = new ArrayList<Documento>();
documentos.add(registro.justificante);
try {
gestorDocumentalService.clasificarDocumentos(this.solicitud, documentos);
} catch (GestorDocumentalServiceException e){
play.Logger.fatal("No se clasificaron algunos documentos sin registro: "+e.getMessage());
Messages.error("Algunos documentos sin registro del trámite de '" + this.getTipoTramite() + "' no pudieron ser clasificados correctamente");
throw new RegistroServiceException("Error al clasificar documentos sin registros");
}
if (!Messages.hasErrors()){
//Clasifica los documentos con registro de entrada
List<Documento> documentosRegistrados = new ArrayList<Documento>();
documentosRegistrados.addAll(this.getDocumentos());
documentosRegistrados.add(registro.oficial);
try {
gestorDocumentalService.clasificarDocumentos(this.solicitud, documentosRegistrados, registro.informacionRegistro);
registro.fasesRegistro.clasificarAed = true;
registro.fasesRegistro.save();
play.Logger.info("Se clasificaron todos los documentos del trámite de '%s'", this.getTipoTramite());
} catch (GestorDocumentalServiceException e){
play.Logger.fatal("No se clasificaron algunos documentos con registro de entrada: "+e.getMessage());
Messages.error("Algunos documentos con registro de entrada del trámite de '" + this.getTipoTramite() + "' no pudieron ser clasificados correctamente");
throw new RegistroServiceException("Error al clasificar documentos con registros");
}
}
tx.commit();
} else {
play.Logger.info("Ya están clasificados todos los documentos del trámite de '%s' de la solicitud %s", this.getTipoTramite(), this.solicitud.id);
}
registro.refresh();
//Añade los documentos a la lista de documentos de la solicitud
if (registro.fasesRegistro.clasificarAed){
tx.begin();
this.moverRegistradas();
for (Documento doc: this.getDocumentos()) {
if (!this.solicitud.documentacion.documentos.contains(doc))
this.solicitud.documentacion.documentos.add(doc);
}
this.prepararNuevo();
solicitud.save();
play.Logger.info("Los documentos del trámite de '%s' se movieron correctamente", this.getTipoTramite());
// Creamos el nuevo tercero, si no existe
if ((solicitud.solicitante.uriTerceros == null) || (solicitud.solicitante.uriTerceros.isEmpty())) {
try {
String tipoNumeroIdentificacion;
if (solicitud.solicitante.isPersonaFisica()){
tipoNumeroIdentificacion = solicitud.solicitante.fisica.nip.tipo;
} else {
tipoNumeroIdentificacion = "cif";
}
TercerosService tercerosService = InjectorConfig.getInjector().getInstance(TercerosService.class);
Solicitante existeTercero = tercerosService.buscarTercerosDetalladosByNumeroIdentificacion(solicitud.solicitante.getNumeroId(), tipoNumeroIdentificacion);
if (existeTercero == null){
String uriTercero = tercerosService.crearTerceroMinimal(solicitud.solicitante);
solicitud.solicitante.uriTerceros = uriTercero;
solicitud.save();
} else {
String uriTercero = existeTercero.uriTerceros;
solicitud.solicitante.uriTerceros = uriTercero;
solicitud.save();
play.Logger.warn("El Tercero ya existe en la BDD a Terceros de Platino: "+solicitud.solicitante.getNumeroId()+" - "+tipoNumeroIdentificacion+". Se ha seteado la uriTerceros a: "+uriTercero);
}
} catch (Exception e){
play.Logger.fatal("No se pudo crear el Tercero en Platino con id: "+solicitud.solicitante.getNumeroId()+" : "+e.getMessage());
}
}
try {
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
Mails.enviar(this.getMail(), solicitud);
} catch (Exception e){
play.Logger.error("Envío del Mail de registro del trámite fallido "+this.getMail()+": "+e.getMessage());
}
play.Logger.info("Correo Registro del trámtite de '%s' enviado", this.getTipoTramite());
tx.commit();
}
}
tx.begin();
}
| public void registrar() throws RegistroServiceException {
EntityTransaction tx = JPA.em().getTransaction();
tx.commit();
//Registra la solicitud
if (!Messages.hasErrors()){
if (!registro.fasesRegistro.registro && registro.fasesRegistro.firmada) {
try {
tx.begin();
//Registra la solicitud
JustificanteRegistro justificante = registroService.registrarEntrada(this.solicitud.solicitante, registro.oficial, this.solicitud.expedientePlatino, null);
play.Logger.info("Se ha registrado la solicitud %s en platino (Algo relativo a ella)", solicitud.id);
tx.commit();
registro.refresh();
tx.begin();
//Almacena la información de registro
registro.informacionRegistro.setDataFromJustificante(justificante);
play.Logger.info("Almacenada la información del registro en la base de datos");
//Guarda el justificante en el AED
play.Logger.info("Se procede a guardar el justificante de la solicitud %s en el AED", solicitud.id);
Documento documento = registro.justificante;
documento.tipo = this.getJustificanteRegistro();
documento.descripcion = this.getDescripcionJustificante();
documento.save();
gestorDocumentalService.saveDocumentoTemporal(documento, justificante.getDocumento().contenido.getInputStream(), this.getNombreFicheroPdf());
play.Logger.info("Justificante Registro del trámite de '%s' almacenado en el AED", this.getTipoTramite());
registro.fasesRegistro.registro = true;
getRegistro().fasesRegistro.registro=true;
registro.fasesRegistro.save();
// Establecemos las fechas de registro para todos los documentos de la solicitud
List<Documento> documentos = new ArrayList<Documento>();
documentos.addAll(this.getDocumentos());
documentos.add(registro.justificante);
documentos.add(registro.oficial);
for (Documento doc: documentos) {
if (doc.fechaRegistro == null) {
doc.fechaRegistro = registro.informacionRegistro.fechaRegistro;
doc.save();
}
}
play.Logger.info("Fechas de registro establecidas a " + this.getRegistro().informacionRegistro.fechaRegistro);
tx.commit();
} catch (Exception e) {
Messages.error("Error al registrar de entrada la solicitud");
play.Logger.error("Error al registrar de entrada la solicitud: "+e.getMessage());
throw new RegistroServiceException("Error al obtener el justificante del registro de entrada");
}
} else {
play.Logger.info("El trámite de '%s' de la solicitud %s ya está registrada", this.getTipoTramite(), this.solicitud.id);
}
registro.refresh();
//Crea el expediente en el Gestor Documental
tx.begin();
crearExpediente();
tx.commit();
//Ahora el estado de la solicitud se cambia después de registrar.
//Clasifica los documentos en el AED
if (!registro.fasesRegistro.clasificarAed && registro.fasesRegistro.registro) {
//Clasifica los documentos sin registro
tx.begin();
List<Documento> documentos = new ArrayList<Documento>();
documentos.add(registro.justificante);
try {
gestorDocumentalService.clasificarDocumentos(this.solicitud, documentos);
} catch (GestorDocumentalServiceException e){
play.Logger.fatal("No se clasificaron algunos documentos sin registro: "+e.getMessage());
Messages.error("Algunos documentos sin registro del trámite de '" + this.getTipoTramite() + "' no pudieron ser clasificados correctamente");
throw new RegistroServiceException("Error al clasificar documentos sin registros");
}
if (!Messages.hasErrors()){
//Clasifica los documentos con registro de entrada
List<Documento> documentosRegistrados = new ArrayList<Documento>();
documentosRegistrados.addAll(this.getDocumentos());
documentosRegistrados.add(registro.oficial);
try {
gestorDocumentalService.clasificarDocumentos(this.solicitud, documentosRegistrados, registro.informacionRegistro);
registro.fasesRegistro.clasificarAed = true;
registro.fasesRegistro.save();
play.Logger.info("Se clasificaron todos los documentos del trámite de '%s'", this.getTipoTramite());
} catch (GestorDocumentalServiceException e){
play.Logger.fatal("No se clasificaron algunos documentos con registro de entrada: "+e.getMessage());
Messages.error("Algunos documentos con registro de entrada del trámite de '" + this.getTipoTramite() + "' no pudieron ser clasificados correctamente");
throw new RegistroServiceException("Error al clasificar documentos con registros");
}
}
tx.commit();
} else {
play.Logger.info("Ya están clasificados todos los documentos del trámite de '%s' de la solicitud %s", this.getTipoTramite(), this.solicitud.id);
}
registro.refresh();
//Añade los documentos a la lista de documentos de la solicitud
if (registro.fasesRegistro.clasificarAed){
tx.begin();
this.moverRegistradas();
for (Documento doc: this.getDocumentos()) {
if (!this.solicitud.documentacion.documentos.contains(doc))
this.solicitud.documentacion.documentos.add(doc);
}
this.prepararNuevo();
solicitud.save();
play.Logger.info("Los documentos del trámite de '%s' se movieron correctamente", this.getTipoTramite());
// Creamos el nuevo tercero, si no existe
if ((solicitud.solicitante.uriTerceros == null) || (solicitud.solicitante.uriTerceros.isEmpty())) {
try {
String tipoNumeroIdentificacion;
if (solicitud.solicitante.isPersonaFisica()){
tipoNumeroIdentificacion = solicitud.solicitante.fisica.nip.tipo;
} else {
tipoNumeroIdentificacion = "cif";
}
TercerosService tercerosService = InjectorConfig.getInjector().getInstance(TercerosService.class);
Solicitante existeTercero = tercerosService.buscarTercerosDetalladosByNumeroIdentificacion(solicitud.solicitante.getNumeroId(), tipoNumeroIdentificacion);
if (existeTercero == null){
String uriTercero = tercerosService.crearTerceroMinimal(solicitud.solicitante);
solicitud.solicitante.uriTerceros = uriTercero;
solicitud.save();
} else {
String uriTercero = existeTercero.uriTerceros;
solicitud.solicitante.uriTerceros = uriTercero;
solicitud.save();
play.Logger.warn("El Tercero ya existe en la BDD a Terceros de Platino: "+solicitud.solicitante.getNumeroId()+" - "+tipoNumeroIdentificacion+". Se ha seteado la uriTerceros a: "+uriTercero);
}
} catch (Exception e){
play.Logger.fatal("No se pudo crear el Tercero en Platino con id: "+solicitud.solicitante.getNumeroId()+" : "+e.getMessage());
}
}
try {
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
Mails.enviar(this.getMail(), solicitud);
} catch (Exception e){
play.Logger.error("Envío del Mail de registro del trámite fallido "+this.getMail()+": "+e.getMessage());
}
play.Logger.info("Correo Registro del trámite de '%s' enviado", this.getTipoTramite());
tx.commit();
}
}
tx.begin();
}
|
diff --git a/src/com/yifanlu/PSXperiaTool/ZpakCreate.java b/src/com/yifanlu/PSXperiaTool/ZpakCreate.java
index 50d0aee..b48b40a 100644
--- a/src/com/yifanlu/PSXperiaTool/ZpakCreate.java
+++ b/src/com/yifanlu/PSXperiaTool/ZpakCreate.java
@@ -1,108 +1,108 @@
/*
* PSXperia Converter Tool - Zpak creation
* Copyright (C) 2011 Yifan Lu (http://yifan.lu/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.yifanlu.PSXperiaTool;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZpakCreate {
public static final int BLOCK_SIZE = 1024;
private OutputStream mOut;
private File mDirectory;
private byte[] mBuffer;
public ZpakCreate(OutputStream out, File directory) {
this.mOut = out;
this.mDirectory = directory;
this.mBuffer = new byte[BLOCK_SIZE];
}
public void create(boolean noCompress) throws IOException {
Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(), !noCompress);
IOFileFilter filter = new IOFileFilter() {
public boolean accept(File file) {
if (file.getName().startsWith(".")) {
Logger.debug("Skipping file %s", file.getPath());
return false;
}
return true;
}
public boolean accept(File file, String s) {
if (s.startsWith(".")) {
Logger.debug("Skipping file %s", file.getPath());
return false;
}
return true;
}
};
Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE);
ZipOutputStream out = new ZipOutputStream(mOut);
out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED);
while (it.hasNext()) {
File current = it.next();
FileInputStream in = new FileInputStream(current);
- ZipEntry zEntry = new ZipEntry(current.getPath().replace(mDirectory.getPath(), "").substring(1));
+ ZipEntry zEntry = new ZipEntry(current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\","/"));
if (noCompress) {
zEntry.setSize(in.getChannel().size());
zEntry.setCompressedSize(in.getChannel().size());
zEntry.setCrc(getCRC32(current));
}
out.putNextEntry(zEntry);
Logger.verbose("Adding file %s", current.getPath());
int n;
while ((n = in.read(mBuffer)) != -1) {
out.write(mBuffer, 0, n);
}
in.close();
out.closeEntry();
}
out.close();
Logger.debug("Done with ZPAK creation.");
}
public static long getCRC32(File file) throws IOException {
CheckedInputStream cis = null;
long fileSize = 0;
// Computer CRC32 checksum
cis = new CheckedInputStream(new FileInputStream(file), new CRC32());
fileSize = file.length();
byte[] buf = new byte[128];
while (cis.read(buf) != -1) ;
long checksum = cis.getChecksum().getValue();
cis.close();
Logger.verbose("CRC32 of %s is %d", file.getPath(), checksum);
return checksum;
}
}
| true | true | public void create(boolean noCompress) throws IOException {
Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(), !noCompress);
IOFileFilter filter = new IOFileFilter() {
public boolean accept(File file) {
if (file.getName().startsWith(".")) {
Logger.debug("Skipping file %s", file.getPath());
return false;
}
return true;
}
public boolean accept(File file, String s) {
if (s.startsWith(".")) {
Logger.debug("Skipping file %s", file.getPath());
return false;
}
return true;
}
};
Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE);
ZipOutputStream out = new ZipOutputStream(mOut);
out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED);
while (it.hasNext()) {
File current = it.next();
FileInputStream in = new FileInputStream(current);
ZipEntry zEntry = new ZipEntry(current.getPath().replace(mDirectory.getPath(), "").substring(1));
if (noCompress) {
zEntry.setSize(in.getChannel().size());
zEntry.setCompressedSize(in.getChannel().size());
zEntry.setCrc(getCRC32(current));
}
out.putNextEntry(zEntry);
Logger.verbose("Adding file %s", current.getPath());
int n;
while ((n = in.read(mBuffer)) != -1) {
out.write(mBuffer, 0, n);
}
in.close();
out.closeEntry();
}
out.close();
Logger.debug("Done with ZPAK creation.");
}
| public void create(boolean noCompress) throws IOException {
Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(), !noCompress);
IOFileFilter filter = new IOFileFilter() {
public boolean accept(File file) {
if (file.getName().startsWith(".")) {
Logger.debug("Skipping file %s", file.getPath());
return false;
}
return true;
}
public boolean accept(File file, String s) {
if (s.startsWith(".")) {
Logger.debug("Skipping file %s", file.getPath());
return false;
}
return true;
}
};
Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE);
ZipOutputStream out = new ZipOutputStream(mOut);
out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED);
while (it.hasNext()) {
File current = it.next();
FileInputStream in = new FileInputStream(current);
ZipEntry zEntry = new ZipEntry(current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\","/"));
if (noCompress) {
zEntry.setSize(in.getChannel().size());
zEntry.setCompressedSize(in.getChannel().size());
zEntry.setCrc(getCRC32(current));
}
out.putNextEntry(zEntry);
Logger.verbose("Adding file %s", current.getPath());
int n;
while ((n = in.read(mBuffer)) != -1) {
out.write(mBuffer, 0, n);
}
in.close();
out.closeEntry();
}
out.close();
Logger.debug("Done with ZPAK creation.");
}
|
diff --git a/src/com/android/contacts/ViewContactActivity.java b/src/com/android/contacts/ViewContactActivity.java
index 3d5ac859c..e6dd623e9 100644
--- a/src/com/android/contacts/ViewContactActivity.java
+++ b/src/com/android/contacts/ViewContactActivity.java
@@ -1,1248 +1,1247 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts;
import com.android.contacts.Collapser.Collapsible;
import com.android.contacts.model.ContactsSource;
import com.android.contacts.model.Sources;
import com.android.contacts.model.ContactsSource.DataKind;
import com.android.contacts.ui.EditContactActivity;
import com.android.contacts.util.Constants;
import com.android.contacts.util.DataStatus;
import com.android.contacts.util.NotifyingAsyncQueryHandler;
import com.android.internal.telephony.ITelephony;
import com.android.internal.widget.ContactHeaderWidget;
import com.google.android.collect.Lists;
import com.google.android.collect.Maps;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Entity;
import android.content.EntityIterator;
import android.content.Intent;
import android.content.Entity.NamedContentValues;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.AggregationExceptions;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.StatusUpdates;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
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.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Displays the details of a specific contact.
*/
public class ViewContactActivity extends Activity
implements View.OnCreateContextMenuListener, DialogInterface.OnClickListener,
AdapterView.OnItemClickListener, NotifyingAsyncQueryHandler.AsyncQueryListener {
private static final String TAG = "ViewContact";
private static final boolean SHOW_SEPARATORS = false;
private static final int DIALOG_CONFIRM_DELETE = 1;
private static final int DIALOG_CONFIRM_READONLY_DELETE = 2;
private static final int DIALOG_CONFIRM_MULTIPLE_DELETE = 3;
private static final int DIALOG_CONFIRM_READONLY_HIDE = 4;
private static final int REQUEST_JOIN_CONTACT = 1;
private static final int REQUEST_EDIT_CONTACT = 2;
public static final int MENU_ITEM_MAKE_DEFAULT = 3;
protected Uri mLookupUri;
private ContentResolver mResolver;
private ViewAdapter mAdapter;
private int mNumPhoneNumbers = 0;
/**
* A list of distinct contact IDs included in the current contact.
*/
private ArrayList<Long> mRawContactIds = new ArrayList<Long>();
/* package */ ArrayList<ViewEntry> mPhoneEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mSmsEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mEmailEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mPostalEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mImEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mOrganizationEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mGroupEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ViewEntry> mOtherEntries = new ArrayList<ViewEntry>();
/* package */ ArrayList<ArrayList<ViewEntry>> mSections = new ArrayList<ArrayList<ViewEntry>>();
private Cursor mCursor;
protected ContactHeaderWidget mContactHeaderWidget;
private NotifyingAsyncQueryHandler mHandler;
protected LayoutInflater mInflater;
protected int mReadOnlySourcesCnt;
protected int mWritableSourcesCnt;
protected ArrayList<Long> mWritableRawContactIds = new ArrayList<Long>();
private static final int TOKEN_ENTITIES = 0;
private static final int TOKEN_STATUSES = 1;
private boolean mHasEntities = false;
private boolean mHasStatuses = false;
private ArrayList<Entity> mEntities = Lists.newArrayList();
private HashMap<Long, DataStatus> mStatuses = Maps.newHashMap();
private ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
if (mCursor != null && !mCursor.isClosed()) {
startEntityQuery();
}
}
};
public void onClick(DialogInterface dialog, int which) {
closeCursor();
getContentResolver().delete(mLookupUri, null, null);
finish();
}
private FrameLayout mTabContentLayout;
private ListView mListView;
private boolean mShowSmsLinksForAllPhones;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
final Intent intent = getIntent();
Uri data = intent.getData();
String authority = data.getAuthority();
if (ContactsContract.AUTHORITY.equals(authority)) {
mLookupUri = data;
} else if (android.provider.Contacts.AUTHORITY.equals(authority)) {
final long rawContactId = ContentUris.parseId(data);
mLookupUri = RawContacts.getContactLookupUri(getContentResolver(),
ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
}
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.contact_card_layout);
mContactHeaderWidget = (ContactHeaderWidget) findViewById(R.id.contact_header_widget);
mContactHeaderWidget.showStar(true);
mContactHeaderWidget.setExcludeMimes(new String[] {
Contacts.CONTENT_ITEM_TYPE
});
mHandler = new NotifyingAsyncQueryHandler(this, this);
mListView = new ListView(this);
mListView.setOnCreateContextMenuListener(this);
mListView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_OVERLAY);
mListView.setOnItemClickListener(this);
mTabContentLayout = (FrameLayout) findViewById(android.R.id.tabcontent);
mTabContentLayout.addView(mListView);
mResolver = getContentResolver();
// Build the list of sections. The order they're added to mSections dictates the
// order they are displayed in the list.
mSections.add(mPhoneEntries);
mSections.add(mSmsEntries);
mSections.add(mEmailEntries);
mSections.add(mImEntries);
mSections.add(mPostalEntries);
mSections.add(mOrganizationEntries);
mSections.add(mGroupEntries);
mSections.add(mOtherEntries);
//TODO Read this value from a preference
mShowSmsLinksForAllPhones = true;
}
@Override
protected void onResume() {
super.onResume();
startEntityQuery();
}
@Override
protected void onPause() {
super.onPause();
closeCursor();
}
@Override
protected void onDestroy() {
super.onDestroy();
closeCursor();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CONFIRM_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.deleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_READONLY_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.readOnlyContactDeleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_MULTIPLE_DELETE:
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.multipleContactDeleteConfirmation)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, this)
.setCancelable(false)
.create();
case DIALOG_CONFIRM_READONLY_HIDE: {
return new AlertDialog.Builder(this)
.setTitle(R.string.deleteConfirmation_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.readOnlyContactWarning)
.setPositiveButton(android.R.string.ok, this)
.create();
}
}
return null;
}
// QUERY CODE //
/** {@inheritDoc} */
public void onQueryEntitiesComplete(int token, Object cookie, EntityIterator iterator) {
try {
// Read incoming entities and consider binding
readEntities(iterator);
considerBindData();
} finally {
if (iterator != null) {
iterator.close();
}
}
}
/** {@inheritDoc} */
public void onQueryComplete(int token, Object cookie, Cursor cursor) {
try {
// Read available social rows and consider binding
readStatuses(cursor);
considerBindData();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private long getRefreshedContactId() {
Uri freshContactUri = Contacts.lookupContact(getContentResolver(), mLookupUri);
if (freshContactUri != null) {
return ContentUris.parseId(freshContactUri);
}
return -1;
}
/**
* Read from the given {@link EntityIterator} to build internal set of
* {@link #mEntities} for data display.
*/
private synchronized void readEntities(EntityIterator iterator) {
mEntities.clear();
try {
while (iterator.hasNext()) {
mEntities.add(iterator.next());
}
mHasEntities = true;
} catch (RemoteException e) {
Log.w(TAG, "Problem reading contact data: " + e.toString());
}
}
/**
* Read from the given {@link Cursor} and build a set of {@link DataStatus}
* objects to match any valid statuses found.
*/
private synchronized void readStatuses(Cursor cursor) {
mStatuses.clear();
// Walk found statuses, creating internal row for each
while (cursor.moveToNext()) {
final DataStatus status = new DataStatus(cursor);
final long dataId = cursor.getLong(StatusQuery._ID);
mStatuses.put(dataId, status);
}
mHasStatuses = true;
}
private synchronized void startEntityQuery() {
closeCursor();
Uri uri = null;
if (mLookupUri != null) {
mLookupUri = Contacts.getLookupUri(getContentResolver(), mLookupUri);
if (mLookupUri != null) {
uri = Contacts.lookupContact(getContentResolver(), mLookupUri);
}
}
if (uri == null) {
// TODO either figure out a way to prevent a flash of black background or
// use some other UI than a toast
Toast.makeText(this, R.string.invalidContactMessage, Toast.LENGTH_SHORT).show();
Log.e(TAG, "invalid contact uri: " + mLookupUri);
finish();
return;
}
final Uri dataUri = Uri.withAppendedPath(uri, Contacts.Data.CONTENT_DIRECTORY);
// Keep stub cursor open on side to watch for change events
mCursor = mResolver.query(dataUri,
new String[] {Contacts.DISPLAY_NAME}, null, null, null);
mCursor.registerContentObserver(mObserver);
final long contactId = ContentUris.parseId(uri);
// Clear flags and start queries to data and status
mHasEntities = false;
mHasStatuses = false;
mHandler.startQueryEntities(TOKEN_ENTITIES, null, RawContacts.CONTENT_URI,
RawContacts.CONTACT_ID + "=" + contactId, null, null);
mHandler.startQuery(TOKEN_STATUSES, null, dataUri, StatusQuery.PROJECTION,
StatusUpdates.PRESENCE + " IS NOT NULL OR " + StatusUpdates.STATUS
+ " IS NOT NULL", null, null);
mContactHeaderWidget.bindFromContactLookupUri(mLookupUri);
}
private void closeCursor() {
if (mCursor != null) {
mCursor.unregisterContentObserver(mObserver);
mCursor.close();
mCursor = null;
}
}
/**
* Consider binding views after any of several background queries has
* completed. We check internal flags and only bind when all data has
* arrived.
*/
private void considerBindData() {
if (mHasEntities && mHasStatuses) {
bindData();
}
}
private void bindData() {
// Build up the contact entries
buildEntries();
// Collapse similar data items in select sections.
Collapser.collapseList(mPhoneEntries);
Collapser.collapseList(mSmsEntries);
Collapser.collapseList(mEmailEntries);
Collapser.collapseList(mPostalEntries);
Collapser.collapseList(mImEntries);
if (mAdapter == null) {
mAdapter = new ViewAdapter(this, mSections);
mListView.setAdapter(mAdapter);
} else {
mAdapter.setSections(mSections, SHOW_SEPARATORS);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// Only allow edit when we have at least one raw_contact id
final boolean hasRawContact = (mRawContactIds.size() > 0);
menu.findItem(R.id.menu_edit).setEnabled(hasRawContact);
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return;
}
// This can be null sometimes, don't crash...
if (info == null) {
Log.e(TAG, "bad menuInfo");
return;
}
ViewEntry entry = ContactEntryAdapter.getEntry(mSections, info.position, SHOW_SEPARATORS);
menu.setHeaderTitle(R.string.contactOptionsTitle);
if (entry.mimetype.equals(CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_call).setIntent(entry.intent);
menu.add(0, 0, 0, R.string.menu_sendSMS).setIntent(entry.secondaryIntent);
if (!entry.isPrimary) {
menu.add(0, MENU_ITEM_MAKE_DEFAULT, 0, R.string.menu_makeDefaultNumber);
}
} else if (entry.mimetype.equals(CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_sendEmail).setIntent(entry.intent);
if (!entry.isPrimary) {
menu.add(0, MENU_ITEM_MAKE_DEFAULT, 0, R.string.menu_makeDefaultEmail);
}
} else if (entry.mimetype.equals(CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)) {
menu.add(0, 0, 0, R.string.menu_viewAddress).setIntent(entry.intent);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit: {
Long rawContactIdToEdit = null;
if (mRawContactIds.size() > 0) {
rawContactIdToEdit = mRawContactIds.get(0);
} else {
// There is no rawContact to edit.
break;
}
Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI,
rawContactIdToEdit);
startActivityForResult(new Intent(Intent.ACTION_EDIT, rawContactUri),
REQUEST_EDIT_CONTACT);
break;
}
case R.id.menu_delete: {
// Get confirmation
if (mReadOnlySourcesCnt > 0 & mWritableSourcesCnt > 0) {
showDialog(DIALOG_CONFIRM_READONLY_DELETE);
} else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) {
showDialog(DIALOG_CONFIRM_READONLY_HIDE);
} else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) {
showDialog(DIALOG_CONFIRM_MULTIPLE_DELETE);
} else {
showDialog(DIALOG_CONFIRM_DELETE);
}
return true;
}
case R.id.menu_join: {
showJoinAggregateActivity();
return true;
}
case R.id.menu_options: {
showOptionsActivity();
return true;
}
case R.id.menu_share: {
// TODO: Keep around actual LOOKUP_KEY, or formalize method of extracting
final String lookupKey = mLookupUri.getPathSegments().get(2);
final Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(Contacts.CONTENT_VCARD_TYPE);
intent.putExtra(Intent.EXTRA_STREAM, shareUri);
// Launch chooser to share contact via
final CharSequence chooseTitle = getText(R.string.share_via);
final Intent chooseIntent = Intent.createChooser(intent, chooseTitle);
try {
startActivity(chooseIntent);
} catch (ActivityNotFoundException ex) {
Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show();
}
return true;
}
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ITEM_MAKE_DEFAULT: {
if (makeItemDefault(item)) {
return true;
}
break;
}
}
return super.onContextItemSelected(item);
}
private boolean makeItemDefault(MenuItem item) {
ViewEntry entry = getViewEntryForMenuItem(item);
if (entry == null) {
return false;
}
// Update the primary values in the data record.
ContentValues values = new ContentValues(1);
values.put(Data.IS_SUPER_PRIMARY, 1);
getContentResolver().update(ContentUris.withAppendedId(Data.CONTENT_URI, entry.id),
values, null, null);
startEntityQuery();
return true;
}
/**
* Shows a list of aggregates that can be joined into the currently viewed aggregate.
*/
public void showJoinAggregateActivity() {
long freshId = getRefreshedContactId();
if (freshId > 0) {
String displayName = null;
if (mCursor.moveToFirst()) {
displayName = mCursor.getString(0);
}
Intent intent = new Intent(ContactsListActivity.JOIN_AGGREGATE);
intent.putExtra(ContactsListActivity.EXTRA_AGGREGATE_ID, freshId);
if (displayName != null) {
intent.putExtra(ContactsListActivity.EXTRA_AGGREGATE_NAME, displayName);
}
startActivityForResult(intent, REQUEST_JOIN_CONTACT);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_JOIN_CONTACT) {
if (resultCode == RESULT_OK && intent != null) {
final long contactId = ContentUris.parseId(intent.getData());
joinAggregate(contactId);
}
} else if (requestCode == REQUEST_EDIT_CONTACT) {
if (resultCode == EditContactActivity.RESULT_CLOSE_VIEW_ACTIVITY) {
finish();
} else if (resultCode == Activity.RESULT_OK) {
mLookupUri = intent.getData();
if (mLookupUri == null) {
finish();
}
}
}
}
private void splitContact(long rawContactId) {
setAggregationException(rawContactId, AggregationExceptions.TYPE_KEEP_SEPARATE);
// The split operation may have removed the original aggregate contact, so we need
// to requery everything
Toast.makeText(this, R.string.contactsSplitMessage, Toast.LENGTH_LONG).show();
startEntityQuery();
}
private void joinAggregate(final long contactId) {
Cursor c = mResolver.query(RawContacts.CONTENT_URI, new String[] {RawContacts._ID},
RawContacts.CONTACT_ID + "=" + contactId, null, null);
try {
while(c.moveToNext()) {
long rawContactId = c.getLong(0);
setAggregationException(rawContactId, AggregationExceptions.TYPE_KEEP_TOGETHER);
}
} finally {
c.close();
}
Toast.makeText(this, R.string.contactsJoinedMessage, Toast.LENGTH_LONG).show();
startEntityQuery();
}
/**
* Given a contact ID sets an aggregation exception to either join the contact with the
* current aggregate or split off.
*/
protected void setAggregationException(long rawContactId, int exceptionType) {
ContentValues values = new ContentValues(3);
for (long aRawContactId : mRawContactIds) {
if (aRawContactId != rawContactId) {
values.put(AggregationExceptions.RAW_CONTACT_ID1, aRawContactId);
values.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId);
values.put(AggregationExceptions.TYPE, exceptionType);
mResolver.update(AggregationExceptions.CONTENT_URI, values, null, null);
}
}
}
private void showOptionsActivity() {
final Intent intent = new Intent(this, ContactOptionsActivity.class);
intent.setData(mLookupUri);
startActivity(intent);
}
private ViewEntry getViewEntryForMenuItem(MenuItem item) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return null;
}
return ContactEntryAdapter.getEntry(mSections, info.position, SHOW_SEPARATORS);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_CALL: {
try {
ITelephony phone = ITelephony.Stub.asInterface(
ServiceManager.checkService("phone"));
if (phone != null && !phone.isIdle()) {
// Skip out and let the key be handled at a higher level
break;
}
} catch (RemoteException re) {
// Fall through and try to call the contact
}
int index = mListView.getSelectedItemPosition();
if (index != -1) {
ViewEntry entry = ViewAdapter.getEntry(mSections, index, SHOW_SEPARATORS);
if (entry.intent.getAction() == Intent.ACTION_CALL_PRIVILEGED) {
startActivity(entry.intent);
}
} else if (mNumPhoneNumbers != 0) {
// There isn't anything selected, call the default number
long freshContactId = getRefreshedContactId();
if (freshContactId > 0) {
Uri hardContacUri = ContentUris.withAppendedId(
Contacts.CONTENT_URI, freshContactId);
Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, hardContacUri);
startActivity(intent);
}
}
return true;
}
case KeyEvent.KEYCODE_DEL: {
if (mReadOnlySourcesCnt > 0 & mWritableSourcesCnt > 0) {
showDialog(DIALOG_CONFIRM_READONLY_DELETE);
} else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) {
showDialog(DIALOG_CONFIRM_READONLY_HIDE);
} else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) {
showDialog(DIALOG_CONFIRM_MULTIPLE_DELETE);
} else {
showDialog(DIALOG_CONFIRM_DELETE);
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView parent, View v, int position, long id) {
ViewEntry entry = ViewAdapter.getEntry(mSections, position, SHOW_SEPARATORS);
if (entry != null) {
Intent intent = entry.intent;
if (intent != null) {
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity found for intent: " + intent);
signalError();
}
} else {
signalError();
}
} else {
signalError();
}
}
/**
* Signal an error to the user via a beep, or some other method.
*/
private void signalError() {
//TODO: implement this when we have the sonification APIs
}
/**
* Build up the entries to display on the screen.
*
* @param personCursor the URI for the contact being displayed
*/
private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
- entry.data = PhoneNumberUtils.stripSeparators(entry.data);
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE
|| mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType)
|| Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) {
// Build organization and note entries
entry.uri = null;
mOrganizationEntries.add(entry);
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
static String buildActionString(DataKind kind, ContentValues values, boolean lowerCase,
Context context) {
if (kind.actionHeader == null) {
return null;
}
CharSequence actionHeader = kind.actionHeader.inflateUsing(context, values);
if (actionHeader == null) {
return null;
}
return lowerCase ? actionHeader.toString().toLowerCase() : actionHeader.toString();
}
static String buildDataString(DataKind kind, ContentValues values, Context context) {
if (kind.actionBody == null) {
return null;
}
CharSequence actionBody = kind.actionBody.inflateUsing(context, values);
return actionBody == null ? null : actionBody.toString();
}
/**
* A basic structure with the data for a contact entry in the list.
*/
static class ViewEntry extends ContactEntryAdapter.Entry implements Collapsible<ViewEntry> {
public Context context = null;
public String resPackageName = null;
public int actionIcon = -1;
public boolean isPrimary = false;
public int secondaryActionIcon = -1;
public Intent intent;
public Intent secondaryIntent = null;
public int maxLabelLines = 1;
public ArrayList<Long> ids = new ArrayList<Long>();
public int collapseCount = 0;
public int presence = -1;
public int presenceIcon = -1;
public CharSequence footerLine = null;
private ViewEntry() {
}
/**
* Build new {@link ViewEntry} and populate from the given values.
*/
public static ViewEntry fromValues(Context context, String mimeType, DataKind kind,
long rawContactId, long dataId, ContentValues values) {
final ViewEntry entry = new ViewEntry();
entry.context = context;
entry.contactId = rawContactId;
entry.id = dataId;
entry.uri = ContentUris.withAppendedId(Data.CONTENT_URI, entry.id);
entry.mimetype = mimeType;
entry.label = buildActionString(kind, values, false, context);
entry.data = buildDataString(kind, values, context);
if (kind.typeColumn != null && values.containsKey(kind.typeColumn)) {
entry.type = values.getAsInteger(kind.typeColumn);
}
if (kind.iconRes > 0) {
entry.resPackageName = kind.resPackageName;
entry.actionIcon = kind.iconRes;
}
return entry;
}
/**
* Apply given {@link DataStatus} values over this {@link ViewEntry}
*
* @param fillData When true, the given status replaces {@link #data}
* and {@link #footerLine}. Otherwise only {@link #presence}
* is updated.
*/
public ViewEntry applyStatus(DataStatus status, boolean fillData) {
presence = status.getPresence();
presenceIcon = (presence == -1) ? -1 :
StatusUpdates.getPresenceIconResourceId(this.presence);
if (fillData && status.isValid()) {
this.data = status.getStatus().toString();
this.footerLine = status.getTimestampLabel(context);
}
return this;
}
public boolean collapseWith(ViewEntry entry) {
// assert equal collapse keys
if (!shouldCollapseWith(entry)) {
return false;
}
// Choose the label associated with the highest type precedence.
if (TypePrecedence.getTypePrecedence(mimetype, type)
> TypePrecedence.getTypePrecedence(entry.mimetype, entry.type)) {
type = entry.type;
label = entry.label;
}
// Choose the max of the maxLines and maxLabelLines values.
maxLines = Math.max(maxLines, entry.maxLines);
maxLabelLines = Math.max(maxLabelLines, entry.maxLabelLines);
// Choose the presence with the highest precedence.
if (StatusUpdates.getPresencePrecedence(presence)
< StatusUpdates.getPresencePrecedence(entry.presence)) {
presence = entry.presence;
}
// If any of the collapsed entries are primary make the whole thing primary.
isPrimary = entry.isPrimary ? true : isPrimary;
// uri, and contactdId, shouldn't make a difference. Just keep the original.
// Keep track of all the ids that have been collapsed with this one.
ids.add(entry.id);
collapseCount++;
return true;
}
public boolean shouldCollapseWith(ViewEntry entry) {
if (entry == null) {
return false;
}
if (Phone.CONTENT_ITEM_TYPE.equals(mimetype)
&& Phone.CONTENT_ITEM_TYPE.equals(entry.mimetype)) {
if (!PhoneNumberUtils.compare(this.context, data, entry.data)) {
return false;
}
} else {
if (!equals(data, entry.data)) {
return false;
}
}
if (!equals(mimetype, entry.mimetype)
|| !intentCollapsible(intent, entry.intent)
|| !intentCollapsible(secondaryIntent, entry.secondaryIntent)
|| actionIcon != entry.actionIcon) {
return false;
}
return true;
}
private boolean equals(Object a, Object b) {
return a==b || (a != null && a.equals(b));
}
private boolean intentCollapsible(Intent a, Intent b) {
if (a == b) {
return true;
} else if ((a != null && b != null) && equals(a.getAction(), b.getAction())) {
return true;
}
return false;
}
}
/** Cache of the children views of a row */
static class ViewCache {
public TextView label;
public TextView data;
public TextView footer;
public ImageView actionIcon;
public ImageView presenceIcon;
public ImageView primaryIcon;
public ImageView secondaryActionButton;
public View secondaryActionDivider;
// Need to keep track of this too
ViewEntry entry;
}
private final class ViewAdapter extends ContactEntryAdapter<ViewEntry>
implements View.OnClickListener {
ViewAdapter(Context context, ArrayList<ArrayList<ViewEntry>> sections) {
super(context, sections, SHOW_SEPARATORS);
}
public void onClick(View v) {
Intent intent = (Intent) v.getTag();
startActivity(intent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewEntry entry = getEntry(mSections, position, false);
View v;
ViewCache views;
// Check to see if we can reuse convertView
if (convertView != null) {
v = convertView;
views = (ViewCache) v.getTag();
} else {
// Create a new view if needed
v = mInflater.inflate(R.layout.list_item_text_icons, parent, false);
// Cache the children
views = new ViewCache();
views.label = (TextView) v.findViewById(android.R.id.text1);
views.data = (TextView) v.findViewById(android.R.id.text2);
views.footer = (TextView) v.findViewById(R.id.footer);
views.actionIcon = (ImageView) v.findViewById(R.id.action_icon);
views.primaryIcon = (ImageView) v.findViewById(R.id.primary_icon);
views.presenceIcon = (ImageView) v.findViewById(R.id.presence_icon);
views.secondaryActionButton = (ImageView) v.findViewById(
R.id.secondary_action_button);
views.secondaryActionButton.setOnClickListener(this);
views.secondaryActionDivider = v.findViewById(R.id.divider);
v.setTag(views);
}
// Update the entry in the view cache
views.entry = entry;
// Bind the data to the view
bindView(v, entry);
return v;
}
@Override
protected View newView(int position, ViewGroup parent) {
// getView() handles this
throw new UnsupportedOperationException();
}
@Override
protected void bindView(View view, ViewEntry entry) {
final Resources resources = mContext.getResources();
ViewCache views = (ViewCache) view.getTag();
// Set the label
TextView label = views.label;
setMaxLines(label, entry.maxLabelLines);
label.setText(entry.label);
// Set the data
TextView data = views.data;
if (data != null) {
if (entry.mimetype.equals(Phone.CONTENT_ITEM_TYPE)
|| entry.mimetype.equals(Constants.MIME_SMS_ADDRESS)) {
data.setText(PhoneNumberUtils.formatNumber(entry.data));
} else {
data.setText(entry.data);
}
setMaxLines(data, entry.maxLines);
}
// Set the footer
if (!TextUtils.isEmpty(entry.footerLine)) {
views.footer.setText(entry.footerLine);
views.footer.setVisibility(View.VISIBLE);
} else {
views.footer.setVisibility(View.GONE);
}
// Set the primary icon
views.primaryIcon.setVisibility(entry.isPrimary ? View.VISIBLE : View.GONE);
// Set the action icon
ImageView action = views.actionIcon;
if (entry.actionIcon != -1) {
Drawable actionIcon;
if (entry.resPackageName != null) {
// Load external resources through PackageManager
actionIcon = mContext.getPackageManager().getDrawable(entry.resPackageName,
entry.actionIcon, null);
} else {
actionIcon = resources.getDrawable(entry.actionIcon);
}
action.setImageDrawable(actionIcon);
action.setVisibility(View.VISIBLE);
} else {
// Things should still line up as if there was an icon, so make it invisible
action.setVisibility(View.INVISIBLE);
}
// Set the presence icon
Drawable presenceIcon = null;
if (entry.presenceIcon != -1) {
presenceIcon = resources.getDrawable(entry.presenceIcon);
} else if (entry.presence != -1) {
presenceIcon = resources.getDrawable(
StatusUpdates.getPresenceIconResourceId(entry.presence));
}
ImageView presenceIconView = views.presenceIcon;
if (presenceIcon != null) {
presenceIconView.setImageDrawable(presenceIcon);
presenceIconView.setVisibility(View.VISIBLE);
} else {
presenceIconView.setVisibility(View.GONE);
}
// Set the secondary action button
ImageView secondaryActionView = views.secondaryActionButton;
Drawable secondaryActionIcon = null;
if (entry.secondaryActionIcon != -1) {
secondaryActionIcon = resources.getDrawable(entry.secondaryActionIcon);
}
if (entry.secondaryIntent != null && secondaryActionIcon != null) {
secondaryActionView.setImageDrawable(secondaryActionIcon);
secondaryActionView.setTag(entry.secondaryIntent);
secondaryActionView.setVisibility(View.VISIBLE);
views.secondaryActionDivider.setVisibility(View.VISIBLE);
} else {
secondaryActionView.setVisibility(View.GONE);
views.secondaryActionDivider.setVisibility(View.GONE);
}
}
private void setMaxLines(TextView textView, int maxLines) {
if (maxLines == 1) {
textView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END);
} else {
textView.setSingleLine(false);
textView.setMaxLines(maxLines);
textView.setEllipsize(null);
}
}
}
private interface StatusQuery {
final String[] PROJECTION = new String[] {
Data._ID,
Data.STATUS,
Data.STATUS_RES_PACKAGE,
Data.STATUS_ICON,
Data.STATUS_LABEL,
Data.STATUS_TIMESTAMP,
Data.PRESENCE,
};
final int _ID = 0;
}
}
| true | true | private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
entry.data = PhoneNumberUtils.stripSeparators(entry.data);
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE
|| mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType)
|| Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) {
// Build organization and note entries
entry.uri = null;
mOrganizationEntries.add(entry);
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
| private final void buildEntries() {
// Clear out the old entries
final int numSections = mSections.size();
for (int i = 0; i < numSections; i++) {
mSections.get(i).clear();
}
mRawContactIds.clear();
mReadOnlySourcesCnt = 0;
mWritableSourcesCnt = 0;
mWritableRawContactIds.clear();
final Context context = this;
final Sources sources = Sources.getInstance(context);
// Build up method entries
if (mLookupUri != null) {
for (Entity entity: mEntities) {
final ContentValues entValues = entity.getEntityValues();
final String accountType = entValues.getAsString(RawContacts.ACCOUNT_TYPE);
final long rawContactId = entValues.getAsLong(RawContacts._ID);
if (!mRawContactIds.contains(rawContactId)) {
mRawContactIds.add(rawContactId);
}
ContactsSource contactsSource = sources.getInflatedSource(accountType,
ContactsSource.LEVEL_SUMMARY);
if (contactsSource != null && contactsSource.readOnly) {
mReadOnlySourcesCnt += 1;
} else {
mWritableSourcesCnt += 1;
mWritableRawContactIds.add(rawContactId);
}
for (NamedContentValues subValue : entity.getSubValues()) {
final ContentValues entryValues = subValue.values;
entryValues.put(Data.RAW_CONTACT_ID, rawContactId);
final long dataId = entryValues.getAsLong(Data._ID);
final String mimeType = entryValues.getAsString(Data.MIMETYPE);
if (mimeType == null) continue;
final DataKind kind = sources.getKindOrFallback(accountType, mimeType, this,
ContactsSource.LEVEL_MIMETYPES);
if (kind == null) continue;
final ViewEntry entry = ViewEntry.fromValues(context, mimeType, kind,
rawContactId, dataId, entryValues);
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = entryValues.getAsInteger(
Data.IS_SUPER_PRIMARY) != 0;
if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build phone entries
mNumPhoneNumbers++;
entry.intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
Uri.fromParts(Constants.SCHEME_TEL, entry.data, null));
entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mPhoneEntries.add(entry);
if (entry.type == CommonDataKinds.Phone.TYPE_MOBILE
|| mShowSmsLinksForAllPhones) {
// Add an SMS entry
if (kind.iconAltRes > 0) {
entry.secondaryActionIcon = kind.iconAltRes;
}
}
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
mEmailEntries.add(entry);
// When Email rows have status, create additional Im row
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
final String imMime = Im.CONTENT_ITEM_TYPE;
final DataKind imKind = sources.getKindOrFallback(accountType,
imMime, this, ContactsSource.LEVEL_MIMETYPES);
final ViewEntry imEntry = ViewEntry.fromValues(context,
imMime, imKind, rawContactId, dataId, entryValues);
imEntry.intent = ContactsUtils.buildImIntent(entryValues);
imEntry.applyStatus(status, false);
mImEntries.add(imEntry);
}
} else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build postal entries
entry.maxLines = 4;
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
mPostalEntries.add(entry);
} else if (Im.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build IM entries
entry.intent = ContactsUtils.buildImIntent(entryValues);
if (TextUtils.isEmpty(entry.label)) {
entry.label = getString(R.string.chat).toLowerCase();
}
// Apply presence and status details when available
final DataStatus status = mStatuses.get(entry.id);
if (status != null) {
entry.applyStatus(status, false);
}
mImEntries.add(entry);
} else if ((Organization.CONTENT_ITEM_TYPE.equals(mimeType)
|| Nickname.CONTENT_ITEM_TYPE.equals(mimeType)) && hasData) {
// Build organization and note entries
entry.uri = null;
mOrganizationEntries.add(entry);
} else if (Note.CONTENT_ITEM_TYPE.equals(mimeType) && hasData) {
// Build note entries
entry.uri = null;
entry.maxLines = 10;
mOtherEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW, entry.uri);
// Use social summary when requested by external source
final DataStatus status = mStatuses.get(entry.id);
final boolean hasSocial = kind.actionBodySocial && status != null;
if (hasSocial) {
entry.applyStatus(status, true);
}
if (hasSocial || hasData) {
mOtherEntries.add(entry);
}
}
}
}
}
}
|
diff --git a/processor/src/org/gwtmpv/processor/EventGenerator.java b/processor/src/org/gwtmpv/processor/EventGenerator.java
index d24eefe..95d586a 100644
--- a/processor/src/org/gwtmpv/processor/EventGenerator.java
+++ b/processor/src/org/gwtmpv/processor/EventGenerator.java
@@ -1,105 +1,105 @@
package org.gwtmpv.processor;
import java.util.List;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import joist.sourcegen.GClass;
import joist.sourcegen.GMethod;
import org.exigencecorp.aptutil.GenericSuffix;
import org.exigencecorp.aptutil.Prop;
import org.exigencecorp.aptutil.PropUtil;
import org.exigencecorp.aptutil.Util;
import org.gwtmpv.GenEvent;
public class EventGenerator {
private final ProcessingEnvironment env;
private final TypeElement element;
private final GClass eventClass;
private final GenEvent eventSpec;
private final String handlerName;
private final GenericSuffix generics;
private final List<Prop> properties;
public EventGenerator(ProcessingEnvironment env, TypeElement element, GenEvent eventSpec) throws InvalidTypeElementException {
if (!element.toString().endsWith("EventSpec")) {
- env.getMessager().printMessage(Kind.ERROR, "GenEvent target must end with a suffix EventSpec");
+ env.getMessager().printMessage(Kind.ERROR, "GenEvent target must end with a suffix EventSpec", element);
throw new InvalidTypeElementException();
}
this.env = env;
this.element = element;
this.generics = new GenericSuffix(element);
this.eventClass = new GClass(element.toString().replaceAll("Spec$", "") + generics.varsWithBounds);
this.eventSpec = eventSpec;
this.handlerName = element.getSimpleName().toString().replaceAll("EventSpec$", "Handler");
this.eventClass.baseClassName("com.google.gwt.event.shared.GwtEvent<{}.{}>", eventClass.getSimpleClassNameWithoutGeneric(), handlerName
+ generics.vars);
properties = PropUtil.getProperties(element, "p");
}
public void generate() {
generateInnerInterface();
generateType();
generateDispatch();
generateFields();
PropUtil.addEquals(eventClass, generics, properties);
PropUtil.addHashCode(eventClass, properties);
PropUtil.addToString(eventClass, properties);
PropUtil.addGenerated(eventClass, DispatchGenerator.class);
Util.saveCode(env, eventClass);
}
private void generateInnerInterface() {
GClass inner = eventClass.getInnerClass(handlerName + generics.varsWithBounds);
inner.setInterface().baseClassName("com.google.gwt.event.shared.EventHandler");
inner.getMethod(getMethodName()).argument(eventClass.getFullClassNameWithoutGeneric() + generics.vars, "event");
}
private void generateType() {
eventClass.getField("TYPE").setStatic().setPublic().setFinal().type("Type<{}>", handlerName + generics.varsAsStatic).initialValue(
"new Type<{}>()",
handlerName + generics.varsAsStatic);
eventClass.getMethod("getType").setStatic().returnType("Type<{}>", handlerName + generics.varsAsStatic).body.append("return TYPE;");
GMethod associatedType = eventClass.getMethod("getAssociatedType");
associatedType.returnType("Type<{}>", handlerName + generics.vars).addAnnotation("@Override");
if (generics.vars.length() > 0) {
associatedType.addAnnotation("@SuppressWarnings(\"all\")");
associatedType.body.line("return (Type) TYPE;");
} else {
associatedType.body.line("return TYPE;");
}
}
private void generateDispatch() {
eventClass.getMethod("dispatch").setProtected().addAnnotation("@Override").argument(handlerName + generics.vars, "handler").body.line(
"handler.{}(this);",
getMethodName());
}
private void generateFields() {
GMethod cstr = eventClass.getConstructor();
for (Prop p : properties) {
eventClass.getField(p.name).type(p.type).setFinal();
eventClass.getMethod("get" + Util.upper(p.name)).returnType(p.type).body.append("return {};", p.name);
cstr.argument(p.type, p.name);
cstr.body.line("this.{} = {};", p.name, p.name);
}
}
private String getMethodName() {
if (eventSpec.methodName().length() > 0) {
return eventSpec.methodName();
} else {
return "on" + element.getSimpleName().toString().replaceAll("EventSpec$", "");
}
}
}
| true | true | public EventGenerator(ProcessingEnvironment env, TypeElement element, GenEvent eventSpec) throws InvalidTypeElementException {
if (!element.toString().endsWith("EventSpec")) {
env.getMessager().printMessage(Kind.ERROR, "GenEvent target must end with a suffix EventSpec");
throw new InvalidTypeElementException();
}
this.env = env;
this.element = element;
this.generics = new GenericSuffix(element);
this.eventClass = new GClass(element.toString().replaceAll("Spec$", "") + generics.varsWithBounds);
this.eventSpec = eventSpec;
this.handlerName = element.getSimpleName().toString().replaceAll("EventSpec$", "Handler");
this.eventClass.baseClassName("com.google.gwt.event.shared.GwtEvent<{}.{}>", eventClass.getSimpleClassNameWithoutGeneric(), handlerName
+ generics.vars);
properties = PropUtil.getProperties(element, "p");
}
| public EventGenerator(ProcessingEnvironment env, TypeElement element, GenEvent eventSpec) throws InvalidTypeElementException {
if (!element.toString().endsWith("EventSpec")) {
env.getMessager().printMessage(Kind.ERROR, "GenEvent target must end with a suffix EventSpec", element);
throw new InvalidTypeElementException();
}
this.env = env;
this.element = element;
this.generics = new GenericSuffix(element);
this.eventClass = new GClass(element.toString().replaceAll("Spec$", "") + generics.varsWithBounds);
this.eventSpec = eventSpec;
this.handlerName = element.getSimpleName().toString().replaceAll("EventSpec$", "Handler");
this.eventClass.baseClassName("com.google.gwt.event.shared.GwtEvent<{}.{}>", eventClass.getSimpleClassNameWithoutGeneric(), handlerName
+ generics.vars);
properties = PropUtil.getProperties(element, "p");
}
|
diff --git a/org.talend.libraries.sdi/src/main/java/org/talend/sdi/metadata/Catalogue.java b/org.talend.libraries.sdi/src/main/java/org/talend/sdi/metadata/Catalogue.java
index 17f306b..0f95c2b 100755
--- a/org.talend.libraries.sdi/src/main/java/org/talend/sdi/metadata/Catalogue.java
+++ b/org.talend.libraries.sdi/src/main/java/org/talend/sdi/metadata/Catalogue.java
@@ -1,150 +1,150 @@
package org.talend.sdi.metadata;
import java.io.IOException;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
/**
* Catalogue is the abstract base class for all catalogue.
*
* @author Fxp
* @version
*/
public abstract class Catalogue {
/**
* Host name or IP adresse of the catalogue
*/
public String host;
/**
* Port number
*/
public int port;
/**
* Username to log into the catalogue
*/
public String username;
/**
* Password to log into the catalogue
*/
public String password;
/**
* Username to be used if Basic Authentication is required
*/
public String baUsername;
/**
* Password to be used if Basic Authentication is required
*/
public String baPassword;
/**
* Proxy url
*/
public String proxyURL;
/**
* Proxy port
*/
public int proxyPort;
/**
* Proxy username
*/
public String proxyUsername;
/**
* Proxy password
*/
public String proxyPassword;
/**
* Class constructor.
*/
public Catalogue() {
}
/**
* Return Catalogue type
*
* @return Abstract
*
*/
public String getType() {
return "Abstract";
}
/**
* Create an http connection in order to execute a request.
* If needed, Basic Authentication and Proxy configuration are defined here.
*
* @param httpclient HTTP client which store the session info
* @param req Request
*
* @return Document returned by request (eg. xml document, html page, ...)
*
*/
public Document httpConnect (HttpClient httpclient, PostMethod req) {
Document doc = null;
Credentials creds = null;
// Basic Authentification initialisation
if (this.baUsername != null && this.baPassword != null) {
creds = new UsernamePasswordCredentials(this.baUsername, this.baPassword);
httpclient.getState().setCredentials(AuthScope.ANY, creds);
}
// Proxy initialisation
if (this.proxyURL != null) {
// TODO
}
try {
// Connect
int result = httpclient.executeMethod(req);
String redirectLocation;
Header locationHeader = req.getResponseHeader("location");
if (locationHeader != null) {
redirectLocation = locationHeader.getValue();
req.setPath(redirectLocation);
result = httpclient.executeMethod(req);
}
if (result == HttpStatus.SC_OK) {
// Convert response to xml
doc = DocumentHelper.parseText(req.getResponseBodyAsString ());
} else
- System.err.println ("org.talend.sdi.metadata.Catalogue | Bad status");
+ System.err.println ("org.talend.sdi.metadata.Catalogue | Bad status : " + result);
} catch (DocumentException e){
System.err.println("org.talend.sdi.metadata.Catalogue | Invalid XML Document '" + e.getMessage() + "'");
} catch (HttpException he) {
- System.err.println("org.talend.sdi.metadata.Catalogue | Http error connecting to '" + httpclient.toString() + "'");
+ System.err.println("org.talend.sdi.metadata.Catalogue | Http error connecting to '" + this.host+":"+this.port + "'");
System.err.println(he.getMessage());
System.exit(-4);
} catch (IOException ioe){
- System.err.println("org.talend.sdi.metadata.Catalogue | Unable to connect to '" + httpclient.toString() + "'");
+ System.err.println("org.talend.sdi.metadata.Catalogue | Unable to connect to '" + this.host+":"+this.port + "'");
System.exit(-3);
} finally {
// Release current connection to the connection pool once you are done
req.releaseConnection();
}
return doc;
}
}
| false | true | public Document httpConnect (HttpClient httpclient, PostMethod req) {
Document doc = null;
Credentials creds = null;
// Basic Authentification initialisation
if (this.baUsername != null && this.baPassword != null) {
creds = new UsernamePasswordCredentials(this.baUsername, this.baPassword);
httpclient.getState().setCredentials(AuthScope.ANY, creds);
}
// Proxy initialisation
if (this.proxyURL != null) {
// TODO
}
try {
// Connect
int result = httpclient.executeMethod(req);
String redirectLocation;
Header locationHeader = req.getResponseHeader("location");
if (locationHeader != null) {
redirectLocation = locationHeader.getValue();
req.setPath(redirectLocation);
result = httpclient.executeMethod(req);
}
if (result == HttpStatus.SC_OK) {
// Convert response to xml
doc = DocumentHelper.parseText(req.getResponseBodyAsString ());
} else
System.err.println ("org.talend.sdi.metadata.Catalogue | Bad status");
} catch (DocumentException e){
System.err.println("org.talend.sdi.metadata.Catalogue | Invalid XML Document '" + e.getMessage() + "'");
} catch (HttpException he) {
System.err.println("org.talend.sdi.metadata.Catalogue | Http error connecting to '" + httpclient.toString() + "'");
System.err.println(he.getMessage());
System.exit(-4);
} catch (IOException ioe){
System.err.println("org.talend.sdi.metadata.Catalogue | Unable to connect to '" + httpclient.toString() + "'");
System.exit(-3);
} finally {
// Release current connection to the connection pool once you are done
req.releaseConnection();
}
return doc;
}
| public Document httpConnect (HttpClient httpclient, PostMethod req) {
Document doc = null;
Credentials creds = null;
// Basic Authentification initialisation
if (this.baUsername != null && this.baPassword != null) {
creds = new UsernamePasswordCredentials(this.baUsername, this.baPassword);
httpclient.getState().setCredentials(AuthScope.ANY, creds);
}
// Proxy initialisation
if (this.proxyURL != null) {
// TODO
}
try {
// Connect
int result = httpclient.executeMethod(req);
String redirectLocation;
Header locationHeader = req.getResponseHeader("location");
if (locationHeader != null) {
redirectLocation = locationHeader.getValue();
req.setPath(redirectLocation);
result = httpclient.executeMethod(req);
}
if (result == HttpStatus.SC_OK) {
// Convert response to xml
doc = DocumentHelper.parseText(req.getResponseBodyAsString ());
} else
System.err.println ("org.talend.sdi.metadata.Catalogue | Bad status : " + result);
} catch (DocumentException e){
System.err.println("org.talend.sdi.metadata.Catalogue | Invalid XML Document '" + e.getMessage() + "'");
} catch (HttpException he) {
System.err.println("org.talend.sdi.metadata.Catalogue | Http error connecting to '" + this.host+":"+this.port + "'");
System.err.println(he.getMessage());
System.exit(-4);
} catch (IOException ioe){
System.err.println("org.talend.sdi.metadata.Catalogue | Unable to connect to '" + this.host+":"+this.port + "'");
System.exit(-3);
} finally {
// Release current connection to the connection pool once you are done
req.releaseConnection();
}
return doc;
}
|
diff --git a/src/main/java/com/mingebag/grover/falsebook/ic/datatype/string/MC002S.java b/src/main/java/com/mingebag/grover/falsebook/ic/datatype/string/MC002S.java
index 915b751..3eb0e3f 100644
--- a/src/main/java/com/mingebag/grover/falsebook/ic/datatype/string/MC002S.java
+++ b/src/main/java/com/mingebag/grover/falsebook/ic/datatype/string/MC002S.java
@@ -1,39 +1,40 @@
package com.mingebag.grover.falsebook.ic.datatype.string;
import org.bukkit.block.Sign;
import com.bukkit.gemo.FalseBook.IC.ICs.BaseChip;
import com.bukkit.gemo.FalseBook.IC.ICs.ICGroup;
import com.bukkit.gemo.FalseBook.IC.ICs.InputState;
import com.grover.mingebag.ic.BaseDataChip;
import com.grover.mingebag.ic.StringData;
public class MC002S extends BaseDataChip {
public MC002S() {
this.ICName = "STRING COMBINE";
this.ICNumber = "[MC002S]";
setICGroup(ICGroup.CUSTOM_0);
this.chipState = new BaseChip(false, true, true, "String", "String", "String");
this.chipState.setOutputs("String", "", "");
this.chipState.setLines("", "");
this.ICDescription = "This combines strings from left to right.";
}
public void Execute(Sign signBlock, InputState currentInputs, InputState previousInputs) {
String input1 = null;
String input2 = null;
String out = null;
if(currentInputs.isInputTwoHigh() && previousInputs.isInputTwoLow())
input1 = ((StringData) getDataLeft(signBlock)).getString();
+ if(currentInputs.isInputThreeHigh() && previousInputs.isInputThreeLow())
input2 = ((StringData) getDataRight(signBlock)).getString();
if(input1 != null && input2 != null) {
out = input1 + input2;
} else {
return;
}
this.outputData(new StringData(out), signBlock, 2, 2);
}
}
| true | true | public void Execute(Sign signBlock, InputState currentInputs, InputState previousInputs) {
String input1 = null;
String input2 = null;
String out = null;
if(currentInputs.isInputTwoHigh() && previousInputs.isInputTwoLow())
input1 = ((StringData) getDataLeft(signBlock)).getString();
input2 = ((StringData) getDataRight(signBlock)).getString();
if(input1 != null && input2 != null) {
out = input1 + input2;
} else {
return;
}
this.outputData(new StringData(out), signBlock, 2, 2);
}
| public void Execute(Sign signBlock, InputState currentInputs, InputState previousInputs) {
String input1 = null;
String input2 = null;
String out = null;
if(currentInputs.isInputTwoHigh() && previousInputs.isInputTwoLow())
input1 = ((StringData) getDataLeft(signBlock)).getString();
if(currentInputs.isInputThreeHigh() && previousInputs.isInputThreeLow())
input2 = ((StringData) getDataRight(signBlock)).getString();
if(input1 != null && input2 != null) {
out = input1 + input2;
} else {
return;
}
this.outputData(new StringData(out), signBlock, 2, 2);
}
|
diff --git a/shims/mapr/src/org/pentaho/hadoop/shim/mapr/HadoopShim.java b/shims/mapr/src/org/pentaho/hadoop/shim/mapr/HadoopShim.java
index f56fb48e..ccda3e92 100644
--- a/shims/mapr/src/org/pentaho/hadoop/shim/mapr/HadoopShim.java
+++ b/shims/mapr/src/org/pentaho/hadoop/shim/mapr/HadoopShim.java
@@ -1,90 +1,90 @@
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.hadoop.shim.mapr;
import java.util.List;
import org.pentaho.hadoop.shim.HadoopConfiguration;
import org.pentaho.hadoop.shim.HadoopConfigurationFileSystemManager;
import org.pentaho.hadoop.shim.api.Configuration;
import org.pentaho.hadoop.shim.common.CommonHadoopShim;
import org.pentaho.hadoop.shim.common.DistributedCacheUtilImpl;
import org.pentaho.hdfs.vfs.MapRFileProvider;
import org.pentaho.hdfs.vfs.MapRFileSystem;
public class HadoopShim extends CommonHadoopShim {
protected static final String DEFAULT_CLUSTER = "/";
protected static final String MFS_SCHEME = "maprfs://";
protected static final String[] EMPTY_CONNECTION_INFO = new String[2];
@Override
public String[] getNamenodeConnectionInfo(Configuration c) {
return EMPTY_CONNECTION_INFO;
}
@Override
public String[] getJobtrackerConnectionInfo(Configuration c) {
return EMPTY_CONNECTION_INFO;
}
@Override
public void configureConnectionInformation(String namenodeHost, String namenodePort, String jobtrackerHost,
String jobtrackerPort, Configuration conf, List<String> logMessages) throws Exception {
if (namenodeHost == null || namenodeHost.length() == 0) {
namenodeHost = DEFAULT_CLUSTER;
logMessages.add("Using MapR default cluster for filesystem");
} else if (namenodePort == null || namenodePort.trim().length() == 0) {
logMessages.add("Using MapR CLDB named cluster: " + namenodeHost
+ " for filesystem");
namenodeHost = "/mapr/" + namenodeHost;
} else {
logMessages.add("Using filesystem at " + namenodeHost + ":" + namenodePort);
namenodeHost = namenodeHost + ":" + namenodePort;
}
if (jobtrackerHost == null || jobtrackerHost.trim().length() == 0) {
jobtrackerHost = DEFAULT_CLUSTER;
logMessages.add("Using MapR default cluster for job tracker");
} else if (jobtrackerPort == null || jobtrackerPort.trim().length() == 0) {
logMessages.add("Using MapR CLDB named cluster: " + jobtrackerHost +
" for job tracker");
jobtrackerHost = "/mapr/" + jobtrackerHost;
} else {
logMessages.add("Using job tracker at " + jobtrackerHost + ":" + jobtrackerPort);
jobtrackerHost = jobtrackerHost + ":" + jobtrackerPort;
}
String fsDefaultName = MFS_SCHEME + namenodeHost;
String jobTracker = MFS_SCHEME + jobtrackerHost;
conf.set("fs.default.name", fsDefaultName);
conf.set("mapred.job.tracker", jobTracker);
- conf.set("fs.maprfs.impl", MapRFileSystem.class.getName());
+ conf.set("fs.maprfs.impl", MapRFileProvider.FS_MAPR_IMPL);
}
@Override
public void onLoad(HadoopConfiguration config, HadoopConfigurationFileSystemManager fsm) throws Exception {
fsm.addProvider(config, MapRFileProvider.SCHEME, config.getIdentifier(), new MapRFileProvider());
setDistributedCacheUtil(new DistributedCacheUtilImpl(config));
}
}
| true | true | public void configureConnectionInformation(String namenodeHost, String namenodePort, String jobtrackerHost,
String jobtrackerPort, Configuration conf, List<String> logMessages) throws Exception {
if (namenodeHost == null || namenodeHost.length() == 0) {
namenodeHost = DEFAULT_CLUSTER;
logMessages.add("Using MapR default cluster for filesystem");
} else if (namenodePort == null || namenodePort.trim().length() == 0) {
logMessages.add("Using MapR CLDB named cluster: " + namenodeHost
+ " for filesystem");
namenodeHost = "/mapr/" + namenodeHost;
} else {
logMessages.add("Using filesystem at " + namenodeHost + ":" + namenodePort);
namenodeHost = namenodeHost + ":" + namenodePort;
}
if (jobtrackerHost == null || jobtrackerHost.trim().length() == 0) {
jobtrackerHost = DEFAULT_CLUSTER;
logMessages.add("Using MapR default cluster for job tracker");
} else if (jobtrackerPort == null || jobtrackerPort.trim().length() == 0) {
logMessages.add("Using MapR CLDB named cluster: " + jobtrackerHost +
" for job tracker");
jobtrackerHost = "/mapr/" + jobtrackerHost;
} else {
logMessages.add("Using job tracker at " + jobtrackerHost + ":" + jobtrackerPort);
jobtrackerHost = jobtrackerHost + ":" + jobtrackerPort;
}
String fsDefaultName = MFS_SCHEME + namenodeHost;
String jobTracker = MFS_SCHEME + jobtrackerHost;
conf.set("fs.default.name", fsDefaultName);
conf.set("mapred.job.tracker", jobTracker);
conf.set("fs.maprfs.impl", MapRFileSystem.class.getName());
}
| public void configureConnectionInformation(String namenodeHost, String namenodePort, String jobtrackerHost,
String jobtrackerPort, Configuration conf, List<String> logMessages) throws Exception {
if (namenodeHost == null || namenodeHost.length() == 0) {
namenodeHost = DEFAULT_CLUSTER;
logMessages.add("Using MapR default cluster for filesystem");
} else if (namenodePort == null || namenodePort.trim().length() == 0) {
logMessages.add("Using MapR CLDB named cluster: " + namenodeHost
+ " for filesystem");
namenodeHost = "/mapr/" + namenodeHost;
} else {
logMessages.add("Using filesystem at " + namenodeHost + ":" + namenodePort);
namenodeHost = namenodeHost + ":" + namenodePort;
}
if (jobtrackerHost == null || jobtrackerHost.trim().length() == 0) {
jobtrackerHost = DEFAULT_CLUSTER;
logMessages.add("Using MapR default cluster for job tracker");
} else if (jobtrackerPort == null || jobtrackerPort.trim().length() == 0) {
logMessages.add("Using MapR CLDB named cluster: " + jobtrackerHost +
" for job tracker");
jobtrackerHost = "/mapr/" + jobtrackerHost;
} else {
logMessages.add("Using job tracker at " + jobtrackerHost + ":" + jobtrackerPort);
jobtrackerHost = jobtrackerHost + ":" + jobtrackerPort;
}
String fsDefaultName = MFS_SCHEME + namenodeHost;
String jobTracker = MFS_SCHEME + jobtrackerHost;
conf.set("fs.default.name", fsDefaultName);
conf.set("mapred.job.tracker", jobTracker);
conf.set("fs.maprfs.impl", MapRFileProvider.FS_MAPR_IMPL);
}
|
diff --git a/src/main/java/org/nuessler/maven/plugin/cakupan/CakupanReportMojo.java b/src/main/java/org/nuessler/maven/plugin/cakupan/CakupanReportMojo.java
index fbccfa5..382ad73 100644
--- a/src/main/java/org/nuessler/maven/plugin/cakupan/CakupanReportMojo.java
+++ b/src/main/java/org/nuessler/maven/plugin/cakupan/CakupanReportMojo.java
@@ -1,185 +1,185 @@
/**
* Copyright 2011 Matthias Nuessler <[email protected]>
*
* 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.nuessler.maven.plugin.cakupan;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.commons.io.FileUtils;
import org.apache.maven.doxia.siterenderer.Renderer;
import org.apache.maven.project.MavenProject;
import org.apache.maven.reporting.AbstractMavenReport;
import org.apache.maven.reporting.MavenReportException;
import com.cakupan.xslt.exception.XSLTCoverageException;
import com.cakupan.xslt.util.CoverageIOUtil;
import com.cakupan.xslt.util.XSLTCakupanUtil;
/**
* Generate a test coverage report for XSLT files.
*
* @author Matthias Nuessler
* @goal cakupan
* @execute phase="test" lifecycle="cakupan"
*/
public class CakupanReportMojo extends AbstractMavenReport {
/**
* <i>Maven Internal</i>: The Doxia Site Renderer.
*
* @component
*/
private Renderer siteRenderer;
/**
* <i>Maven Internal</i>: Project to interact with.
*
* @parameter default-value="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* The output directory for the report.
*
* @parameter default-value="${project.reporting.outputDirectory}/cakupan"
* @required
*/
private File outputDirectory;
/**
* @parameter expression="${xslt.instrument.destdir}"
* default-value="${project.build.directory}/cakupan-instrument"
*/
private File instrumentDestDir;
@Override
public String getOutputName() {
return "cakupan/index";
}
@Override
public String getName(Locale locale) {
return getBundle(locale).getString("report.cakupan.name");
}
@Override
public String getDescription(Locale locale) {
return getBundle(locale).getString("report.cakupan.description");
}
private ResourceBundle getBundle(Locale locale) {
return ResourceBundle.getBundle("cakupan-report", locale);
}
@Override
protected Renderer getSiteRenderer() {
return siteRenderer;
}
@Override
protected String getOutputDirectory() {
return outputDirectory.getAbsolutePath();
}
@Override
protected MavenProject getProject() {
return project;
}
@Override
public boolean isExternalReport() {
return true;
}
@Override
public boolean canGenerateReport() {
File instrumentationFile = new File(instrumentDestDir, "coverage.xml");
if (!(instrumentationFile.exists() && instrumentationFile.isFile())) {
getLog().warn(
"Can't generate Cakupan XSLT coverage report. Instrumentation file does not exist: "
+ instrumentationFile);
return false;
}
return true;
}
@Override
protected void executeReport(final Locale locale)
throws MavenReportException {
if (!canGenerateReport()) {
return;
}
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
getLog().info("Start Cakupan report mojo");
getLog().info("report output dir: " + getOutputDirectory());
try {
Collection<File> coverageFiles = FileUtils.listFiles(
- instrumentDestDir, new String[] { "xml", "dat" }, false);
+ instrumentDestDir, new String[] { "xml" }, false);
for (File file : coverageFiles) {
FileUtils.copyFileToDirectory(file, outputDirectory);
}
} catch (IOException e) {
throw new MavenReportException(e.getMessage());
}
CoverageIOUtil.setDestDir(outputDirectory);
try {
XSLTCakupanUtil.generateCoverageReport();
File destFile = new File(outputDirectory, "index.html");
if (destFile.exists()) {
destFile.delete();
}
FileUtils.moveFile(new File(outputDirectory, "xslt_summary.html"),
destFile);
} catch (XSLTCoverageException e) {
if (e.getRefId() == XSLTCoverageException.NO_COVERAGE_FILE) {
getLog().error(
"No coverage files found in "
+ outputDirectory.getPath());
} else {
throw new MavenReportException(
"Failed to create the Cakupan coverage report", e);
}
} catch (IOException e) {
throw new MavenReportException(
"Failed to move coverage report to correct location", e);
}
getLog().info("End Cakupan report mojo");
}
@Override
public void setReportOutputDirectory(File reportOutputDirectory) {
// the output directory is set differently by Maven, depending if the
// mojo is executed directly via cakupan:cakupan or as part of the site
// generation
if ((reportOutputDirectory != null)
&& (!reportOutputDirectory.getAbsolutePath()
.endsWith("cakupan"))) {
this.outputDirectory = new File(reportOutputDirectory, "cakupan");
} else {
this.outputDirectory = reportOutputDirectory;
}
}
}
| true | true | protected void executeReport(final Locale locale)
throws MavenReportException {
if (!canGenerateReport()) {
return;
}
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
getLog().info("Start Cakupan report mojo");
getLog().info("report output dir: " + getOutputDirectory());
try {
Collection<File> coverageFiles = FileUtils.listFiles(
instrumentDestDir, new String[] { "xml", "dat" }, false);
for (File file : coverageFiles) {
FileUtils.copyFileToDirectory(file, outputDirectory);
}
} catch (IOException e) {
throw new MavenReportException(e.getMessage());
}
CoverageIOUtil.setDestDir(outputDirectory);
try {
XSLTCakupanUtil.generateCoverageReport();
File destFile = new File(outputDirectory, "index.html");
if (destFile.exists()) {
destFile.delete();
}
FileUtils.moveFile(new File(outputDirectory, "xslt_summary.html"),
destFile);
} catch (XSLTCoverageException e) {
if (e.getRefId() == XSLTCoverageException.NO_COVERAGE_FILE) {
getLog().error(
"No coverage files found in "
+ outputDirectory.getPath());
} else {
throw new MavenReportException(
"Failed to create the Cakupan coverage report", e);
}
} catch (IOException e) {
throw new MavenReportException(
"Failed to move coverage report to correct location", e);
}
getLog().info("End Cakupan report mojo");
}
| protected void executeReport(final Locale locale)
throws MavenReportException {
if (!canGenerateReport()) {
return;
}
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
getLog().info("Start Cakupan report mojo");
getLog().info("report output dir: " + getOutputDirectory());
try {
Collection<File> coverageFiles = FileUtils.listFiles(
instrumentDestDir, new String[] { "xml" }, false);
for (File file : coverageFiles) {
FileUtils.copyFileToDirectory(file, outputDirectory);
}
} catch (IOException e) {
throw new MavenReportException(e.getMessage());
}
CoverageIOUtil.setDestDir(outputDirectory);
try {
XSLTCakupanUtil.generateCoverageReport();
File destFile = new File(outputDirectory, "index.html");
if (destFile.exists()) {
destFile.delete();
}
FileUtils.moveFile(new File(outputDirectory, "xslt_summary.html"),
destFile);
} catch (XSLTCoverageException e) {
if (e.getRefId() == XSLTCoverageException.NO_COVERAGE_FILE) {
getLog().error(
"No coverage files found in "
+ outputDirectory.getPath());
} else {
throw new MavenReportException(
"Failed to create the Cakupan coverage report", e);
}
} catch (IOException e) {
throw new MavenReportException(
"Failed to move coverage report to correct location", e);
}
getLog().info("End Cakupan report mojo");
}
|
diff --git a/src/eu/webtoolkit/jwt/WBootstrapTheme.java b/src/eu/webtoolkit/jwt/WBootstrapTheme.java
index f6ee0c8d..5e72a1a7 100644
--- a/src/eu/webtoolkit/jwt/WBootstrapTheme.java
+++ b/src/eu/webtoolkit/jwt/WBootstrapTheme.java
@@ -1,349 +1,352 @@
/*
* Copyright (C) 2009 Emweb bvba, Leuven, Belgium.
*
* See the LICENSE file for terms of use.
*/
package eu.webtoolkit.jwt;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import java.lang.ref.*;
import java.util.concurrent.locks.ReentrantLock;
import javax.servlet.http.*;
import javax.servlet.*;
import eu.webtoolkit.jwt.*;
import eu.webtoolkit.jwt.chart.*;
import eu.webtoolkit.jwt.utils.*;
import eu.webtoolkit.jwt.servlet.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Theme based on the Twitter Bootstrap CSS framework.
* <p>
*
* By default, the theme will use CSS resources that are shipped together with
* the JWt distribution.
* <p>
*
* @see WApplication#setTheme(WTheme theme)
*/
public class WBootstrapTheme extends WTheme {
private static Logger logger = LoggerFactory
.getLogger(WBootstrapTheme.class);
/**
* Constructor.
*/
public WBootstrapTheme(WObject parent) {
super(parent);
}
/**
* Constructor.
* <p>
* Calls {@link #WBootstrapTheme(WObject parent) this((WObject)null)}
*/
public WBootstrapTheme() {
this((WObject) null);
}
public String getName() {
return "bootstrap";
}
public List<WCssStyleSheet> getStyleSheets() {
List<WCssStyleSheet> result = new ArrayList<WCssStyleSheet>();
String themeDir = WApplication.getResourcesUrl() + "themes/"
+ this.getName();
result.add(new WCssStyleSheet(new WLink(themeDir + "/bootstrap.css")));
result.add(new WCssStyleSheet(new WLink(themeDir
+ "/bootstrap-responsive.css")));
result.add(new WCssStyleSheet(new WLink(themeDir + "/wt.css")));
return result;
}
public void apply(WWidget widget, WWidget child, int widgetRole) {
switch (widgetRole) {
case WidgetThemeRole.MenuItemIconRole:
child.addStyleClass("Wt-icon");
break;
case WidgetThemeRole.MenuItemCheckBoxRole:
child.addStyleClass("Wt-chkbox");
break;
case WidgetThemeRole.DialogCoverRole:
child.addStyleClass("modal-backdrop");
break;
case WidgetThemeRole.DialogTitleBarRole:
child.addStyleClass("modal-header");
break;
case WidgetThemeRole.DialogBodyRole:
child.addStyleClass("modal-body");
break;
case WidgetThemeRole.DialogFooterRole:
child.addStyleClass("modal-footer");
break;
case WidgetThemeRole.DialogCloseIconRole: {
child.addStyleClass("close");
WText t = ((child) instanceof WText ? (WText) (child) : null);
t.setText("×");
break;
}
case WidgetThemeRole.TableViewRowContainerRole: {
WAbstractItemView view = ((widget) instanceof WAbstractItemView ? (WAbstractItemView) (widget)
: null);
child
.toggleStyleClass("Wt-striped", view
.hasAlternatingRowColors());
break;
}
case WidgetThemeRole.DatePickerPopupRole:
child.addStyleClass("Wt-datepicker");
break;
case WidgetThemeRole.PanelTitleBarRole:
child.addStyleClass("accordion-heading");
break;
case WidgetThemeRole.PanelCollapseButtonRole:
case WidgetThemeRole.PanelTitleRole:
child.addStyleClass("accordion-toggle");
break;
case WidgetThemeRole.PanelBodyRole:
child.addStyleClass("accordion-inner");
break;
case WidgetThemeRole.AuthWidgets:
WApplication app = WApplication.getInstance();
app.getBuiltinLocalizedStrings().useBuiltin(
WtServlet.AuthBootstrapTheme_xml);
break;
}
}
public void apply(WWidget widget, DomElement element, int elementRole) {
{
WPopupWidget popup = ((widget) instanceof WPopupWidget ? (WPopupWidget) (widget)
: null);
if (popup != null) {
- element
- .addPropertyWord(Property.PropertyClass,
- "dropdown-menu");
+ WDialog dialog = ((widget) instanceof WDialog ? (WDialog) (widget)
+ : null);
+ if (!(dialog != null)) {
+ element.addPropertyWord(Property.PropertyClass,
+ "dropdown-menu");
+ }
}
}
switch (element.getType()) {
case DomElement_A:
if (((widget) instanceof WPushButton ? (WPushButton) (widget)
: null) != null) {
element.addPropertyWord(Property.PropertyClass, "btn");
}
break;
case DomElement_BUTTON: {
element.addPropertyWord(Property.PropertyClass, "btn");
WPushButton button = ((widget) instanceof WPushButton ? (WPushButton) (widget)
: null);
if (button != null) {
if (button.isDefault()) {
element.addPropertyWord(Property.PropertyClass,
"btn-primary");
}
if (button.getMenu() != null) {
element.addPropertyWord(Property.PropertyInnerHTML,
"<span class=\"caret\"></span>");
}
}
break;
}
case DomElement_DIV: {
WDialog dialog = ((widget) instanceof WDialog ? (WDialog) (widget)
: null);
if (dialog != null) {
element.addPropertyWord(Property.PropertyClass, "modal");
return;
}
WPanel panel = ((widget) instanceof WPanel ? (WPanel) (widget)
: null);
if (panel != null) {
element.addPropertyWord(Property.PropertyClass,
"accordion-group");
return;
}
WProgressBar bar = ((widget) instanceof WProgressBar ? (WProgressBar) (widget)
: null);
if (bar != null) {
switch (elementRole) {
case ElementThemeRole.MainElementThemeRole:
element.addPropertyWord(Property.PropertyClass, "progress");
break;
case ElementThemeRole.ProgressBarBarRole:
element.addPropertyWord(Property.PropertyClass, "bar");
break;
case ElementThemeRole.ProgressBarLabelRole:
element
.addPropertyWord(Property.PropertyClass,
"bar-label");
}
return;
}
WGoogleMap map = ((widget) instanceof WGoogleMap ? (WGoogleMap) (widget)
: null);
if (map != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-googlemap");
return;
}
WAbstractItemView itemView = ((widget) instanceof WAbstractItemView ? (WAbstractItemView) (widget)
: null);
if (itemView != null) {
element.addPropertyWord(Property.PropertyClass,
"form-horizontal");
return;
}
}
break;
case DomElement_LABEL: {
WCheckBox cb = ((widget) instanceof WCheckBox ? (WCheckBox) (widget)
: null);
if (cb != null) {
element.addPropertyWord(Property.PropertyClass, "checkbox");
if (cb.isInline()) {
element.addPropertyWord(Property.PropertyClass, "inline");
}
} else {
WRadioButton rb = ((widget) instanceof WRadioButton ? (WRadioButton) (widget)
: null);
if (rb != null) {
element.addPropertyWord(Property.PropertyClass, "radio");
if (rb.isInline()) {
element.addPropertyWord(Property.PropertyClass,
"inline");
}
}
}
}
break;
case DomElement_LI: {
WMenuItem item = ((widget) instanceof WMenuItem ? (WMenuItem) (widget)
: null);
if (item != null) {
if (item.isSeparator()) {
element.addPropertyWord(Property.PropertyClass, "divider");
}
if (item.isSectionHeader()) {
element.addPropertyWord(Property.PropertyClass,
"nav-header");
}
}
}
break;
case DomElement_INPUT: {
WAbstractSpinBox spinBox = ((widget) instanceof WAbstractSpinBox ? (WAbstractSpinBox) (widget)
: null);
if (spinBox != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-spinbox");
return;
}
WDateEdit dateEdit = ((widget) instanceof WDateEdit ? (WDateEdit) (widget)
: null);
if (dateEdit != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-dateedit");
return;
}
}
break;
case DomElement_UL: {
WPopupMenu popupMenu = ((widget) instanceof WPopupMenu ? (WPopupMenu) (widget)
: null);
if (popupMenu != null) {
element
.addPropertyWord(Property.PropertyClass,
"dropdown-menu");
} else {
WMenu menu = ((widget) instanceof WMenu ? (WMenu) (widget)
: null);
if (menu != null) {
element.addPropertyWord(Property.PropertyClass, "nav");
WTabWidget tabs = ((menu.getParent().getParent()) instanceof WTabWidget ? (WTabWidget) (menu
.getParent().getParent())
: null);
if (tabs != null) {
element.addPropertyWord(Property.PropertyClass,
"nav-tabs");
}
} else {
WSuggestionPopup suggestions = ((widget) instanceof WSuggestionPopup ? (WSuggestionPopup) (widget)
: null);
if (suggestions != null) {
element.addPropertyWord(Property.PropertyClass,
"typeahead");
}
}
}
}
case DomElement_SPAN: {
WInPlaceEdit inPlaceEdit = ((widget) instanceof WInPlaceEdit ? (WInPlaceEdit) (widget)
: null);
if (inPlaceEdit != null) {
element.addPropertyWord(Property.PropertyClass,
"Wt-in-place-edit");
}
}
break;
default:
break;
}
}
public String getDisabledClass() {
return "disabled";
}
public String getActiveClass() {
return "active";
}
public boolean isCanStyleAnchorAsButton() {
return true;
}
public void applyValidationStyle(WWidget widget,
WValidator.Result validation, EnumSet<ValidationStyleFlag> styles) {
WApplication app = WApplication.getInstance();
app.loadJavaScript("js/BootstrapValidate.js", wtjs1());
app.loadJavaScript("js/BootstrapValidate.js", wtjs2());
if (app.getEnvironment().hasAjax()) {
StringBuilder js = new StringBuilder();
js.append("Wt3_3_0.setValidationState(").append(widget.getJsRef())
.append(",").append(
validation.getState() == WValidator.State.Valid ? 1
: 0).append(",").append(
WString.toWString(validation.getMessage())
.getJsStringLiteral()).append(",").append(
EnumUtils.valueOf(styles)).append(");");
widget.doJavaScript(js.toString());
} else {
boolean validStyle = validation.getState() == WValidator.State.Valid
&& !EnumUtils.mask(styles,
ValidationStyleFlag.ValidationValidStyle).isEmpty();
boolean invalidStyle = validation.getState() != WValidator.State.Valid
&& !EnumUtils.mask(styles,
ValidationStyleFlag.ValidationInvalidStyle)
.isEmpty();
widget.toggleStyleClass("Wt-valid", validStyle);
widget.toggleStyleClass("Wt-invalid", invalidStyle);
}
}
static WJavaScriptPreamble wtjs1() {
return new WJavaScriptPreamble(
JavaScriptScope.WtClassScope,
JavaScriptObjectType.JavaScriptFunction,
"validate",
"function(a){var b;b=a.options?a.options.item(a.selectedIndex).text:a.value;b=a.wtValidate.validate(b);this.setValidationState(a,b.valid,b.message,1)}");
}
static WJavaScriptPreamble wtjs2() {
return new WJavaScriptPreamble(
JavaScriptScope.WtClassScope,
JavaScriptObjectType.JavaScriptFunction,
"setValidationState",
"function(a,b,f,c){var e=b==1&&(c&2)!=0;c=b!=1&&(c&1)!=0;var d=$(a);d.toggleClass(\"Wt-valid\",e).toggleClass(\"Wt-invalid\",c);(d=d.closest(\".control-group\"))&&d.toggleClass(\"success\",e).toggleClass(\"error\",c);a.defaultTT=typeof a.defaultTT===\"undefined\"?a.getAttribute(\"title\")||\"\":\"\";b?a.setAttribute(\"title\",a.defaultTT):a.setAttribute(\"title\",f)}");
}
}
| true | true | public void apply(WWidget widget, DomElement element, int elementRole) {
{
WPopupWidget popup = ((widget) instanceof WPopupWidget ? (WPopupWidget) (widget)
: null);
if (popup != null) {
element
.addPropertyWord(Property.PropertyClass,
"dropdown-menu");
}
}
switch (element.getType()) {
case DomElement_A:
if (((widget) instanceof WPushButton ? (WPushButton) (widget)
: null) != null) {
element.addPropertyWord(Property.PropertyClass, "btn");
}
break;
case DomElement_BUTTON: {
element.addPropertyWord(Property.PropertyClass, "btn");
WPushButton button = ((widget) instanceof WPushButton ? (WPushButton) (widget)
: null);
if (button != null) {
if (button.isDefault()) {
element.addPropertyWord(Property.PropertyClass,
"btn-primary");
}
if (button.getMenu() != null) {
element.addPropertyWord(Property.PropertyInnerHTML,
"<span class=\"caret\"></span>");
}
}
break;
}
case DomElement_DIV: {
WDialog dialog = ((widget) instanceof WDialog ? (WDialog) (widget)
: null);
if (dialog != null) {
element.addPropertyWord(Property.PropertyClass, "modal");
return;
}
WPanel panel = ((widget) instanceof WPanel ? (WPanel) (widget)
: null);
if (panel != null) {
element.addPropertyWord(Property.PropertyClass,
"accordion-group");
return;
}
WProgressBar bar = ((widget) instanceof WProgressBar ? (WProgressBar) (widget)
: null);
if (bar != null) {
switch (elementRole) {
case ElementThemeRole.MainElementThemeRole:
element.addPropertyWord(Property.PropertyClass, "progress");
break;
case ElementThemeRole.ProgressBarBarRole:
element.addPropertyWord(Property.PropertyClass, "bar");
break;
case ElementThemeRole.ProgressBarLabelRole:
element
.addPropertyWord(Property.PropertyClass,
"bar-label");
}
return;
}
WGoogleMap map = ((widget) instanceof WGoogleMap ? (WGoogleMap) (widget)
: null);
if (map != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-googlemap");
return;
}
WAbstractItemView itemView = ((widget) instanceof WAbstractItemView ? (WAbstractItemView) (widget)
: null);
if (itemView != null) {
element.addPropertyWord(Property.PropertyClass,
"form-horizontal");
return;
}
}
break;
case DomElement_LABEL: {
WCheckBox cb = ((widget) instanceof WCheckBox ? (WCheckBox) (widget)
: null);
if (cb != null) {
element.addPropertyWord(Property.PropertyClass, "checkbox");
if (cb.isInline()) {
element.addPropertyWord(Property.PropertyClass, "inline");
}
} else {
WRadioButton rb = ((widget) instanceof WRadioButton ? (WRadioButton) (widget)
: null);
if (rb != null) {
element.addPropertyWord(Property.PropertyClass, "radio");
if (rb.isInline()) {
element.addPropertyWord(Property.PropertyClass,
"inline");
}
}
}
}
break;
case DomElement_LI: {
WMenuItem item = ((widget) instanceof WMenuItem ? (WMenuItem) (widget)
: null);
if (item != null) {
if (item.isSeparator()) {
element.addPropertyWord(Property.PropertyClass, "divider");
}
if (item.isSectionHeader()) {
element.addPropertyWord(Property.PropertyClass,
"nav-header");
}
}
}
break;
case DomElement_INPUT: {
WAbstractSpinBox spinBox = ((widget) instanceof WAbstractSpinBox ? (WAbstractSpinBox) (widget)
: null);
if (spinBox != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-spinbox");
return;
}
WDateEdit dateEdit = ((widget) instanceof WDateEdit ? (WDateEdit) (widget)
: null);
if (dateEdit != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-dateedit");
return;
}
}
break;
case DomElement_UL: {
WPopupMenu popupMenu = ((widget) instanceof WPopupMenu ? (WPopupMenu) (widget)
: null);
if (popupMenu != null) {
element
.addPropertyWord(Property.PropertyClass,
"dropdown-menu");
} else {
WMenu menu = ((widget) instanceof WMenu ? (WMenu) (widget)
: null);
if (menu != null) {
element.addPropertyWord(Property.PropertyClass, "nav");
WTabWidget tabs = ((menu.getParent().getParent()) instanceof WTabWidget ? (WTabWidget) (menu
.getParent().getParent())
: null);
if (tabs != null) {
element.addPropertyWord(Property.PropertyClass,
"nav-tabs");
}
} else {
WSuggestionPopup suggestions = ((widget) instanceof WSuggestionPopup ? (WSuggestionPopup) (widget)
: null);
if (suggestions != null) {
element.addPropertyWord(Property.PropertyClass,
"typeahead");
}
}
}
}
case DomElement_SPAN: {
WInPlaceEdit inPlaceEdit = ((widget) instanceof WInPlaceEdit ? (WInPlaceEdit) (widget)
: null);
if (inPlaceEdit != null) {
element.addPropertyWord(Property.PropertyClass,
"Wt-in-place-edit");
}
}
break;
default:
break;
}
}
| public void apply(WWidget widget, DomElement element, int elementRole) {
{
WPopupWidget popup = ((widget) instanceof WPopupWidget ? (WPopupWidget) (widget)
: null);
if (popup != null) {
WDialog dialog = ((widget) instanceof WDialog ? (WDialog) (widget)
: null);
if (!(dialog != null)) {
element.addPropertyWord(Property.PropertyClass,
"dropdown-menu");
}
}
}
switch (element.getType()) {
case DomElement_A:
if (((widget) instanceof WPushButton ? (WPushButton) (widget)
: null) != null) {
element.addPropertyWord(Property.PropertyClass, "btn");
}
break;
case DomElement_BUTTON: {
element.addPropertyWord(Property.PropertyClass, "btn");
WPushButton button = ((widget) instanceof WPushButton ? (WPushButton) (widget)
: null);
if (button != null) {
if (button.isDefault()) {
element.addPropertyWord(Property.PropertyClass,
"btn-primary");
}
if (button.getMenu() != null) {
element.addPropertyWord(Property.PropertyInnerHTML,
"<span class=\"caret\"></span>");
}
}
break;
}
case DomElement_DIV: {
WDialog dialog = ((widget) instanceof WDialog ? (WDialog) (widget)
: null);
if (dialog != null) {
element.addPropertyWord(Property.PropertyClass, "modal");
return;
}
WPanel panel = ((widget) instanceof WPanel ? (WPanel) (widget)
: null);
if (panel != null) {
element.addPropertyWord(Property.PropertyClass,
"accordion-group");
return;
}
WProgressBar bar = ((widget) instanceof WProgressBar ? (WProgressBar) (widget)
: null);
if (bar != null) {
switch (elementRole) {
case ElementThemeRole.MainElementThemeRole:
element.addPropertyWord(Property.PropertyClass, "progress");
break;
case ElementThemeRole.ProgressBarBarRole:
element.addPropertyWord(Property.PropertyClass, "bar");
break;
case ElementThemeRole.ProgressBarLabelRole:
element
.addPropertyWord(Property.PropertyClass,
"bar-label");
}
return;
}
WGoogleMap map = ((widget) instanceof WGoogleMap ? (WGoogleMap) (widget)
: null);
if (map != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-googlemap");
return;
}
WAbstractItemView itemView = ((widget) instanceof WAbstractItemView ? (WAbstractItemView) (widget)
: null);
if (itemView != null) {
element.addPropertyWord(Property.PropertyClass,
"form-horizontal");
return;
}
}
break;
case DomElement_LABEL: {
WCheckBox cb = ((widget) instanceof WCheckBox ? (WCheckBox) (widget)
: null);
if (cb != null) {
element.addPropertyWord(Property.PropertyClass, "checkbox");
if (cb.isInline()) {
element.addPropertyWord(Property.PropertyClass, "inline");
}
} else {
WRadioButton rb = ((widget) instanceof WRadioButton ? (WRadioButton) (widget)
: null);
if (rb != null) {
element.addPropertyWord(Property.PropertyClass, "radio");
if (rb.isInline()) {
element.addPropertyWord(Property.PropertyClass,
"inline");
}
}
}
}
break;
case DomElement_LI: {
WMenuItem item = ((widget) instanceof WMenuItem ? (WMenuItem) (widget)
: null);
if (item != null) {
if (item.isSeparator()) {
element.addPropertyWord(Property.PropertyClass, "divider");
}
if (item.isSectionHeader()) {
element.addPropertyWord(Property.PropertyClass,
"nav-header");
}
}
}
break;
case DomElement_INPUT: {
WAbstractSpinBox spinBox = ((widget) instanceof WAbstractSpinBox ? (WAbstractSpinBox) (widget)
: null);
if (spinBox != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-spinbox");
return;
}
WDateEdit dateEdit = ((widget) instanceof WDateEdit ? (WDateEdit) (widget)
: null);
if (dateEdit != null) {
element.addPropertyWord(Property.PropertyClass, "Wt-dateedit");
return;
}
}
break;
case DomElement_UL: {
WPopupMenu popupMenu = ((widget) instanceof WPopupMenu ? (WPopupMenu) (widget)
: null);
if (popupMenu != null) {
element
.addPropertyWord(Property.PropertyClass,
"dropdown-menu");
} else {
WMenu menu = ((widget) instanceof WMenu ? (WMenu) (widget)
: null);
if (menu != null) {
element.addPropertyWord(Property.PropertyClass, "nav");
WTabWidget tabs = ((menu.getParent().getParent()) instanceof WTabWidget ? (WTabWidget) (menu
.getParent().getParent())
: null);
if (tabs != null) {
element.addPropertyWord(Property.PropertyClass,
"nav-tabs");
}
} else {
WSuggestionPopup suggestions = ((widget) instanceof WSuggestionPopup ? (WSuggestionPopup) (widget)
: null);
if (suggestions != null) {
element.addPropertyWord(Property.PropertyClass,
"typeahead");
}
}
}
}
case DomElement_SPAN: {
WInPlaceEdit inPlaceEdit = ((widget) instanceof WInPlaceEdit ? (WInPlaceEdit) (widget)
: null);
if (inPlaceEdit != null) {
element.addPropertyWord(Property.PropertyClass,
"Wt-in-place-edit");
}
}
break;
default:
break;
}
}
|
diff --git a/fap/app/services/portafirma/PortafirmaImpl.java b/fap/app/services/portafirma/PortafirmaImpl.java
index 678ad469..742a7236 100644
--- a/fap/app/services/portafirma/PortafirmaImpl.java
+++ b/fap/app/services/portafirma/PortafirmaImpl.java
@@ -1,132 +1,132 @@
package services.portafirma;
import java.net.URL;
import javax.xml.ws.BindingProvider;
import models.ResolucionFAP;
import enumerado.fap.gen.EstadoPortafirmaEnum;
import es.gobcan.aciisi.portafirma.ws.PortafirmaException;
import es.gobcan.aciisi.portafirma.ws.PortafirmaService;
import es.gobcan.aciisi.portafirma.ws.PortafirmaSoapService;
import es.gobcan.aciisi.portafirma.ws.dominio.CrearSolicitudResponseType;
import es.gobcan.aciisi.portafirma.ws.dominio.CrearSolicitudType;
import es.gobcan.aciisi.portafirma.ws.dominio.ObtenerEstadoSolicitudResponseType;
import es.gobcan.aciisi.portafirma.ws.dominio.ObtenerEstadoSolicitudType;
import es.gobcan.aciisi.portafirma.ws.dominio.PrioridadEnumType;
import platino.PlatinoProxy;
import properties.FapProperties;
import services.PortafirmaFapService;
import services.PortafirmaFapServiceException;
import services.responses.PortafirmaCrearSolicitudResponse;
public class PortafirmaImpl implements PortafirmaFapService {
private static PortafirmaService portafirmaService;
static {
URL wsdlURL =PortafirmaFapService.class.getClassLoader()
.getResource("wsdl/PortafirmaServiceImpl.wsdl");
portafirmaService= new PortafirmaSoapService(wsdlURL).getPortafirmaSoapService();
BindingProvider bp = (BindingProvider) portafirmaService;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
FapProperties.get("portafirma.webservice.wsdlURL"));
PlatinoProxy.setProxy(portafirmaService);
}
@Override
public PortafirmaCrearSolicitudResponse crearSolicitudFirma(ResolucionFAP resolucion) throws PortafirmaFapServiceException {
CrearSolicitudType solFirma = getCrearSolicitudWSTypeFromResolucionFAP(resolucion);
CrearSolicitudResponseType wsType = new CrearSolicitudResponseType();
try {
wsType = portafirmaService.crearSolicitud(solFirma);
} catch (PortafirmaException e) {
// TODO Auto-generated catch block
throw new PortafirmaFapServiceException(e.getMessage(), e);
}
PortafirmaCrearSolicitudResponse response = new PortafirmaCrearSolicitudResponse();
response.setIdSolicitud(wsType.getIdSolicitud());
response.setComentarios(wsType.getComentario());
return response;
}
private CrearSolicitudType getCrearSolicitudWSTypeFromResolucionFAP (ResolucionFAP resolucion) {
CrearSolicitudType solFirma=new CrearSolicitudType();
solFirma.setTitulo(resolucion.tituloInterno);
solFirma.setDescripcion(resolucion.descripcion);
solFirma.setPrioridad(getEnumTypeFromValue(resolucion.prioridadFirma));
// solFirma.setEmailNotificacion();
// solFirma.
// solFirma.setComentario("");
// TODO: Rellenar los datos necesarios
return solFirma;
}
private PrioridadEnumType getEnumTypeFromValue (String strPrioridad) {
if (strPrioridad.equalsIgnoreCase("ALTA"))
return PrioridadEnumType.ALTA;
if (strPrioridad.equalsIgnoreCase("NORMAL"))
return PrioridadEnumType.NORMAL;
return PrioridadEnumType.BAJA;
}
public boolean isConfigured() {
try {
return (portafirmaService.obtenerVersion() != null);
} catch (PortafirmaException e) {
play.Logger.error("Error al obetner la versión del servicio de Portafirma", e);
}
return false;
}
@Override
public void mostrarInfoInyeccion() {
if (isConfigured())
play.Logger.info("El servicio de Portafirma ha sido inyectado con PortafirmaService y está operativo.");
else
play.Logger.info("El servicio de Portafirma ha sido inyectado con PortafirmaService y NO está operativo.");
}
@Override
public void obtenerEstadoFirma() throws PortafirmaFapServiceException {
// TODO Auto-generated method stub
}
@Override
public void eliminarSolicitudFirma() throws PortafirmaFapServiceException {
// TODO Auto-generated method stub
}
@Override
public String obtenerVersion() throws PortafirmaFapServiceException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean comprobarSiResolucionFirmada(String idSolicitudFirma) throws PortafirmaFapServiceException {
ObtenerEstadoSolicitudType o = new ObtenerEstadoSolicitudType();
o.setIdSolicitud(idSolicitudFirma);
ObtenerEstadoSolicitudResponseType response;
try {
response = portafirmaService.obtenerEstadoSolicitud(o);
play.Logger.info("¿La resolución ha sido firmada en el portafirma? Está en estado " + response.getEstado());
} catch (PortafirmaException e) {
throw new PortafirmaFapServiceException(e.getMessage(), e);
}
// TODO: dependiendo del valor de response devolver si está firmada o no.
- if (response.getEstado().equals(EstadoPortafirmaEnum.Firmadayfinalizada))
+ if (response.getEstado().equals(EstadoPortafirmaEnum.Firmadayfinalizada.name()))
return true;
return false;
}
}
| true | true | public boolean comprobarSiResolucionFirmada(String idSolicitudFirma) throws PortafirmaFapServiceException {
ObtenerEstadoSolicitudType o = new ObtenerEstadoSolicitudType();
o.setIdSolicitud(idSolicitudFirma);
ObtenerEstadoSolicitudResponseType response;
try {
response = portafirmaService.obtenerEstadoSolicitud(o);
play.Logger.info("¿La resolución ha sido firmada en el portafirma? Está en estado " + response.getEstado());
} catch (PortafirmaException e) {
throw new PortafirmaFapServiceException(e.getMessage(), e);
}
// TODO: dependiendo del valor de response devolver si está firmada o no.
if (response.getEstado().equals(EstadoPortafirmaEnum.Firmadayfinalizada))
return true;
return false;
}
| public boolean comprobarSiResolucionFirmada(String idSolicitudFirma) throws PortafirmaFapServiceException {
ObtenerEstadoSolicitudType o = new ObtenerEstadoSolicitudType();
o.setIdSolicitud(idSolicitudFirma);
ObtenerEstadoSolicitudResponseType response;
try {
response = portafirmaService.obtenerEstadoSolicitud(o);
play.Logger.info("¿La resolución ha sido firmada en el portafirma? Está en estado " + response.getEstado());
} catch (PortafirmaException e) {
throw new PortafirmaFapServiceException(e.getMessage(), e);
}
// TODO: dependiendo del valor de response devolver si está firmada o no.
if (response.getEstado().equals(EstadoPortafirmaEnum.Firmadayfinalizada.name()))
return true;
return false;
}
|
diff --git a/src/com/gitblit/wicket/panels/BranchesPanel.java b/src/com/gitblit/wicket/panels/BranchesPanel.java
index 92413ee..d784354 100644
--- a/src/com/gitblit/wicket/panels/BranchesPanel.java
+++ b/src/com/gitblit/wicket/panels/BranchesPanel.java
@@ -1,155 +1,155 @@
/*
* Copyright 2011 gitblit.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.gitblit.wicket.panels;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.model.StringResourceModel;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import com.gitblit.SyndicationServlet;
import com.gitblit.models.RefModel;
import com.gitblit.models.RepositoryModel;
import com.gitblit.utils.JGitUtils;
import com.gitblit.utils.JGitUtils.SearchType;
import com.gitblit.utils.StringUtils;
import com.gitblit.wicket.WicketUtils;
import com.gitblit.wicket.pages.BranchesPage;
import com.gitblit.wicket.pages.CommitPage;
import com.gitblit.wicket.pages.LogPage;
import com.gitblit.wicket.pages.MetricsPage;
import com.gitblit.wicket.pages.SearchPage;
import com.gitblit.wicket.pages.SummaryPage;
import com.gitblit.wicket.pages.TreePage;
public class BranchesPanel extends BasePanel {
private static final long serialVersionUID = 1L;
private final boolean hasBranches;
public BranchesPanel(String wicketId, final RepositoryModel model, Repository r,
final int maxCount) {
super(wicketId);
// branches
List<RefModel> branches = new ArrayList<RefModel>();
branches.addAll(JGitUtils.getLocalBranches(r, false, maxCount));
if (model.showRemoteBranches) {
branches.addAll(JGitUtils.getRemoteBranches(r, false, maxCount));
}
Collections.sort(branches);
Collections.reverse(branches);
if (maxCount > 0 && branches.size() > maxCount) {
branches = new ArrayList<RefModel>(branches.subList(0, maxCount));
}
if (maxCount > 0) {
// summary page
// show branches page link
add(new LinkPanel("branches", "title", new StringResourceModel("gb.branches", this,
null), BranchesPage.class, WicketUtils.newRepositoryParameter(model.name)));
} else {
// branches page
// show repository summary page link
add(new LinkPanel("branches", "title", model.name, SummaryPage.class,
WicketUtils.newRepositoryParameter(model.name)));
}
ListDataProvider<RefModel> branchesDp = new ListDataProvider<RefModel>(branches);
DataView<RefModel> branchesView = new DataView<RefModel>("branch", branchesDp) {
private static final long serialVersionUID = 1L;
int counter;
public void populateItem(final Item<RefModel> item) {
final RefModel entry = item.getModelObject();
item.add(WicketUtils.createDateLabel("branchDate", entry.getDate(), getTimeZone()));
item.add(new LinkPanel("branchName", "list name", StringUtils.trimString(
entry.displayName, 28), LogPage.class, WicketUtils.newObjectParameter(
model.name, entry.getName())));
String author = entry.getAuthorIdent().getName();
LinkPanel authorLink = new LinkPanel("branchAuthor", "list", author,
SearchPage.class, WicketUtils.newSearchParameter(model.name,
entry.getName(), author, SearchType.AUTHOR));
setPersonSearchTooltip(authorLink, author, SearchType.AUTHOR);
item.add(authorLink);
// short message
String shortMessage = entry.getShortMessage();
String trimmedMessage = StringUtils.trimShortLog(shortMessage);
LinkPanel shortlog = new LinkPanel("branchLog", "list subject", trimmedMessage,
CommitPage.class, WicketUtils.newObjectParameter(model.name,
entry.getName()));
if (!shortMessage.equals(trimmedMessage)) {
WicketUtils.setHtmlTooltip(shortlog, shortMessage);
}
item.add(shortlog);
if (maxCount <= 0) {
Fragment fragment = new Fragment("branchLinks", "branchPageLinks", this);
fragment.add(new BookmarkablePageLink<Void>("log", LogPage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("tree", TreePage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("metrics", MetricsPage.class,
WicketUtils.newObjectParameter(model.name, entry.getName())));
fragment.add(new ExternalLink("syndication", SyndicationServlet.asLink(
getRequest().getRelativePathPrefixToContextRoot(), model.name,
entry.getName(), 0)));
item.add(fragment);
} else {
Fragment fragment = new Fragment("branchLinks", "branchPanelLinks", this);
fragment.add(new BookmarkablePageLink<Void>("log", LogPage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("tree", TreePage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
item.add(fragment);
}
WicketUtils.setAlternatingBackground(item, counter);
counter++;
}
};
add(branchesView);
if (branches.size() < maxCount || maxCount <= 0) {
add(new Label("allBranches", "").setVisible(false));
} else {
add(new LinkPanel("allBranches", "link", new StringResourceModel("gb.allBranches",
this, null), BranchesPage.class, WicketUtils.newRepositoryParameter(model.name)));
}
// We always have 1 branch
hasBranches = (branches.size() > 1)
|| ((branches.size() == 1) && !branches.get(0).displayName
- .equalsIgnoreCase(Constants.HEAD));
+ .equalsIgnoreCase("master"));
}
public BranchesPanel hideIfEmpty() {
setVisible(hasBranches);
return this;
}
}
| true | true | public BranchesPanel(String wicketId, final RepositoryModel model, Repository r,
final int maxCount) {
super(wicketId);
// branches
List<RefModel> branches = new ArrayList<RefModel>();
branches.addAll(JGitUtils.getLocalBranches(r, false, maxCount));
if (model.showRemoteBranches) {
branches.addAll(JGitUtils.getRemoteBranches(r, false, maxCount));
}
Collections.sort(branches);
Collections.reverse(branches);
if (maxCount > 0 && branches.size() > maxCount) {
branches = new ArrayList<RefModel>(branches.subList(0, maxCount));
}
if (maxCount > 0) {
// summary page
// show branches page link
add(new LinkPanel("branches", "title", new StringResourceModel("gb.branches", this,
null), BranchesPage.class, WicketUtils.newRepositoryParameter(model.name)));
} else {
// branches page
// show repository summary page link
add(new LinkPanel("branches", "title", model.name, SummaryPage.class,
WicketUtils.newRepositoryParameter(model.name)));
}
ListDataProvider<RefModel> branchesDp = new ListDataProvider<RefModel>(branches);
DataView<RefModel> branchesView = new DataView<RefModel>("branch", branchesDp) {
private static final long serialVersionUID = 1L;
int counter;
public void populateItem(final Item<RefModel> item) {
final RefModel entry = item.getModelObject();
item.add(WicketUtils.createDateLabel("branchDate", entry.getDate(), getTimeZone()));
item.add(new LinkPanel("branchName", "list name", StringUtils.trimString(
entry.displayName, 28), LogPage.class, WicketUtils.newObjectParameter(
model.name, entry.getName())));
String author = entry.getAuthorIdent().getName();
LinkPanel authorLink = new LinkPanel("branchAuthor", "list", author,
SearchPage.class, WicketUtils.newSearchParameter(model.name,
entry.getName(), author, SearchType.AUTHOR));
setPersonSearchTooltip(authorLink, author, SearchType.AUTHOR);
item.add(authorLink);
// short message
String shortMessage = entry.getShortMessage();
String trimmedMessage = StringUtils.trimShortLog(shortMessage);
LinkPanel shortlog = new LinkPanel("branchLog", "list subject", trimmedMessage,
CommitPage.class, WicketUtils.newObjectParameter(model.name,
entry.getName()));
if (!shortMessage.equals(trimmedMessage)) {
WicketUtils.setHtmlTooltip(shortlog, shortMessage);
}
item.add(shortlog);
if (maxCount <= 0) {
Fragment fragment = new Fragment("branchLinks", "branchPageLinks", this);
fragment.add(new BookmarkablePageLink<Void>("log", LogPage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("tree", TreePage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("metrics", MetricsPage.class,
WicketUtils.newObjectParameter(model.name, entry.getName())));
fragment.add(new ExternalLink("syndication", SyndicationServlet.asLink(
getRequest().getRelativePathPrefixToContextRoot(), model.name,
entry.getName(), 0)));
item.add(fragment);
} else {
Fragment fragment = new Fragment("branchLinks", "branchPanelLinks", this);
fragment.add(new BookmarkablePageLink<Void>("log", LogPage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("tree", TreePage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
item.add(fragment);
}
WicketUtils.setAlternatingBackground(item, counter);
counter++;
}
};
add(branchesView);
if (branches.size() < maxCount || maxCount <= 0) {
add(new Label("allBranches", "").setVisible(false));
} else {
add(new LinkPanel("allBranches", "link", new StringResourceModel("gb.allBranches",
this, null), BranchesPage.class, WicketUtils.newRepositoryParameter(model.name)));
}
// We always have 1 branch
hasBranches = (branches.size() > 1)
|| ((branches.size() == 1) && !branches.get(0).displayName
.equalsIgnoreCase(Constants.HEAD));
}
| public BranchesPanel(String wicketId, final RepositoryModel model, Repository r,
final int maxCount) {
super(wicketId);
// branches
List<RefModel> branches = new ArrayList<RefModel>();
branches.addAll(JGitUtils.getLocalBranches(r, false, maxCount));
if (model.showRemoteBranches) {
branches.addAll(JGitUtils.getRemoteBranches(r, false, maxCount));
}
Collections.sort(branches);
Collections.reverse(branches);
if (maxCount > 0 && branches.size() > maxCount) {
branches = new ArrayList<RefModel>(branches.subList(0, maxCount));
}
if (maxCount > 0) {
// summary page
// show branches page link
add(new LinkPanel("branches", "title", new StringResourceModel("gb.branches", this,
null), BranchesPage.class, WicketUtils.newRepositoryParameter(model.name)));
} else {
// branches page
// show repository summary page link
add(new LinkPanel("branches", "title", model.name, SummaryPage.class,
WicketUtils.newRepositoryParameter(model.name)));
}
ListDataProvider<RefModel> branchesDp = new ListDataProvider<RefModel>(branches);
DataView<RefModel> branchesView = new DataView<RefModel>("branch", branchesDp) {
private static final long serialVersionUID = 1L;
int counter;
public void populateItem(final Item<RefModel> item) {
final RefModel entry = item.getModelObject();
item.add(WicketUtils.createDateLabel("branchDate", entry.getDate(), getTimeZone()));
item.add(new LinkPanel("branchName", "list name", StringUtils.trimString(
entry.displayName, 28), LogPage.class, WicketUtils.newObjectParameter(
model.name, entry.getName())));
String author = entry.getAuthorIdent().getName();
LinkPanel authorLink = new LinkPanel("branchAuthor", "list", author,
SearchPage.class, WicketUtils.newSearchParameter(model.name,
entry.getName(), author, SearchType.AUTHOR));
setPersonSearchTooltip(authorLink, author, SearchType.AUTHOR);
item.add(authorLink);
// short message
String shortMessage = entry.getShortMessage();
String trimmedMessage = StringUtils.trimShortLog(shortMessage);
LinkPanel shortlog = new LinkPanel("branchLog", "list subject", trimmedMessage,
CommitPage.class, WicketUtils.newObjectParameter(model.name,
entry.getName()));
if (!shortMessage.equals(trimmedMessage)) {
WicketUtils.setHtmlTooltip(shortlog, shortMessage);
}
item.add(shortlog);
if (maxCount <= 0) {
Fragment fragment = new Fragment("branchLinks", "branchPageLinks", this);
fragment.add(new BookmarkablePageLink<Void>("log", LogPage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("tree", TreePage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("metrics", MetricsPage.class,
WicketUtils.newObjectParameter(model.name, entry.getName())));
fragment.add(new ExternalLink("syndication", SyndicationServlet.asLink(
getRequest().getRelativePathPrefixToContextRoot(), model.name,
entry.getName(), 0)));
item.add(fragment);
} else {
Fragment fragment = new Fragment("branchLinks", "branchPanelLinks", this);
fragment.add(new BookmarkablePageLink<Void>("log", LogPage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
fragment.add(new BookmarkablePageLink<Void>("tree", TreePage.class, WicketUtils
.newObjectParameter(model.name, entry.getName())));
item.add(fragment);
}
WicketUtils.setAlternatingBackground(item, counter);
counter++;
}
};
add(branchesView);
if (branches.size() < maxCount || maxCount <= 0) {
add(new Label("allBranches", "").setVisible(false));
} else {
add(new LinkPanel("allBranches", "link", new StringResourceModel("gb.allBranches",
this, null), BranchesPage.class, WicketUtils.newRepositoryParameter(model.name)));
}
// We always have 1 branch
hasBranches = (branches.size() > 1)
|| ((branches.size() == 1) && !branches.get(0).displayName
.equalsIgnoreCase("master"));
}
|
diff --git a/AttributesImpl/src/org/gephi/data/attributes/AttributeContollerImpl.java b/AttributesImpl/src/org/gephi/data/attributes/AttributeContollerImpl.java
index 3d4c6fa5d..6ebd0b30c 100644
--- a/AttributesImpl/src/org/gephi/data/attributes/AttributeContollerImpl.java
+++ b/AttributesImpl/src/org/gephi/data/attributes/AttributeContollerImpl.java
@@ -1,101 +1,104 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi 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.
Gephi 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 Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.data.attributes;
import org.gephi.data.attributes.api.AttributeController;
import org.gephi.data.attributes.api.AttributeModel;
import org.gephi.data.attributes.model.IndexedAttributeModel;
import org.gephi.data.attributes.model.TemporaryAttributeModel;
import org.gephi.project.api.ProjectController;
import org.gephi.project.api.WorkspaceProvider;
import org.gephi.project.api.Workspace;
import org.gephi.project.api.WorkspaceListener;
import org.openide.util.Lookup;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author Mathieu Bastian
*/
@ServiceProvider(service = AttributeController.class)
public class AttributeContollerImpl implements AttributeController {
private ProjectController projectController;
public AttributeContollerImpl() {
projectController = Lookup.getDefault().lookup(ProjectController.class);
projectController.addWorkspaceListener(new WorkspaceListener() {
public void initialize(Workspace workspace) {
- workspace.add(new IndexedAttributeModel());
+ AttributeModel m = workspace.getLookup().lookup(AttributeModel.class);
+ if (m == null) {
+ workspace.add(new IndexedAttributeModel());
+ }
}
public void select(Workspace workspace) {
}
public void unselect(Workspace workspace) {
}
public void close(Workspace workspace) {
}
public void disable() {
}
});
if (projectController.getCurrentProject() != null) {
for (Workspace workspace : projectController.getCurrentProject().getLookup().lookup(WorkspaceProvider.class).getWorkspaces()) {
AttributeModel m = workspace.getLookup().lookup(AttributeModel.class);
if (m == null) {
workspace.add(new IndexedAttributeModel());
}
}
}
}
public AttributeModel getModel() {
Workspace workspace = projectController.getCurrentWorkspace();
if (workspace != null) {
AttributeModel model = workspace.getLookup().lookup(AttributeModel.class);
if (model != null) {
return model;
}
model = new IndexedAttributeModel();
workspace.add(model);
return model;
}
return null;
}
public AttributeModel getModel(Workspace workspace) {
AttributeModel model = workspace.getLookup().lookup(AttributeModel.class);
if (model != null) {
return model;
}
model = new IndexedAttributeModel();
workspace.add(model);
return model;
}
public AttributeModel newModel() {
TemporaryAttributeModel model = new TemporaryAttributeModel();
return model;
}
}
| true | true | public AttributeContollerImpl() {
projectController = Lookup.getDefault().lookup(ProjectController.class);
projectController.addWorkspaceListener(new WorkspaceListener() {
public void initialize(Workspace workspace) {
workspace.add(new IndexedAttributeModel());
}
public void select(Workspace workspace) {
}
public void unselect(Workspace workspace) {
}
public void close(Workspace workspace) {
}
public void disable() {
}
});
if (projectController.getCurrentProject() != null) {
for (Workspace workspace : projectController.getCurrentProject().getLookup().lookup(WorkspaceProvider.class).getWorkspaces()) {
AttributeModel m = workspace.getLookup().lookup(AttributeModel.class);
if (m == null) {
workspace.add(new IndexedAttributeModel());
}
}
}
}
| public AttributeContollerImpl() {
projectController = Lookup.getDefault().lookup(ProjectController.class);
projectController.addWorkspaceListener(new WorkspaceListener() {
public void initialize(Workspace workspace) {
AttributeModel m = workspace.getLookup().lookup(AttributeModel.class);
if (m == null) {
workspace.add(new IndexedAttributeModel());
}
}
public void select(Workspace workspace) {
}
public void unselect(Workspace workspace) {
}
public void close(Workspace workspace) {
}
public void disable() {
}
});
if (projectController.getCurrentProject() != null) {
for (Workspace workspace : projectController.getCurrentProject().getLookup().lookup(WorkspaceProvider.class).getWorkspaces()) {
AttributeModel m = workspace.getLookup().lookup(AttributeModel.class);
if (m == null) {
workspace.add(new IndexedAttributeModel());
}
}
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionStatusPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionStatusPage.java
index 53898942d..c6c42232e 100644
--- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionStatusPage.java
+++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/p2/ui/dialogs/ResolutionStatusPage.java
@@ -1,227 +1,228 @@
/*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* EclipseSource - ongoing development
*******************************************************************************/
package org.eclipse.equinox.internal.p2.ui.dialogs;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.internal.p2.ui.ProvUIActivator;
import org.eclipse.equinox.internal.p2.ui.ProvUIMessages;
import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.internal.provisional.p2.ui.IUPropertyUtils;
import org.eclipse.equinox.internal.provisional.p2.ui.ProvUI;
import org.eclipse.equinox.internal.provisional.p2.ui.model.IUElementListRoot;
import org.eclipse.equinox.internal.provisional.p2.ui.operations.PlannerResolutionOperation;
import org.eclipse.equinox.internal.provisional.p2.ui.viewers.IUColumnConfig;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.ui.statushandlers.StatusManager;
/**
* A wizard page that presents a check box list of IUs and allows the user
* to select and deselect them. Typically the first page in a provisioning
* operation wizard, and usually it is the page used to report resolution errors
* before advancing to resolution detail.
*
* @since 3.5
*
*/
public abstract class ResolutionStatusPage extends ProvisioningWizardPage {
private static final String LIST_WEIGHT = "ListSashWeight"; //$NON-NLS-1$
private static final String DETAILS_WEIGHT = "DetailsSashWeight"; //$NON-NLS-1$
private static final String NAME_COLUMN_WIDTH = "NameColumnWidth"; //$NON-NLS-1$
private static final String VERSION_COLUMN_WIDTH = "VersionColumnWidth"; //$NON-NLS-1$
protected String profileId;
/**
* @param pageName
*/
protected ResolutionStatusPage(String pageName, String profileId) {
super(pageName);
this.profileId = profileId;
}
protected abstract void updateCaches(IUElementListRoot root, PlannerResolutionOperation resolvedOperation);
protected abstract boolean isCreated();
protected abstract IUDetailsGroup getDetailsGroup();
protected abstract IInstallableUnit getSelectedIU();
/**
* Update the status area of the wizard to report the results of the operation.
*
* @param newRoot the root that describes the root IUs involved in creating the plan
* @param op the PlannerResolutionOperation that describes the plan that was created.
* Should not be <code>null</code>, but subclasses can be more forgiving.
*/
public void updateStatus(IUElementListRoot newRoot, PlannerResolutionOperation op) {
Assert.isNotNull(op);
updateCaches(newRoot, op);
IStatus currentStatus;
int messageType = IMessageProvider.NONE;
boolean pageComplete = true;
currentStatus = op.getResolutionResult().getSummaryStatus();
if (currentStatus != null && !currentStatus.isOK()) {
messageType = IMessageProvider.INFORMATION;
int severity = currentStatus.getSeverity();
if (severity == IStatus.ERROR) {
messageType = IMessageProvider.ERROR;
pageComplete = false;
// Log errors for later support
ProvUI.reportStatus(currentStatus, StatusManager.LOG);
} else if (severity == IStatus.WARNING) {
messageType = IMessageProvider.WARNING;
// Log warnings for later support
ProvUI.reportStatus(currentStatus, StatusManager.LOG);
}
}
setPageComplete(pageComplete);
if (!isCreated())
return;
setMessage(getMessageText(currentStatus), messageType);
setDetailText(op);
}
protected String getIUDescription(IInstallableUnit iu) {
// Get the iu description in the default locale
String description = IUPropertyUtils.getIUProperty(iu, IInstallableUnit.PROP_DESCRIPTION);
if (description == null)
description = ""; //$NON-NLS-1$
return description;
}
String getMessageText(IStatus currentStatus) {
if (currentStatus == null || currentStatus.isOK())
return getDescription();
if (currentStatus.getSeverity() == IStatus.CANCEL)
return ProvUIMessages.ResolutionWizardPage_Canceled;
if (currentStatus.getSeverity() == IStatus.ERROR)
return ProvUIMessages.ResolutionWizardPage_ErrorStatus;
return ProvUIMessages.ResolutionWizardPage_WarningInfoStatus;
}
void setDetailText(PlannerResolutionOperation resolvedOperation) {
String detail = null;
IInstallableUnit selectedIU = getSelectedIU();
IUDetailsGroup detailsGroup = getDetailsGroup();
// We either haven't resolved, or we failed to resolve and reported some error
// while doing so. Since the specific error was already reported, the description
// text can be used for the selected IU.
if (resolvedOperation == null) {
if (selectedIU != null) {
detail = getIUDescription(selectedIU);
detailsGroup.enablePropertyLink(true);
} else {
detail = ""; //$NON-NLS-1$
detailsGroup.enablePropertyLink(false);
}
detailsGroup.getDetailsArea().setText(detail);
return;
}
// An IU is selected and we have resolved. Look for information about the specific IU.
if (selectedIU != null) {
detail = resolvedOperation.getResolutionResult().getDetailedReport(new IInstallableUnit[] {selectedIU});
if (detail != null) {
detailsGroup.enablePropertyLink(false);
detailsGroup.getDetailsArea().setText(detail);
return;
}
// No specific error about this IU. Show the overall error if it is in error.
if (resolvedOperation.getResolutionResult().getSummaryStatus().getSeverity() == IStatus.ERROR) {
detail = resolvedOperation.getResolutionResult().getSummaryReport();
detailsGroup.enablePropertyLink(false);
detailsGroup.getDetailsArea().setText(detail);
+ return;
}
// The overall status is not an error, so we may as well just show info about this iu rather than everything.
detailsGroup.enablePropertyLink(true);
detailsGroup.getDetailsArea().setText(getIUDescription(selectedIU));
return;
}
//No IU is selected, give the overall report
detail = resolvedOperation.getResolutionResult().getSummaryReport();
detailsGroup.enablePropertyLink(false);
if (detail == null)
detail = ""; //$NON-NLS-1$
detailsGroup.getDetailsArea().setText(detail);
}
protected abstract String getDialogSettingsName();
protected abstract SashForm getSashForm();
protected abstract IUColumnConfig getNameColumn();
protected abstract IUColumnConfig getVersionColumn();
protected abstract int getNameColumnWidth();
protected abstract int getVersionColumnWidth();
protected int[] getSashWeights() {
IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings();
IDialogSettings section = settings.getSection(getDialogSettingsName());
if (section != null) {
try {
int[] weights = new int[2];
if (section.get(LIST_WEIGHT) != null) {
weights[0] = section.getInt(LIST_WEIGHT);
if (section.get(DETAILS_WEIGHT) != null) {
weights[1] = section.getInt(DETAILS_WEIGHT);
return weights;
}
}
} catch (NumberFormatException e) {
// Ignore if there actually was a value that didn't parse.
}
}
return ILayoutConstants.IUS_TO_DETAILS_WEIGHTS;
}
protected void getColumnWidthsFromSettings() {
IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings();
IDialogSettings section = settings.getSection(getDialogSettingsName());
if (section != null) {
try {
if (section.get(NAME_COLUMN_WIDTH) != null)
getNameColumn().columnWidth = section.getInt(NAME_COLUMN_WIDTH);
if (section.get(VERSION_COLUMN_WIDTH) != null)
getVersionColumn().columnWidth = section.getInt(VERSION_COLUMN_WIDTH);
} catch (NumberFormatException e) {
// Ignore if there actually was a value that didn't parse.
}
}
}
public void saveBoundsRelatedSettings() {
if (!isCreated())
return;
IDialogSettings settings = ProvUIActivator.getDefault().getDialogSettings();
IDialogSettings section = settings.getSection(getDialogSettingsName());
if (section == null) {
section = settings.addNewSection(getDialogSettingsName());
}
section.put(NAME_COLUMN_WIDTH, getNameColumnWidth());
section.put(VERSION_COLUMN_WIDTH, getVersionColumnWidth());
int[] weights = getSashForm().getWeights();
section.put(LIST_WEIGHT, weights[0]);
section.put(DETAILS_WEIGHT, weights[1]);
}
}
| true | true | void setDetailText(PlannerResolutionOperation resolvedOperation) {
String detail = null;
IInstallableUnit selectedIU = getSelectedIU();
IUDetailsGroup detailsGroup = getDetailsGroup();
// We either haven't resolved, or we failed to resolve and reported some error
// while doing so. Since the specific error was already reported, the description
// text can be used for the selected IU.
if (resolvedOperation == null) {
if (selectedIU != null) {
detail = getIUDescription(selectedIU);
detailsGroup.enablePropertyLink(true);
} else {
detail = ""; //$NON-NLS-1$
detailsGroup.enablePropertyLink(false);
}
detailsGroup.getDetailsArea().setText(detail);
return;
}
// An IU is selected and we have resolved. Look for information about the specific IU.
if (selectedIU != null) {
detail = resolvedOperation.getResolutionResult().getDetailedReport(new IInstallableUnit[] {selectedIU});
if (detail != null) {
detailsGroup.enablePropertyLink(false);
detailsGroup.getDetailsArea().setText(detail);
return;
}
// No specific error about this IU. Show the overall error if it is in error.
if (resolvedOperation.getResolutionResult().getSummaryStatus().getSeverity() == IStatus.ERROR) {
detail = resolvedOperation.getResolutionResult().getSummaryReport();
detailsGroup.enablePropertyLink(false);
detailsGroup.getDetailsArea().setText(detail);
}
// The overall status is not an error, so we may as well just show info about this iu rather than everything.
detailsGroup.enablePropertyLink(true);
detailsGroup.getDetailsArea().setText(getIUDescription(selectedIU));
return;
}
//No IU is selected, give the overall report
detail = resolvedOperation.getResolutionResult().getSummaryReport();
detailsGroup.enablePropertyLink(false);
if (detail == null)
detail = ""; //$NON-NLS-1$
detailsGroup.getDetailsArea().setText(detail);
}
| void setDetailText(PlannerResolutionOperation resolvedOperation) {
String detail = null;
IInstallableUnit selectedIU = getSelectedIU();
IUDetailsGroup detailsGroup = getDetailsGroup();
// We either haven't resolved, or we failed to resolve and reported some error
// while doing so. Since the specific error was already reported, the description
// text can be used for the selected IU.
if (resolvedOperation == null) {
if (selectedIU != null) {
detail = getIUDescription(selectedIU);
detailsGroup.enablePropertyLink(true);
} else {
detail = ""; //$NON-NLS-1$
detailsGroup.enablePropertyLink(false);
}
detailsGroup.getDetailsArea().setText(detail);
return;
}
// An IU is selected and we have resolved. Look for information about the specific IU.
if (selectedIU != null) {
detail = resolvedOperation.getResolutionResult().getDetailedReport(new IInstallableUnit[] {selectedIU});
if (detail != null) {
detailsGroup.enablePropertyLink(false);
detailsGroup.getDetailsArea().setText(detail);
return;
}
// No specific error about this IU. Show the overall error if it is in error.
if (resolvedOperation.getResolutionResult().getSummaryStatus().getSeverity() == IStatus.ERROR) {
detail = resolvedOperation.getResolutionResult().getSummaryReport();
detailsGroup.enablePropertyLink(false);
detailsGroup.getDetailsArea().setText(detail);
return;
}
// The overall status is not an error, so we may as well just show info about this iu rather than everything.
detailsGroup.enablePropertyLink(true);
detailsGroup.getDetailsArea().setText(getIUDescription(selectedIU));
return;
}
//No IU is selected, give the overall report
detail = resolvedOperation.getResolutionResult().getSummaryReport();
detailsGroup.enablePropertyLink(false);
if (detail == null)
detail = ""; //$NON-NLS-1$
detailsGroup.getDetailsArea().setText(detail);
}
|
diff --git a/src/org/gots/ui/LoginActivity.java b/src/org/gots/ui/LoginActivity.java
index e2b6bbaa..2b6be771 100644
--- a/src/org/gots/ui/LoginActivity.java
+++ b/src/org/gots/ui/LoginActivity.java
@@ -1,421 +1,421 @@
package org.gots.ui;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.gots.R;
import org.gots.garden.provider.nuxeo.NuxeoGardenProvider;
import org.gots.preferences.GotsPreferences;
import org.nuxeo.ecm.automation.client.jaxrs.Constants;
import org.nuxeo.ecm.automation.client.jaxrs.Session;
import org.nuxeo.ecm.automation.client.jaxrs.impl.HttpAutomationClient;
import org.nuxeo.ecm.automation.client.jaxrs.model.Documents;
import org.nuxeo.ecm.automation.client.jaxrs.spi.auth.TokenRequestInterceptor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Base64;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
public class LoginActivity extends AbstractActivity {
private TextView loginText;
private TextView passwordText;
// String myToken = GotsPreferences.getInstance(this).getToken();
// String myLogin = GotsPreferences.getInstance(this).getNUXEO_LOGIN();
// String myPassword =
// GotsPreferences.getInstance(this).getNUXEO_PASSWORD();
// String myDeviceId = GotsPreferences.getInstance(this).getDeviceId();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setTitle(R.string.app_name);
}
@Override
protected void onResume() {
super.onResume();
loginText = (TextView) findViewById(R.id.edittextLogin);
loginText.setText(GotsPreferences.getInstance(this).getNuxeoLogin());
passwordText = (TextView) findViewById(R.id.edittextPassword);
passwordText.setText(GotsPreferences.getInstance(this).getNuxeoPassword());
LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.idLayoutConnection);
buttonLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(LoginActivity.this,
getResources().getString(R.string.feature_unavalaible),
Toast.LENGTH_SHORT).show();
// launchGoogle();
// tokenNuxeoConnect();
// finish();
}
});
Button connect = (Button) findViewById(R.id.buttonConnect);
connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String login = loginText.getText().toString();
String password = passwordText.getText().toString();
if ("".equals(login) || "".equals(password))
Toast.makeText(
LoginActivity.this,
getResources().getString(
R.string.login_missinginformation),
Toast.LENGTH_SHORT).show();
else {
basicNuxeoConnect(login, password);
//TODO test if connexion is OK, then finish, else ask for login modification
// new NuxeoGardenProvider(LoginActivity.this);
finish();
}
}
protected void basicNuxeoConnect(String login, String password) {
String device_id = getDeviceID();
GotsPreferences.getInstance(LoginActivity.this).setDeviceId(
device_id);
String token = request_basicauth_token(false);
if (token == null) {
Toast.makeText(LoginActivity.this, "Error logging",
Toast.LENGTH_SHORT).show();
} else {
GotsPreferences.getInstance(LoginActivity.this).setToken(
token);
GotsPreferences.getInstance(LoginActivity.this).setNuxeoLogin(
login);
GotsPreferences.getInstance(LoginActivity.this).setNuxeoPassword(
password);
GotsPreferences.getInstance(LoginActivity.this).setConnectedToServer(
true);
}
}
});
}
protected String getDeviceID() {
String device_id = Secure.getString(getContentResolver(),
Secure.ANDROID_ID);
return device_id;
}
protected void tokenNuxeoConnect() {
String device_id = getDeviceID();
GotsPreferences.getInstance(LoginActivity.this).setDeviceId(device_id);
String tmp_token = request_temporaryauth_token(false);
if (tmp_token == null) {
Toast.makeText(LoginActivity.this, "Authentication ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, tmp_token, Toast.LENGTH_SHORT).show();
}
}
public String request_temporaryauth_token(boolean revoke) {
AsyncTask<Object, Void, String> task = new AsyncTask<Object, Void, String>() {
String token = null;
@Override
protected String doInBackground(Object... objects) {
try {
String email = "[email protected]";
HttpAutomationClient client = new HttpAutomationClient(
- GotsPreferences.getGardeningManagerServerURI());
+ GotsPreferences.getGardeningManagerServerURI()+"/site/automation");
client.setRequestInterceptor(new TokenRequestInterceptor(
"myApp",
"myToken",
"myLogin",
GotsPreferences.getInstance(LoginActivity.this).getDeviceId()));
Session session = client.getSession();
Documents docs = (Documents) session.newRequest(
"Document.Email").setHeader(
Constants.HEADER_NX_SCHEMAS, "*").set("email",
email).execute();
// String uri =
// GotsPreferences.getInstance(getApplicationContext())
// .getGardeningManagerNuxeoAuthentication();
//
// List<NameValuePair> params = new
// LinkedList<NameValuePair>();
// params.add(new BasicNameValuePair("deviceId",
// GotsPreferences.getInstance(getApplicationContext())
// .getDeviceId()));
// params.add(new BasicNameValuePair("applicationName",
// GotsPreferences.getInstance(
// getApplicationContext()).getGardeningManagerAppname()));
// params.add(new BasicNameValuePair("deviceDescription",
// Build.MODEL + "(" + Build.MANUFACTURER +
// ")"));
// params.add(new BasicNameValuePair("permission",
// "ReadWrite"));
// params.add(new BasicNameValuePair("revoke", "false"));
//
// String paramString = URLEncodedUtils.format(params,
// "utf-8");
// uri += paramString;
// URL url = new URL(uri);
//
// URLConnection urlConnection;
// urlConnection = url.openConnection();
//
// urlConnection.addRequestProperty("X-User-Id",
// loginText.getText().toString());
// urlConnection.addRequestProperty("X-Device-Id",
// GotsPreferences
// .getInstance(getApplicationContext()).getDeviceId());
// urlConnection.addRequestProperty("X-Application-Name",
// GotsPreferences.getInstance(getApplicationContext()).getGardeningManagerAppname());
// urlConnection.addRequestProperty(
// "Authorization",
// "Basic "
// + Base64.encodeToString((loginText.getText().toString() +
// ":" + passwordText
// .getText().toString()).getBytes(), Base64.NO_WRAP));
// urlConnection.addRequestProperty(
// "Authorization",
// "Basic "
// + Base64.encodeBase64((loginText.getText().toString() +
// ":" + passwordText.getText()
// .toString()).getBytes()));
// InputStream in = new
// BufferedInputStream(urlConnection.getInputStream());
// try {
// // readStream(in);
// StringBuilder builder = new StringBuilder();
// String line;
// BufferedReader reader = new BufferedReader(new
// InputStreamReader(in, "UTF-8"));
// while ((line = reader.readLine()) != null) {
// builder.append(line);
// }
//
// token = builder.toString();
// Log.d("LoginActivity", "Token acquired: " + token);
//
// } finally {
// in.close();
// }
} catch (IOException e) {
Log.e("LoginActivity", e.getMessage(), e);
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return token;
}
}.execute(new Object());
String tokenAcquired = null;
try {
tokenAcquired = task.get();
} catch (InterruptedException e) {
Log.e("LoginActivity", e.getMessage(), e);
} catch (ExecutionException e) {
Log.e("LoginActivity", e.getMessage(), e);
}
return tokenAcquired;
}
public String request_basicauth_token(boolean revoke) {
AsyncTask<Object, Void, String> task = new AsyncTask<Object, Void, String>() {
String token = null;
@Override
protected String doInBackground(Object... objects) {
try {
String uri = GotsPreferences.getInstance(
getApplicationContext()).getGardeningManagerNuxeoAuthentication();
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair(
"deviceId",
GotsPreferences.getInstance(getApplicationContext()).getDeviceId()));
params.add(new BasicNameValuePair(
"applicationName",
GotsPreferences.getInstance(getApplicationContext()).getGardeningManagerAppname()));
params.add(new BasicNameValuePair("deviceDescription",
Build.MODEL + "(" + Build.MANUFACTURER + ")"));
params.add(new BasicNameValuePair("permission", "ReadWrite"));
params.add(new BasicNameValuePair("revoke", "false"));
String paramString = URLEncodedUtils.format(params, "utf-8");
uri += paramString;
URL url = new URL(uri);
URLConnection urlConnection;
urlConnection = url.openConnection();
urlConnection.addRequestProperty("X-User-Id",
loginText.getText().toString());
urlConnection.addRequestProperty(
"X-Device-Id",
GotsPreferences.getInstance(getApplicationContext()).getDeviceId());
urlConnection.addRequestProperty(
"X-Application-Name",
GotsPreferences.getInstance(getApplicationContext()).getGardeningManagerAppname());
urlConnection.addRequestProperty(
"Authorization",
"Basic "
+ Base64.encodeToString(
(loginText.getText().toString()
+ ":" + passwordText.getText().toString()).getBytes(),
Base64.NO_WRAP));
// urlConnection.addRequestProperty(
// "Authorization",
// "Basic "
// + Base64.encodeBase64((loginText.getText().toString() +
// ":" + passwordText.getText()
// .toString()).getBytes()));
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
try {
// readStream(in);
StringBuilder builder = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
token = builder.toString();
Log.d("LoginActivity", "Token acquired: " + token);
} finally {
in.close();
}
} catch (IOException e) {
Log.e("LoginActivity", e.getMessage(), e);
return null;
}
return token;
}
}.execute(new Object());
String tokenAcquired = null;
try {
tokenAcquired = task.get();
} catch (InterruptedException e) {
Log.e("LoginActivity", e.getMessage(), e);
} catch (ExecutionException e) {
Log.e("LoginActivity", e.getMessage(), e);
}
return tokenAcquired;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
// case R.id.help:
// Intent browserIntent = new Intent(Intent.ACTION_VIEW,
// Uri.parse(HelpUriBuilder.getUri(getClass()
// .getSimpleName())));
// startActivity(browserIntent);
//
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
void launchGoogle() {
// // if (isChecked) {
// // loginBox.setVisibility(View.VISIBLE);
// //
// // // Create an instance of SocialAuthConfgi object
// SocialAuthConfig config = SocialAuthConfig.getDefault();
// //
// // // load configuration. By default load the configuration
// // // from oauth_consumer.properties.
// // // You can also pass input stream, properties object or
// // // properties file name.
// try {
// config.load();
//
// // Create an instance of SocialAuthManager and set
// // config
// SocialAuthManager manager = new SocialAuthManager();
// manager.setSocialAuthConfig(config);
//
// // URL of YOUR application which will be called after
// // authentication
// String successUrl =
// "http://srv2.gardening-manager.com:8090/nuxeo/nxstartup.faces?provider=GoogleOpenIDConnect";
//
// // get Provider URL to which you should redirect for
// // authentication.
// // id can have values "facebook", "twitter", "yahoo"
// // etc. or the OpenID URL
// String url = manager.getAuthenticationUrl("google",
// successUrl);
//
// // Store in session
// // session.setAttribute("authManager", manager);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
| true | true | public String request_temporaryauth_token(boolean revoke) {
AsyncTask<Object, Void, String> task = new AsyncTask<Object, Void, String>() {
String token = null;
@Override
protected String doInBackground(Object... objects) {
try {
String email = "[email protected]";
HttpAutomationClient client = new HttpAutomationClient(
GotsPreferences.getGardeningManagerServerURI());
client.setRequestInterceptor(new TokenRequestInterceptor(
"myApp",
"myToken",
"myLogin",
GotsPreferences.getInstance(LoginActivity.this).getDeviceId()));
Session session = client.getSession();
Documents docs = (Documents) session.newRequest(
"Document.Email").setHeader(
Constants.HEADER_NX_SCHEMAS, "*").set("email",
email).execute();
// String uri =
// GotsPreferences.getInstance(getApplicationContext())
// .getGardeningManagerNuxeoAuthentication();
//
// List<NameValuePair> params = new
// LinkedList<NameValuePair>();
// params.add(new BasicNameValuePair("deviceId",
// GotsPreferences.getInstance(getApplicationContext())
// .getDeviceId()));
// params.add(new BasicNameValuePair("applicationName",
// GotsPreferences.getInstance(
// getApplicationContext()).getGardeningManagerAppname()));
// params.add(new BasicNameValuePair("deviceDescription",
// Build.MODEL + "(" + Build.MANUFACTURER +
// ")"));
// params.add(new BasicNameValuePair("permission",
// "ReadWrite"));
// params.add(new BasicNameValuePair("revoke", "false"));
//
// String paramString = URLEncodedUtils.format(params,
// "utf-8");
// uri += paramString;
// URL url = new URL(uri);
//
// URLConnection urlConnection;
// urlConnection = url.openConnection();
//
// urlConnection.addRequestProperty("X-User-Id",
// loginText.getText().toString());
// urlConnection.addRequestProperty("X-Device-Id",
// GotsPreferences
// .getInstance(getApplicationContext()).getDeviceId());
// urlConnection.addRequestProperty("X-Application-Name",
// GotsPreferences.getInstance(getApplicationContext()).getGardeningManagerAppname());
// urlConnection.addRequestProperty(
// "Authorization",
// "Basic "
// + Base64.encodeToString((loginText.getText().toString() +
// ":" + passwordText
// .getText().toString()).getBytes(), Base64.NO_WRAP));
// urlConnection.addRequestProperty(
// "Authorization",
// "Basic "
// + Base64.encodeBase64((loginText.getText().toString() +
// ":" + passwordText.getText()
// .toString()).getBytes()));
// InputStream in = new
// BufferedInputStream(urlConnection.getInputStream());
// try {
// // readStream(in);
// StringBuilder builder = new StringBuilder();
// String line;
// BufferedReader reader = new BufferedReader(new
// InputStreamReader(in, "UTF-8"));
// while ((line = reader.readLine()) != null) {
// builder.append(line);
// }
//
// token = builder.toString();
// Log.d("LoginActivity", "Token acquired: " + token);
//
// } finally {
// in.close();
// }
} catch (IOException e) {
Log.e("LoginActivity", e.getMessage(), e);
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return token;
}
}.execute(new Object());
String tokenAcquired = null;
try {
tokenAcquired = task.get();
} catch (InterruptedException e) {
Log.e("LoginActivity", e.getMessage(), e);
} catch (ExecutionException e) {
Log.e("LoginActivity", e.getMessage(), e);
}
return tokenAcquired;
}
| public String request_temporaryauth_token(boolean revoke) {
AsyncTask<Object, Void, String> task = new AsyncTask<Object, Void, String>() {
String token = null;
@Override
protected String doInBackground(Object... objects) {
try {
String email = "[email protected]";
HttpAutomationClient client = new HttpAutomationClient(
GotsPreferences.getGardeningManagerServerURI()+"/site/automation");
client.setRequestInterceptor(new TokenRequestInterceptor(
"myApp",
"myToken",
"myLogin",
GotsPreferences.getInstance(LoginActivity.this).getDeviceId()));
Session session = client.getSession();
Documents docs = (Documents) session.newRequest(
"Document.Email").setHeader(
Constants.HEADER_NX_SCHEMAS, "*").set("email",
email).execute();
// String uri =
// GotsPreferences.getInstance(getApplicationContext())
// .getGardeningManagerNuxeoAuthentication();
//
// List<NameValuePair> params = new
// LinkedList<NameValuePair>();
// params.add(new BasicNameValuePair("deviceId",
// GotsPreferences.getInstance(getApplicationContext())
// .getDeviceId()));
// params.add(new BasicNameValuePair("applicationName",
// GotsPreferences.getInstance(
// getApplicationContext()).getGardeningManagerAppname()));
// params.add(new BasicNameValuePair("deviceDescription",
// Build.MODEL + "(" + Build.MANUFACTURER +
// ")"));
// params.add(new BasicNameValuePair("permission",
// "ReadWrite"));
// params.add(new BasicNameValuePair("revoke", "false"));
//
// String paramString = URLEncodedUtils.format(params,
// "utf-8");
// uri += paramString;
// URL url = new URL(uri);
//
// URLConnection urlConnection;
// urlConnection = url.openConnection();
//
// urlConnection.addRequestProperty("X-User-Id",
// loginText.getText().toString());
// urlConnection.addRequestProperty("X-Device-Id",
// GotsPreferences
// .getInstance(getApplicationContext()).getDeviceId());
// urlConnection.addRequestProperty("X-Application-Name",
// GotsPreferences.getInstance(getApplicationContext()).getGardeningManagerAppname());
// urlConnection.addRequestProperty(
// "Authorization",
// "Basic "
// + Base64.encodeToString((loginText.getText().toString() +
// ":" + passwordText
// .getText().toString()).getBytes(), Base64.NO_WRAP));
// urlConnection.addRequestProperty(
// "Authorization",
// "Basic "
// + Base64.encodeBase64((loginText.getText().toString() +
// ":" + passwordText.getText()
// .toString()).getBytes()));
// InputStream in = new
// BufferedInputStream(urlConnection.getInputStream());
// try {
// // readStream(in);
// StringBuilder builder = new StringBuilder();
// String line;
// BufferedReader reader = new BufferedReader(new
// InputStreamReader(in, "UTF-8"));
// while ((line = reader.readLine()) != null) {
// builder.append(line);
// }
//
// token = builder.toString();
// Log.d("LoginActivity", "Token acquired: " + token);
//
// } finally {
// in.close();
// }
} catch (IOException e) {
Log.e("LoginActivity", e.getMessage(), e);
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return token;
}
}.execute(new Object());
String tokenAcquired = null;
try {
tokenAcquired = task.get();
} catch (InterruptedException e) {
Log.e("LoginActivity", e.getMessage(), e);
} catch (ExecutionException e) {
Log.e("LoginActivity", e.getMessage(), e);
}
return tokenAcquired;
}
|
diff --git a/src/input/CSVParser.java b/src/input/CSVParser.java
index 1460a41..4554c8d 100644
--- a/src/input/CSVParser.java
+++ b/src/input/CSVParser.java
@@ -1,61 +1,62 @@
package input;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import knapsackj.Item;
import knapsackj.ItemCollection;
/**
* Parses a CSV file. Found from StackOverflow. Adapted for my needs.
* @source http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-in-java
* @author peter-lawrey
* @author tcc10a
*/
public class CSVParser
{
String file;
public CSVParser(String filename)
{
file = filename;
}
public ItemCollection parse()
{
int cap = -1;
ArrayList<Item> items = new ArrayList<Item>();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
boolean first = true;
while ((line = br.readLine()) != null) {
// process the line.
String[] strArr=line.split(",");
if (first)
{
cap = Integer.parseInt(strArr[0]);
+ first = false;
} else {
int weight = Integer.parseInt(strArr[0]);
int value = Integer.parseInt(strArr[1]);
String name = strArr[2];
Item temp = new Item(weight,value,name);
items.add(temp);
}
}
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CSVParser.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
System.err.println("An error ocurred while processing the CSV file!");
}
ItemCollection ic = new ItemCollection(items, cap);
return ic;
}
}
| true | true | public ItemCollection parse()
{
int cap = -1;
ArrayList<Item> items = new ArrayList<Item>();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
boolean first = true;
while ((line = br.readLine()) != null) {
// process the line.
String[] strArr=line.split(",");
if (first)
{
cap = Integer.parseInt(strArr[0]);
} else {
int weight = Integer.parseInt(strArr[0]);
int value = Integer.parseInt(strArr[1]);
String name = strArr[2];
Item temp = new Item(weight,value,name);
items.add(temp);
}
}
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CSVParser.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
System.err.println("An error ocurred while processing the CSV file!");
}
ItemCollection ic = new ItemCollection(items, cap);
return ic;
}
| public ItemCollection parse()
{
int cap = -1;
ArrayList<Item> items = new ArrayList<Item>();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
boolean first = true;
while ((line = br.readLine()) != null) {
// process the line.
String[] strArr=line.split(",");
if (first)
{
cap = Integer.parseInt(strArr[0]);
first = false;
} else {
int weight = Integer.parseInt(strArr[0]);
int value = Integer.parseInt(strArr[1]);
String name = strArr[2];
Item temp = new Item(weight,value,name);
items.add(temp);
}
}
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CSVParser.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
System.err.println("An error ocurred while processing the CSV file!");
}
ItemCollection ic = new ItemCollection(items, cap);
return ic;
}
|
diff --git a/easysoa-registry/easysoa-registry-rest-miner/src/main/java/org/easysoa/records/filters/ExchangeRecordServletFilterImpl.java b/easysoa-registry/easysoa-registry-rest-miner/src/main/java/org/easysoa/records/filters/ExchangeRecordServletFilterImpl.java
index d7d9cc5d..b8703f3f 100644
--- a/easysoa-registry/easysoa-registry-rest-miner/src/main/java/org/easysoa/records/filters/ExchangeRecordServletFilterImpl.java
+++ b/easysoa-registry/easysoa-registry-rest-miner/src/main/java/org/easysoa/records/filters/ExchangeRecordServletFilterImpl.java
@@ -1,142 +1,142 @@
/**
* EasySOA Registry Rest Miner
* Copyright 2011 Open Wide
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact : [email protected]
*/
package org.easysoa.records.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.easysoa.frascati.api.FraSCAtiServiceItf;
import org.easysoa.frascati.api.FraSCAtiServiceProviderItf;
import org.easysoa.servlet.http.HttpMessageRequestWrapper;
import org.easysoa.servlet.http.HttpMessageResponseWrapper;
import org.nuxeo.runtime.api.Framework;
import com.openwide.easysoa.exchangehandler.HttpExchangeHandler;
import com.openwide.easysoa.run.RunManager;
/**
* Servlet filter to record exchanges in Easysoa.
*
* @author jguillemotte, mkalam-alami
*
*/
public class ExchangeRecordServletFilterImpl implements Filter, ExchangeRecordServletFilter {
// Logger
private static Logger logger = Logger.getLogger(ExchangeRecordServletFilterImpl.class);
// Singleton
private static ExchangeRecordServletFilterImpl singleton = null;
// Exchange handler
private HttpExchangeHandler exchangeHandler = null;
/**
* Initialize the filter
*/
//@Override
public void init(FilterConfig filterConfig) throws ServletException {
singleton = this;
// Registering the event receiver
try {
FraSCAtiServiceItf frascati = Framework.getLocalService(FraSCAtiServiceProviderItf.class).getFraSCAtiService();
RunManager runManager = frascati.getService("httpDiscoveryProxy/runManagerComponent", "runManagerService", RunManager.class);
runManager.addEventReceiver(new ExchangeRecordServletFilterEventReceiver());
} catch (Exception ex) {
logger.error("Unable to register the ExchangeRecordServletFilterEventReceiver in the run manager", ex);
}
}
/**
* Process the filter
*/
//@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
- logger.info("Filtering a EasySOA API request");
if (exchangeHandler != null) {
+ logger.info("Filtering a EasySOA API request");
response = new HttpMessageResponseWrapper((HttpServletResponse) response);
}
// Let the request continue
chain.doFilter(request, response);
// Forward to the exchange handler
if (exchangeHandler != null) {
// Filtering HTTP requests only for registering exchanges
if (request instanceof HttpServletRequest) {
try {
exchangeHandler.handleExchange((HttpServletRequest) request, (HttpServletResponse) response);
} catch (Exception e) {
logger.error("An error occurred during the exchange handling", e);
}
}
}
}
/**
* Destroy the filter
*/
//@Override
public void destroy() {
// Nothing to do
}
/**
* Start the mining
*/
public void start(HttpExchangeHandler exchangeHandler)
throws Exception {
// NOTE: We probably can't make start() and stop() static
// as the caller will be in a separate classloader.
if (singleton != null) {
logger.info("Starting mining with handler " + exchangeHandler.toString());
singleton.exchangeHandler = exchangeHandler;
}
else {
logger.warn("Can't start mining, the filter is not ready yet");
}
}
/**
* Stop the mining
*/
public void stop() {
if (singleton != null) {
logger.info("Stopping mining");
singleton.exchangeHandler = null;
}
else {
logger.info("Nothing to stop, the filter is not ready yet");
}
}
}
| false | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("Filtering a EasySOA API request");
if (exchangeHandler != null) {
response = new HttpMessageResponseWrapper((HttpServletResponse) response);
}
// Let the request continue
chain.doFilter(request, response);
// Forward to the exchange handler
if (exchangeHandler != null) {
// Filtering HTTP requests only for registering exchanges
if (request instanceof HttpServletRequest) {
try {
exchangeHandler.handleExchange((HttpServletRequest) request, (HttpServletResponse) response);
} catch (Exception e) {
logger.error("An error occurred during the exchange handling", e);
}
}
}
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (exchangeHandler != null) {
logger.info("Filtering a EasySOA API request");
response = new HttpMessageResponseWrapper((HttpServletResponse) response);
}
// Let the request continue
chain.doFilter(request, response);
// Forward to the exchange handler
if (exchangeHandler != null) {
// Filtering HTTP requests only for registering exchanges
if (request instanceof HttpServletRequest) {
try {
exchangeHandler.handleExchange((HttpServletRequest) request, (HttpServletResponse) response);
} catch (Exception e) {
logger.error("An error occurred during the exchange handling", e);
}
}
}
}
|
diff --git a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
index c80267b94..45621e560 100644
--- a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
+++ b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
@@ -1,334 +1,335 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.inputmethod;
import com.android.settings.R;
import com.android.settings.Settings.SpellCheckersSettingsActivity;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.UserDictionarySettings;
import com.android.settings.Utils;
import com.android.settings.VoiceInputOutputSettings;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.provider.Settings.System;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class InputMethodAndLanguageSettings extends SettingsPreferenceFragment
implements Preference.OnPreferenceChangeListener{
private static final String KEY_PHONE_LANGUAGE = "phone_language";
private static final String KEY_CURRENT_INPUT_METHOD = "current_input_method";
private static final String KEY_INPUT_METHOD_SELECTOR = "input_method_selector";
private static final String KEY_USER_DICTIONARY_SETTINGS = "key_user_dictionary_settings";
// false: on ICS or later
private static final boolean SHOW_INPUT_METHOD_SWITCHER_SETTINGS = false;
private static final String[] sSystemSettingNames = {
System.TEXT_AUTO_REPLACE, System.TEXT_AUTO_CAPS, System.TEXT_AUTO_PUNCTUATE,
};
private static final String[] sHardKeyboardKeys = {
"auto_replace", "auto_caps", "auto_punctuate",
};
private int mDefaultInputMethodSelectorVisibility = 0;
private ListPreference mShowInputMethodSelectorPref;
private Preference mLanguagePref;
private ArrayList<InputMethodPreference> mInputMethodPreferenceList =
new ArrayList<InputMethodPreference>();
private boolean mHaveHardKeyboard;
private PreferenceCategory mHardKeyboardCategory;
private InputMethodManager mImm;
private List<InputMethodInfo> mImis;
private boolean mIsOnlyImeSettings;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_settings);
try {
mDefaultInputMethodSelectorVisibility = Integer.valueOf(
getString(R.string.input_method_selector_visibility_default_value));
} catch (NumberFormatException e) {
}
if (getActivity().getAssets().getLocales().length == 1) {
// No "Select language" pref if there's only one system locale available.
getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE));
} else {
mLanguagePref = findPreference(KEY_PHONE_LANGUAGE);
}
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref = (ListPreference)findPreference(
KEY_INPUT_METHOD_SELECTOR);
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
// TODO: Update current input method name on summary
updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility());
}
new VoiceInputOutputSettings(this).onCreate();
// Hard keyboard
final Configuration config = getResources().getConfiguration();
mHaveHardKeyboard = (config.keyboard == Configuration.KEYBOARD_QWERTY);
// IME
mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals(
getActivity().getIntent().getAction());
+ getActivity().getIntent().setAction(null);
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImis = mImm.getInputMethodList();
createImePreferenceHierarchy((PreferenceGroup)findPreference("keyboard_settings_category"));
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(getActivity(), SpellCheckersSettingsActivity.class);
final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference(
"spellcheckers_settings"));
if (scp != null) {
scp.setFragmentIntent(this, intent);
}
}
private void updateInputMethodSelectorSummary(int value) {
String[] inputMethodSelectorTitles = getResources().getStringArray(
R.array.input_method_selector_titles);
if (inputMethodSelectorTitles.length > value) {
mShowInputMethodSelectorPref.setSummary(inputMethodSelectorTitles[value]);
mShowInputMethodSelectorPref.setValue(String.valueOf(value));
}
}
private void updateUserDictionaryPreference(Preference userDictionaryPreference) {
final Activity activity = getActivity();
final Set<String> localeList = UserDictionaryList.getUserDictionaryLocalesList(activity);
if (null == localeList) {
// The locale list is null if and only if the user dictionary service is
// not present or disabled. In this case we need to remove the preference.
((PreferenceGroup)findPreference("language_settings_category")).removePreference(
userDictionaryPreference);
} else if (localeList.size() <= 1) {
userDictionaryPreference.setTitle(R.string.user_dict_single_settings_title);
userDictionaryPreference.setFragment(UserDictionarySettings.class.getName());
// If the size of localeList is 0, we don't set the locale parameter in the
// extras. This will be interpreted by the UserDictionarySettings class as
// meaning "the current locale".
// Note that with the current code for UserDictionaryList#getUserDictionaryLocalesList()
// the locale list always has at least one element, since it always includes the current
// locale explicitly. @see UserDictionaryList.getUserDictionaryLocalesList().
if (localeList.size() == 1) {
final String locale = (String)localeList.toArray()[0];
userDictionaryPreference.getExtras().putString("locale", locale);
}
} else {
userDictionaryPreference.setTitle(R.string.user_dict_multiple_settings_title);
userDictionaryPreference.setFragment(UserDictionaryList.class.getName());
}
}
@Override
public void onResume() {
super.onResume();
if (!mIsOnlyImeSettings) {
if (mLanguagePref != null) {
Configuration conf = getResources().getConfiguration();
String locale = conf.locale.getDisplayName(conf.locale);
if (locale != null && locale.length() > 1) {
locale = Character.toUpperCase(locale.charAt(0)) + locale.substring(1);
mLanguagePref.setSummary(locale);
}
}
updateUserDictionaryPreference(findPreference(KEY_USER_DICTIONARY_SETTINGS));
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
}
}
// Hard keyboard
if (mHaveHardKeyboard) {
for (int i = 0; i < sHardKeyboardKeys.length; ++i) {
CheckBoxPreference chkPref = (CheckBoxPreference)
mHardKeyboardCategory.findPreference(sHardKeyboardKeys[i]);
chkPref.setChecked(
System.getInt(getContentResolver(), sSystemSettingNames[i], 1) > 0);
}
}
// IME
InputMethodAndSubtypeUtil.loadInputMethodSubtypeList(
this, getContentResolver(), mImis, null);
updateActiveInputMethodsSummary();
}
@Override
public void onPause() {
super.onPause();
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(null);
}
InputMethodAndSubtypeUtil.saveInputMethodSubtypeList(
this, getContentResolver(), mImis, mHaveHardKeyboard);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
// Input Method stuff
if (Utils.isMonkeyRunning()) {
return false;
}
if (preference instanceof PreferenceScreen) {
if (preference.getFragment() != null) {
// Fragment will be handled correctly by the super class.
} else if (KEY_CURRENT_INPUT_METHOD.equals(preference.getKey())) {
final InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showInputMethodPicker();
}
} else if (preference instanceof CheckBoxPreference) {
final CheckBoxPreference chkPref = (CheckBoxPreference) preference;
if (mHaveHardKeyboard) {
for (int i = 0; i < sHardKeyboardKeys.length; ++i) {
if (chkPref == mHardKeyboardCategory.findPreference(sHardKeyboardKeys[i])) {
System.putInt(getContentResolver(), sSystemSettingNames[i],
chkPref.isChecked() ? 1 : 0);
return true;
}
}
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
private void saveInputMethodSelectorVisibility(String value) {
try {
int intValue = Integer.valueOf(value);
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.INPUT_METHOD_SELECTOR_VISIBILITY, intValue);
updateInputMethodSelectorSummary(intValue);
} catch(NumberFormatException e) {
}
}
private int loadInputMethodSelectorVisibility() {
return Settings.Secure.getInt(getContentResolver(),
Settings.Secure.INPUT_METHOD_SELECTOR_VISIBILITY,
mDefaultInputMethodSelectorVisibility);
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
if (preference == mShowInputMethodSelectorPref) {
if (value instanceof String) {
saveInputMethodSelectorVisibility((String)value);
}
}
}
return false;
}
private void updateActiveInputMethodsSummary() {
for (Preference pref : mInputMethodPreferenceList) {
if (pref instanceof InputMethodPreference) {
((InputMethodPreference)pref).updateSummary();
}
}
}
private InputMethodPreference getInputMethodPreference(InputMethodInfo imi, int imiSize) {
final PackageManager pm = getPackageManager();
final CharSequence label = imi.loadLabel(pm);
// IME settings
final Intent intent;
final String settingsActivity = imi.getSettingsActivity();
if (!TextUtils.isEmpty(settingsActivity)) {
intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName(imi.getPackageName(), settingsActivity);
} else {
intent = null;
}
// Add a check box for enabling/disabling IME
InputMethodPreference pref = new InputMethodPreference(this, intent, mImm, imi, imiSize);
pref.setKey(imi.getId());
pref.setTitle(label);
return pref;
}
private void createImePreferenceHierarchy(PreferenceGroup root) {
final Preference hardKeyPref = findPreference("hard_keyboard");
if (mIsOnlyImeSettings) {
getPreferenceScreen().removeAll();
if (hardKeyPref != null && mHaveHardKeyboard) {
getPreferenceScreen().addPreference(hardKeyPref);
}
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
getPreferenceScreen().addPreference(mShowInputMethodSelectorPref);
}
getPreferenceScreen().addPreference(root);
}
if (hardKeyPref != null) {
if (mHaveHardKeyboard) {
mHardKeyboardCategory = (PreferenceCategory) hardKeyPref;
} else {
getPreferenceScreen().removePreference(hardKeyPref);
}
}
root.removeAll();
mInputMethodPreferenceList.clear();
if (!mIsOnlyImeSettings) {
// Current IME selection
final PreferenceScreen currentIme = new PreferenceScreen(getActivity(), null);
currentIme.setKey(KEY_CURRENT_INPUT_METHOD);
currentIme.setTitle(getResources().getString(R.string.current_input_method));
root.addPreference(currentIme);
}
final int N = (mImis == null ? 0 : mImis.size());
for (int i = 0; i < N; ++i) {
final InputMethodInfo imi = mImis.get(i);
final InputMethodPreference pref = getInputMethodPreference(imi, N);
mInputMethodPreferenceList.add(pref);
}
Collections.sort(mInputMethodPreferenceList);
for (int i = 0; i < N; ++i) {
root.addPreference(mInputMethodPreferenceList.get(i));
}
}
}
| true | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_settings);
try {
mDefaultInputMethodSelectorVisibility = Integer.valueOf(
getString(R.string.input_method_selector_visibility_default_value));
} catch (NumberFormatException e) {
}
if (getActivity().getAssets().getLocales().length == 1) {
// No "Select language" pref if there's only one system locale available.
getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE));
} else {
mLanguagePref = findPreference(KEY_PHONE_LANGUAGE);
}
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref = (ListPreference)findPreference(
KEY_INPUT_METHOD_SELECTOR);
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
// TODO: Update current input method name on summary
updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility());
}
new VoiceInputOutputSettings(this).onCreate();
// Hard keyboard
final Configuration config = getResources().getConfiguration();
mHaveHardKeyboard = (config.keyboard == Configuration.KEYBOARD_QWERTY);
// IME
mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals(
getActivity().getIntent().getAction());
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImis = mImm.getInputMethodList();
createImePreferenceHierarchy((PreferenceGroup)findPreference("keyboard_settings_category"));
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(getActivity(), SpellCheckersSettingsActivity.class);
final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference(
"spellcheckers_settings"));
if (scp != null) {
scp.setFragmentIntent(this, intent);
}
}
| public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_settings);
try {
mDefaultInputMethodSelectorVisibility = Integer.valueOf(
getString(R.string.input_method_selector_visibility_default_value));
} catch (NumberFormatException e) {
}
if (getActivity().getAssets().getLocales().length == 1) {
// No "Select language" pref if there's only one system locale available.
getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE));
} else {
mLanguagePref = findPreference(KEY_PHONE_LANGUAGE);
}
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref = (ListPreference)findPreference(
KEY_INPUT_METHOD_SELECTOR);
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
// TODO: Update current input method name on summary
updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility());
}
new VoiceInputOutputSettings(this).onCreate();
// Hard keyboard
final Configuration config = getResources().getConfiguration();
mHaveHardKeyboard = (config.keyboard == Configuration.KEYBOARD_QWERTY);
// IME
mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals(
getActivity().getIntent().getAction());
getActivity().getIntent().setAction(null);
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImis = mImm.getInputMethodList();
createImePreferenceHierarchy((PreferenceGroup)findPreference("keyboard_settings_category"));
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(getActivity(), SpellCheckersSettingsActivity.class);
final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference(
"spellcheckers_settings"));
if (scp != null) {
scp.setFragmentIntent(this, intent);
}
}
|
diff --git a/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/EnwikiContentSource.java b/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/EnwikiContentSource.java
index 71d066c7e..93d2e5262 100644
--- a/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/EnwikiContentSource.java
+++ b/lucene/contrib/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/EnwikiContentSource.java
@@ -1,304 +1,307 @@
package org.apache.lucene.benchmark.byTask.feeds;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.benchmark.byTask.utils.Config;
import org.apache.lucene.util.ThreadInterruptedException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* A {@link ContentSource} which reads the English Wikipedia dump. You can read
* the .bz2 file directly (it will be decompressed on the fly). Config
* properties:
* <ul>
* <li>keep.image.only.docs=false|true (default <b>true</b>).
* <li>docs.file=<path to the file>
* </ul>
*/
public class EnwikiContentSource extends ContentSource {
private class Parser extends DefaultHandler implements Runnable {
private Thread t;
private boolean threadDone;
private String[] tuple;
private NoMoreDataException nmde;
private StringBuffer contents = new StringBuffer();
private String title;
private String body;
private String time;
private String id;
String[] next() throws NoMoreDataException {
if (t == null) {
threadDone = false;
t = new Thread(this);
t.setDaemon(true);
t.start();
}
String[] result;
synchronized(this){
while(tuple == null && nmde == null && !threadDone) {
try {
wait();
} catch (InterruptedException ie) {
throw new ThreadInterruptedException(ie);
}
}
if (nmde != null) {
// Set to null so we will re-start thread in case
// we are re-used:
t = null;
throw nmde;
}
if (t != null && threadDone) {
// The thread has exited yet did not hit end of
// data, so this means it hit an exception. We
// throw NoMorDataException here to force
// benchmark to stop the current alg:
throw new NoMoreDataException();
}
result = tuple;
tuple = null;
notify();
}
return result;
}
String time(String original) {
StringBuffer buffer = new StringBuffer();
buffer.append(original.substring(8, 10));
buffer.append('-');
buffer.append(months[Integer.valueOf(original.substring(5, 7)).intValue() - 1]);
buffer.append('-');
buffer.append(original.substring(0, 4));
buffer.append(' ');
buffer.append(original.substring(11, 19));
buffer.append(".000");
return buffer.toString();
}
@Override
public void characters(char[] ch, int start, int length) {
contents.append(ch, start, length);
}
@Override
public void endElement(String namespace, String simple, String qualified)
throws SAXException {
int elemType = getElementType(qualified);
switch (elemType) {
case PAGE:
// the body must be null and we either are keeping image docs or the
// title does not start with Image:
if (body != null && (keepImages || !title.startsWith("Image:"))) {
String[] tmpTuple = new String[LENGTH];
tmpTuple[TITLE] = title.replace('\t', ' ');
tmpTuple[DATE] = time.replace('\t', ' ');
tmpTuple[BODY] = body.replaceAll("[\t\n]", " ");
tmpTuple[ID] = id;
synchronized(this) {
while (tuple != null) {
try {
wait();
} catch (InterruptedException ie) {
throw new ThreadInterruptedException(ie);
}
}
tuple = tmpTuple;
notify();
}
}
break;
case BODY:
body = contents.toString();
//workaround that startswith doesn't have an ignore case option, get at least 20 chars.
String startsWith = body.substring(0, Math.min(10, contents.length())).toLowerCase();
if (startsWith.startsWith("#redirect")) {
body = null;
}
break;
case DATE:
time = time(contents.toString());
break;
case TITLE:
title = contents.toString();
break;
case ID:
- id = contents.toString();
+ //the doc id is the first one in the page. All other ids after that one can be ignored according to the schema
+ if (id == null) {
+ id = contents.toString();
+ }
break;
default:
// this element should be discarded.
}
}
public void run() {
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(this);
reader.setErrorHandler(this);
while(true){
final InputStream localFileIS = is;
try {
reader.parse(new InputSource(localFileIS));
} catch (IOException ioe) {
synchronized(EnwikiContentSource.this) {
if (localFileIS != is) {
// fileIS was closed on us, so, just fall
// through
} else
// Exception is real
throw ioe;
}
}
synchronized(this) {
if (!forever) {
nmde = new NoMoreDataException();
notify();
return;
} else if (localFileIS == is) {
// If file is not already re-opened then re-open it now
is = getInputStream(file);
}
}
}
} catch (SAXException sae) {
throw new RuntimeException(sae);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
synchronized(this) {
threadDone = true;
notify();
}
}
}
@Override
public void startElement(String namespace, String simple, String qualified,
Attributes attributes) {
int elemType = getElementType(qualified);
switch (elemType) {
case PAGE:
title = null;
body = null;
time = null;
id = null;
break;
// intentional fall-through.
case BODY:
case DATE:
case TITLE:
case ID:
contents.setLength(0);
break;
default:
// this element should be discarded.
}
}
}
private static final Map<String,Integer> ELEMENTS = new HashMap<String,Integer>();
private static final int TITLE = 0;
private static final int DATE = TITLE + 1;
private static final int BODY = DATE + 1;
private static final int ID = BODY + 1;
private static final int LENGTH = ID + 1;
// LENGTH is used as the size of the tuple, so whatever constants we need that
// should not be part of the tuple, we should define them after LENGTH.
private static final int PAGE = LENGTH + 1;
private static final String[] months = {"JAN", "FEB", "MAR", "APR",
"MAY", "JUN", "JUL", "AUG",
"SEP", "OCT", "NOV", "DEC"};
static {
ELEMENTS.put("page", Integer.valueOf(PAGE));
ELEMENTS.put("text", Integer.valueOf(BODY));
ELEMENTS.put("timestamp", Integer.valueOf(DATE));
ELEMENTS.put("title", Integer.valueOf(TITLE));
ELEMENTS.put("id", Integer.valueOf(ID));
}
/**
* Returns the type of the element if defined, otherwise returns -1. This
* method is useful in startElement and endElement, by not needing to compare
* the element qualified name over and over.
*/
private final static int getElementType(String elem) {
Integer val = ELEMENTS.get(elem);
return val == null ? -1 : val.intValue();
}
private File file;
private boolean keepImages = true;
private InputStream is;
private Parser parser = new Parser();
@Override
public void close() throws IOException {
synchronized (EnwikiContentSource.this) {
if (is != null) {
is.close();
is = null;
}
}
}
@Override
public synchronized DocData getNextDocData(DocData docData) throws NoMoreDataException, IOException {
String[] tuple = parser.next();
docData.clear();
docData.setName(tuple[ID]);
docData.setBody(tuple[BODY]);
docData.setDate(tuple[DATE]);
docData.setTitle(tuple[TITLE]);
return docData;
}
@Override
public void resetInputs() throws IOException {
super.resetInputs();
is = getInputStream(file);
}
@Override
public void setConfig(Config config) {
super.setConfig(config);
keepImages = config.get("keep.image.only.docs", true);
String fileName = config.get("docs.file", null);
if (fileName == null) {
throw new IllegalArgumentException("docs.file must be set");
}
file = new File(fileName).getAbsoluteFile();
}
}
| true | true | public void endElement(String namespace, String simple, String qualified)
throws SAXException {
int elemType = getElementType(qualified);
switch (elemType) {
case PAGE:
// the body must be null and we either are keeping image docs or the
// title does not start with Image:
if (body != null && (keepImages || !title.startsWith("Image:"))) {
String[] tmpTuple = new String[LENGTH];
tmpTuple[TITLE] = title.replace('\t', ' ');
tmpTuple[DATE] = time.replace('\t', ' ');
tmpTuple[BODY] = body.replaceAll("[\t\n]", " ");
tmpTuple[ID] = id;
synchronized(this) {
while (tuple != null) {
try {
wait();
} catch (InterruptedException ie) {
throw new ThreadInterruptedException(ie);
}
}
tuple = tmpTuple;
notify();
}
}
break;
case BODY:
body = contents.toString();
//workaround that startswith doesn't have an ignore case option, get at least 20 chars.
String startsWith = body.substring(0, Math.min(10, contents.length())).toLowerCase();
if (startsWith.startsWith("#redirect")) {
body = null;
}
break;
case DATE:
time = time(contents.toString());
break;
case TITLE:
title = contents.toString();
break;
case ID:
id = contents.toString();
break;
default:
// this element should be discarded.
}
}
| public void endElement(String namespace, String simple, String qualified)
throws SAXException {
int elemType = getElementType(qualified);
switch (elemType) {
case PAGE:
// the body must be null and we either are keeping image docs or the
// title does not start with Image:
if (body != null && (keepImages || !title.startsWith("Image:"))) {
String[] tmpTuple = new String[LENGTH];
tmpTuple[TITLE] = title.replace('\t', ' ');
tmpTuple[DATE] = time.replace('\t', ' ');
tmpTuple[BODY] = body.replaceAll("[\t\n]", " ");
tmpTuple[ID] = id;
synchronized(this) {
while (tuple != null) {
try {
wait();
} catch (InterruptedException ie) {
throw new ThreadInterruptedException(ie);
}
}
tuple = tmpTuple;
notify();
}
}
break;
case BODY:
body = contents.toString();
//workaround that startswith doesn't have an ignore case option, get at least 20 chars.
String startsWith = body.substring(0, Math.min(10, contents.length())).toLowerCase();
if (startsWith.startsWith("#redirect")) {
body = null;
}
break;
case DATE:
time = time(contents.toString());
break;
case TITLE:
title = contents.toString();
break;
case ID:
//the doc id is the first one in the page. All other ids after that one can be ignored according to the schema
if (id == null) {
id = contents.toString();
}
break;
default:
// this element should be discarded.
}
}
|
diff --git a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/I18n.java b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/I18n.java
index a2c14fb50..6d76041c6 100644
--- a/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/I18n.java
+++ b/scm-clients/scm-cli-client/src/main/java/sonia/scm/cli/I18n.java
@@ -1,111 +1,111 @@
/**
* Copyright (c) 2010, Sebastian Sdorra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of SCM-Manager; 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 REGENTS 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.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.cli;
//~--- non-JDK imports --------------------------------------------------------
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//~--- JDK imports ------------------------------------------------------------
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
*
* @author Sebastian Sdorra
*/
public class I18n
{
/** Field description */
public static final String RESOURCE_BUNDLE = "sonia.resources.i18n";
/** the logger for I18n */
private static final Logger logger = LoggerFactory.getLogger(I18n.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*/
public I18n()
{
bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE);
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public ResourceBundle getBundle()
{
return bundle;
}
/**
* Method description
*
*
* @param key
*
* @return
*/
public String getMessage(String key)
{
String value = key;
try
{
- key = bundle.getString(key);
+ value = bundle.getString(key);
}
catch (MissingResourceException ex)
{
logger.warn("could not find resource for key {}", key);
}
return value;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private ResourceBundle bundle;
}
| true | true | public String getMessage(String key)
{
String value = key;
try
{
key = bundle.getString(key);
}
catch (MissingResourceException ex)
{
logger.warn("could not find resource for key {}", key);
}
return value;
}
| public String getMessage(String key)
{
String value = key;
try
{
value = bundle.getString(key);
}
catch (MissingResourceException ex)
{
logger.warn("could not find resource for key {}", key);
}
return value;
}
|
diff --git a/src/com/facebook/buck/android/AndroidBinaryBuildRuleFactory.java b/src/com/facebook/buck/android/AndroidBinaryBuildRuleFactory.java
index a1eec75d57..03f4a9f936 100644
--- a/src/com/facebook/buck/android/AndroidBinaryBuildRuleFactory.java
+++ b/src/com/facebook/buck/android/AndroidBinaryBuildRuleFactory.java
@@ -1,110 +1,107 @@
/*
* Copyright 2012-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.model.BuildTarget;
import com.facebook.buck.parser.AbstractBuildRuleFactory;
import com.facebook.buck.parser.BuildRuleFactoryParams;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.parser.ParseContext;
import com.facebook.buck.rules.AbstractBuildRuleBuilder;
import com.facebook.buck.util.ZipSplitter;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import java.util.List;
public class AndroidBinaryBuildRuleFactory extends AbstractBuildRuleFactory {
@Override
public AndroidBinaryRule.Builder newBuilder() {
return AndroidBinaryRule.newAndroidBinaryRuleBuilder();
}
@Override
protected void amendBuilder(AbstractBuildRuleBuilder abstractBuilder,
BuildRuleFactoryParams params) throws NoSuchBuildTargetException {
AndroidBinaryRule.Builder builder = ((AndroidBinaryRule.Builder)abstractBuilder);
// manifest
String manifestAttribute = params.getRequiredStringAttribute("manifest");
String manifestPath = params.resolveFilePathRelativeToBuildFileDirectory(manifestAttribute);
builder.setManifest(manifestPath);
// target
String target = params.getRequiredStringAttribute("target");
builder.setTarget(target);
// keystore_properties
String keystoreProperties = params.getRequiredStringAttribute("keystore_properties");
String keystorePropertiesPath = params.resolveFilePathRelativeToBuildFileDirectory(
keystoreProperties);
builder.setKeystorePropertiesPath(keystorePropertiesPath);
// package_type
// Note that it is not required for the user to supply this attribute, but buck.py should
// supply 'debug' if the user has not supplied a value.
String packageType = params.getRequiredStringAttribute("package_type");
builder.setPackageType(packageType);
// no_dx
ParseContext buildFileParseContext = ParseContext.forBaseName(params.target.getBaseName());
for (String noDx : params.getOptionalListAttribute("no_dx")) {
BuildTarget buildTarget = params.buildTargetParser.parse(noDx, buildFileParseContext);
builder.addBuildRuleToExcludeFromDex(buildTarget.getFullyQualifiedName());
}
// use_split_dex
boolean useSplitDex = params.getBooleanAttribute("use_split_dex");
ZipSplitter.DexSplitStrategy dexSplitStrategy = params.getBooleanAttribute("minimize_primary_dex_size")
? ZipSplitter.DexSplitStrategy.MINIMIZE_PRIMARY_DEX_SIZE
: ZipSplitter.DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE;
builder.setDexSplitMode(new AndroidBinaryRule.DexSplitMode(useSplitDex, dexSplitStrategy));
// use_android_proguard_config_with_optimizations
boolean useAndroidProguardConfigWithOptimizations =
params.getBooleanAttribute("use_android_proguard_config_with_optimizations");
builder.setUseAndroidProguardConfigWithOptimizations(useAndroidProguardConfigWithOptimizations);
// proguard_config
Optional<String> proguardConfig = params.getOptionalStringAttribute("proguard_config");
builder.setProguardConfig(
proguardConfig.transform(params.getResolveFilePathRelativeToBuildFileDirectoryTransform()));
// compress_resources
boolean compressResources = params.getBooleanAttribute("compress_resources");
builder.setCompressResources(compressResources);
// primary_dex_substrings
List<String> primaryDexSubstrings = params.getOptionalListAttribute("primary_dex_substrings");
builder.addPrimaryDexSubstrings(primaryDexSubstrings);
// resource_filter
Optional<String> resourceFilter = params.getOptionalStringAttribute("resource_filter");
if (resourceFilter.isPresent()) {
- String trimmedResourceFilter = resourceFilter.get().trim();
- builder.setResourceFilter(Optional.fromNullable(
- Strings.emptyToNull(trimmedResourceFilter)));
- } else {
- builder.setProguardConfig(resourceFilter);
+ String trimmedResourceFilter = Strings.emptyToNull(resourceFilter.get().trim());
+ builder.setResourceFilter(Optional.fromNullable(trimmedResourceFilter));
}
}
}
| true | true | protected void amendBuilder(AbstractBuildRuleBuilder abstractBuilder,
BuildRuleFactoryParams params) throws NoSuchBuildTargetException {
AndroidBinaryRule.Builder builder = ((AndroidBinaryRule.Builder)abstractBuilder);
// manifest
String manifestAttribute = params.getRequiredStringAttribute("manifest");
String manifestPath = params.resolveFilePathRelativeToBuildFileDirectory(manifestAttribute);
builder.setManifest(manifestPath);
// target
String target = params.getRequiredStringAttribute("target");
builder.setTarget(target);
// keystore_properties
String keystoreProperties = params.getRequiredStringAttribute("keystore_properties");
String keystorePropertiesPath = params.resolveFilePathRelativeToBuildFileDirectory(
keystoreProperties);
builder.setKeystorePropertiesPath(keystorePropertiesPath);
// package_type
// Note that it is not required for the user to supply this attribute, but buck.py should
// supply 'debug' if the user has not supplied a value.
String packageType = params.getRequiredStringAttribute("package_type");
builder.setPackageType(packageType);
// no_dx
ParseContext buildFileParseContext = ParseContext.forBaseName(params.target.getBaseName());
for (String noDx : params.getOptionalListAttribute("no_dx")) {
BuildTarget buildTarget = params.buildTargetParser.parse(noDx, buildFileParseContext);
builder.addBuildRuleToExcludeFromDex(buildTarget.getFullyQualifiedName());
}
// use_split_dex
boolean useSplitDex = params.getBooleanAttribute("use_split_dex");
ZipSplitter.DexSplitStrategy dexSplitStrategy = params.getBooleanAttribute("minimize_primary_dex_size")
? ZipSplitter.DexSplitStrategy.MINIMIZE_PRIMARY_DEX_SIZE
: ZipSplitter.DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE;
builder.setDexSplitMode(new AndroidBinaryRule.DexSplitMode(useSplitDex, dexSplitStrategy));
// use_android_proguard_config_with_optimizations
boolean useAndroidProguardConfigWithOptimizations =
params.getBooleanAttribute("use_android_proguard_config_with_optimizations");
builder.setUseAndroidProguardConfigWithOptimizations(useAndroidProguardConfigWithOptimizations);
// proguard_config
Optional<String> proguardConfig = params.getOptionalStringAttribute("proguard_config");
builder.setProguardConfig(
proguardConfig.transform(params.getResolveFilePathRelativeToBuildFileDirectoryTransform()));
// compress_resources
boolean compressResources = params.getBooleanAttribute("compress_resources");
builder.setCompressResources(compressResources);
// primary_dex_substrings
List<String> primaryDexSubstrings = params.getOptionalListAttribute("primary_dex_substrings");
builder.addPrimaryDexSubstrings(primaryDexSubstrings);
// resource_filter
Optional<String> resourceFilter = params.getOptionalStringAttribute("resource_filter");
if (resourceFilter.isPresent()) {
String trimmedResourceFilter = resourceFilter.get().trim();
builder.setResourceFilter(Optional.fromNullable(
Strings.emptyToNull(trimmedResourceFilter)));
} else {
builder.setProguardConfig(resourceFilter);
}
}
| protected void amendBuilder(AbstractBuildRuleBuilder abstractBuilder,
BuildRuleFactoryParams params) throws NoSuchBuildTargetException {
AndroidBinaryRule.Builder builder = ((AndroidBinaryRule.Builder)abstractBuilder);
// manifest
String manifestAttribute = params.getRequiredStringAttribute("manifest");
String manifestPath = params.resolveFilePathRelativeToBuildFileDirectory(manifestAttribute);
builder.setManifest(manifestPath);
// target
String target = params.getRequiredStringAttribute("target");
builder.setTarget(target);
// keystore_properties
String keystoreProperties = params.getRequiredStringAttribute("keystore_properties");
String keystorePropertiesPath = params.resolveFilePathRelativeToBuildFileDirectory(
keystoreProperties);
builder.setKeystorePropertiesPath(keystorePropertiesPath);
// package_type
// Note that it is not required for the user to supply this attribute, but buck.py should
// supply 'debug' if the user has not supplied a value.
String packageType = params.getRequiredStringAttribute("package_type");
builder.setPackageType(packageType);
// no_dx
ParseContext buildFileParseContext = ParseContext.forBaseName(params.target.getBaseName());
for (String noDx : params.getOptionalListAttribute("no_dx")) {
BuildTarget buildTarget = params.buildTargetParser.parse(noDx, buildFileParseContext);
builder.addBuildRuleToExcludeFromDex(buildTarget.getFullyQualifiedName());
}
// use_split_dex
boolean useSplitDex = params.getBooleanAttribute("use_split_dex");
ZipSplitter.DexSplitStrategy dexSplitStrategy = params.getBooleanAttribute("minimize_primary_dex_size")
? ZipSplitter.DexSplitStrategy.MINIMIZE_PRIMARY_DEX_SIZE
: ZipSplitter.DexSplitStrategy.MAXIMIZE_PRIMARY_DEX_SIZE;
builder.setDexSplitMode(new AndroidBinaryRule.DexSplitMode(useSplitDex, dexSplitStrategy));
// use_android_proguard_config_with_optimizations
boolean useAndroidProguardConfigWithOptimizations =
params.getBooleanAttribute("use_android_proguard_config_with_optimizations");
builder.setUseAndroidProguardConfigWithOptimizations(useAndroidProguardConfigWithOptimizations);
// proguard_config
Optional<String> proguardConfig = params.getOptionalStringAttribute("proguard_config");
builder.setProguardConfig(
proguardConfig.transform(params.getResolveFilePathRelativeToBuildFileDirectoryTransform()));
// compress_resources
boolean compressResources = params.getBooleanAttribute("compress_resources");
builder.setCompressResources(compressResources);
// primary_dex_substrings
List<String> primaryDexSubstrings = params.getOptionalListAttribute("primary_dex_substrings");
builder.addPrimaryDexSubstrings(primaryDexSubstrings);
// resource_filter
Optional<String> resourceFilter = params.getOptionalStringAttribute("resource_filter");
if (resourceFilter.isPresent()) {
String trimmedResourceFilter = Strings.emptyToNull(resourceFilter.get().trim());
builder.setResourceFilter(Optional.fromNullable(trimmedResourceFilter));
}
}
|
diff --git a/src/test/java/org/chaoticbits/collabcloud/codeprocessor/java/JavaProjectSummarizerTest.java b/src/test/java/org/chaoticbits/collabcloud/codeprocessor/java/JavaProjectSummarizerTest.java
index 5606c9f..1af7584 100755
--- a/src/test/java/org/chaoticbits/collabcloud/codeprocessor/java/JavaProjectSummarizerTest.java
+++ b/src/test/java/org/chaoticbits/collabcloud/codeprocessor/java/JavaProjectSummarizerTest.java
@@ -1,47 +1,47 @@
package org.chaoticbits.collabcloud.codeprocessor.java;
import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.*;
import japa.parser.JavaParser;
import japa.parser.ast.CompilationUnit;
import java.io.File;
import org.chaoticbits.collabcloud.codeprocessor.CloudWeights;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ JavaParser.class, CompilationUnit.class })
public class JavaProjectSummarizerTest {
@Test
public void testProject() throws Exception {
- IMocksControl ctrl = EasyMock.createStrictControl();
+ IMocksControl ctrl = EasyMock.createControl();
JavaProjectSummarizer summarizer = new JavaProjectSummarizer();
PowerMock.mockStatic(JavaParser.class);
CompilationUnit unit = PowerMock.createMock(CompilationUnit.class);
File mockDir = ctrl.createMock(File.class);
File mockFile = ctrl.createMock(File.class);
CloudWeights weights = new CloudWeights();
expect(mockDir.isDirectory()).andReturn(true).anyTimes();
expect(mockDir.listFiles()).andReturn(new File[] { mockFile }).once();
expect(mockFile.isDirectory()).andReturn(false).anyTimes();
expect(mockFile.getName()).andReturn("a.java").anyTimes();
expect(JavaParser.parse(mockFile)).andReturn(unit).once();
-// expect(unit.accept((JavaSummarizeVisitor) EasyMock.anyObject(), (CloudWeights) EasyMock.anyObject())).andReturn(weights).once();
+ expect(unit.accept((JavaSummarizeVisitor) EasyMock.anyObject(), (CloudWeights) EasyMock.anyObject())).andReturn(weights).once();
ctrl.replay();
- PowerMock.replay();
+ PowerMock.replay(JavaParser.class, unit);
summarizer.summarize(mockDir);
PowerMock.verify(JavaParser.class);
ctrl.verify();
}
}
| false | true | public void testProject() throws Exception {
IMocksControl ctrl = EasyMock.createStrictControl();
JavaProjectSummarizer summarizer = new JavaProjectSummarizer();
PowerMock.mockStatic(JavaParser.class);
CompilationUnit unit = PowerMock.createMock(CompilationUnit.class);
File mockDir = ctrl.createMock(File.class);
File mockFile = ctrl.createMock(File.class);
CloudWeights weights = new CloudWeights();
expect(mockDir.isDirectory()).andReturn(true).anyTimes();
expect(mockDir.listFiles()).andReturn(new File[] { mockFile }).once();
expect(mockFile.isDirectory()).andReturn(false).anyTimes();
expect(mockFile.getName()).andReturn("a.java").anyTimes();
expect(JavaParser.parse(mockFile)).andReturn(unit).once();
// expect(unit.accept((JavaSummarizeVisitor) EasyMock.anyObject(), (CloudWeights) EasyMock.anyObject())).andReturn(weights).once();
ctrl.replay();
PowerMock.replay();
summarizer.summarize(mockDir);
PowerMock.verify(JavaParser.class);
ctrl.verify();
}
| public void testProject() throws Exception {
IMocksControl ctrl = EasyMock.createControl();
JavaProjectSummarizer summarizer = new JavaProjectSummarizer();
PowerMock.mockStatic(JavaParser.class);
CompilationUnit unit = PowerMock.createMock(CompilationUnit.class);
File mockDir = ctrl.createMock(File.class);
File mockFile = ctrl.createMock(File.class);
CloudWeights weights = new CloudWeights();
expect(mockDir.isDirectory()).andReturn(true).anyTimes();
expect(mockDir.listFiles()).andReturn(new File[] { mockFile }).once();
expect(mockFile.isDirectory()).andReturn(false).anyTimes();
expect(mockFile.getName()).andReturn("a.java").anyTimes();
expect(JavaParser.parse(mockFile)).andReturn(unit).once();
expect(unit.accept((JavaSummarizeVisitor) EasyMock.anyObject(), (CloudWeights) EasyMock.anyObject())).andReturn(weights).once();
ctrl.replay();
PowerMock.replay(JavaParser.class, unit);
summarizer.summarize(mockDir);
PowerMock.verify(JavaParser.class);
ctrl.verify();
}
|
diff --git a/webapp/lib/src/test/java/com/github/podd/restlet/test/GetArtifactResourceImplTest.java b/webapp/lib/src/test/java/com/github/podd/restlet/test/GetArtifactResourceImplTest.java
index 53d64e63..e2ec62dc 100644
--- a/webapp/lib/src/test/java/com/github/podd/restlet/test/GetArtifactResourceImplTest.java
+++ b/webapp/lib/src/test/java/com/github/podd/restlet/test/GetArtifactResourceImplTest.java
@@ -1,364 +1,364 @@
/**
*
*/
package com.github.podd.restlet.test;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Test;
import org.openrdf.model.Model;
import org.openrdf.rio.RDFFormat;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import com.github.ansell.restletutils.RestletUtilMediaType;
import com.github.ansell.restletutils.test.RestletTestUtils;
import com.github.podd.api.test.TestConstants;
import com.github.podd.utils.DebugUtils;
import com.github.podd.utils.PoddWebConstants;
/**
* Test various forms of GetArtifact
*
* @author kutila
*
*/
public class GetArtifactResourceImplTest extends AbstractResourceImplTest
{
// private static final String TEST_ARTIFACT_WITH_1_INTERNAL_OBJECT =
// "/test/artifacts/basicProject-1-internal-object.rdf";
/**
* Test access without artifactID parameter gives a BAD_REQUEST error.
*/
@Test
public void testErrorGetArtifactWithoutArtifactId() throws Exception
{
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
try
{
getArtifactClientResource.get(MediaType.TEXT_HTML);
Assert.fail("Should have thrown a ResourceException with Status Code 400");
}
catch(final ResourceException e)
{
Assert.assertEquals("Not the expected HTTP status code", Status.CLIENT_ERROR_BAD_REQUEST, e.getStatus());
}
}
/**
* Test unauthenticated access gives an UNAUTHORIZED error.
*/
@Test
public void testErrorGetArtifactWithoutAuthentication() throws Exception
{
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER,
"http://purl.org/podd/ns/artifact/artifact89");
try
{
getArtifactClientResource.get(MediaType.TEXT_HTML);
Assert.fail("Should have thrown a ResourceException with Status Code 401");
}
catch(final ResourceException e)
{
Assert.assertEquals("Not the expected HTTP status code", Status.CLIENT_ERROR_UNAUTHORIZED, e.getStatus());
}
}
/**
* Test authenticated access to get Artifact in HTML
*/
@Test
public void testGetArtifactBasicHtml() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact(TestConstants.TEST_ARTIFACT_BASIC_1_INTERNAL_OBJECT);
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.TEXT_HTML, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
// verify:
Assert.assertTrue("Page does not identify Administrator", body.contains("Administrator"));
Assert.assertFalse("Page contained a 404 error", body.contains("ERROR: 404"));
Assert.assertTrue("Missing: Project Details", body.contains("Project Details"));
Assert.assertTrue("Missng: ANZSRC FOR Code", body.contains("ANZSRC FOR Code:"));
Assert.assertTrue("Missng: Project#2012...", body.contains("Project#2012-0006_ Cotton Leaf Morphology"));
this.assertFreemarker(body);
}
/**
* Test authenticated access to get Artifact in HTML with a check on the RDFa
*/
@Test
public void testGetArtifactBasicHtmlRDFa() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact(TestConstants.TEST_ARTIFACT_BASIC_1_INTERNAL_OBJECT);
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.TEXT_HTML, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
// verify:
Assert.assertTrue("Page does not identify Administrator", body.contains("Administrator"));
Assert.assertFalse("Page contained a 404 error", body.contains("ERROR: 404"));
Assert.assertTrue("Missing: Project Details", body.contains("Project Details"));
Assert.assertTrue("Missng: ANZSRC FOR Code", body.contains("ANZSRC FOR Code:"));
Assert.assertTrue("Missng: Project#2012...", body.contains("Project#2012-0006_ Cotton Leaf Morphology"));
this.assertFreemarker(body);
final Model model =
- this.assertRdf(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)), RDFFormat.RDFA, 14);
+ this.assertRdf(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)), RDFFormat.RDFA, 15);
// RDFa generates spurious triples, use at your own risk
// Only rely on numbers from actual RDF serialisations
Assert.assertEquals(7, model.subjects().size());
Assert.assertEquals(12, model.predicates().size());
- Assert.assertEquals(14, model.objects().size());
+ Assert.assertEquals(15, model.objects().size());
if(this.log.isDebugEnabled())
{
DebugUtils.printContents(model);
}
}
/**
* Test authenticated access to get Artifact in RDF/JSON
*/
@Test
public void testGetArtifactBasicJson() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact(TestConstants.TEST_ARTIFACT_BASIC_1_INTERNAL_OBJECT);
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
RestletUtilMediaType.APPLICATION_RDF_JSON, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
// System.out.println(body);
// verify: received contents are in RDF/JSON
// Assert.assertTrue("Result does not have @prefix", body.contains("@prefix"));
// verify: received contents have artifact's ontology and version IRIs
Assert.assertTrue("Result does not contain artifact URI", body.contains(artifactUri));
final Model model =
this.assertRdf(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)), RDFFormat.RDFJSON, 28);
Assert.assertEquals(5, model.subjects().size());
Assert.assertEquals(15, model.predicates().size());
Assert.assertEquals(24, model.objects().size());
if(this.log.isDebugEnabled())
{
DebugUtils.printContents(model);
}
}
/**
* Test authenticated access to get Artifact in RDF/XML
*/
@Test
public void testGetArtifactBasicRdf() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact(TestConstants.TEST_ARTIFACT_BASIC_1_INTERNAL_OBJECT);
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.APPLICATION_RDF_XML, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
// verify: received contents are in RDF
Assert.assertTrue("Result does not have RDF", body.contains("<rdf:RDF"));
Assert.assertTrue("Result does not have RDF", body.endsWith("</rdf:RDF>"));
// verify: received contents have artifact URI
Assert.assertTrue("Result does not contain artifact URI", body.contains(artifactUri));
final Model model =
this.assertRdf(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)), RDFFormat.RDFXML, 28);
Assert.assertEquals(5, model.subjects().size());
Assert.assertEquals(15, model.predicates().size());
Assert.assertEquals(24, model.objects().size());
if(this.log.isDebugEnabled())
{
DebugUtils.printContents(model);
}
}
/**
* Test authenticated access to get Artifact in RDF/Turtle
*/
@Test
public void testGetArtifactBasicTurtle() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact(TestConstants.TEST_ARTIFACT_BASIC_1_INTERNAL_OBJECT);
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.APPLICATION_RDF_TURTLE, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
// verify: received contents are in Turtle
Assert.assertTrue("Result does not have @prefix", body.contains("@prefix"));
// verify: received contents have artifact's ontology and version IRIs
Assert.assertTrue("Result does not contain artifact URI", body.contains(artifactUri));
final Model model =
this.assertRdf(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)), RDFFormat.TURTLE, 28);
Assert.assertEquals(5, model.subjects().size());
Assert.assertEquals(15, model.predicates().size());
Assert.assertEquals(24, model.objects().size());
if(this.log.isDebugEnabled())
{
DebugUtils.printContents(model);
}
}
/**
* Test authenticated access to get an internal podd object in HTML
*/
@Test
public void testGetArtifactHtmlAnalysisObject() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact(TestConstants.TEST_ARTIFACT_BASIC_1_INTERNAL_OBJECT);
final String objectUri = "urn:poddinternal:7616392e-802b-4c5d-953d-bf81da5a98f4:0";
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_OBJECT_IDENTIFIER, objectUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.TEXT_HTML, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
// verify:
Assert.assertTrue("Page does not identify Administrator", body.contains("Administrator"));
Assert.assertFalse("Page contained a 404 error", body.contains("ERROR: 404"));
Assert.assertTrue("Missing: Analysis Details", body.contains("Analysis Details"));
Assert.assertTrue("Missng title: poddScience#Analysis 0", body.contains("poddScience#Analysis 0"));
this.assertFreemarker(body);
}
/**
* Test authenticated access to get an internal podd object in HTML
*/
@Test
public void testGetArtifactHtmlPublicationObject() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact("/test/artifacts/basic-2.rdf");
final String objectUri = "urn:hardcoded:purl:artifact:1#publication45";
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_OBJECT_IDENTIFIER, objectUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.TEXT_HTML, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
System.out.println(body);
// verify:
Assert.assertTrue("Page does not identify Administrator", body.contains("Administrator"));
Assert.assertFalse("Page contained a 404 error", body.contains("ERROR: 404"));
Assert.assertTrue("Publication title is missing",
body.contains("Towards An Extensible, Domain-agnostic Scientific Data Management System"));
Assert.assertTrue("#publishedIn value is missing", body.contains("Proceedings of the IEEE eScience 2010"));
Assert.assertTrue("Publicatin's PURL value is missing",
body.contains("http://dx.doi.org/10.1109/eScience.2010.44"));
this.assertFreemarker(body);
}
/**
* Test parsing a simple RDFa document
*/
@Test
public void testSimpleRDFaParse() throws Exception
{
final StringBuilder sb = new StringBuilder();
sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML+RDFa 1.0//EN\" \"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd\">");
sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
sb.append(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"");
sb.append(" version=\"XHTML+RDFa 1.0\">");
sb.append("<head>");
sb.append(" <link rel=\"stylesheet\" href=\"http://localhost:8080/test/styles/mystyle.css\" media=\"screen\" type=\"text/css\" />");
sb.append("</head>");
sb.append("<body>");
sb.append("</body>");
sb.append("</html>");
this.assertRdf(new ByteArrayInputStream(sb.toString().getBytes(StandardCharsets.UTF_8)), RDFFormat.RDFA, 1);
}
}
| false | true | public void testGetArtifactBasicHtmlRDFa() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact(TestConstants.TEST_ARTIFACT_BASIC_1_INTERNAL_OBJECT);
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.TEXT_HTML, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
// verify:
Assert.assertTrue("Page does not identify Administrator", body.contains("Administrator"));
Assert.assertFalse("Page contained a 404 error", body.contains("ERROR: 404"));
Assert.assertTrue("Missing: Project Details", body.contains("Project Details"));
Assert.assertTrue("Missng: ANZSRC FOR Code", body.contains("ANZSRC FOR Code:"));
Assert.assertTrue("Missng: Project#2012...", body.contains("Project#2012-0006_ Cotton Leaf Morphology"));
this.assertFreemarker(body);
final Model model =
this.assertRdf(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)), RDFFormat.RDFA, 14);
// RDFa generates spurious triples, use at your own risk
// Only rely on numbers from actual RDF serialisations
Assert.assertEquals(7, model.subjects().size());
Assert.assertEquals(12, model.predicates().size());
Assert.assertEquals(14, model.objects().size());
if(this.log.isDebugEnabled())
{
DebugUtils.printContents(model);
}
}
| public void testGetArtifactBasicHtmlRDFa() throws Exception
{
// prepare: add an artifact
final String artifactUri = this.loadTestArtifact(TestConstants.TEST_ARTIFACT_BASIC_1_INTERNAL_OBJECT);
final ClientResource getArtifactClientResource =
new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
getArtifactClientResource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactUri);
final Representation results =
RestletTestUtils.doTestAuthenticatedRequest(getArtifactClientResource, Method.GET, null,
MediaType.TEXT_HTML, Status.SUCCESS_OK, this.testWithAdminPrivileges);
final String body = results.getText();
// verify:
Assert.assertTrue("Page does not identify Administrator", body.contains("Administrator"));
Assert.assertFalse("Page contained a 404 error", body.contains("ERROR: 404"));
Assert.assertTrue("Missing: Project Details", body.contains("Project Details"));
Assert.assertTrue("Missng: ANZSRC FOR Code", body.contains("ANZSRC FOR Code:"));
Assert.assertTrue("Missng: Project#2012...", body.contains("Project#2012-0006_ Cotton Leaf Morphology"));
this.assertFreemarker(body);
final Model model =
this.assertRdf(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)), RDFFormat.RDFA, 15);
// RDFa generates spurious triples, use at your own risk
// Only rely on numbers from actual RDF serialisations
Assert.assertEquals(7, model.subjects().size());
Assert.assertEquals(12, model.predicates().size());
Assert.assertEquals(15, model.objects().size());
if(this.log.isDebugEnabled())
{
DebugUtils.printContents(model);
}
}
|
diff --git a/src/model/Movie_Info.java b/src/model/Movie_Info.java
index 42d9680..795c779 100644
--- a/src/model/Movie_Info.java
+++ b/src/model/Movie_Info.java
@@ -1,121 +1,121 @@
package model;
import java.util.ArrayList;
public class Movie_Info{
private String movie_name = null;
private String haibao_path = null;
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<String> downloadlinks = new ArrayList<String>();
private ArrayList<String> downloadnames = new ArrayList<String>();
public Movie_Info(){}
public Movie_Info(String name, String path){
this.movie_name = name;
this.haibao_path = path;
}
private Movie_Info(Movie_Info info){
this.movie_name = info.movie_name;
this.haibao_path = info.haibao_path;
this.names = info.names;
this.downloadlinks = info.downloadlinks;
this.downloadnames = info.downloadnames;
}
public boolean hasName(){
return this.movie_name != null;
}
public boolean hasHaiBaoPath(){
return this.haibao_path != null;
}
public void setMovieName(String movie_name){
this.movie_name = movie_name;
}
public void setHaiBaoPath(String haibao_path){
this.haibao_path = haibao_path;
}
public void setNames(ArrayList<String> names){
this.names = names;
}
// public void setDownLoadLinks(ArrayList<String> downloadlinks){
// this.downloadlinks = downloadlinks;
// }
// public void setDownLoadNames(ArrayList<String> downloadnames){
// this.downloadnames = downloadnames;
// }
public void addName(String name){
this.names.add(name);
}
public void addDownLoadLinks(ArrayList<String> downloadlinks, String downloadname){
this.downloadlinks.addAll(downloadlinks);
for(int i = 0; i < downloadlinks.size() ; i++){
this.downloadnames.add(downloadname);
}
}
public void addDownLoadLinks(String downloadlink, String downloadname){
this.downloadlinks.add(downloadlink);
this.downloadnames.add(downloadname);
}
public String getMovieName(){
return this.movie_name;
}
public String getHaiBaoPath(){
return this.haibao_path;
}
public ArrayList<String> getNames(){
return this.names;
}
public ArrayList<String> getDownLoadLinks(){
return this.downloadlinks;
}
public ArrayList<String> getDownLoadNames(){
return this.downloadnames;
}
@Override
public String toString(){
StringBuffer sb = new StringBuffer("movie name: " + movie_name + "\nhaibao path: " + haibao_path + "\n");
if(names.size() != 0){
sb.append("movie has names: ");
for(int i = 0; i < names.size(); i ++){
sb.append(names.get(i) + " ");
}
}
sb.append("\n");
if(downloadlinks.size() != 0){
sb.append("movie has down loads : ");
for(int i = 0; i < downloadlinks.size(); i ++){
sb.append("\n " + downloadnames.get(i) + " " + downloadlinks.get(i));
}
}
return sb.toString();
}
@Override
public Movie_Info clone(){
return new Movie_Info(this);
}
public Movie_Info convertForMySQL(){
try {
if(movie_name != null){
- movie_name.replaceAll("'","''");
+ movie_name = movie_name.replaceAll("'","''");
}
if(haibao_path != null){
- haibao_path.replaceAll("'","''");
+ haibao_path = haibao_path.replaceAll("'","''");
}
for(int i = 0 ; i < names.size(); i ++){
names.set(i, names.get(i).replaceAll("'","''"));
}
for(int i = 0 ; i < downloadlinks.size(); i ++){
downloadlinks.set(i, downloadlinks.get(i).replaceAll("'","''"));
}
for(int i = 0 ; i < downloadnames.size(); i ++){
downloadnames.set(i, downloadnames.get(i).replaceAll("'","''"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
}
| false | true | public Movie_Info convertForMySQL(){
try {
if(movie_name != null){
movie_name.replaceAll("'","''");
}
if(haibao_path != null){
haibao_path.replaceAll("'","''");
}
for(int i = 0 ; i < names.size(); i ++){
names.set(i, names.get(i).replaceAll("'","''"));
}
for(int i = 0 ; i < downloadlinks.size(); i ++){
downloadlinks.set(i, downloadlinks.get(i).replaceAll("'","''"));
}
for(int i = 0 ; i < downloadnames.size(); i ++){
downloadnames.set(i, downloadnames.get(i).replaceAll("'","''"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
| public Movie_Info convertForMySQL(){
try {
if(movie_name != null){
movie_name = movie_name.replaceAll("'","''");
}
if(haibao_path != null){
haibao_path = haibao_path.replaceAll("'","''");
}
for(int i = 0 ; i < names.size(); i ++){
names.set(i, names.get(i).replaceAll("'","''"));
}
for(int i = 0 ; i < downloadlinks.size(); i ++){
downloadlinks.set(i, downloadlinks.get(i).replaceAll("'","''"));
}
for(int i = 0 ; i < downloadnames.size(); i ++){
downloadnames.set(i, downloadnames.get(i).replaceAll("'","''"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
|
diff --git a/code/src/adapters/db/sqlite/inventory/InventoryEntry.java b/code/src/adapters/db/sqlite/inventory/InventoryEntry.java
index 5038ed1..9e4ca46 100644
--- a/code/src/adapters/db/sqlite/inventory/InventoryEntry.java
+++ b/code/src/adapters/db/sqlite/inventory/InventoryEntry.java
@@ -1,37 +1,37 @@
package adapters.db.sqlite.inventory;
import adapters.db.sqlite.upcMap.UPCEntry;
public class InventoryEntry {
private UPCEntry upc = null;
private String created = null;
/*
* timestamp should be in seconds
*/
public InventoryEntry(UPCEntry upc, long timestamp) {
this.upc = upc;
- this.created = Long.toString(timestamp);
+ this.created = Long.toString(timestamp / 1000);
}
public InventoryEntry(UPCEntry upc, String created) {
this.upc = upc;
this.created = created;
}
public UPCEntry getUPC(){
return upc;
}
public String getCreated(){
return created;
}
public String toString() {
return getUPC().toString() + " (Created: " + getCreated() + ")";
}
public String toCSV(){
return getUPC() + "," + upc.getItemName() + "," + upc.getAmount() + "," + getCreated();
}
}
| true | true | public InventoryEntry(UPCEntry upc, long timestamp) {
this.upc = upc;
this.created = Long.toString(timestamp);
}
| public InventoryEntry(UPCEntry upc, long timestamp) {
this.upc = upc;
this.created = Long.toString(timestamp / 1000);
}
|
diff --git a/plugins/org.eclipselabs.recommenders.codesearch.rcp/src/org/eclipse/recommenders/internal/codesearch/rcp/views/QL1EditorWrapper.java b/plugins/org.eclipselabs.recommenders.codesearch.rcp/src/org/eclipse/recommenders/internal/codesearch/rcp/views/QL1EditorWrapper.java
index 711b1352..c1d76045 100644
--- a/plugins/org.eclipselabs.recommenders.codesearch.rcp/src/org/eclipse/recommenders/internal/codesearch/rcp/views/QL1EditorWrapper.java
+++ b/plugins/org.eclipselabs.recommenders.codesearch.rcp/src/org/eclipse/recommenders/internal/codesearch/rcp/views/QL1EditorWrapper.java
@@ -1,77 +1,77 @@
package org.eclipse.recommenders.internal.codesearch.rcp.views;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.embedded.EmbeddedEditorFactory;
import org.eclipse.xtext.ui.editor.embedded.IEditedResourceProvider;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.eclipselabs.recommenders.codesearch.rcp.dslQL1.QL1StandaloneSetup;
import org.eclipselabs.recommenders.codesearch.rcp.dslQL1.ui.internal.QL1Activator;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
@SuppressWarnings("restriction")
public class QL1EditorWrapper extends AbstractEmbeddedEditorWrapper {
@Override
void createQueryEditorInternal() {
final IEditedResourceProvider resourceProvider = new IEditedResourceProvider() {
@Override
public XtextResource createResource() {
try {
QL1StandaloneSetup.doSetup();
final ResourceSet resourceSet = new ResourceSetImpl();
final Resource resource = resourceSet.createResource(URI.createURI("embedded.ql1"));
return (XtextResource) resource;
} catch (final Exception e) {
return null;
}
}
};
final QL1Activator activator = QL1Activator.getInstance();
final Injector injector = activator
- .getInjector(QL1Activator.ORG_ECLIPSELABS_RECOMMENDERS_codesearch_RCP_DSLQL1_QL1);
+ .getInjector(QL1Activator.ORG_ECLIPSELABS_RECOMMENDERS_CODESEARCH_RCP_DSLQL1_QL1);
final EmbeddedEditorFactory factory = injector.getInstance(EmbeddedEditorFactory.class);
handle = factory.newEditor(resourceProvider).withParent(parent);
// keep the partialEditor as instance var to read / write the edited
// text
partialEditor = handle.createPartialEditor(true);
searchView.setSearchEnabled(false); // No translation to lucene query
// yet :-(
}
@Override
List<Document> search() throws ParseException, CorruptIndexException, IOException {
return Lists.newArrayList();
}
@Override
String[] getExampleQueriesInternal() {
return new String[] {};
}
public static String getName() {
return "Query Language 1";
}
@Override
IUnitOfWork<Set<String>, XtextResource> getSEarchTermExtractor() {
return null;
}
}
| true | true | void createQueryEditorInternal() {
final IEditedResourceProvider resourceProvider = new IEditedResourceProvider() {
@Override
public XtextResource createResource() {
try {
QL1StandaloneSetup.doSetup();
final ResourceSet resourceSet = new ResourceSetImpl();
final Resource resource = resourceSet.createResource(URI.createURI("embedded.ql1"));
return (XtextResource) resource;
} catch (final Exception e) {
return null;
}
}
};
final QL1Activator activator = QL1Activator.getInstance();
final Injector injector = activator
.getInjector(QL1Activator.ORG_ECLIPSELABS_RECOMMENDERS_codesearch_RCP_DSLQL1_QL1);
final EmbeddedEditorFactory factory = injector.getInstance(EmbeddedEditorFactory.class);
handle = factory.newEditor(resourceProvider).withParent(parent);
// keep the partialEditor as instance var to read / write the edited
// text
partialEditor = handle.createPartialEditor(true);
searchView.setSearchEnabled(false); // No translation to lucene query
// yet :-(
}
| void createQueryEditorInternal() {
final IEditedResourceProvider resourceProvider = new IEditedResourceProvider() {
@Override
public XtextResource createResource() {
try {
QL1StandaloneSetup.doSetup();
final ResourceSet resourceSet = new ResourceSetImpl();
final Resource resource = resourceSet.createResource(URI.createURI("embedded.ql1"));
return (XtextResource) resource;
} catch (final Exception e) {
return null;
}
}
};
final QL1Activator activator = QL1Activator.getInstance();
final Injector injector = activator
.getInjector(QL1Activator.ORG_ECLIPSELABS_RECOMMENDERS_CODESEARCH_RCP_DSLQL1_QL1);
final EmbeddedEditorFactory factory = injector.getInstance(EmbeddedEditorFactory.class);
handle = factory.newEditor(resourceProvider).withParent(parent);
// keep the partialEditor as instance var to read / write the edited
// text
partialEditor = handle.createPartialEditor(true);
searchView.setSearchEnabled(false); // No translation to lucene query
// yet :-(
}
|
diff --git a/framework/src/play/Play.java b/framework/src/play/Play.java
index 0f50cea3..862cd8d0 100644
--- a/framework/src/play/Play.java
+++ b/framework/src/play/Play.java
@@ -1,826 +1,831 @@
package play;
import java.io.File;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.LineNumberReader;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import play.cache.Cache;
import play.classloading.ApplicationClasses;
import play.classloading.ApplicationClassloader;
import play.exceptions.PlayException;
import play.exceptions.UnexpectedException;
import play.libs.IO;
import play.mvc.Http;
import play.mvc.Router;
import play.plugins.PluginCollection;
import play.templates.TemplateLoader;
import play.utils.OrderSafeProperties;
import play.vfs.VirtualFile;
/**
* Main framework class
*/
public class Play {
/**
* 2 modes
*/
public enum Mode {
/**
* Enable development-specific features, e.g. view the documentation at the URL {@literal "/@documentation"}.
*/
DEV,
/**
* Disable development-specific features.
*/
PROD;
public boolean isDev() {
return this == DEV;
}
public boolean isProd() {
return this == PROD;
}
}
/**
* Is the application initialized
*/
public static boolean initialized = false;
/**
* Is the application started
*/
public static boolean started = false;
/**
* True when the one and only shutdown hook is enabled
*/
private static boolean shutdownHookEnabled = false;
/**
* The framework ID
*/
public static String id;
/**
* The application mode
*/
public static Mode mode;
/**
* The application root
*/
public static File applicationPath = null;
/**
* tmp dir
*/
public static File tmpDir = null;
/**
* tmp dir is readOnly
*/
public static boolean readOnlyTmp = false;
/**
* The framework root
*/
public static File frameworkPath = null;
/**
* All loaded application classes
*/
public static ApplicationClasses classes;
/**
* The application classLoader
*/
public static ApplicationClassloader classloader;
/**
* All paths to search for files
*/
public static List<VirtualFile> roots = new ArrayList<VirtualFile>(16);
/**
* All paths to search for Java files
*/
public static List<VirtualFile> javaPath;
/**
* All paths to search for templates files
*/
public static List<VirtualFile> templatesPath;
/**
* Main routes file
*/
public static VirtualFile routes;
/**
* Plugin routes files
*/
public static Map<String, VirtualFile> modulesRoutes;
/**
* The loaded configuration files
*/
public static Set<VirtualFile> confs = new HashSet<VirtualFile>(1);
/**
* The app configuration (already resolved from the framework id)
*/
public static Properties configuration;
/**
* The last time than the application has started
*/
public static long startedAt;
/**
* The list of supported locales
*/
public static List<String> langs = new ArrayList<String>(16);
/**
* The very secret key
*/
public static String secretKey;
/**
* pluginCollection that holds all loaded plugins and all enabled plugins..
*/
public static PluginCollection pluginCollection = new PluginCollection();
/**
* Readonly list containing currently enabled plugins.
* This list is updated from pluginCollection when pluginCollection is modified
* Play plugins
* @deprecated Use pluginCollection instead.
*/
@Deprecated
public static List<PlayPlugin> plugins = pluginCollection.getEnabledPlugins();
/**
* Modules
*/
public static Map<String, VirtualFile> modules = new HashMap<String, VirtualFile>(16);
/**
* Framework version
*/
public static String version = null;
/**
* Context path (when several application are deployed on the same host)
*/
public static String ctxPath = "";
static boolean firstStart = true;
public static boolean usePrecompiled = false;
public static boolean forceProd = false;
/**
* Lazy load the templates on demand
*/
public static boolean lazyLoadTemplates = false;
/**
* This is used as default encoding everywhere related to the web: request, response, WS
*/
public static String defaultWebEncoding = "utf-8";
/**
* This flag indicates if the app is running in a standalone Play server or
* as a WAR in an applicationServer
*/
public static boolean standalonePlayServer = true;
/**
* Init the framework
*
* @param root The application path
* @param id The framework id to use
*/
public static void init(File root, String id) {
// Simple things
Play.id = id;
Play.started = false;
Play.applicationPath = root;
// load all play.static of exists
initStaticStuff();
guessFrameworkPath();
// Read the configuration file
readConfiguration();
Play.classes = new ApplicationClasses();
// Configure logs
Logger.init();
String logLevel = configuration.getProperty("application.log", "INFO");
//only override log-level if Logger was not configured manually
if (!Logger.configuredManually) {
Logger.setUp(logLevel);
}
Logger.recordCaller = Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));
Logger.info("Starting %s", root.getAbsolutePath());
if (configuration.getProperty("play.tmp", "tmp").equals("none")) {
tmpDir = null;
Logger.debug("No tmp folder will be used (play.tmp is set to none)");
} else {
tmpDir = new File(configuration.getProperty("play.tmp", "tmp"));
if (!tmpDir.isAbsolute()) {
tmpDir = new File(applicationPath, tmpDir.getPath());
}
if (Logger.isTraceEnabled()) {
Logger.trace("Using %s as tmp dir", Play.tmpDir);
}
if (!tmpDir.exists()) {
try {
if (readOnlyTmp) {
throw new Exception("ReadOnly tmp");
}
tmpDir.mkdirs();
} catch (Throwable e) {
tmpDir = null;
Logger.warn("No tmp folder will be used (cannot create the tmp dir)");
}
}
}
// Mode
- mode = Mode.valueOf(configuration.getProperty("application.mode", "DEV").toUpperCase());
- if (usePrecompiled || forceProd) {
+ try {
+ mode = Mode.valueOf(configuration.getProperty("application.mode", "DEV").toUpperCase());
+ } catch (IllegalArgumentException e) {
+ Logger.error("Illegal mode '%s', use either prod or dev", configuration.getProperty("application.mode"));
+ fatalServerErrorOccurred();
+ }
+ if (usePrecompiled || forceProd) {
mode = Mode.PROD;
}
// Context path
ctxPath = configuration.getProperty("http.path", ctxPath);
// Build basic java source path
VirtualFile appRoot = VirtualFile.open(applicationPath);
roots.add(appRoot);
javaPath = new CopyOnWriteArrayList<VirtualFile>();
javaPath.add(appRoot.child("app"));
javaPath.add(appRoot.child("conf"));
// Build basic templates path
if (appRoot.child("app/views").exists()) {
templatesPath = new ArrayList<VirtualFile>(2);
templatesPath.add(appRoot.child("app/views"));
} else {
templatesPath = new ArrayList<VirtualFile>(1);
}
// Main route file
routes = appRoot.child("conf/routes");
// Plugin route files
modulesRoutes = new HashMap<String, VirtualFile>(16);
// Load modules
loadModules();
// Load the templates from the framework after the one from the modules
templatesPath.add(VirtualFile.open(new File(frameworkPath, "framework/templates")));
// Enable a first classloader
classloader = new ApplicationClassloader();
// Fix ctxPath
if ("/".equals(Play.ctxPath)) {
Play.ctxPath = "";
}
// Default cookie domain
Http.Cookie.defaultDomain = configuration.getProperty("application.defaultCookieDomain", null);
if (Http.Cookie.defaultDomain != null) {
Logger.info("Using default cookie domain: " + Http.Cookie.defaultDomain);
}
// Plugins
pluginCollection.loadPlugins();
// Done !
if (mode == Mode.PROD || System.getProperty("precompile") != null) {
mode = Mode.PROD;
if (preCompile() && System.getProperty("precompile") == null) {
start();
} else {
return;
}
} else {
Logger.warn("You're running Play! in DEV mode");
}
// Plugins
pluginCollection.onApplicationReady();
Play.initialized = true;
}
public static void guessFrameworkPath() {
// Guess the framework path
try {
URL versionUrl = Play.class.getResource("/play/version");
// Read the content of the file
Play.version = new LineNumberReader(new InputStreamReader(versionUrl.openStream())).readLine();
// This is used only by the embedded server (Mina, Netty, Jetty etc)
URI uri = new URI(versionUrl.toString().replace(" ", "%20"));
if (frameworkPath == null || !frameworkPath.exists()) {
if (uri.getScheme().equals("jar")) {
String jarPath = uri.getSchemeSpecificPart().substring(5, uri.getSchemeSpecificPart().lastIndexOf("!"));
frameworkPath = new File(jarPath).getParentFile().getParentFile().getAbsoluteFile();
} else if (uri.getScheme().equals("file")) {
frameworkPath = new File(uri).getParentFile().getParentFile().getParentFile().getParentFile();
} else {
throw new UnexpectedException("Cannot find the Play! framework - trying with uri: " + uri + " scheme " + uri.getScheme());
}
}
} catch (Exception e) {
throw new UnexpectedException("Where is the framework ?", e);
}
}
/**
* Read application.conf and resolve overriden key using the play id mechanism.
*/
public static void readConfiguration() {
confs = new HashSet<VirtualFile>();
configuration = readOneConfigurationFile("application.conf");
extractHttpPort();
// Plugins
pluginCollection.onConfigurationRead();
}
private static void extractHttpPort() {
final String javaCommand = System.getProperty("sun.java.command", "");
jregex.Matcher m = new jregex.Pattern(".* --http.port=({port}\\d+)").matcher(javaCommand);
if (m.matches()) {
configuration.setProperty("http.port", m.group("port"));
}
}
private static Properties readOneConfigurationFile(String filename) {
Properties propsFromFile=null;
VirtualFile appRoot = VirtualFile.open(applicationPath);
VirtualFile conf = appRoot.child("conf/" + filename);
if (confs.contains(conf)) {
throw new RuntimeException("Detected recursive @include usage. Have seen the file " + filename + " before");
}
try {
propsFromFile = IO.readUtf8Properties(conf.inputstream());
} catch (RuntimeException e) {
if (e.getCause() instanceof IOException) {
Logger.fatal("Cannot read "+filename);
fatalServerErrorOccurred();
}
}
confs.add(conf);
// OK, check for instance specifics configuration
Properties newConfiguration = new OrderSafeProperties();
Pattern pattern = Pattern.compile("^%([a-zA-Z0-9_\\-]+)\\.(.*)$");
for (Object key : propsFromFile.keySet()) {
Matcher matcher = pattern.matcher(key + "");
if (!matcher.matches()) {
newConfiguration.put(key, propsFromFile.get(key).toString().trim());
}
}
for (Object key : propsFromFile.keySet()) {
Matcher matcher = pattern.matcher(key + "");
if (matcher.matches()) {
String instance = matcher.group(1);
if (instance.equals(id)) {
newConfiguration.put(matcher.group(2), propsFromFile.get(key).toString().trim());
}
}
}
propsFromFile = newConfiguration;
// Resolve ${..}
pattern = Pattern.compile("\\$\\{([^}]+)}");
for (Object key : propsFromFile.keySet()) {
String value = propsFromFile.getProperty(key.toString());
Matcher matcher = pattern.matcher(value);
StringBuffer newValue = new StringBuffer(100);
while (matcher.find()) {
String jp = matcher.group(1);
String r;
if (jp.equals("application.path")) {
r = Play.applicationPath.getAbsolutePath();
} else if (jp.equals("play.path")) {
r = Play.frameworkPath.getAbsolutePath();
} else {
r = System.getProperty(jp);
if (r == null) {
r = System.getenv(jp);
}
if (r == null) {
Logger.warn("Cannot replace %s in configuration (%s=%s)", jp, key, value);
continue;
}
}
matcher.appendReplacement(newValue, r.replaceAll("\\\\", "\\\\\\\\"));
}
matcher.appendTail(newValue);
propsFromFile.setProperty(key.toString(), newValue.toString());
}
// Include
Map<Object, Object> toInclude = new HashMap<Object, Object>(16);
for (Object key : propsFromFile.keySet()) {
if (key.toString().startsWith("@include.")) {
try {
String filenameToInclude = propsFromFile.getProperty(key.toString());
toInclude.putAll( readOneConfigurationFile(filenameToInclude) );
} catch (Exception ex) {
Logger.warn("Missing include: %s", key);
}
}
}
propsFromFile.putAll(toInclude);
return propsFromFile;
}
/**
* Start the application.
* Recall to restart !
*/
public static synchronized void start() {
try {
if (started) {
stop();
}
if( standalonePlayServer) {
// Can only register shutdown-hook if running as standalone server
if (!shutdownHookEnabled) {
//registers shutdown hook - Now there's a good chance that we can notify
//our plugins that we're going down when some calls ctrl+c or just kills our process..
shutdownHookEnabled = true;
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
Play.stop();
}
});
}
}
if (mode == Mode.DEV) {
// Need a new classloader
classloader = new ApplicationClassloader();
// Put it in the current context for any code that relies on having it there
Thread.currentThread().setContextClassLoader(classloader);
// Reload plugins
pluginCollection.reloadApplicationPlugins();
}
// Reload configuration
readConfiguration();
// Configure logs
String logLevel = configuration.getProperty("application.log", "INFO");
//only override log-level if Logger was not configured manually
if (!Logger.configuredManually) {
Logger.setUp(logLevel);
}
Logger.recordCaller = Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));
// Locales
langs = new ArrayList<String>(Arrays.asList(configuration.getProperty("application.langs", "").split(",")));
if (langs.size() == 1 && langs.get(0).trim().length() == 0) {
langs = new ArrayList<String>(16);
}
// Clean templates
TemplateLoader.cleanCompiledCache();
// SecretKey
secretKey = configuration.getProperty("application.secret", "").trim();
if (secretKey.length() == 0) {
Logger.warn("No secret key defined. Sessions will not be encrypted");
}
// Default web encoding
String _defaultWebEncoding = configuration.getProperty("application.web_encoding");
if (_defaultWebEncoding != null) {
Logger.info("Using custom default web encoding: " + _defaultWebEncoding);
defaultWebEncoding = _defaultWebEncoding;
// Must update current response also, since the request/response triggering
// this configuration-loading in dev-mode have already been
// set up with the previous encoding
if (Http.Response.current() != null) {
Http.Response.current().encoding = _defaultWebEncoding;
}
}
// Try to load all classes
Play.classloader.getAllClasses();
// Routes
Router.detectChanges(ctxPath);
// Cache
Cache.init();
// Plugins
try {
pluginCollection.onApplicationStart();
} catch (Exception e) {
if (Play.mode.isProd()) {
Logger.error(e, "Can't start in PROD mode with errors");
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new UnexpectedException(e);
}
if (firstStart) {
Logger.info("Application '%s' is now started !", configuration.getProperty("application.name", ""));
firstStart = false;
}
// We made it
started = true;
startedAt = System.currentTimeMillis();
// Plugins
pluginCollection.afterApplicationStart();
} catch (PlayException e) {
started = false;
try { Cache.stop(); } catch(Exception ignored) {}
throw e;
} catch (Exception e) {
started = false;
try { Cache.stop(); } catch(Exception ignored) {}
throw new UnexpectedException(e);
}
}
/**
* Stop the application
*/
public static synchronized void stop() {
if (started) {
Logger.trace("Stopping the play application");
pluginCollection.onApplicationStop();
started = false;
Cache.stop();
Router.lastLoading = 0L;
}
}
/**
* Force all java source and template compilation.
*
* @return success ?
*/
static boolean preCompile() {
if (usePrecompiled) {
if (Play.getFile("precompiled").exists()) {
classloader.getAllClasses();
Logger.info("Application is precompiled");
return true;
}
Logger.error("Precompiled classes are missing!!");
fatalServerErrorOccurred();
return false;
}
try {
Logger.info("Precompiling ...");
Thread.currentThread().setContextClassLoader(Play.classloader);
long start = System.currentTimeMillis();
classloader.getAllClasses();
if (Logger.isTraceEnabled()) {
Logger.trace("%sms to precompile the Java stuff", System.currentTimeMillis() - start);
}
if (!lazyLoadTemplates) {
start = System.currentTimeMillis();
TemplateLoader.getAllTemplate();
if (Logger.isTraceEnabled()) {
Logger.trace("%sms to precompile the templates", System.currentTimeMillis() - start);
}
}
return true;
} catch (Throwable e) {
Logger.error(e, "Cannot start in PROD mode with errors");
fatalServerErrorOccurred();
return false;
}
}
/**
* Detect sources modifications
*/
public static synchronized void detectChanges() {
if (mode == Mode.PROD) {
return;
}
try {
pluginCollection.beforeDetectingChanges();
if(!pluginCollection.detectClassesChange()) {
classloader.detectChanges();
}
Router.detectChanges(ctxPath);
for(VirtualFile conf : confs) {
if (conf.lastModified() > startedAt) {
start();
return;
}
}
pluginCollection.detectChange();
if (!Play.started) {
throw new RuntimeException("Not started");
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
// We have to do a clean refresh
start();
}
}
@SuppressWarnings("unchecked")
public static <T> T plugin(Class<T> clazz) {
return (T) pluginCollection.getPluginInstance((Class<? extends PlayPlugin>) clazz);
}
/**
* Allow some code to run very early in Play - Use with caution !
*/
public static void initStaticStuff() {
// Play! plugings
Enumeration<URL> urls = null;
try {
urls = Play.class.getClassLoader().getResources("play.static");
} catch (Exception e) {
}
while (urls != null && urls.hasMoreElements()) {
URL url = urls.nextElement();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
try {
Class.forName(line);
} catch (Exception e) {
Logger.warn("! Cannot init static: " + line);
}
}
} catch (Exception ex) {
Logger.error(ex, "Cannot load %s", url);
}
}
}
/**
* Load all modules.
* You can even specify the list using the MODULES environement variable.
*/
public static void loadModules() {
if (System.getenv("MODULES") != null) {
// Modules path is prepended with a env property
if (System.getenv("MODULES") != null && System.getenv("MODULES").trim().length() > 0) {
for (String m : System.getenv("MODULES").split(System.getProperty("os.name").startsWith("Windows") ? ";" : ":")) {
File modulePath = new File(m);
if (!modulePath.exists() || !modulePath.isDirectory()) {
Logger.error("Module %s will not be loaded because %s does not exist", modulePath.getName(), modulePath.getAbsolutePath());
} else {
final String modulePathName = modulePath.getName();
final String moduleName = modulePathName.contains("-") ?
modulePathName.substring(0, modulePathName.lastIndexOf("-")) :
modulePathName;
addModule(moduleName, modulePath);
}
}
}
}
for (Object key : configuration.keySet()) {
String pName = key.toString();
if (pName.startsWith("module.")) {
Logger.warn("Declaring modules in application.conf is deprecated. Use dependencies.yml instead (%s)", pName);
String moduleName = pName.substring(7);
File modulePath = new File(configuration.getProperty(pName));
if (!modulePath.isAbsolute()) {
modulePath = new File(applicationPath, configuration.getProperty(pName));
}
if (!modulePath.exists() || !modulePath.isDirectory()) {
Logger.error("Module %s will not be loaded because %s does not exist", moduleName, modulePath.getAbsolutePath());
} else {
addModule(moduleName, modulePath);
}
}
}
// Load modules from modules/ directory
File localModules = Play.getFile("modules");
if (localModules.exists() && localModules.isDirectory()) {
for (File module : localModules.listFiles()) {
String moduleName = module.getName();
if (moduleName.startsWith(".")) {
Logger.info("Module %s is ignored, name starts with a dot", moduleName);
continue;
}
if (moduleName.contains("-")) {
moduleName = moduleName.substring(0, moduleName.indexOf("-"));
}
if (module.isDirectory()) {
addModule(moduleName, module);
} else {
File modulePath = new File(IO.readContentAsString(module).trim());
if (!modulePath.exists() || !modulePath.isDirectory()) {
Logger.error("Module %s will not be loaded because %s does not exist", moduleName, modulePath.getAbsolutePath());
} else {
addModule(moduleName, modulePath);
}
}
}
}
// Auto add special modules
if (Play.runningInTestMode()) {
addModule("_testrunner", new File(Play.frameworkPath, "modules/testrunner"));
}
if (Play.mode == Mode.DEV) {
addModule("_docviewer", new File(Play.frameworkPath, "modules/docviewer"));
}
}
/**
* Add a play application (as plugin)
*
* @param path The application path
*/
public static void addModule(String name, File path) {
VirtualFile root = VirtualFile.open(path);
modules.put(name, root);
if (root.child("app").exists()) {
javaPath.add(root.child("app"));
}
if (root.child("app/views").exists()) {
templatesPath.add(root.child("app/views"));
}
if (root.child("conf/routes").exists()) {
modulesRoutes.put(name, root.child("conf/routes"));
}
roots.add(root);
if (!name.startsWith("_")) {
Logger.info("Module %s is available (%s)", name, path.getAbsolutePath());
}
}
/**
* Search a VirtualFile in all loaded applications and plugins
*
* @param path Relative path from the applications root
* @return The virtualFile or null
*/
public static VirtualFile getVirtualFile(String path) {
return VirtualFile.search(roots, path);
}
/**
* Search a File in the current application
*
* @param path Relative path from the application root
* @return The file even if it doesn't exist
*/
public static File getFile(String path) {
return new File(applicationPath, path);
}
/**
* Returns true if application is running in test-mode.
* Test-mode is resolved from the framework id.
*
* Your app is running in test-mode if the framwork id (Play.id)
* is 'test' or 'test-?.*'
* @return true if testmode
*/
public static boolean runningInTestMode() {
return id.matches("test|test-?.*");
}
/**
* Call this method when there has been a fatal error that Play cannot recover from
*/
public static void fatalServerErrorOccurred() {
if (standalonePlayServer) {
// Just quit the process
System.exit(-1);
} else {
// Cannot quit the process while running inside an applicationServer
String msg = "A fatal server error occurred";
Logger.error(msg);
throw new Error(msg);
}
}
}
| true | true | public static void init(File root, String id) {
// Simple things
Play.id = id;
Play.started = false;
Play.applicationPath = root;
// load all play.static of exists
initStaticStuff();
guessFrameworkPath();
// Read the configuration file
readConfiguration();
Play.classes = new ApplicationClasses();
// Configure logs
Logger.init();
String logLevel = configuration.getProperty("application.log", "INFO");
//only override log-level if Logger was not configured manually
if (!Logger.configuredManually) {
Logger.setUp(logLevel);
}
Logger.recordCaller = Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));
Logger.info("Starting %s", root.getAbsolutePath());
if (configuration.getProperty("play.tmp", "tmp").equals("none")) {
tmpDir = null;
Logger.debug("No tmp folder will be used (play.tmp is set to none)");
} else {
tmpDir = new File(configuration.getProperty("play.tmp", "tmp"));
if (!tmpDir.isAbsolute()) {
tmpDir = new File(applicationPath, tmpDir.getPath());
}
if (Logger.isTraceEnabled()) {
Logger.trace("Using %s as tmp dir", Play.tmpDir);
}
if (!tmpDir.exists()) {
try {
if (readOnlyTmp) {
throw new Exception("ReadOnly tmp");
}
tmpDir.mkdirs();
} catch (Throwable e) {
tmpDir = null;
Logger.warn("No tmp folder will be used (cannot create the tmp dir)");
}
}
}
// Mode
mode = Mode.valueOf(configuration.getProperty("application.mode", "DEV").toUpperCase());
if (usePrecompiled || forceProd) {
mode = Mode.PROD;
}
// Context path
ctxPath = configuration.getProperty("http.path", ctxPath);
// Build basic java source path
VirtualFile appRoot = VirtualFile.open(applicationPath);
roots.add(appRoot);
javaPath = new CopyOnWriteArrayList<VirtualFile>();
javaPath.add(appRoot.child("app"));
javaPath.add(appRoot.child("conf"));
// Build basic templates path
if (appRoot.child("app/views").exists()) {
templatesPath = new ArrayList<VirtualFile>(2);
templatesPath.add(appRoot.child("app/views"));
} else {
templatesPath = new ArrayList<VirtualFile>(1);
}
// Main route file
routes = appRoot.child("conf/routes");
// Plugin route files
modulesRoutes = new HashMap<String, VirtualFile>(16);
// Load modules
loadModules();
// Load the templates from the framework after the one from the modules
templatesPath.add(VirtualFile.open(new File(frameworkPath, "framework/templates")));
// Enable a first classloader
classloader = new ApplicationClassloader();
// Fix ctxPath
if ("/".equals(Play.ctxPath)) {
Play.ctxPath = "";
}
// Default cookie domain
Http.Cookie.defaultDomain = configuration.getProperty("application.defaultCookieDomain", null);
if (Http.Cookie.defaultDomain != null) {
Logger.info("Using default cookie domain: " + Http.Cookie.defaultDomain);
}
// Plugins
pluginCollection.loadPlugins();
// Done !
if (mode == Mode.PROD || System.getProperty("precompile") != null) {
mode = Mode.PROD;
if (preCompile() && System.getProperty("precompile") == null) {
start();
} else {
return;
}
} else {
Logger.warn("You're running Play! in DEV mode");
}
// Plugins
pluginCollection.onApplicationReady();
Play.initialized = true;
}
| public static void init(File root, String id) {
// Simple things
Play.id = id;
Play.started = false;
Play.applicationPath = root;
// load all play.static of exists
initStaticStuff();
guessFrameworkPath();
// Read the configuration file
readConfiguration();
Play.classes = new ApplicationClasses();
// Configure logs
Logger.init();
String logLevel = configuration.getProperty("application.log", "INFO");
//only override log-level if Logger was not configured manually
if (!Logger.configuredManually) {
Logger.setUp(logLevel);
}
Logger.recordCaller = Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));
Logger.info("Starting %s", root.getAbsolutePath());
if (configuration.getProperty("play.tmp", "tmp").equals("none")) {
tmpDir = null;
Logger.debug("No tmp folder will be used (play.tmp is set to none)");
} else {
tmpDir = new File(configuration.getProperty("play.tmp", "tmp"));
if (!tmpDir.isAbsolute()) {
tmpDir = new File(applicationPath, tmpDir.getPath());
}
if (Logger.isTraceEnabled()) {
Logger.trace("Using %s as tmp dir", Play.tmpDir);
}
if (!tmpDir.exists()) {
try {
if (readOnlyTmp) {
throw new Exception("ReadOnly tmp");
}
tmpDir.mkdirs();
} catch (Throwable e) {
tmpDir = null;
Logger.warn("No tmp folder will be used (cannot create the tmp dir)");
}
}
}
// Mode
try {
mode = Mode.valueOf(configuration.getProperty("application.mode", "DEV").toUpperCase());
} catch (IllegalArgumentException e) {
Logger.error("Illegal mode '%s', use either prod or dev", configuration.getProperty("application.mode"));
fatalServerErrorOccurred();
}
if (usePrecompiled || forceProd) {
mode = Mode.PROD;
}
// Context path
ctxPath = configuration.getProperty("http.path", ctxPath);
// Build basic java source path
VirtualFile appRoot = VirtualFile.open(applicationPath);
roots.add(appRoot);
javaPath = new CopyOnWriteArrayList<VirtualFile>();
javaPath.add(appRoot.child("app"));
javaPath.add(appRoot.child("conf"));
// Build basic templates path
if (appRoot.child("app/views").exists()) {
templatesPath = new ArrayList<VirtualFile>(2);
templatesPath.add(appRoot.child("app/views"));
} else {
templatesPath = new ArrayList<VirtualFile>(1);
}
// Main route file
routes = appRoot.child("conf/routes");
// Plugin route files
modulesRoutes = new HashMap<String, VirtualFile>(16);
// Load modules
loadModules();
// Load the templates from the framework after the one from the modules
templatesPath.add(VirtualFile.open(new File(frameworkPath, "framework/templates")));
// Enable a first classloader
classloader = new ApplicationClassloader();
// Fix ctxPath
if ("/".equals(Play.ctxPath)) {
Play.ctxPath = "";
}
// Default cookie domain
Http.Cookie.defaultDomain = configuration.getProperty("application.defaultCookieDomain", null);
if (Http.Cookie.defaultDomain != null) {
Logger.info("Using default cookie domain: " + Http.Cookie.defaultDomain);
}
// Plugins
pluginCollection.loadPlugins();
// Done !
if (mode == Mode.PROD || System.getProperty("precompile") != null) {
mode = Mode.PROD;
if (preCompile() && System.getProperty("precompile") == null) {
start();
} else {
return;
}
} else {
Logger.warn("You're running Play! in DEV mode");
}
// Plugins
pluginCollection.onApplicationReady();
Play.initialized = true;
}
|
diff --git a/src/core/org/luaj/vm/LuaState.java b/src/core/org/luaj/vm/LuaState.java
index ada47d6..0e517c0 100644
--- a/src/core/org/luaj/vm/LuaState.java
+++ b/src/core/org/luaj/vm/LuaState.java
@@ -1,2640 +1,2640 @@
/*******************************************************************************
* Copyright (c) 2007 LuaJ. 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 THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Stack;
import org.luaj.lib.BaseLib;
import org.luaj.lib.CoroutineLib;
import org.luaj.lib.MathLib;
import org.luaj.lib.PackageLib;
import org.luaj.lib.StringLib;
import org.luaj.lib.TableLib;
/**
* <hr>
* <h3><a name="LuaState"><code>LuaState</code></a></h3>
*
* <pre>
* typedef struct LuaState;
* </pre>
*
* <p>
* Opaque structure that keeps the whole state of a Lua interpreter. The Lua
* library is fully reentrant: it has no global variables. All information about
* a state is kept in this structure.
*
*
* <p>
* Here we list all functions and types from the C API in alphabetical
* order. Each function has an indicator like this: <span class="apii">[-o, +p,
* <em>x</em>]</span>
*
* <p>
* The first field, <code>o</code>, is how many elements the function pops
* from the stack. The second field, <code>p</code>, is how many elements the
* function pushes onto the stack. (Any function always pushes its results after
* popping its arguments.) A field in the form <code>x|y</code> means the
* function may push (or pop) <code>x</code> or <code>y</code> elements,
* depending on the situation; an interrogation mark '<code>?</code>' means
* that we cannot know how many elements the function pops/pushes by looking
* only at its arguments (e.g., they may depend on what is on the stack). The
* third field, <code>x</code>, tells whether the function may throw errors: '<code>-</code>'
* means the function never throws any error; '<code>m</code>' means the
* function may throw an error only due to not enough memory; '<code>e</code>'
* means the function may throw other kinds of errors; '<code>v</code>'
* means the function may throw an error on purpose.
*
*
*/
public class LuaState extends Lua {
/* thread status; 0 is OK */
private static final int LUA_YIELD = 1;
private static final int LUA_ERRRUN = 2;
private static final int LUA_ERRSYNTAX = 3;
private static final int LUA_ERRMEM = 4;
private static final int LUA_ERRERR = 5;
private static final int LUA_MINSTACK = 20;
private static final int LUA_MINCALLS = 10;
private static final int MAXTAGLOOP = 100;
public int base = 0;
public int top = 0;
protected int nresults = -1;
public LValue[] stack = new LValue[LUA_MINSTACK];
public int cc = -1;
public CallInfo[] calls = new CallInfo[LUA_MINCALLS];
protected Stack upvals = new Stack();
protected LFunction panic;
static LuaState mainState;
public LTable _G;
// main debug hook, overridden by DebugStackState
protected void debugHooks(int pc) {
}
protected void debugAssert(boolean b) {
}
// ------------------- constructors ---------------------
/**
* Creates a new, independent LuaState instance. <span class="apii">[-0, +0,
* <em>-</em>]</span>
*
* <p>
* Returns <code>NULL</code> if cannot create the state (due to lack of
* memory). The argument <code>f</code> is the allocator function; Lua
* does all memory allocation for this state through this function. The
* second argument, <code>ud</code>, is an opaque pointer that Lua simply
* passes to the allocator in every call.
*/
protected LuaState() {
_G = new LTable();
mainState = this;
}
/**
* Create a LuaState with a specific global environment. Used by LThread.
*
* @param globals the LTable to use as globals for this LuaState
*/
LuaState(LTable globals) {
_G = globals;
}
/**
* Performs the initialization.
*/
public void init() {}
/**
* Perform any shutdown/clean up tasks if needed
*/
public void shutdown() {}
/**
* Install the standard set of libraries used by most implementations:
* BaseLib, CoroutineLib, MathLib, PackageLib, TableLib, StringLib
*/
public void installStandardLibs() {
BaseLib.install(_G);
CoroutineLib.install(_G);
MathLib.install(_G);
PackageLib.install(_G);
TableLib.install(_G);
StringLib.install(_G);
}
// ================ interfaces for performing calls
/**
* Create a call frame for a call that has been set up on
* the stack. The first value on the stack must be a Closure,
* and subsequent values are arguments to the closure.
*/
public void prepStackCall() {
LClosure c = (LClosure) stack[base];
int resultbase = base;
// Expand the stack if necessary
checkstack( c.p.maxstacksize );
if ( ! c.p.is_vararg ) {
base += 1;
luaV_adjusttop( base+c.p.numparams );
} else {
/* vararg function */
int npar = c.p.numparams;
int narg = Math.max(0, top - base - 1);
int nfix = Math.min(narg, npar);
int nvar = Math.max(0, narg-nfix);
// must copy args into position, add number parameter
stack[top] = LInteger.valueOf(nvar);
System.arraycopy(stack, base+1, stack, top+1, nfix);
base = top + 1;
top = base + nfix;
luaV_adjusttop( base + npar );
}
final int newcc = cc + 1;
if ( newcc >= calls.length ) {
CallInfo[] newcalls = new CallInfo[ calls.length * 2 ];
System.arraycopy( calls, 0, newcalls, 0, cc+1 );
calls = newcalls;
}
calls[newcc] = new CallInfo(c, base, top, resultbase, nresults);
cc = newcc;
stackClear( top, base + c.p.maxstacksize );
}
/**
* Execute bytecodes until the current call completes
* or the vm yields.
*/
public void execute() {
for ( int cb=cc; cc>=cb; )
exec();
}
/**
* Put the closure on the stack with arguments,
* then perform the call. Leave return values
* on the stack for later querying.
*
* @param c
* @param values
*/
public void doCall( LClosure c, LValue[] args ) {
settop(0);
pushlvalue( c );
for ( int i=0, n=(args!=null? args.length: 0); i<n; i++ )
pushlvalue( args[i] );
prepStackCall();
execute();
base = (cc>=0? calls[cc].base: 0);
}
/**
* Invoke a LFunction being called via prepStackCall()
* @param javaFunction
*/
public void invokeJavaFunction(LFunction javaFunction) {
int resultbase = base;
int resultsneeded = nresults;
++base;
int nactual = javaFunction.invoke(this);
debugAssert(nactual>=0);
debugAssert(top-nactual>=base);
System.arraycopy(stack, top-nactual, stack, base=resultbase, nactual);
settop( nactual );
if ( resultsneeded >= 0 )
settop( resultsneeded );
}
// ================== error processing =================
/**
* Calls a function. <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
*
*
* <p>
* To call a function you must use the following protocol: first, the
* function to be called is pushed onto the stack; then, the arguments to
* the function are pushed in direct order; that is, the first argument is
* pushed first. Finally you call <a href="#lua_call"><code>lua_call</code></a>;
* <code>nargs</code> is the number of arguments that you pushed onto the
* stack. All arguments and the function value are popped from the stack
* when the function is called. The function results are pushed onto the
* stack when the function returns. The number of results is adjusted to
* <code>nresults</code>, unless <code>nresults</code> is <a
* name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>. In this case,
* <em>all</em> results from the function are pushed. Lua takes care that
* the returned values fit into the stack space. The function results are
* pushed onto the stack in direct order (the first result is pushed first),
* so that after the call the last result is on the top of the stack.
*
*
* <p>
* Any error inside the called function is propagated upwards (with a
* <code>longjmp</code>).
*
*
* <p>
* The following example shows how the host program may do the equivalent to
* this Lua code:
*
* <pre>
* a = f("how", t.x, 14)
* </pre>
*
* <p>
* Here it is in C:
*
* <pre>
* lua_getfield(L, LUA_GLOBALSINDEX, "f"); // function to be called
* lua_pushstring(L, "how"); // 1st argument
* lua_getfield(L, LUA_GLOBALSINDEX, "t"); // table to be indexed
* lua_getfield(L, -1, "x"); // push result of t.x (2nd arg)
* lua_remove(L, -2); // remove 't' from the stack
* lua_pushinteger(L, 14); // 3rd argument
* lua_call(L, 3, 1); // call 'f' with 3 arguments and 1 result
* lua_setfield(L, LUA_GLOBALSINDEX, "a"); // set global 'a'
* </pre>
*
* <p>
* Note that the code above is "balanced": at its end, the stack is back to
* its original configuration. This is considered good programming practice.
*/
public void call( int nargs, int nreturns ) {
// save stack state
int oldbase = base;
// rb is base of new call frame
int rb = this.base = top - 1 - nargs;
// make or set up the call
this.nresults = nreturns;
if (this.stack[base].luaStackCall(this)) {
// call was set up on the stack,
// we still have to execute it
execute();
}
// adjustTop only for case when call was completed
// and number of args > 0. If call completed but
// c == 0, leave top to point to end of results
if (nreturns >= 0)
luaV_adjusttop(rb + nreturns);
// restore base
this.base = oldbase;
}
/**
* Calls a function in protected mode. <span class="apii">[-(nargs + 1),
* +(nresults|1), <em>-</em>]</span>
*
*
* <p>
* Both <code>nargs</code> and <code>nresults</code> have the same
* meaning as in <a href="#lua_call"><code>lua_call</code></a>. If there
* are no errors during the call, <a href="#lua_pcall"><code>lua_pcall</code></a>
* behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
* However, if there is any error, <a href="#lua_pcall"><code>lua_pcall</code></a>
* catches it, pushes a single value on the stack (the error message), and
* returns an error code. Like <a href="#lua_call"><code>lua_call</code></a>,
* <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the
* function and its arguments from the stack.
*
*
* <p>
* If <code>errfunc</code> is 0, then the error message returned on the
* stack is exactly the original error message. Otherwise,
* <code>errfunc</code> is the stack index of an
* <em>error handler function</em>. (In the current implementation, this
* index cannot be a pseudo-index.) In case of runtime errors, this function
* will be called with the error message and its return value will be the
* message returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
*
*
* <p>
* Typically, the error handler function is used to add more debug
* information to the error message, such as a stack traceback. Such
* information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
* since by then the stack has unwound.
*
*
* <p>
* The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns
* 0 in case of success or one of the following error codes (defined in
* <code>lua.h</code>):
*
* <ul>
*
* <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>:</b> a
* runtime error. </li>
*
* <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
* memory allocation error. For such errors, Lua does not call the error
* handler function. </li>
*
* <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>:</b>
* error while running the error handler function. </li>
*
* </ul>
*/
public int pcall( int nargs, int nreturns, int errfunc ) {
// save stack state
int oldtop = top;
int oldbase = base;
int oldcc = cc;
try {
// rb is base of new call frame
int rb = this.base = top - 1 - nargs;
// make or set up the call
this.nresults = nreturns;
if (this.stack[base].luaStackCall(this)) {
// call was set up on the stack,
// we still have to execute it
execute();
}
// adjustTop only for case when call was completed
// and number of args > 0. If call completed but
// c == 0, leave top to point to end of results
if (nreturns >= 0)
luaV_adjusttop(rb + nreturns);
// restore base
this.base = oldbase;
return 0;
} catch ( Throwable t ) {
this.base = oldbase;
this.cc = oldcc;
closeUpVals(oldtop); /* close eventual pending closures */
String s = t.getMessage();
resettop();
pushstring( s!=null? s: t.toString() );
return (t instanceof OutOfMemoryError? LUA_ERRMEM: LUA_ERRRUN);
}
}
/**
* Loads a Lua chunk. <span class="apii">[-0, +1, <em>-</em>]</span>
*
* <p>
* If there are no errors, <a href="#lua_load"><code>lua_load</code></a>
* pushes the compiled chunk as a Lua function on top of the stack.
* Otherwise, it pushes an error message. The return values of <a
* href="#lua_load"><code>lua_load</code></a> are:
*
* <ul>
*
* <li><b>0:</b> no errors;</li>
*
* <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>:</b>
* syntax error during pre-compilation;</li>
*
* <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
* memory allocation error.</li>
*
* </ul>
*
* <p>
* This function only loads a chunk; it does not run it.
*
*
* <p>
* <a href="#lua_load"><code>lua_load</code></a> automatically detects
* whether the chunk is text or binary, and loads it accordingly (see
* program <code>luac</code>).
*
*
* <p>
* The <a href="#lua_load"><code>lua_load</code></a> function uses a
* user-supplied <code>reader</code> function to read the chunk (see <a
* href="#lua_Reader"><code>lua_Reader</code></a>). The
* <code>data</code> argument is an opaque value passed to the reader
* function.
*
*
* <p>
* The <code>chunkname</code> argument gives a name to the chunk, which is
* used for error messages and in debug information (see <a
* href="#3.8">§3.8</a>).
*/
public int load( InputStream is, String chunkname ) {
try {
LPrototype p = LoadState.undump(this, is, chunkname );
pushlvalue( p.newClosure( _G ) );
return 0;
} catch ( Throwable t ) {
pushstring( t.getMessage() );
return (t instanceof OutOfMemoryError? LUA_ERRMEM: LUA_ERRSYNTAX);
}
}
// ================ execute instructions
private LValue RKBC(LValue[] k, int bc) {
return LuaState.ISK(bc) ?
k[LuaState.INDEXK(bc)]:
stack[base + bc];
}
private LValue GETARG_RKB(LValue[] k, int i) {
return RKBC(k, GETARG_B(i));
}
private LValue GETARG_RKC(LValue[] k, int i) {
return RKBC(k, GETARG_C(i));
}
private final void stackClear(int startIndex, int endIndex) {
for (; startIndex < endIndex; startIndex++) {
stack[startIndex] = LNil.NIL;
}
}
/** execute instructions up to a yield, return, or call */
public void exec() {
if ( cc < 0 )
return;
int i, a, b, c, o, n, cb;
LValue rkb, rkc, nvarargs, key, val;
LValue i0, step, idx, limit, init, table;
boolean back, body;
LPrototype proto;
LClosure newClosure;
// reload values from the current call frame
// into local variables
CallInfo ci = calls[cc];
LClosure cl = ci.closure;
LPrototype p = cl.p;
int[] code = p.code;
LValue[] k = p.k;
this.base = ci.base;
// loop until a return instruction is processed,
// or the vm yields
while (true) {
debugAssert( ci == calls[cc] );
// sync up top
ci.top = top;
// allow debug hooks a chance to operate
debugHooks( ci.pc );
// advance program counter
i = code[ci.pc++];
// get opcode and first arg
o = (i >> POS_OP) & MAX_OP;
a = (i >> POS_A) & MAXARG_A;
switch (o) {
case LuaState.OP_MOVE: {
b = LuaState.GETARG_B(i);
this.stack[base + a] = this.stack[base + b];
continue;
}
case LuaState.OP_LOADK: {
b = LuaState.GETARG_Bx(i);
this.stack[base + a] = k[b];
continue;
}
case LuaState.OP_LOADBOOL: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
this.stack[base + a] = (b != 0 ? LBoolean.TRUE : LBoolean.FALSE);
if (c != 0)
ci.pc++; /* skip next instruction (if C) */
continue;
}
case LuaState.OP_LOADNIL: {
b = LuaState.GETARG_B(i);
do {
this.stack[base + b] = LNil.NIL;
} while ((--b) >= a);
continue;
}
case LuaState.OP_GETUPVAL: {
b = LuaState.GETARG_B(i);
this.stack[base + a] = cl.upVals[b].getValue();
continue;
}
case LuaState.OP_GETGLOBAL: {
b = LuaState.GETARG_Bx(i);
key = k[b];
- table = cl.env;
- this.stack[base + a] = luaV_gettable(table, key);
+ table = cl.env;
+ val = luaV_gettable(table, key);
+ this.stack[base + a] = val;
continue;
}
case LuaState.OP_GETTABLE: {
b = LuaState.GETARG_B(i);
key = GETARG_RKC(k, i);
table = this.stack[base + b];
- this.stack[base + a] = luaV_gettable(table, key);
+ val = luaV_gettable(table, key);
+ this.stack[base + a] = val;
continue;
}
case LuaState.OP_SETGLOBAL: {
b = LuaState.GETARG_Bx(i);
key = k[b];
val = this.stack[base + a];
table = cl.env;
luaV_settable(table, key, val);
continue;
}
case LuaState.OP_SETUPVAL: {
b = LuaState.GETARG_B(i);
cl.upVals[b].setValue( this.stack[base + a] );
continue;
}
case LuaState.OP_SETTABLE: {
key = GETARG_RKB(k, i);
val = GETARG_RKC(k, i);
table = this.stack[base + a];
luaV_settable(table, key, val);
continue;
}
case LuaState.OP_NEWTABLE: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
this.stack[base + a] = new LTable(b, c);
continue;
}
case LuaState.OP_SELF: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
- this.stack[base + a] = luaV_gettable(rkb, rkc);
+ val = luaV_gettable(rkb, rkc);
+ this.stack[base + a] = val;
this.stack[base + a + 1] = rkb;
- // StkId rb = RB(i);
- // setobjs2s(L, ra+1, rb);
- // Protect(luaV_gettable(L, rb, RKC(i), ra));
continue;
}
case LuaState.OP_ADD:
case LuaState.OP_SUB:
case LuaState.OP_MUL:
case LuaState.OP_DIV:
case LuaState.OP_MOD:
case LuaState.OP_POW: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
this.stack[base + a] = rkc.luaBinOpUnknown(o, rkb);
continue;
}
case LuaState.OP_UNM: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = rkb.luaUnaryMinus();
continue;
}
case LuaState.OP_NOT: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = (!rkb.toJavaBoolean() ? LBoolean.TRUE
: LBoolean.FALSE);
continue;
}
case LuaState.OP_LEN: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = LInteger.valueOf( rkb.luaLength() );
continue;
}
case LuaState.OP_CONCAT: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
int numValues = c - b + 1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int j = b, l = 0; j <= c; j++, l++) {
this.stack[base + j].luaConcatTo( baos );
}
this.stack[base + a] = new LString( baos.toByteArray() );
continue;
}
case LuaState.OP_JMP: {
ci.pc += LuaState.GETARG_sBx(i);
continue;
}
case LuaState.OP_EQ:
case LuaState.OP_LT:
case LuaState.OP_LE: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
boolean test = rkc.luaBinCmpUnknown(o, rkb);
if (test == (a == 0))
ci.pc++;
continue;
}
case LuaState.OP_TEST: {
c = LuaState.GETARG_C(i);
if (this.stack[base + a].toJavaBoolean() != (c != 0))
ci.pc++;
continue;
}
case LuaState.OP_TESTSET: {
rkb = GETARG_RKB(k, i);
c = LuaState.GETARG_C(i);
if (rkb.toJavaBoolean() != (c != 0))
ci.pc++;
else
this.stack[base + a] = rkb;
continue;
}
case LuaState.OP_CALL: {
// ra is base of new call frame
this.base += a;
// number of args
b = LuaState.GETARG_B(i);
if (b != 0) // else use previous instruction set top
luaV_settop_fillabove( base + b );
// number of return values we need
c = LuaState.GETARG_C(i);
// make or set up the call
this.nresults = c - 1;
if (this.stack[base].luaStackCall(this))
return;
// adjustTop only for case when call was completed
// and number of args > 0. If call completed but
// c == 0, leave top to point to end of results
if (c > 0)
luaV_adjusttop(base + c - 1);
// restore base
base = ci.base;
continue;
}
case LuaState.OP_TAILCALL: {
closeUpVals(base);
// copy down the frame before calling!
// number of args (including the function)
b = LuaState.GETARG_B(i);
if (b != 0) // else use previous instruction set top
luaV_settop_fillabove( base + a + b );
else
b = top - (base + a);
// copy call + all args, discard current frame
System.arraycopy(stack, base + a, stack, ci.resultbase, b);
this.base = ci.resultbase;
luaV_settop_fillabove( base + b );
this.nresults = ci.nresults;
--cc;
// make or set up the call
try {
if (this.stack[base].luaStackCall(this)) {
return;
}
} catch (LuaErrorException e) {
// in case of lua error, we need to restore cc so that
// the debug can get the correct location where the error
// occured.
cc++;
throw e;
}
// adjustTop only for case when call was completed
// and number of args > 0. If call completed but
// c == 0, leave top to point to end of results
if (this.nresults >= 0)
luaV_adjusttop(base + nresults);
// force restore of base, etc.
return;
}
case LuaState.OP_RETURN: {
closeUpVals( base );
// number of return vals to return
b = LuaState.GETARG_B(i) - 1;
if (b >= 0) // else use previous instruction set top
luaV_settop_fillabove( base + a + b );
else
b = top - (base + a);
// number to copy down
System.arraycopy(stack, base + a, stack, ci.resultbase, b);
debugAssert( ci.resultbase + b <= top );
luaV_settop_fillabove( ci.resultbase + b );
// adjust results to what caller expected
if (ci.nresults >= 0)
luaV_adjusttop(ci.resultbase + ci.nresults);
// pop the call stack
--cc;
// force a reload of the calling context
return;
}
case LuaState.OP_FORLOOP: {
i0 = this.stack[base + a];
step = this.stack[base + a + 2];
idx = step.luaBinOpUnknown(Lua.OP_ADD, i0);
limit = this.stack[base + a + 1];
back = step.luaBinCmpInteger(Lua.OP_LT, 0);
body = (back ? idx.luaBinCmpUnknown(Lua.OP_LE, limit) : limit
.luaBinCmpUnknown(Lua.OP_LE, idx));
if (body) {
this.stack[base + a] = idx;
this.stack[base + a + 3] = idx;
ci.pc += LuaState.GETARG_sBx(i);
}
continue;
}
case LuaState.OP_FORPREP: {
init = this.stack[base + a];
step = this.stack[base + a + 2];
this.stack[base + a] = step.luaBinOpUnknown(Lua.OP_SUB, init);
b = LuaState.GETARG_sBx(i);
ci.pc += b;
continue;
}
case LuaState.OP_TFORLOOP: {
cb = base + a + 3; /* call base */
base = cb;
System.arraycopy(this.stack, cb-3, this.stack, cb, 3);
luaV_settop_fillabove( cb + 3 );
// call the iterator
c = LuaState.GETARG_C(i);
this.nresults = c;
if (this.stack[cb].luaStackCall(this))
execute();
base = ci.base;
luaV_adjusttop( cb + c );
// test for continuation
if (!this.stack[cb].isNil() ) { // continue?
this.stack[cb-1] = this.stack[cb]; // save control variable
} else {
ci.pc++; // skip over jump
}
continue;
}
case LuaState.OP_SETLIST: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
int listBase = base + a;
if (b == 0) {
b = top - listBase - 1;
}
if (c == 0) {
c = code[ci.pc++];
}
int offset = (c-1) * LFIELDS_PER_FLUSH;
LTable tbl = (LTable) this.stack[base + a];
for (int j=1; j<=b; j++) {
tbl.put(offset+j, stack[listBase + j]);
}
continue;
}
case LuaState.OP_CLOSE: {
closeUpVals( base + a ); // close upvals higher in the stack than position a
continue;
}
case LuaState.OP_CLOSURE: {
b = LuaState.GETARG_Bx(i);
proto = cl.p.p[b];
newClosure = proto.newClosure(cl.env);
for (int j = 0; j < newClosure.upVals.length; j++, ci.pc++) {
i = code[ci.pc];
o = LuaState.GET_OPCODE(i);
b = LuaState.GETARG_B(i);
if (o == LuaState.OP_GETUPVAL) {
newClosure.upVals[j] = cl.upVals[b];
} else if (o == LuaState.OP_MOVE) {
newClosure.upVals[j] = findUpVal( base + b );
} else {
throw new java.lang.IllegalArgumentException(
"bad opcode: " + o);
}
}
this.stack[base + a] = newClosure;
continue;
}
case LuaState.OP_VARARG: {
// figure out how many args to copy
b = LuaState.GETARG_B(i) - 1;
nvarargs = this.stack[base - 1];
n = nvarargs.toJavaInt();
if (b == LuaState.LUA_MULTRET) {
b = n; // use entire varargs supplied
}
// copy args up to call stack area
checkstack(a+b);
for (int j = 0; j < b; j++)
this.stack[base + a + j] = (j < n ? this.stack[base
- n + j - 1]
: LNil.NIL);
luaV_settop_fillabove( base + a + b );
continue;
}
}
}
}
public UpVal findUpVal( int target ) {
UpVal up;
int i;
for ( i = this.upvals.size() - 1; i >= 0; --i ) {
up = (UpVal) this.upvals.elementAt( i );
if ( up.state == this && up.position == target ) {
return up;
} else if ( up.position < target ) {
break;
}
}
up = new UpVal( this, target );
this.upvals.insertElementAt( up, i + 1 );
return up;
}
public void closeUpVals( int limit ) {
while ( !upvals.empty() && ( (UpVal) this.upvals.lastElement() ).close( limit ) ) {
this.upvals.pop();
}
}
public CallInfo getStackFrame(int callStackDepth) {
return calls[cc-callStackDepth];
}
private LValue mtget(LValue t, LString tag) {
LTable mt = t.luaGetMetatable();
if ( mt == null )
return null;
LValue h = mt.get(tag);
return h.isNil()? null: h;
}
private void indexError(LValue nontable) {
error( "attempt to index ? (a "+nontable.luaGetTypeName()+" value)", 1 );
}
public LValue luaV_gettable(LValue table, LValue key) {
LValue h=LNil.NIL,t=table;
for ( int loop=0; loop<MAXTAGLOOP; loop++ ) {
if ( t.isTable() ) {
LValue v = ((LTable) t).get(key);
if ( !v.isNil() ) {
return v;
}
h = mtget(t, LTable.TM_INDEX);
if ( h == null ) {
return v;
}
} else {
h = mtget(t, LTable.TM_INDEX);
if ( h == null ) {
indexError(t);
}
}
if (h.isFunction()) {
int oldtop = top;
int oldbase = base;
try {
base = base + this.calls[cc].closure.p.maxstacksize;
top = base;
pushlvalue(h);
pushlvalue(table);
pushlvalue(key);
call(2,1);
return poplvalue();
} finally {
resettop();
base = oldbase;
top = oldtop;
}
}
t = h;
}
error("loop in gettable");
return LNil.NIL;
}
public void luaV_settable(LValue table, LValue key, LValue val) {
LValue h=LNil.NIL,t=table;
for ( int loop=0; loop<MAXTAGLOOP; loop++ ) {
if ( t.isTable() ) {
LTable lt = (LTable) t;
if ( lt.containsKey(key) ) {
lt.put(key, val);
return;
}
h = mtget(t, LTable.TM_NEWINDEX);
if ( h == null ) {
lt.put(key, val);
return;
}
} else {
h = mtget(t, LTable.TM_NEWINDEX);
if ( h == null ) {
indexError(t);
}
}
if (h.isFunction()) {
int oldtop = top;
int oldbase = base;
try {
base = base + this.calls[cc].closure.p.maxstacksize;
top = base;
pushlvalue(h);
pushlvalue(table);
pushlvalue(key);
pushlvalue(val);
call(3,0);
return;
} finally {
resettop();
base = oldbase;
top = oldtop;
}
}
t = h;
}
error("loop in settable");
}
/** Move top, and fill in both directions */
private void luaV_adjusttop(int newTop) {
while (top < newTop)
this.stack[top++] = LNil.NIL;
while (top > newTop)
this.stack[--top] = LNil.NIL;
}
/** Move top down, filling from above */
private void luaV_settop_fillabove(int newTop) {
while (top > newTop)
this.stack[--top] = LNil.NIL;
top = newTop;
}
//===============================================================
// Lua Java API
//===============================================================
private void notImplemented() {
throw new LuaErrorException("AbstractStack: not yet implemented");
}
/**
* Sets a new panic function and returns the old one. <span
* class="apii">[-0, +0, <em>-</em>]</span>
*
*
* <p>
* If an error happens outside any protected environment, Lua calls a
* <em>panic function</em> and then calls <code>exit(EXIT_FAILURE)</code>,
* thus exiting the host application. Your panic function may avoid this
* exit by never returning (e.g., doing a long jump).
*
*
* <p>
* The panic function can access the error message at the top of the stack.
*/
public LFunction atpanic(LFunction panicf) {
LFunction f = panic;
panic = panicf;
return f;
}
/**
* Returns the current program counter for the given call frame.
* @param ci -- A call frame
* @return the current program counter for the given call frame.
*/
protected int getCurrentPc(CallInfo ci) {
int pc = (ci != calls[cc] ? ci.pc - 1 : ci.pc);
return pc;
}
protected String getSourceFileName(LString source) {
String sourceStr = LoadState.getSourceName(source.toJavaString());
return getSourceFileName(sourceStr);
}
protected String getSourceFileName(String sourceStr) {
if (!LoadState.SOURCE_BINARY_STRING.equals(sourceStr)) {
sourceStr = sourceStr.replace('\\', '/');
}
int index = sourceStr.lastIndexOf('/');
if (index != -1) {
sourceStr = sourceStr.substring(index + 1);
}
return sourceStr;
}
/**
* Get the file line number info for a particular call frame.
* @param cindex index into call stack
* @return
*/
protected String getFileLine(int cindex) {
String source = "?";
String line = "";
if (cindex >= 0 && cindex <= cc) {
CallInfo call = this.calls[cindex];
LPrototype p = call.closure.p;
if (p != null && p.source != null)
source = getSourceFileName(p.source);
int pc = getCurrentPc(call);
if (p.lineinfo != null && p.lineinfo.length > pc)
line = ":" + String.valueOf(p.lineinfo[pc]);
}
return source + line;
}
public String getStackTrace() {
StringBuffer buffer = new StringBuffer("Stack Trace:\n");
for (int i = cc; i >= 0; i--) {
buffer.append(" ");
buffer.append(getFileLine(i));
buffer.append("\n");
}
return buffer.toString();
}
/**
* Raises an error. The message is pushed onto the stack and used as the error message.
* It also adds at the beginning of the message the file name and the line number where
* the error occurred, if this information is available.
*
* In the java implementation this throws a LuaErrorException
* after filling line number information first when level > 0.
*/
public void error(String message, int level) {
throw new LuaErrorException( this, message, level );
}
/**
* Raises an error with the default level.
*/
public void error(String message) {
throw new LuaErrorException( this, message, 1 );
}
/**
* Generates a Lua error. <span class="apii">[-1, +0, <em>v</em>]</span>
*
* <p>
* The error message (which can actually be a Lua value of any type) must be
* on the stack top. This function does a long jump, and therefore never
* returns. (see <a href="#luaL_error"><code>luaL_error</code></a>).
*
*/
public void error() {
throw new LuaErrorException( this, tostring(-1), 0);
}
/**
* Dumps a function as a binary chunk. <span class="apii">[-0, +0,
* <em>m</em>]</span>
*
* <p>
* Receives a Lua function on the top of the stack and produces a binary
* chunk that, if loaded again, results in a function equivalent to the one
* dumped. As it produces parts of the chunk, <a href="#lua_dump"><code>lua_dump</code></a>
* calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
* with the given <code>data</code> to write them.
* <p>
* The value returned is the error code returned by the last call to the
* writer; 0 means no errors.
*
*
* <p>
* This function does not pop the Lua function from the stack.
*
*/
public void dump() {
notImplemented();
}
/**
* Pushes a new C closure onto the stack. <span class="apii">[-n, +1,
* <em>m</em>]</span>
*
*
* <p>
* When a Java function is created, it is possible to associate some
* values with it, thus creating a C closure (see <a
* href="#3.4">§3.4</a>); these values are then accessible to the
* function whenever it is called. To associate values with a
* C function, first these values should be pushed onto the stack (when
* there are multiple values, the first value is pushed first). Then <a
* href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> is called
* to create and push the C function onto the stack, with the argument
* <code>n</code> telling how many values should be associated with the
* function. <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
* also pops these values from the stack.
*/
public void pushclosure(LFunction fn, int n) {
notImplemented();
}
/**
* Calls the C function <code>func</code> in protected mode. <span
* class="apii">[-0, +(0|1), <em>-</em>]</span>
*
* <p>
* <code>func</code> starts with only one element in its stack, a light
* userdata containing <code>ud</code>. In case of errors, <a
* href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error
* codes as <a href="#lua_pcall"><code>lua_pcall</code></a>, plus the
* error object on the top of the stack; otherwise, it returns zero, and
* does not change the stack. All values returned by <code>func</code> are
* discarded.
*/
public int javapcall(LFunction func, Object ud) {
this.pushjavafunction(func);
this.pushlightuserdata(ud);
return this.pcall(1, 0, 0);
}
/**
* Format and push a string. <span class="apii">[-0, +1, <em>m</em>]</span>
*
* <p>
* Pushes onto the stack a formatted string and returns a pointer to this
* string. It is similar to the C function <code>sprintf</code>, but
* has some important differences:
*
* <ul>
*
* <li> You do not have to allocate space for the result: the result is a
* Lua string and Lua takes care of memory allocation (and deallocation,
* through garbage collection). </li>
*
* <li> The conversion specifiers are quite restricted. There are no flags,
* widths, or precisions. The conversion specifiers can only be '<code>%%</code>'
* (inserts a '<code>%</code>' in the string), '<code>%s</code>'
* (inserts a zero-terminated string, with no size restrictions), '<code>%f</code>'
* (inserts a <a href="#lua_Number"><code>lua_Number</code></a>), '<code>%p</code>'
* (inserts a pointer as a hexadecimal numeral), '<code>%d</code>'
* (inserts an <code>int</code>), and '<code>%c</code>' (inserts an
* <code>int</code> as a character). </li>
*
* </ul>
*/
public String pushfstring(String fmt, Object[] args) {
notImplemented();
return null;
}
/**
* Format and push a string. <span class="apii">[-0, +1, <em>m</em>]</span>
*
* <p>
* Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>,
* except that it receives a <code>va_list</code> instead of a variable
* number of arguments.
*/
public void pushvfstring(String format, Object[] args) {
notImplemented();
}
/**
* Test if two objects are the same object. <span class="apii">[-0, +0,
* <em>-</em>]</span>
*
* <p>
* Returns 1 if the two values in acceptable indices <code>index1</code>
* and <code>index2</code> are primitively equal (that is, without calling
* metamethods). Otherwise returns 0. Also returns 0 if any of the
* indices are non valid.
*/
public void rawequal(int index1, int index2) {
notImplemented();
}
/**
* Pushes a value's environment table. <span class="apii">[-0, +1,
* <em>-</em>]</span>
*
* <p>
* Pushes onto the stack the environment table of the value at the given
* index.
*/
public void getfenv(int index) {
LValue f = topointer(index);
pushlvalue( ((LClosure) f).env );
}
/**
* Set the environment for a value. <span class="apii">[-1, +0, <em>-</em>]</span>
*
* <p>
* Pops a table from the stack and sets it as the new environment for the
* value at the given index. If the value at the given index is neither a
* function nor a thread nor a userdata, <a href="#lua_setfenv"><code>lua_setfenv</code></a>
* returns 0. Otherwise it returns 1.
*/
public int setfenv(int index) {
LTable t = totable(-1);
LValue f = topointer(index);
pop(1);
return f.luaSetEnv(t);
}
/**
*
* Ensures that there are at least <code>extra</code> free stack slots in
* the stack. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* It returns false if it cannot grow the stack to that size. This function
* never shrinks the stack; if the stack is already larger than the new
* size, it is left unchanged.
*
*/
public void checkstack(int extra) {
if ( top + extra >= stack.length ) {
int n = Math.max( top + extra + LUA_MINSTACK, stack.length * 2 );
LValue[] s = new LValue[n];
System.arraycopy(stack, 0, s, 0, stack.length);
stack = s;
}
}
/**
* Closes the given Lua state. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Destroys all objects in the given Lua state (calling the corresponding
* garbage-collection metamethods, if any) and frees all dynamic memory used
* by this state. On several platforms, you may not need to call this
* function, because all resources are naturally released when the host
* program ends. On the other hand, long-running programs, such as a daemon
* or a web server, might need to release states as soon as they are not
* needed, to avoid growing too large.
*/
public void close() {
stack = new LValue[20];
base = top = 0;
}
/**
* Concatenates the <code>n</code> values at the top of the stack. <span
* class="apii">[-n, +1, <em>e</em>]</span>
*
* <p>
* Concatenates the <code>n</code> values at the top of the stack, pops
* them, and leaves the result at the top. If <code>n</code> is 1,
* the result is the single value on the stack (that is, the function does
* nothing); if <code>n</code> is 0, the result is the empty string.
* Concatenation is performed following the usual semantics of Lua (see <a
* href="#2.5.4">§2.5.4</a>).
*/
public void concat(int n) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for ( int i=-n; i<0; i++ ) {
LString ls = tolstring(i);
baos.write(ls.m_bytes, ls.m_offset, ls.m_length);
}
pop(n);
pushlvalue( new LString(baos.toByteArray()));
}
/**
* Creates a new empty table and pushes it onto the stack. <span
* class="apii">[-0, +1, <em>m</em>]</span>
*
* <p>
* The new table has space pre-allocated for <code>narr</code> array
* elements and <code>nrec</code> non-array elements. This pre-allocation
* is useful when you know exactly how many elements the table will have.
* Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
*/
public void createtable(int narr, int nrec) {
pushlvalue( new LTable(narr, nrec) );
}
/**
* Tests if two items on the stack are equal. <span class="apii">[-0, +0,
* <em>e</em>]</span>
*
* <p>
* Returns 1 if the two values in acceptable indices <code>index1</code>
* and <code>index2</code> are equal, following the semantics of the Lua
* <code>==</code> operator (that is, may call metamethods). Otherwise
* returns 0. Also returns 0 if any of the indices is non valid.
*
*
*/
public boolean equal(int index1, int index2) {
return topointer(index2).luaBinOpUnknown(Lua.OP_EQ,
topointer(index1)).toJavaBoolean();
}
/**
* Controls the garbage collector. <span class="apii">[-0, +0, <em>e</em>]</span>
*
* <p>
* This function performs several tasks, according to the value of the
* parameter <code>what</code>:
*
* <ul>
*
* <li><b><code>LUA_GCSTOP</code>:</b> stops the garbage collector.
* </li>
*
* <li><b><code>LUA_GCRESTART</code>:</b> restarts the garbage
* collector. </li>
*
* <li><b><code>LUA_GCCOLLECT</code>:</b> performs a full
* garbage-collection cycle. </li>
*
* <li><b><code>LUA_GCCOUNT</code>:</b> returns the current amount of
* memory (in Kbytes) in use by Lua. </li>
*
* <li><b><code>LUA_GCCOUNTB</code>:</b> returns the remainder of
* dividing the current amount of bytes of memory in use by Lua by 1024.
* </li>
*
* <li><b><code>LUA_GCSTEP</code>:</b> performs an incremental step of
* garbage collection. The step "size" is controlled by <code>data</code>
* (larger values mean more steps) in a non-specified way. If you want to
* control the step size you must experimentally tune the value of
* <code>data</code>. The function returns 1 if the step finished a
* garbage-collection cycle. </li>
*
* <li><b><code>LUA_GCSETPAUSE</code>:</b> sets <code>data</code>/100
* as the new value for the <em>pause</em> of the collector (see <a
* href="#2.10">§2.10</a>). The function returns the previous value of
* the pause. </li>
*
* <li><b><code>LUA_GCSETSTEPMUL</code>:</b> sets <code>data</code>/100
* as the new value for the <em>step multiplier</em> of the collector (see
* <a href="#2.10">§2.10</a>). The function returns the previous value
* of the step multiplier. </li>
*
* </ul>
*/
public void gc(int what, int data) {
notImplemented();
}
/**
* Dereference a tables field. <span class="apii">[-0, +1, <em>e</em>]</span>
*
* <p>
* Pushes onto the stack the value <code>t[k]</code>, where
* <code>t</code> is the value at the given valid index. As in Lua, this
* function may trigger a metamethod for the "index" event (see <a
* href="#2.8">§2.8</a>).
*
*/
public void getfield(int index, LString k) {
LTable t = totable(index);
pushlvalue( luaV_gettable(t, k) );
}
/**
* Look up a global value. <span class="apii">[-0, +1, <em>e</em>]</span>
*
* <p>
* Pushes onto the stack the value of the global <code>name</code>. It is
* defined as a macro:
*
* <pre>
* #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
*
* </pre>
*/
public void getglobal(String s) {
pushlvalue( luaV_gettable(_G, new LString(s)) );
}
/**
* Get a value's metatable. <span class="apii">[-0, +(0|1), <em>-</em>]</span>
*
* <p>
* Pushes onto the stack the metatable of the value at the given acceptable
* index. If the index is not valid, or if the value does not have a
* metatable, the function returns false and pushes nothing on the stack.
*
* @return true if the metatable was pushed onto the stack, false otherwise
*/
public boolean getmetatable(int index) {
LTable mt = topointer(index).luaGetMetatable();
if ( mt != null ) {
pushlvalue( mt );
return true;
}
return false;
}
/**
* Dereference a table's list element. <span class="apii">[-1, +1,
* <em>e</em>]</span>
*
* <p>
* Pushes onto the stack the value <code>t[k]</code>, where
* <code>t</code> is the value at the given valid index and <code>k</code>
* is the value at the top of the stack.
*
* <p>
* This function pops the key from the stack (putting the resulting value in
* its place). As in Lua, this function may trigger a metamethod for the
* "index" event (see <a href="#2.8">§2.8</a>).
*/
public void gettable(int index) {
LValue t = totable(index);
LValue k = poplvalue();
pushlvalue( luaV_gettable(t, k) );
}
/**
* Insert the top item somewhere in the stack. <span class="apii">[-1, +1,
* <em>-</em>]</span>
*
* <p>
* Moves the top element into the given valid index, shifting up the
* elements above this index to open space. Cannot be called with a
* pseudo-index, because a pseudo-index is not an actual stack position.
*
*/
public void insert(int index) {
int ai = index2adr(index);
LValue v = stack[top-1];
System.arraycopy(stack, ai, stack, ai+1, top-ai-1);
stack[ai] = v;
}
/**
* Test if a value is boolean. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index has type boolean,
* and 0 otherwise.
*
*/
public boolean isboolean(int index) {
return type(index) == Lua.LUA_TBOOLEAN;
}
/**
* Test if a value is a function. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns true if the value at the given acceptable index is a function
* (either C or Lua), and false otherwise.
*
*/
public boolean isfunction(int index) {
return type(index) == Lua.LUA_TFUNCTION;
}
/**
* Test if a value is a JavaFunction. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index is a
* C function, and 0 otherwise.
*
*/
public boolean isjavafunction(int index) {
return topointer(index) instanceof LFunction;
}
/**
* Test if a value is light user data <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index is a light userdata,
* and 0 otherwise.
*/
public boolean islightuserdata(int index) {
return false;
}
/**
* Test if a value is nil <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index is <b>nil</b>, and
* 0 otherwise.
*/
public boolean isnil(int index) {
return topointer(index).isNil();
}
/**
* Test if a value is not valid <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the the given acceptable index is not valid (that is, it
* refers to an element outside the current stack), and 0 otherwise.
*/
public boolean isnone(int index) {
return topointer(index) == null;
}
/**
* Test if a value is nil or not valid <span class="apii">[-0, +0,
* <em>-</em>]</span>
*
* <p>
* Returns 1 if the the given acceptable index is not valid (that is, it
* refers to an element outside the current stack) or if the value at this
* index is <b>nil</b>, and 0 otherwise.
*/
public boolean isnoneornil(int index) {
Object v = topointer(index);
return v == null || v == LNil.NIL;
}
/**
* Test if a value is a number <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index is a number or a
* string convertible to a number, and 0 otherwise.
*/
public boolean isnumber(int index) {
return ! tolnumber(index).isNil();
}
/**
* Convert a value to an LNumber<span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns an LNumber if the value at the given acceptable index is a number or a
* string convertible to a number, and LNil.NIL otherwise.
*/
public LValue tolnumber(int index) {
return topointer(index).luaToNumber();
}
/**
* Test if a value is a string <span class="apii">[-0, +0, <em>m</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index is a string or a
* number (which is always convertible to a string), and 0 otherwise.
*/
public boolean isstring(int index) {
return topointer(index).isString();
}
/**
* Test if a value is a table <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index is a table, and
* 0 otherwise.
*/
public boolean istable(int index) {
return topointer(index).isTable();
}
/**
* Test if a value is a thread <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index is a thread, and
* 0 otherwise.
*/
public boolean isthread(int index) {
return type(index) == Lua.LUA_TTHREAD;
}
/**
* Test if a value is a userdata <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns 1 if the value at the given acceptable index is a userdata
* (either full or light), and 0 otherwise.
*/
public boolean isuserdata(int index) {
return type(index) == Lua.LUA_TUSERDATA;
}
/**
* Compare two values <span class="apii">[-0, +0, <em>e</em>]</span>
*
* <p>
* Returns 1 if the value at acceptable index <code>index1</code> is
* smaller than the value at acceptable index <code>index2</code>,
* following the semantics of the Lua <code><</code> operator (that is,
* may call metamethods). Otherwise returns 0. Also returns 0 if
* any of the indices is non valid.
*/
public boolean lessthan(int index1, int index2) {
return topointer(index2).luaBinOpUnknown(Lua.OP_LT,
topointer(index1)).toJavaBoolean();
}
/**
* Create a table <span class="apii">[-0, +1, <em>m</em>]</span>
*
* <p>
* Creates a new empty table and pushes it onto the stack. It is equivalent
* to <code>lua_createtable(L, 0, 0)</code>.
*/
public void newtable() {
pushlvalue( new LTable() );
}
/**
* Create a thread <span class="apii">[-0, +1, <em>m</em>]</span>
*
* <p>
* Creates a new thread, pushes it on the stack, and returns a pointer to a
* <a href="#lua_State"><code>lua_State</code></a> that represents this
* new thread. The new state returned by this function shares with the
* original state all global objects (such as tables), but has an
* independent execution stack.
*
*
* <p>
* There is no explicit function to close or to destroy a thread. Threads
* are subject to garbage collection, like any Lua object.
*/
public void newthread() {
notImplemented();
}
/**
* Create a userdata <span class="apii">[-0, +1, <em>m</em>]</span>
*
* <p>
* This function allocates a new block of memory with the given size, pushes
* onto the stack a new full userdata with the block address, and returns
* this address.
*
*
* <p>
* Userdata represent C values in Lua. A <em>full userdata</em>
* represents a block of memory. It is an object (like a table): you must
* create it, it can have its own metatable, and you can detect when it is
* being collected. A full userdata is only equal to itself (under raw
* equality).
*
*
* <p>
* When Lua collects a full userdata with a <code>gc</code> metamethod,
* Lua calls the metamethod and marks the userdata as finalized. When this
* userdata is collected again then Lua frees its corresponding memory.
*/
public void newuserdata(Object o) {
pushlvalue( new LUserData(o) );
}
/**
* Traverse to the next table item. <span class="apii">[-1, +(2|0),
* <em>e</em>]</span>
*
* <p>
* Pops a key from the stack, and pushes a key-value pair from the table at
* the given index (the "next" pair after the given key). If there are no
* more elements in the table, then <a href="#lua_next"><code>lua_next</code></a>
* returns 0 (and pushes nothing).
*
*
* <p>
* A typical traversal looks like this:
*
* <pre>
* // table is in the stack at index 't'
* lua_pushnil(L); // first key
* while (lua_next(L, t) != 0) {
* // uses 'key' (at index -2) and 'value' (at index -1)
* printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L,
* lua_type(L, -1)));
* // removes 'value'; keeps 'key' for next iteration
* lua_pop(L, 1);
* }
* </pre>
*
* <p>
* While traversing a table, do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a>
* directly on a key, unless you know that the key is actually a string.
* Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a>
* <em>changes</em> the value at the given index; this confuses the next
* call to <a href="#lua_next"><code>lua_next</code></a>.
*/
public int next(int index) {
notImplemented();
return 0;
}
/**
* Get the length of an object <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns the "length" of the value at the given acceptable index: for
* strings, this is the string length; for tables, this is the result of the
* length operator ('<code>#</code>'); for userdata, this is the size of
* the block of memory allocated for the userdata; for other values, it
* is 0.
*/
public int objlen(int index) {
return tostring(index).length();
}
/**
* Pops <code>n</code> elements from the stack. <span class="apii">[-n,
* +0, <em>-</em>]</span>
*/
public void pop(int n) {
for ( int i=0; i<n; i++ )
stack[--top] = LNil.NIL;
}
public LValue poplvalue() {
LValue p = stack[--top];
stack[top] = LNil.NIL;
return p;
}
/**
* Push an LValue onto the stack. <span class="apii">[-0, +1,
* <em>m</em>]</span>
*/
public void pushlvalue(LValue value) {
if ( value == null )
throw new java.lang.IllegalArgumentException("stack values cannot be null");
try {
stack[top] = value;
} catch ( java.lang.ArrayIndexOutOfBoundsException aiobe ) {
checkstack( LUA_MINSTACK );
stack[top] = value;
} finally {
++top;
}
}
/**
* Pushes a boolean value with value <code>b</code> onto the stack. <span
* class="apii">[-0, +1, <em>-</em>]</span>
*
*/
public void pushboolean(boolean b) {
pushlvalue( LBoolean.valueOf(b) );
}
/**
* Pushes a number with value <code>n</code> onto the stack. <span
* class="apii">[-0, +1, <em>-</em>]</span>
*/
public void pushinteger(int n) {
pushlvalue( LInteger.valueOf(n) );
}
/**
* Pushes a Java function onto the stack. <span class="apii">[-0, +1,
* <em>m</em>]</span>
*
* <p>
* This function receives a pointer to a C function and pushes onto the
* stack a Lua value of type <code>function</code> that, when called,
* invokes the corresponding C function.
*
*
* <p>
* Any function to be registered in Lua must follow the correct protocol to
* receive its parameters and return its results (see <a
* href="#lua_CFunction"><code>lua_CFunction</code></a>).
*
*/
public void pushjavafunction(LFunction f) {
pushlvalue( f );
}
/**
* Pushes a light userdata onto the stack. <span class="apii">[-0, +1,
* <em>-</em>]</span>
*
*
* <p>
* Userdata represent C values in Lua. A <em>light userdata</em>
* represents a pointer. It is a value (like a number): you do not create
* it, it has no individual metatable, and it is not collected (as it was
* never created). A light userdata is equal to "any" light userdata with
* the same C address.
*/
public void pushlightuserdata(Object p) {
notImplemented();
}
/**
* Push an LString onto the stack. <span class="apii">[-0, +1,
* <em>m</em>]</span>
*/
public void pushlstring(LString s) {
pushlvalue(s);
}
/**
* Push string bytes onto the stack as a string. <span class="apii">[-0, +1,
* <em>m</em>]</span>
*
* Pushes the string pointed to by <code>s</code> with size
* <code>len</code> onto the stack. Lua makes (or reuses) an internal copy
* of the given string, so the memory at <code>s</code> can be freed or
* reused immediately after the function returns. The string can contain
* embedded zeros.
*/
public void pushlstring(byte[] bytes, int offset, int length) {
pushlvalue(new LString(bytes, offset, length));
}
/**
* Push string bytes onto the stack as a string. <span class="apii">[-0, +1,
* <em>m</em>]</span>
*
* Pushes the bytes in byteArray onto the stack as a lua string.
*/
public void pushlstring(byte[] byteArray) {
pushlstring(byteArray, 0, byteArray.length);
}
/**
* Pushes a nil value onto the stack. <span class="apii">[-0, +1, <em>-</em>]</span>
*
*/
public void pushnil() {
pushlvalue(LNil.NIL);
}
/**
* Pushes a number with value <code>d</code> onto the stack. <span
* class="apii">[-0, +1, <em>-</em>]</span>
*
*/
public void pushnumber(double d) {
pushlvalue(new LDouble(d));
}
/**
* Push a String onto the stack. <span class="apii">[-0, +1, <em>m</em>]</span>
*
* <p>
* Pushes the String <code>s</code> onto the stack. Lua makes (or reuses)
* an internal copy of the given string, so the memory at <code>s</code>
* can be freed or reused immediately after the function returns. The string
* cannot contain embedded zeros; it is assumed to end at the first zero.
*/
public void pushstring(String s) {
if ( s == null )
pushnil();
else
pushlstring( LString.valueOf(s) );
}
/**
* Push a thread onto the stack. <span class="apii">[-0, +1, <em>-</em>]</span>
*
* Pushes the thread represented by <code>L</code> onto the stack. Returns
* 1 if this thread is the main thread of its state.
*/
public void pushthread() {
notImplemented();
}
/**
* Push a value from the stack onto the stack. <span class="apii">[-0, +1,
* <em>-</em>]</span>
*
* <p>
* Pushes a copy of the element at the given valid index onto the stack.
*/
public void pushvalue(int index) {
pushlvalue(topointer(index));
}
/**
* Do a table get without metadata calls. <span class="apii">[-1, +1,
* <em>-</em>]</span>
*
* <p>
* Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but
* does a raw access (i.e., without metamethods).
*/
public void rawget(int index) {
pushlvalue( totable(index).get(poplvalue()) );
}
/**
* Do a integer-key table get without metadata calls. <span
* class="apii">[-0, +1, <em>-</em>]</span>
*
* <p>
* Pushes onto the stack the value <code>t[n]</code>, where
* <code>t</code> is the value at the given valid index. The access is
* raw; that is, it does not invoke metamethods.
*/
public void rawgeti(int index, int n) {
pushlvalue( totable(index).get(n) );
}
/**
* Do a table set without metadata calls. <span class="apii">[-2, +0,
* <em>m</em>]</span>
*
* <p>
* Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but
* does a raw assignment (i.e., without metamethods).
*/
public void rawset(int index) {
LTable t = totable(index);
LValue v = poplvalue();
LValue k = poplvalue();
t.put(k,v);
}
/**
* Do a integer-key table set without metadata calls. <span
* class="apii">[-1, +0, <em>m</em>]</span>
*
* <p>
* Does the equivalent of <code>t[n] = v</code>, where <code>t</code>
* is the value at the given valid index and <code>v</code> is the value
* at the top of the stack.
*
*
* <p>
* This function pops the value from the stack. The assignment is raw; that
* is, it does not invoke metamethods.
*/
public void rawseti(int index, int n) {
LTable t = totable(index);
LValue v = poplvalue();
t.put(n,v);
}
/**
* Register a LFunction with a specific name. <span class="apii">[-0, +0,
* <em>m</em>]</span>
*
* <p>
* Sets the function <code>f</code> as the new value of global
* <code>name</code>. It is defined as a macro:
*
* <pre>
* #define lua_register(L,n,f) \
* (lua_pushcfunction(L, f), lua_setglobal(L, n))
*
* </pre>
*/
public void register(String name, LFunction f) {
pushjavafunction(f);
setglobal(name);
}
/**
* Remove an element from the stack. <span class="apii">[-1, +0, <em>-</em>]</span>
*
* <p>
* Removes the element at the given valid index, shifting down the elements
* above this index to fill the gap. Cannot be called with a pseudo-index,
* because a pseudo-index is not an actual stack position.
*/
public void remove(int index) {
int ai = index2adr(index);
System.arraycopy(stack, ai+1, stack, ai, top-ai-1);
poplvalue();
}
/**
* Replace an element on the stack. <span class="apii">[-1, +0, <em>-</em>]</span>
*
* <p>
* Moves the top element into the given position (and pops it), without
* shifting any element (therefore replacing the value at the given
* position).
*/
public void replace(int index) {
int ai = index2adr(index);
stack[ai] = poplvalue();
}
/**
* Starts and resumes a coroutine in a given thread. <span class="apii">[-?,
* +?, <em>-</em>]</span>
*
*
* <p>
* To start a coroutine, you first create a new thread (see <a
* href="#lua_newthread"><code>lua_newthread</code></a>); then you push
* onto its stack the main function plus any arguments; then you call <a
* href="#lua_resume"><code>lua_resume</code></a>, with
* <code>narg</code> being the number of arguments. This call returns when
* the coroutine suspends or finishes its execution. When it returns, the
* stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
* or all values returned by the body function. <a href="#lua_resume"><code>lua_resume</code></a>
* returns <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the
* coroutine yields, 0 if the coroutine finishes its execution without
* errors, or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
* In case of errors, the stack is not unwound, so you can use the debug API
* over it. The error message is on the top of the stack. To restart a
* coroutine, you put on its stack only the values to be passed as results
* from <code>yield</code>, and then call <a href="#lua_resume"><code>lua_resume</code></a>.
*/
public void resume(int narg) {
notImplemented();
}
/**
* Set the value of a table field. <span class="apii">[-1, +0, <em>e</em>]</span>
*
* <p>
* Does the equivalent to <code>t[k] = v</code>, where <code>t</code>
* is the value at the given valid index and <code>v</code> is the value
* at the top of the stack.
*
*
* <p>
* This function pops the value from the stack. As in Lua, this function may
* trigger a metamethod for the "newindex" event (see <a
* href="#2.8">§2.8</a>).
*/
public void setfield(int index, LString k) {
LTable t = totable(index);
luaV_settable(t, k, poplvalue());
}
/**
* Set the value of a global variable. <span class="apii">[-1, +0,
* <em>e</em>]</span>
*
* <p>
* Pops a value from the stack and sets it as the new value of global
* <code>name</code>. It is defined as a macro:
*
* <pre>
* #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
*
* </pre>
*/
public void setglobal(String name) {
luaV_settable(_G, new LString(name), poplvalue());
}
/**
* Set the metatable of a value. <span class="apii">[-1, +0, <em>-</em>]</span>
*
* <p>
* Pops a table from the stack and sets it as the new metatable for the
* value at the given acceptable index.
*/
public void setmetatable(int index) {
LTable t = totable(index);
LValue v = poplvalue();
LValue n = t.luaSetMetatable(v);
if ( n != null ) {
pushlvalue(n);
replace(index);
}
}
/**
* Set the value of a table for a key. <span class="apii">[-2, +0,
* <em>e</em>]</span>
*
* <p>
* Does the equivalent to <code>t[k] = v</code>, where <code>t</code>
* is the value at the given valid index, <code>v</code> is the value at
* the top of the stack, and <code>k</code> is the value just below the
* top.
*
*
* <p>
* This function pops both the key and the value from the stack. As in Lua,
* this function may trigger a metamethod for the "newindex" event (see <a
* href="#2.8">§2.8</a>).
*/
public void settable(int index) {
LTable t = totable(index);
LValue v = poplvalue();
LValue k = poplvalue();
luaV_settable(t, k, v);
}
/**
* Returns the status of the thread <code>L</code>. <span
* class="apii">[-0, +0, <em>-</em>]</span>
*
*
*
* <p>
* The status can be 0 for a normal thread, an error code if the thread
* finished its execution with an error, or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
* if the thread is suspended.
*
*/
public void status() {
notImplemented();
}
/**
* Get a thread value from the stack. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Converts the value at the given acceptable index to a Lua thread
* (represented as <code>lua_State*</code>). This value must be a thread;
* otherwise, the function returns <code>NULL</code>.
*/
public LuaState tothread(int index) {
notImplemented();
return null;
}
/**
* Get a value as a boolean. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Converts the Lua value at the given acceptable index to a C boolean
* value (0 or 1). Like all tests in Lua, <a
* href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for
* any Lua value different from <b>false</b> and <b>nil</b>; otherwise it
* returns 0. It also returns 0 when called with a non-valid index. (If you
* want to accept only actual boolean values, use <a href="#lua_isboolean"><code>lua_isboolean</code></a>
* to test the value's type.)
*
*/
public boolean toboolean(int index) {
return topointer(index).toJavaBoolean();
}
/**
* Get a value as an int. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Converts the Lua value at the given acceptable index to the signed
* integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
* The Lua value must be a number or a string convertible to a number (see
* <a href="#2.2.1">§2.2.1</a>); otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a>
* returns 0.
*
*
* <p>
* If the number is not an integer, it is truncated in some non-specified
* way.
*/
public int tointeger(int index) {
return topointer(index).toJavaInt();
}
/**
* Get a value as a JavaFunction.
* <hr>
* <h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3>
* <p>
* <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <pre>
* lua_CFunction lua_tocfunction (lua_State *L, int index);
* </pre>
*
* <p>
* Converts a value at the given acceptable index to a C function. That
* value must be a C function; otherwise, returns <code>NULL</code>.
*/
public LFunction tojavafunction(int index) {
return (LFunction) topointer(index);
}
/**
* Gets the value of a string as byte array. <span class="apii">[-0, +0,
* <em>m</em>]</span>
*
* <p>
* Converts the Lua value at the given acceptable index to a C string.
* If <code>len</code> is not <code>NULL</code>, it also sets
* <code>*len</code> with the string length. The Lua value must be a
* string or a number; otherwise, the function returns <code>NULL</code>.
* If the value is a number, then <a href="#lua_tolstring"><code>lua_tolstring</code></a>
* also <em>changes the actual value in the stack to a string</em>. (This
* change confuses <a href="#lua_next"><code>lua_next</code></a> when <a
* href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to
* keys during a table traversal.)
*
*
* <p>
* <a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a
* fully aligned pointer to a string inside the Lua state. This string
* always has a zero ('<code>\0</code>') after its last character (as
* in C), but may contain other zeros in its body. Because Lua has
* garbage collection, there is no guarantee that the pointer returned by <a
* href="#lua_tolstring"><code>lua_tolstring</code></a> will be valid
* after the corresponding value is removed from the stack.
*/
public LString tolstring(int index) {
return topointer(index).luaAsString();
}
/**
* Convert a value to a double. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Converts the Lua value at the given acceptable index to the C type
* <a href="#lua_Number"><code>lua_Number</code></a> (see <a
* href="#lua_Number"><code>lua_Number</code></a>). The Lua value must
* be a number or a string convertible to a number (see <a
* href="#2.2.1">§2.2.1</a>); otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a>
* returns 0.
*
*/
public double tonumber(int index) {
return topointer(index).toJavaDouble();
}
/**
* Returns the index of the top element in the stack. <span
* class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Because indices start at 1, this result is equal to the number of
* elements in the stack (and so 0 means an empty stack).
*/
public int gettop() {
return top - base;
}
/**
* Set the top of the stack. <span class="apii">[-?, +?, <em>-</em>]</span>
*
* <p>
* Accepts any acceptable index, or 0, and sets the stack top to this
* index. If the new top is larger than the old one, then the new elements
* are filled with <b>nil</b>. If <code>index</code> is 0, then all
* stack elements are removed.
*/
public void settop(int nt) {
int ant = nt>=0? base+nt: top+nt;
if ( ant < base )
throw new IllegalArgumentException("index out of bounds: "+ant );
luaV_adjusttop(ant);
}
/**
* Set the top to the base. Equivalent to settop(0)
*/
public void resettop() {
luaV_settop_fillabove( base );
}
private int index2adr(int index) {
// TODO: upvalues? globals? environment?
int ai = index>0? base+index-1: top+index;
if ( ai < base )
throw new IllegalArgumentException("index out of bounds: "+ai );
return ai;
}
/**
* Get the raw Object at a stack location. <span class="apii">[-0, +0,
* <em>-</em>]</span>
*
* <p>
* Converts the value at the given acceptable index to a generic
* C pointer (<code>void*</code>). The value may be a userdata, a
* table, a thread, or a function; otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a>
* returns <code>NULL</code>. Different objects will give different
* pointers. There is no way to convert the pointer back to its original
* value.
*
*
* <p>
* Typically this function is used only for debug information.
*/
public LValue topointer(int index) {
int ai = index2adr(index);
if ( ai >= top )
return LNil.NIL;
return stack[ai];
}
/**
* Get a stack value as a String. <span class="apii">[-0, +0, <em>m</em>]</span>
*
* <p>
* Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a>
* with <code>len</code> equal to <code>NULL</code>.
*/
public String tostring(int index) {
return topointer(index).toJavaString();
}
/**
* Get a value from the stack as a lua table. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Converts the value at the given acceptable index to a Lua table
* This value must be a table otherwise, the function returns <code>NIL</code>.
*/
public LTable totable(int index) {
return (LTable) topointer(index);
}
/**
* Get the Object from a userdata value. <span class="apii">[-0, +0,
* <em>-</em>]</span>
*
* <p>
* If the value at the given acceptable index is a full userdata, returns
* its block address. If the value is a light userdata, returns its pointer.
* Otherwise, returns <code>NULL</code>.
*
*/
public Object touserdata(int index) {
LValue v = topointer(index);
if ( v.luaGetType() != Lua.LUA_TUSERDATA )
return null;
return ((LUserData)v).m_instance;
}
/**
* Get the type of a value. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns the type of the value in the given acceptable index, or
* <code>LUA_TNONE</code> for a non-valid index (that is, an index to an
* "empty" stack position). The types returned by <a href="#lua_type"><code>lua_type</code></a>
* are coded by the following constants defined in <code>lua.h</code>:
* <code>LUA_TNIL</code>, <code>LUA_TNUMBER</code>,
* <code>LUA_TBOOLEAN</code>, <code>LUA_TSTRING</code>,
* <code>LUA_TTABLE</code>, <code>LUA_TFUNCTION</code>,
* <code>LUA_TUSERDATA</code>, <code>LUA_TTHREAD</code>, and
* <code>LUA_TLIGHTUSERDATA</code>.
*/
public int type(int index) {
return topointer(index).luaGetType();
}
/**
* Get the type name for a value. <span class="apii">[-0, +0, <em>-</em>]</span>
*
* <p>
* Returns the name of the type encoded by the value <code>tp</code>,
* which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
*/
public String typename(int index) {
return topointer(index).luaGetTypeName().toJavaString();
}
/**
* Exchange values between threads. <span class="apii">[-?, +?, <em>-</em>]</span>
*
* <p>
* Exchange values between different threads of the <em>same</em> global
* state.
*
*
* <p>
* This function pops <code>n</code> values from the stack
* <code>from</code>, and pushes them onto the stack <code>to</code>.
*/
public void xmove(LuaState to, int n) {
if ( n > 0 ) {
to.checkstack(n);
LuaState ss = (LuaState)to;
ss.checkstack(n);
System.arraycopy(stack, top-n, ss.stack, ss.top, n);
ss.top += n;
}
}
/**
* Yields a coroutine. <span class="apii">[-?, +?, <em>-</em>]</span>
*
*
* <p>
* This function should only be called as the return expression of a
* C function, as follows:
*
* <pre>
* return lua_yield(L, nresults);
* </pre>
*
* <p>
* When a C function calls <a href="#lua_yield"><code>lua_yield</code></a>
* in that way, the running coroutine suspends its execution, and the call
* to <a href="#lua_resume"><code>lua_resume</code></a> that started
* this coroutine returns. The parameter <code>nresults</code> is the
* number of values from the stack that are passed as results to <a
* href="#lua_resume"><code>lua_resume</code></a>.
*
*/
public void yield(int nresults) {
notImplemented();
}
// ============================= conversion to and from Java boxed types ====================
/**
* Push a Java Boolean value, or nil if the value is null.
* @param b Boolean value to convert, or null to to nil.
*/
public void pushboolean(Boolean b) {
if ( b == null )
pushnil();
else
pushboolean( b.booleanValue() );
}
/**
* Push a Java Byte value, or nil if the value is null.
* @param b Byte value to convert, or null to to nil.
*/
public void pushinteger(Byte b) {
if ( b == null )
pushnil();
else
pushinteger( b.byteValue() );
}
/**
* Push a Java Character value, or nil if the value is null.
* @param c Character value to convert, or null to to nil.
*/
public void pushinteger(Character c) {
if ( c == null )
pushnil();
else
pushinteger( c.charValue() );
}
/**
* Push a Java Double as a double, or nil if the value is null.
* @param d Double value to convert, or null to to nil.
*/
public void pushnumber(Double d) {
if ( d == null )
pushnil();
else
pushnumber( d.doubleValue() );
}
/**
* Push a Java Float value, or nil if the value is null.
* @param f Float value to convert, or null to to nil.
*/
public void pushnumber(Float f) {
if ( f == null )
pushnil();
else
pushnumber( f.doubleValue() );
}
/**
* Push a Java Integer value, or nil if the value is null.
* @param i Integer value to convert, or null to to nil.
*/
public void pushinteger(Integer i) {
if ( i == null )
pushnil();
else
pushinteger( i.intValue() );
}
/**
* Push a Java Short value, or nil if the value is null.
* @param s Short value to convert, or null to to nil.
*/
public void pushinteger(Short s) {
if ( s == null )
pushnil();
else
pushinteger( s.shortValue() );
}
/**
* Push a Java Long value, or nil if the value is null.
* @param l Long value to convert, or null to to nil.
*/
public void pushnumber(Long l) {
if ( l == null )
pushnil();
else
pushnumber( l.doubleValue() );
}
/**
* Push a Java Object as userdata, or nil if the value is null.
* @param o Object value to push, or null to to nil.
*/
public void pushuserdata( Object o ) {
if ( o == null )
pushnil();
else
newuserdata( o );
}
/**
* Convert a value to a Java Boolean value, or null if the value is nil.
* @param index index of the parameter to convert.
* @return Boolean value at the index, or null if the value was not a boolean.
*/
public Boolean toboxedboolean(int index) {
return topointer(index).toJavaBoxedBoolean();
}
/**
* Convert a value to a Java Byte value, or null if the value is not a number.
* @param index index of the parameter to convert.
* @return Byte value at the index, or null if the value was not a number.
*/
public Byte toboxedbyte(int index) {
return topointer(index).toJavaBoxedByte();
}
/**
* Convert a value to a Java Double value, or null if the value is not a number.
* @param index index of the parameter to convert.
* @return Double value at the index, or null if the value was not a number.
*/
public Double toboxeddouble(int index) {
return topointer(index).toJavaBoxedDouble();
}
/**
* Convert a value to a Java Float value, or null if the value is not a number.
* @param index index of the parameter to convert.
* @return Float value at the index, or null if the value was not a boolean.
*/
public Float toboxedfloat(int index) {
return topointer(index).toJavaBoxedFloat();
}
/**
* Convert a value to a Java Integer value, or null if the value is not a number.
* @param index index of the parameter to convert.
* @return Integer value at the index, or null if the value was not a number.
*/
public Integer toboxedinteger(int index) {
return topointer(index).toJavaBoxedInteger();
}
/**
* Convert a value to a Java Long value, or null if the value is nil.
* @param index index of the parameter to convert.
* @return Long value at the index, or null if the value was not a number.
*/
public Long toboxedlong(int index) {
return topointer(index).toJavaBoxedLong();
}
/**
* Method to indicate a vm internal error has occurred.
* Generally, this is not recoverable, so we convert to
* a lua error during production so that the code may recover.
*/
public static void vmerror(String description) {
throw new LuaErrorException( "internal error: "+description );
}
}
| false | true | public void exec() {
if ( cc < 0 )
return;
int i, a, b, c, o, n, cb;
LValue rkb, rkc, nvarargs, key, val;
LValue i0, step, idx, limit, init, table;
boolean back, body;
LPrototype proto;
LClosure newClosure;
// reload values from the current call frame
// into local variables
CallInfo ci = calls[cc];
LClosure cl = ci.closure;
LPrototype p = cl.p;
int[] code = p.code;
LValue[] k = p.k;
this.base = ci.base;
// loop until a return instruction is processed,
// or the vm yields
while (true) {
debugAssert( ci == calls[cc] );
// sync up top
ci.top = top;
// allow debug hooks a chance to operate
debugHooks( ci.pc );
// advance program counter
i = code[ci.pc++];
// get opcode and first arg
o = (i >> POS_OP) & MAX_OP;
a = (i >> POS_A) & MAXARG_A;
switch (o) {
case LuaState.OP_MOVE: {
b = LuaState.GETARG_B(i);
this.stack[base + a] = this.stack[base + b];
continue;
}
case LuaState.OP_LOADK: {
b = LuaState.GETARG_Bx(i);
this.stack[base + a] = k[b];
continue;
}
case LuaState.OP_LOADBOOL: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
this.stack[base + a] = (b != 0 ? LBoolean.TRUE : LBoolean.FALSE);
if (c != 0)
ci.pc++; /* skip next instruction (if C) */
continue;
}
case LuaState.OP_LOADNIL: {
b = LuaState.GETARG_B(i);
do {
this.stack[base + b] = LNil.NIL;
} while ((--b) >= a);
continue;
}
case LuaState.OP_GETUPVAL: {
b = LuaState.GETARG_B(i);
this.stack[base + a] = cl.upVals[b].getValue();
continue;
}
case LuaState.OP_GETGLOBAL: {
b = LuaState.GETARG_Bx(i);
key = k[b];
table = cl.env;
this.stack[base + a] = luaV_gettable(table, key);
continue;
}
case LuaState.OP_GETTABLE: {
b = LuaState.GETARG_B(i);
key = GETARG_RKC(k, i);
table = this.stack[base + b];
this.stack[base + a] = luaV_gettable(table, key);
continue;
}
case LuaState.OP_SETGLOBAL: {
b = LuaState.GETARG_Bx(i);
key = k[b];
val = this.stack[base + a];
table = cl.env;
luaV_settable(table, key, val);
continue;
}
case LuaState.OP_SETUPVAL: {
b = LuaState.GETARG_B(i);
cl.upVals[b].setValue( this.stack[base + a] );
continue;
}
case LuaState.OP_SETTABLE: {
key = GETARG_RKB(k, i);
val = GETARG_RKC(k, i);
table = this.stack[base + a];
luaV_settable(table, key, val);
continue;
}
case LuaState.OP_NEWTABLE: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
this.stack[base + a] = new LTable(b, c);
continue;
}
case LuaState.OP_SELF: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
this.stack[base + a] = luaV_gettable(rkb, rkc);
this.stack[base + a + 1] = rkb;
// StkId rb = RB(i);
// setobjs2s(L, ra+1, rb);
// Protect(luaV_gettable(L, rb, RKC(i), ra));
continue;
}
case LuaState.OP_ADD:
case LuaState.OP_SUB:
case LuaState.OP_MUL:
case LuaState.OP_DIV:
case LuaState.OP_MOD:
case LuaState.OP_POW: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
this.stack[base + a] = rkc.luaBinOpUnknown(o, rkb);
continue;
}
case LuaState.OP_UNM: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = rkb.luaUnaryMinus();
continue;
}
case LuaState.OP_NOT: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = (!rkb.toJavaBoolean() ? LBoolean.TRUE
: LBoolean.FALSE);
continue;
}
case LuaState.OP_LEN: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = LInteger.valueOf( rkb.luaLength() );
continue;
}
case LuaState.OP_CONCAT: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
int numValues = c - b + 1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int j = b, l = 0; j <= c; j++, l++) {
this.stack[base + j].luaConcatTo( baos );
}
this.stack[base + a] = new LString( baos.toByteArray() );
continue;
}
case LuaState.OP_JMP: {
ci.pc += LuaState.GETARG_sBx(i);
continue;
}
case LuaState.OP_EQ:
case LuaState.OP_LT:
case LuaState.OP_LE: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
boolean test = rkc.luaBinCmpUnknown(o, rkb);
if (test == (a == 0))
ci.pc++;
continue;
}
case LuaState.OP_TEST: {
c = LuaState.GETARG_C(i);
if (this.stack[base + a].toJavaBoolean() != (c != 0))
ci.pc++;
continue;
}
case LuaState.OP_TESTSET: {
rkb = GETARG_RKB(k, i);
c = LuaState.GETARG_C(i);
if (rkb.toJavaBoolean() != (c != 0))
ci.pc++;
else
this.stack[base + a] = rkb;
continue;
}
case LuaState.OP_CALL: {
// ra is base of new call frame
this.base += a;
// number of args
b = LuaState.GETARG_B(i);
if (b != 0) // else use previous instruction set top
luaV_settop_fillabove( base + b );
// number of return values we need
c = LuaState.GETARG_C(i);
// make or set up the call
this.nresults = c - 1;
if (this.stack[base].luaStackCall(this))
return;
// adjustTop only for case when call was completed
// and number of args > 0. If call completed but
// c == 0, leave top to point to end of results
if (c > 0)
luaV_adjusttop(base + c - 1);
// restore base
base = ci.base;
continue;
}
case LuaState.OP_TAILCALL: {
closeUpVals(base);
// copy down the frame before calling!
// number of args (including the function)
b = LuaState.GETARG_B(i);
if (b != 0) // else use previous instruction set top
luaV_settop_fillabove( base + a + b );
else
b = top - (base + a);
// copy call + all args, discard current frame
System.arraycopy(stack, base + a, stack, ci.resultbase, b);
this.base = ci.resultbase;
luaV_settop_fillabove( base + b );
this.nresults = ci.nresults;
--cc;
// make or set up the call
try {
if (this.stack[base].luaStackCall(this)) {
return;
}
} catch (LuaErrorException e) {
// in case of lua error, we need to restore cc so that
// the debug can get the correct location where the error
// occured.
cc++;
throw e;
}
// adjustTop only for case when call was completed
// and number of args > 0. If call completed but
// c == 0, leave top to point to end of results
if (this.nresults >= 0)
luaV_adjusttop(base + nresults);
// force restore of base, etc.
return;
}
case LuaState.OP_RETURN: {
closeUpVals( base );
// number of return vals to return
b = LuaState.GETARG_B(i) - 1;
if (b >= 0) // else use previous instruction set top
luaV_settop_fillabove( base + a + b );
else
b = top - (base + a);
// number to copy down
System.arraycopy(stack, base + a, stack, ci.resultbase, b);
debugAssert( ci.resultbase + b <= top );
luaV_settop_fillabove( ci.resultbase + b );
// adjust results to what caller expected
if (ci.nresults >= 0)
luaV_adjusttop(ci.resultbase + ci.nresults);
// pop the call stack
--cc;
// force a reload of the calling context
return;
}
case LuaState.OP_FORLOOP: {
i0 = this.stack[base + a];
step = this.stack[base + a + 2];
idx = step.luaBinOpUnknown(Lua.OP_ADD, i0);
limit = this.stack[base + a + 1];
back = step.luaBinCmpInteger(Lua.OP_LT, 0);
body = (back ? idx.luaBinCmpUnknown(Lua.OP_LE, limit) : limit
.luaBinCmpUnknown(Lua.OP_LE, idx));
if (body) {
this.stack[base + a] = idx;
this.stack[base + a + 3] = idx;
ci.pc += LuaState.GETARG_sBx(i);
}
continue;
}
case LuaState.OP_FORPREP: {
init = this.stack[base + a];
step = this.stack[base + a + 2];
this.stack[base + a] = step.luaBinOpUnknown(Lua.OP_SUB, init);
b = LuaState.GETARG_sBx(i);
ci.pc += b;
continue;
}
case LuaState.OP_TFORLOOP: {
cb = base + a + 3; /* call base */
base = cb;
System.arraycopy(this.stack, cb-3, this.stack, cb, 3);
luaV_settop_fillabove( cb + 3 );
// call the iterator
c = LuaState.GETARG_C(i);
this.nresults = c;
if (this.stack[cb].luaStackCall(this))
execute();
base = ci.base;
luaV_adjusttop( cb + c );
// test for continuation
if (!this.stack[cb].isNil() ) { // continue?
this.stack[cb-1] = this.stack[cb]; // save control variable
} else {
ci.pc++; // skip over jump
}
continue;
}
case LuaState.OP_SETLIST: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
int listBase = base + a;
if (b == 0) {
b = top - listBase - 1;
}
if (c == 0) {
c = code[ci.pc++];
}
int offset = (c-1) * LFIELDS_PER_FLUSH;
LTable tbl = (LTable) this.stack[base + a];
for (int j=1; j<=b; j++) {
tbl.put(offset+j, stack[listBase + j]);
}
continue;
}
case LuaState.OP_CLOSE: {
closeUpVals( base + a ); // close upvals higher in the stack than position a
continue;
}
case LuaState.OP_CLOSURE: {
b = LuaState.GETARG_Bx(i);
proto = cl.p.p[b];
newClosure = proto.newClosure(cl.env);
for (int j = 0; j < newClosure.upVals.length; j++, ci.pc++) {
i = code[ci.pc];
o = LuaState.GET_OPCODE(i);
b = LuaState.GETARG_B(i);
if (o == LuaState.OP_GETUPVAL) {
newClosure.upVals[j] = cl.upVals[b];
} else if (o == LuaState.OP_MOVE) {
newClosure.upVals[j] = findUpVal( base + b );
} else {
throw new java.lang.IllegalArgumentException(
"bad opcode: " + o);
}
}
this.stack[base + a] = newClosure;
continue;
}
case LuaState.OP_VARARG: {
// figure out how many args to copy
b = LuaState.GETARG_B(i) - 1;
nvarargs = this.stack[base - 1];
n = nvarargs.toJavaInt();
if (b == LuaState.LUA_MULTRET) {
b = n; // use entire varargs supplied
}
// copy args up to call stack area
checkstack(a+b);
for (int j = 0; j < b; j++)
this.stack[base + a + j] = (j < n ? this.stack[base
- n + j - 1]
: LNil.NIL);
luaV_settop_fillabove( base + a + b );
continue;
}
}
}
}
| public void exec() {
if ( cc < 0 )
return;
int i, a, b, c, o, n, cb;
LValue rkb, rkc, nvarargs, key, val;
LValue i0, step, idx, limit, init, table;
boolean back, body;
LPrototype proto;
LClosure newClosure;
// reload values from the current call frame
// into local variables
CallInfo ci = calls[cc];
LClosure cl = ci.closure;
LPrototype p = cl.p;
int[] code = p.code;
LValue[] k = p.k;
this.base = ci.base;
// loop until a return instruction is processed,
// or the vm yields
while (true) {
debugAssert( ci == calls[cc] );
// sync up top
ci.top = top;
// allow debug hooks a chance to operate
debugHooks( ci.pc );
// advance program counter
i = code[ci.pc++];
// get opcode and first arg
o = (i >> POS_OP) & MAX_OP;
a = (i >> POS_A) & MAXARG_A;
switch (o) {
case LuaState.OP_MOVE: {
b = LuaState.GETARG_B(i);
this.stack[base + a] = this.stack[base + b];
continue;
}
case LuaState.OP_LOADK: {
b = LuaState.GETARG_Bx(i);
this.stack[base + a] = k[b];
continue;
}
case LuaState.OP_LOADBOOL: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
this.stack[base + a] = (b != 0 ? LBoolean.TRUE : LBoolean.FALSE);
if (c != 0)
ci.pc++; /* skip next instruction (if C) */
continue;
}
case LuaState.OP_LOADNIL: {
b = LuaState.GETARG_B(i);
do {
this.stack[base + b] = LNil.NIL;
} while ((--b) >= a);
continue;
}
case LuaState.OP_GETUPVAL: {
b = LuaState.GETARG_B(i);
this.stack[base + a] = cl.upVals[b].getValue();
continue;
}
case LuaState.OP_GETGLOBAL: {
b = LuaState.GETARG_Bx(i);
key = k[b];
table = cl.env;
val = luaV_gettable(table, key);
this.stack[base + a] = val;
continue;
}
case LuaState.OP_GETTABLE: {
b = LuaState.GETARG_B(i);
key = GETARG_RKC(k, i);
table = this.stack[base + b];
val = luaV_gettable(table, key);
this.stack[base + a] = val;
continue;
}
case LuaState.OP_SETGLOBAL: {
b = LuaState.GETARG_Bx(i);
key = k[b];
val = this.stack[base + a];
table = cl.env;
luaV_settable(table, key, val);
continue;
}
case LuaState.OP_SETUPVAL: {
b = LuaState.GETARG_B(i);
cl.upVals[b].setValue( this.stack[base + a] );
continue;
}
case LuaState.OP_SETTABLE: {
key = GETARG_RKB(k, i);
val = GETARG_RKC(k, i);
table = this.stack[base + a];
luaV_settable(table, key, val);
continue;
}
case LuaState.OP_NEWTABLE: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
this.stack[base + a] = new LTable(b, c);
continue;
}
case LuaState.OP_SELF: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
val = luaV_gettable(rkb, rkc);
this.stack[base + a] = val;
this.stack[base + a + 1] = rkb;
continue;
}
case LuaState.OP_ADD:
case LuaState.OP_SUB:
case LuaState.OP_MUL:
case LuaState.OP_DIV:
case LuaState.OP_MOD:
case LuaState.OP_POW: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
this.stack[base + a] = rkc.luaBinOpUnknown(o, rkb);
continue;
}
case LuaState.OP_UNM: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = rkb.luaUnaryMinus();
continue;
}
case LuaState.OP_NOT: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = (!rkb.toJavaBoolean() ? LBoolean.TRUE
: LBoolean.FALSE);
continue;
}
case LuaState.OP_LEN: {
rkb = GETARG_RKB(k, i);
this.stack[base + a] = LInteger.valueOf( rkb.luaLength() );
continue;
}
case LuaState.OP_CONCAT: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
int numValues = c - b + 1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int j = b, l = 0; j <= c; j++, l++) {
this.stack[base + j].luaConcatTo( baos );
}
this.stack[base + a] = new LString( baos.toByteArray() );
continue;
}
case LuaState.OP_JMP: {
ci.pc += LuaState.GETARG_sBx(i);
continue;
}
case LuaState.OP_EQ:
case LuaState.OP_LT:
case LuaState.OP_LE: {
rkb = GETARG_RKB(k, i);
rkc = GETARG_RKC(k, i);
boolean test = rkc.luaBinCmpUnknown(o, rkb);
if (test == (a == 0))
ci.pc++;
continue;
}
case LuaState.OP_TEST: {
c = LuaState.GETARG_C(i);
if (this.stack[base + a].toJavaBoolean() != (c != 0))
ci.pc++;
continue;
}
case LuaState.OP_TESTSET: {
rkb = GETARG_RKB(k, i);
c = LuaState.GETARG_C(i);
if (rkb.toJavaBoolean() != (c != 0))
ci.pc++;
else
this.stack[base + a] = rkb;
continue;
}
case LuaState.OP_CALL: {
// ra is base of new call frame
this.base += a;
// number of args
b = LuaState.GETARG_B(i);
if (b != 0) // else use previous instruction set top
luaV_settop_fillabove( base + b );
// number of return values we need
c = LuaState.GETARG_C(i);
// make or set up the call
this.nresults = c - 1;
if (this.stack[base].luaStackCall(this))
return;
// adjustTop only for case when call was completed
// and number of args > 0. If call completed but
// c == 0, leave top to point to end of results
if (c > 0)
luaV_adjusttop(base + c - 1);
// restore base
base = ci.base;
continue;
}
case LuaState.OP_TAILCALL: {
closeUpVals(base);
// copy down the frame before calling!
// number of args (including the function)
b = LuaState.GETARG_B(i);
if (b != 0) // else use previous instruction set top
luaV_settop_fillabove( base + a + b );
else
b = top - (base + a);
// copy call + all args, discard current frame
System.arraycopy(stack, base + a, stack, ci.resultbase, b);
this.base = ci.resultbase;
luaV_settop_fillabove( base + b );
this.nresults = ci.nresults;
--cc;
// make or set up the call
try {
if (this.stack[base].luaStackCall(this)) {
return;
}
} catch (LuaErrorException e) {
// in case of lua error, we need to restore cc so that
// the debug can get the correct location where the error
// occured.
cc++;
throw e;
}
// adjustTop only for case when call was completed
// and number of args > 0. If call completed but
// c == 0, leave top to point to end of results
if (this.nresults >= 0)
luaV_adjusttop(base + nresults);
// force restore of base, etc.
return;
}
case LuaState.OP_RETURN: {
closeUpVals( base );
// number of return vals to return
b = LuaState.GETARG_B(i) - 1;
if (b >= 0) // else use previous instruction set top
luaV_settop_fillabove( base + a + b );
else
b = top - (base + a);
// number to copy down
System.arraycopy(stack, base + a, stack, ci.resultbase, b);
debugAssert( ci.resultbase + b <= top );
luaV_settop_fillabove( ci.resultbase + b );
// adjust results to what caller expected
if (ci.nresults >= 0)
luaV_adjusttop(ci.resultbase + ci.nresults);
// pop the call stack
--cc;
// force a reload of the calling context
return;
}
case LuaState.OP_FORLOOP: {
i0 = this.stack[base + a];
step = this.stack[base + a + 2];
idx = step.luaBinOpUnknown(Lua.OP_ADD, i0);
limit = this.stack[base + a + 1];
back = step.luaBinCmpInteger(Lua.OP_LT, 0);
body = (back ? idx.luaBinCmpUnknown(Lua.OP_LE, limit) : limit
.luaBinCmpUnknown(Lua.OP_LE, idx));
if (body) {
this.stack[base + a] = idx;
this.stack[base + a + 3] = idx;
ci.pc += LuaState.GETARG_sBx(i);
}
continue;
}
case LuaState.OP_FORPREP: {
init = this.stack[base + a];
step = this.stack[base + a + 2];
this.stack[base + a] = step.luaBinOpUnknown(Lua.OP_SUB, init);
b = LuaState.GETARG_sBx(i);
ci.pc += b;
continue;
}
case LuaState.OP_TFORLOOP: {
cb = base + a + 3; /* call base */
base = cb;
System.arraycopy(this.stack, cb-3, this.stack, cb, 3);
luaV_settop_fillabove( cb + 3 );
// call the iterator
c = LuaState.GETARG_C(i);
this.nresults = c;
if (this.stack[cb].luaStackCall(this))
execute();
base = ci.base;
luaV_adjusttop( cb + c );
// test for continuation
if (!this.stack[cb].isNil() ) { // continue?
this.stack[cb-1] = this.stack[cb]; // save control variable
} else {
ci.pc++; // skip over jump
}
continue;
}
case LuaState.OP_SETLIST: {
b = LuaState.GETARG_B(i);
c = LuaState.GETARG_C(i);
int listBase = base + a;
if (b == 0) {
b = top - listBase - 1;
}
if (c == 0) {
c = code[ci.pc++];
}
int offset = (c-1) * LFIELDS_PER_FLUSH;
LTable tbl = (LTable) this.stack[base + a];
for (int j=1; j<=b; j++) {
tbl.put(offset+j, stack[listBase + j]);
}
continue;
}
case LuaState.OP_CLOSE: {
closeUpVals( base + a ); // close upvals higher in the stack than position a
continue;
}
case LuaState.OP_CLOSURE: {
b = LuaState.GETARG_Bx(i);
proto = cl.p.p[b];
newClosure = proto.newClosure(cl.env);
for (int j = 0; j < newClosure.upVals.length; j++, ci.pc++) {
i = code[ci.pc];
o = LuaState.GET_OPCODE(i);
b = LuaState.GETARG_B(i);
if (o == LuaState.OP_GETUPVAL) {
newClosure.upVals[j] = cl.upVals[b];
} else if (o == LuaState.OP_MOVE) {
newClosure.upVals[j] = findUpVal( base + b );
} else {
throw new java.lang.IllegalArgumentException(
"bad opcode: " + o);
}
}
this.stack[base + a] = newClosure;
continue;
}
case LuaState.OP_VARARG: {
// figure out how many args to copy
b = LuaState.GETARG_B(i) - 1;
nvarargs = this.stack[base - 1];
n = nvarargs.toJavaInt();
if (b == LuaState.LUA_MULTRET) {
b = n; // use entire varargs supplied
}
// copy args up to call stack area
checkstack(a+b);
for (int j = 0; j < b; j++)
this.stack[base + a + j] = (j < n ? this.stack[base
- n + j - 1]
: LNil.NIL);
luaV_settop_fillabove( base + a + b );
continue;
}
}
}
}
|
diff --git a/src/com/pi/coelho/CookieMonster/CookieMonster.java b/src/com/pi/coelho/CookieMonster/CookieMonster.java
index 868b530..3c508b3 100644
--- a/src/com/pi/coelho/CookieMonster/CookieMonster.java
+++ b/src/com/pi/coelho/CookieMonster/CookieMonster.java
@@ -1,207 +1,207 @@
package com.pi.coelho.CookieMonster;
import com.jascotty2.util.Str;
import com.pi.coelho.CookieMonster.protectcheck.*;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class CookieMonster extends JavaPlugin {
protected final static Logger logger = Logger.getLogger("Minecraft");
public static final String name = "CookieMonster";
protected static CMConfig config = new CMConfig();
private static Server server;
private static CMBlockListener blockListener = null;
private static BlockProtectListener blockProtectListener = new BlockProtectListener();
private static CMEntityListener entityListener = null;
private static EntityProtectListener entityProtectListener = new EntityProtectListener();
protected static CMPlayerListener playerListener = new CMPlayerListener();
private static CMRewardHandler rewardHandler = null;
private static CMEcon economyPluginListener;
protected static CMRegions regions = null;
protected static CMCampTracker killTracker = null;
private static WorldEditPlugin worldEdit = null;
@Override
public void onEnable() {
// Grab plugin details
server = getServer();
PluginManager pm = server.getPluginManager();
PluginDescriptionFile pdfFile = this.getDescription();
// w.e.
Plugin we = pm.getPlugin("WorldEdit");
if (we != null && we instanceof WorldEditPlugin) {
worldEdit = (WorldEditPlugin) we;
} else {
Log(Level.INFO, "Failed to find WorldEdit: regions cannot be defined");
}
try {
regions = new CMRegions(server, getDataFolder());
} catch (NoClassDefFoundError e) {
if (worldEdit == null) {
Log(Level.INFO, "to enable existing regions, put a copy of WorldEdit in the CookieMonster folder, "
+ "or install WorldEdit to the server");
} else {
Log(Level.WARNING, "Unexpected error while loading region manager");
}
regions = null;
}
// Directory
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
//CMConfig.Plugin_Directory = getDataFolder().getPath();
// Configuration
if (!config.load()) {
server.getPluginManager().disablePlugin(this);
Log(Level.SEVERE, "Failed to retrieve configuration from directory.");
Log(Level.SEVERE, "Please back up your current settings and let CookieMonster recreate it.");
return;
}
if (regions != null) {
regions.load();//getServer(), getDataFolder());//new File(getDataFolder(), "regions.yml"));
}
// Initializing Listeners
entityListener = new CMEntityListener(getServer());
blockListener = new CMBlockListener();
rewardHandler = new CMRewardHandler();
if (config.campTrackingEnabled
|| config.globalCampTrackingEnabled) {
killTracker = new CMCampTracker();
}
economyPluginListener = new CMEcon(this);
// Event Registration
pm.registerEvent(Type.ENTITY_DAMAGE, entityProtectListener, Priority.Low, this);
- pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.High, this);
- pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.High, this);
+ pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Highest, this);
+ pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Highest, this);
// pm.registerEvent(Type.PROJECTILE_HIT, entityListener, Priority.Normal, this);
pm.registerEvent(Type.BLOCK_BREAK, blockProtectListener, Priority.Low, this);
- pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.High, this);
+ pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.Normal, this);
pm.registerEvent(Type.PLAYER_RESPAWN, playerListener, Priority.Normal, this);
pm.registerEvent(Type.PLUGIN_ENABLE, economyPluginListener, Priority.Monitor, this);
pm.registerEvent(Type.PLUGIN_DISABLE, economyPluginListener, Priority.Monitor, this);
// Console Detail
Log(" v" + pdfFile.getVersion() + " loaded successfully.");
Log(" Developed by: " + pdfFile.getAuthors());
}
@Override
public void onDisable() {
if (regions != null) {
regions.globalRegionManager.unload();
}
if (killTracker != null) {
killTracker.save();
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("cookiemonster")) {
if (!sender.isOp()) {
sender.sendMessage("You are not an OP!");
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
if (!config.load()) {
sender.sendMessage("Reload Failed!");
} else {
if ((config.campTrackingEnabled || config.globalCampTrackingEnabled)
&& killTracker == null) {
killTracker = new CMCampTracker();
} else if ((config.campTrackingEnabled || config.globalCampTrackingEnabled)
&& killTracker != null) {
//todo:save
killTracker = null;
}
}
sender.sendMessage("Settings Reloaded");
} else if (args.length >= 1 && args[0].equalsIgnoreCase("region")) {
if ((args.length == 2 || args.length == 3) && args[1].equalsIgnoreCase("list")) {
regions.list(sender, args);
} else if (args.length != 3 || !Str.isIn(args[1], "define,def,d,remove,delete,del,rem")) {
sender.sendMessage("Usage: ");
sender.sendMessage("/" + label + " region define <id> - define a cookiemonster region");
sender.sendMessage("/" + label + " region list <page> - list regions");
sender.sendMessage("/" + label + " region remove <id> - remove a cookiemonster region");
} else if (Str.isIn(args[1], "define,def,d")) {//args[1].equalsIgnoreCase("define")) {
if (worldEdit == null) {
sender.sendMessage("WorldEdit (required to define regions) is not installed");
} else if (!(sender instanceof Player)) {
sender.sendMessage("can only be done in-game");
} else {
regions.define((Player) sender, args, worldEdit.getSelection((Player) sender));
}
} else if (Str.isIn(args[1], "remove,delete,del,rem")) {//args[1].equalsIgnoreCase("remove")) {
regions.remove(sender, args);
}
} else {
return false;
}
}
return true;
}
public static Server getBukkitServer() {
return server;
}
public static CMRewardHandler getRewardHandler() {
return rewardHandler;
}
public static CMConfig getSettings() {
return config;
}
public static void Log(String txt) {
logger.log(Level.INFO, String.format("[%s] %s", name, txt));
}
public static void Log(Level loglevel, String txt) {
Log(loglevel, txt, true);
}
public static void Log(Level loglevel, String txt, boolean sendReport) {
logger.log(loglevel, String.format("[%s] %s", name, txt == null ? "" : txt));
}
public static void Log(Level loglevel, String txt, Exception params) {
if (txt == null) {
Log(loglevel, params);
} else {
logger.log(loglevel, String.format("[%s] %s", name, txt == null ? "" : txt), params);
}
}
public static void Log(Level loglevel, Exception err) {
logger.log(loglevel, String.format("[%s] %s", name, err == null ? "? unknown exception ?" : err.getMessage()), err);
}
}
| false | true | public void onEnable() {
// Grab plugin details
server = getServer();
PluginManager pm = server.getPluginManager();
PluginDescriptionFile pdfFile = this.getDescription();
// w.e.
Plugin we = pm.getPlugin("WorldEdit");
if (we != null && we instanceof WorldEditPlugin) {
worldEdit = (WorldEditPlugin) we;
} else {
Log(Level.INFO, "Failed to find WorldEdit: regions cannot be defined");
}
try {
regions = new CMRegions(server, getDataFolder());
} catch (NoClassDefFoundError e) {
if (worldEdit == null) {
Log(Level.INFO, "to enable existing regions, put a copy of WorldEdit in the CookieMonster folder, "
+ "or install WorldEdit to the server");
} else {
Log(Level.WARNING, "Unexpected error while loading region manager");
}
regions = null;
}
// Directory
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
//CMConfig.Plugin_Directory = getDataFolder().getPath();
// Configuration
if (!config.load()) {
server.getPluginManager().disablePlugin(this);
Log(Level.SEVERE, "Failed to retrieve configuration from directory.");
Log(Level.SEVERE, "Please back up your current settings and let CookieMonster recreate it.");
return;
}
if (regions != null) {
regions.load();//getServer(), getDataFolder());//new File(getDataFolder(), "regions.yml"));
}
// Initializing Listeners
entityListener = new CMEntityListener(getServer());
blockListener = new CMBlockListener();
rewardHandler = new CMRewardHandler();
if (config.campTrackingEnabled
|| config.globalCampTrackingEnabled) {
killTracker = new CMCampTracker();
}
economyPluginListener = new CMEcon(this);
// Event Registration
pm.registerEvent(Type.ENTITY_DAMAGE, entityProtectListener, Priority.Low, this);
pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.High, this);
pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.High, this);
// pm.registerEvent(Type.PROJECTILE_HIT, entityListener, Priority.Normal, this);
pm.registerEvent(Type.BLOCK_BREAK, blockProtectListener, Priority.Low, this);
pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.Normal, this);
pm.registerEvent(Type.PLAYER_RESPAWN, playerListener, Priority.Normal, this);
pm.registerEvent(Type.PLUGIN_ENABLE, economyPluginListener, Priority.Monitor, this);
pm.registerEvent(Type.PLUGIN_DISABLE, economyPluginListener, Priority.Monitor, this);
// Console Detail
Log(" v" + pdfFile.getVersion() + " loaded successfully.");
Log(" Developed by: " + pdfFile.getAuthors());
}
| public void onEnable() {
// Grab plugin details
server = getServer();
PluginManager pm = server.getPluginManager();
PluginDescriptionFile pdfFile = this.getDescription();
// w.e.
Plugin we = pm.getPlugin("WorldEdit");
if (we != null && we instanceof WorldEditPlugin) {
worldEdit = (WorldEditPlugin) we;
} else {
Log(Level.INFO, "Failed to find WorldEdit: regions cannot be defined");
}
try {
regions = new CMRegions(server, getDataFolder());
} catch (NoClassDefFoundError e) {
if (worldEdit == null) {
Log(Level.INFO, "to enable existing regions, put a copy of WorldEdit in the CookieMonster folder, "
+ "or install WorldEdit to the server");
} else {
Log(Level.WARNING, "Unexpected error while loading region manager");
}
regions = null;
}
// Directory
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
//CMConfig.Plugin_Directory = getDataFolder().getPath();
// Configuration
if (!config.load()) {
server.getPluginManager().disablePlugin(this);
Log(Level.SEVERE, "Failed to retrieve configuration from directory.");
Log(Level.SEVERE, "Please back up your current settings and let CookieMonster recreate it.");
return;
}
if (regions != null) {
regions.load();//getServer(), getDataFolder());//new File(getDataFolder(), "regions.yml"));
}
// Initializing Listeners
entityListener = new CMEntityListener(getServer());
blockListener = new CMBlockListener();
rewardHandler = new CMRewardHandler();
if (config.campTrackingEnabled
|| config.globalCampTrackingEnabled) {
killTracker = new CMCampTracker();
}
economyPluginListener = new CMEcon(this);
// Event Registration
pm.registerEvent(Type.ENTITY_DAMAGE, entityProtectListener, Priority.Low, this);
pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Highest, this);
pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Highest, this);
// pm.registerEvent(Type.PROJECTILE_HIT, entityListener, Priority.Normal, this);
pm.registerEvent(Type.BLOCK_BREAK, blockProtectListener, Priority.Low, this);
pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.Normal, this);
pm.registerEvent(Type.PLAYER_RESPAWN, playerListener, Priority.Normal, this);
pm.registerEvent(Type.PLUGIN_ENABLE, economyPluginListener, Priority.Monitor, this);
pm.registerEvent(Type.PLUGIN_DISABLE, economyPluginListener, Priority.Monitor, this);
// Console Detail
Log(" v" + pdfFile.getVersion() + " loaded successfully.");
Log(" Developed by: " + pdfFile.getAuthors());
}
|
diff --git a/src/backup/PropertiesSystem.java b/src/backup/PropertiesSystem.java
index 78b3cf0..23c38aa 100644
--- a/src/backup/PropertiesSystem.java
+++ b/src/backup/PropertiesSystem.java
@@ -1,201 +1,204 @@
/*
* Copyright (C) 2011 Kilian Gaertner
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package backup;
import org.bukkit.plugin.Plugin;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import static io.FileUtils.FILE_SEPARATOR;
/**
*
* @author Kilian Gaertner
*/
public class PropertiesSystem implements PropertyConstants {
/** How big is the int value array*/
private final int INT_VALUES_SIZE = 2;
private final int BOOL_VALUES_SIZE = 6;
private final int STRING_VALUES_SIZE = 5;
/** Stores every int property*/
private int[] intValues = new int[INT_VALUES_SIZE];
/** Stores every bool property*/
private boolean[] boolValues = new boolean[BOOL_VALUES_SIZE];
/** Stores every string property */
private String[] stringValues = new String[STRING_VALUES_SIZE];
/**
* When constructed all properties are loaded. When no config.ini exists, the
* default values are used
*/
public PropertiesSystem (Plugin plugin) {
StringBuilder sBuilder = new StringBuilder("plugins");
sBuilder.append(FILE_SEPARATOR);
sBuilder.append("Backup");
sBuilder.append(FILE_SEPARATOR);
sBuilder.append("config.ini");
File configFile = new File(sBuilder.toString());
if (!configFile.exists()) {
System.out.println("[Backup] couldn't find the config, create a default one!");
createDefaultSettings(configFile);
}
loadProperties(configFile, plugin);
}
/**
* Load the default configs from the config.ini , stored in the jar
* @param configFile The configFile, but not in the jar
*/
private void createDefaultSettings (File configFile) {
BufferedReader bReader = null;
BufferedWriter bWriter = null;
try {
// open a stream to the config.ini in the jar, because we can only accecs
// over the class loader
bReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/res/config.ini")));
String line = "";
bWriter = new BufferedWriter(new FileWriter(configFile));
// copy the content
while ((line = bReader.readLine()) != null) {
bWriter.write(line);
bWriter.newLine();
}
}
catch (Exception e) {
e.printStackTrace(System.out);
} // so we can be sure, that the streams are really closed
finally {
try {
if (bReader != null)
bReader.close();
if (bWriter != null)
bWriter.close();
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
/**
* Load the properties from the config.ini
* @param configFile The config.ini in the servers dir
*/
private void loadProperties (File configFile, Plugin plugin) {
BufferedReader bReader = null;
try {
bReader = new BufferedReader(new FileReader(configFile));
String line = "";
String version = null;
while ((line = bReader.readLine()) != null) {
if (line.startsWith("//"))
continue;
String[] split = line.split("=",2);
//------------------------------------------------------------//
- if (split[0].equals("BackupIntervall"))
- intValues[INT_BACKUP_INTERVALL] = Integer.parseInt(split[1]) * 1200;
+ if (split[0].equals("BackupIntervall")) {
+ intValues[INT_BACKUP_INTERVALL] = Integer.parseInt(split[1]);
+ if (intValues[INT_BACKUP_INTERVALL] != -1)
+ intValues[INT_BACKUP_INTERVALL] *= 1200;
+ }
else if (split[0].equals("MaximumBackups"))
intValues[INT_MAX_BACKUPS] = Integer.parseInt(split[1]);
//------------------------------------------------------------//
else if (split[0].equals("OnlyOps"))
boolValues[BOOL_ONLY_OPS] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("BackupOnlyWithPlayer"))
boolValues[BOOL_BACKUP_ONLY_PLAYER] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("ZIPBackup"))
boolValues[BOOL_ZIP] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("EnableAutoSave"))
boolValues[BOOL_ACTIVATE_AUTOSAVE] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("BackupPluginDIR"))
boolValues[BOOL_BACKUP_PLUGINS] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("SummarizeBackupContent"))
boolValues[BOOL_SUMMARIZE_CONTENT] = Boolean.parseBoolean(split[1]);
//------------------------------------------------------------//
else if (split[0].equals("MessageStartBackup")) {
if (split.length == 2)
stringValues[STRING_START_BACKUP_MESSAGE] = split[1];
else
stringValues[STRING_START_BACKUP_MESSAGE] = null;
}
else if (split[0].equals("MessageFinishBackup")) {
if (split.length == 2)
stringValues[STRING_FINISH_BACKUP_MESSAGE] = split[1];
else
stringValues[STRING_FINISH_BACKUP_MESSAGE] = null;
}
else if (split[0].equals("DontBackupWorlds")) {
stringValues[STRING_NO_BACKUP_WORLDNAMES] = "";
if (split.length == 2)
stringValues[STRING_NO_BACKUP_WORLDNAMES] = split[1];
}
else if (split[0].equals("CustomDateFormat"))
stringValues[STRING_CUSTOM_DATE_FORMAT] = split[1];
else if (split[0].equals("BackupDir"))
stringValues[STRING_BACKUP_FOLDER] = split[1];
//----------------------------------------------------------------------------//
else if (split[0].equals("Version"))
version = split[1];
}
if (version == null || !version.equals(plugin.getDescription().getVersion()))
System.out.println("[BACKUP] Your config file is outdated! Please delete your config.ini and the newest will be created!");
}
catch (Exception e) {
e.printStackTrace(System.out);
} // so we can be sure, that the strea is closed
finally {
try {
if (bReader != null)
bReader.close();
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
/**
* Get a value of the integer stored properties
* @param property see the constants of PropertiesSystem
* @return The value of the propertie
*/
public int getIntProperty (int property) {
return intValues[property];
}
/**
* Get a value of the boolean stored properties
* @param property see the constants of PropertiesSystem
* @return The value of the propertie
*/
public boolean getBooleanProperty (int property) {
return boolValues[property];
}
/**
* Get a value of the string stored properties
* @param property see the constants of PropertiesSystem
* @return The value of the propertie
*/
public String getStringProperty (int property) {
return stringValues[property];
}
}
| true | true | private void loadProperties (File configFile, Plugin plugin) {
BufferedReader bReader = null;
try {
bReader = new BufferedReader(new FileReader(configFile));
String line = "";
String version = null;
while ((line = bReader.readLine()) != null) {
if (line.startsWith("//"))
continue;
String[] split = line.split("=",2);
//------------------------------------------------------------//
if (split[0].equals("BackupIntervall"))
intValues[INT_BACKUP_INTERVALL] = Integer.parseInt(split[1]) * 1200;
else if (split[0].equals("MaximumBackups"))
intValues[INT_MAX_BACKUPS] = Integer.parseInt(split[1]);
//------------------------------------------------------------//
else if (split[0].equals("OnlyOps"))
boolValues[BOOL_ONLY_OPS] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("BackupOnlyWithPlayer"))
boolValues[BOOL_BACKUP_ONLY_PLAYER] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("ZIPBackup"))
boolValues[BOOL_ZIP] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("EnableAutoSave"))
boolValues[BOOL_ACTIVATE_AUTOSAVE] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("BackupPluginDIR"))
boolValues[BOOL_BACKUP_PLUGINS] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("SummarizeBackupContent"))
boolValues[BOOL_SUMMARIZE_CONTENT] = Boolean.parseBoolean(split[1]);
//------------------------------------------------------------//
else if (split[0].equals("MessageStartBackup")) {
if (split.length == 2)
stringValues[STRING_START_BACKUP_MESSAGE] = split[1];
else
stringValues[STRING_START_BACKUP_MESSAGE] = null;
}
else if (split[0].equals("MessageFinishBackup")) {
if (split.length == 2)
stringValues[STRING_FINISH_BACKUP_MESSAGE] = split[1];
else
stringValues[STRING_FINISH_BACKUP_MESSAGE] = null;
}
else if (split[0].equals("DontBackupWorlds")) {
stringValues[STRING_NO_BACKUP_WORLDNAMES] = "";
if (split.length == 2)
stringValues[STRING_NO_BACKUP_WORLDNAMES] = split[1];
}
else if (split[0].equals("CustomDateFormat"))
stringValues[STRING_CUSTOM_DATE_FORMAT] = split[1];
else if (split[0].equals("BackupDir"))
stringValues[STRING_BACKUP_FOLDER] = split[1];
//----------------------------------------------------------------------------//
else if (split[0].equals("Version"))
version = split[1];
}
if (version == null || !version.equals(plugin.getDescription().getVersion()))
System.out.println("[BACKUP] Your config file is outdated! Please delete your config.ini and the newest will be created!");
}
catch (Exception e) {
e.printStackTrace(System.out);
} // so we can be sure, that the strea is closed
finally {
try {
if (bReader != null)
bReader.close();
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
| private void loadProperties (File configFile, Plugin plugin) {
BufferedReader bReader = null;
try {
bReader = new BufferedReader(new FileReader(configFile));
String line = "";
String version = null;
while ((line = bReader.readLine()) != null) {
if (line.startsWith("//"))
continue;
String[] split = line.split("=",2);
//------------------------------------------------------------//
if (split[0].equals("BackupIntervall")) {
intValues[INT_BACKUP_INTERVALL] = Integer.parseInt(split[1]);
if (intValues[INT_BACKUP_INTERVALL] != -1)
intValues[INT_BACKUP_INTERVALL] *= 1200;
}
else if (split[0].equals("MaximumBackups"))
intValues[INT_MAX_BACKUPS] = Integer.parseInt(split[1]);
//------------------------------------------------------------//
else if (split[0].equals("OnlyOps"))
boolValues[BOOL_ONLY_OPS] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("BackupOnlyWithPlayer"))
boolValues[BOOL_BACKUP_ONLY_PLAYER] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("ZIPBackup"))
boolValues[BOOL_ZIP] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("EnableAutoSave"))
boolValues[BOOL_ACTIVATE_AUTOSAVE] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("BackupPluginDIR"))
boolValues[BOOL_BACKUP_PLUGINS] = Boolean.parseBoolean(split[1]);
else if (split[0].equals("SummarizeBackupContent"))
boolValues[BOOL_SUMMARIZE_CONTENT] = Boolean.parseBoolean(split[1]);
//------------------------------------------------------------//
else if (split[0].equals("MessageStartBackup")) {
if (split.length == 2)
stringValues[STRING_START_BACKUP_MESSAGE] = split[1];
else
stringValues[STRING_START_BACKUP_MESSAGE] = null;
}
else if (split[0].equals("MessageFinishBackup")) {
if (split.length == 2)
stringValues[STRING_FINISH_BACKUP_MESSAGE] = split[1];
else
stringValues[STRING_FINISH_BACKUP_MESSAGE] = null;
}
else if (split[0].equals("DontBackupWorlds")) {
stringValues[STRING_NO_BACKUP_WORLDNAMES] = "";
if (split.length == 2)
stringValues[STRING_NO_BACKUP_WORLDNAMES] = split[1];
}
else if (split[0].equals("CustomDateFormat"))
stringValues[STRING_CUSTOM_DATE_FORMAT] = split[1];
else if (split[0].equals("BackupDir"))
stringValues[STRING_BACKUP_FOLDER] = split[1];
//----------------------------------------------------------------------------//
else if (split[0].equals("Version"))
version = split[1];
}
if (version == null || !version.equals(plugin.getDescription().getVersion()))
System.out.println("[BACKUP] Your config file is outdated! Please delete your config.ini and the newest will be created!");
}
catch (Exception e) {
e.printStackTrace(System.out);
} // so we can be sure, that the strea is closed
finally {
try {
if (bReader != null)
bReader.close();
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
|
diff --git a/petite/src/wombat/scheme/libraries/TurtleAPI.java b/petite/src/wombat/scheme/libraries/TurtleAPI.java
index 1e5670b..5d5fc88 100644
--- a/petite/src/wombat/scheme/libraries/TurtleAPI.java
+++ b/petite/src/wombat/scheme/libraries/TurtleAPI.java
@@ -1,103 +1,104 @@
package wombat.scheme.libraries;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.*;
import wombat.scheme.libraries.gui.ImageFrame;
/**
* Represent turtle graphics.
*/
public class TurtleAPI {
/**
* Convert a turtle to an image.
* @param data Lines each with "tick x0 y0 x1 y1 r g b"
* @return An image.
*/
public static Image turtleToImage(String data) {
@SuppressWarnings("unused")
class LineData {
int Tick;
double X0;
double Y0;
double X1;
double Y1;
Color C;
LineData(int tick, double x0, double y0, double x1, double y1, Color c) {
Tick = tick;
X0 = x0;
Y0 = y0;
X1 = x1;
Y1 = y1;
C = c;
}
}
List<LineData> lines = new ArrayList<LineData>();
double minX = 0;
double maxX = 0;
double minY = 0;
double maxY = 0;
for (String line : data.split("\n")) {
- String[] parts = line.split(" ");
- if (parts.length != 8) continue;
+ String[] parts = line.trim().split(" ");
+ if (parts.length == 0) continue;
+ if (parts.length != 8) throw new IllegalArgumentException("Malformed turtle data with line: " + line);
lines.add(new LineData(
Integer.parseInt(parts[0]),
Double.parseDouble(parts[1]),
-1.0 * Double.parseDouble(parts[2]),
Double.parseDouble(parts[3]),
-1.0 * Double.parseDouble(parts[4]),
new Color(
Integer.parseInt(parts[5]),
Integer.parseInt(parts[6]),
Integer.parseInt(parts[7])
)
));
- }
+ }
for (LineData line : lines) {
minX = Math.min(line.X0, Math.min(line.X1, minX));
maxX = Math.max(line.X0, Math.max(line.X1, maxX));
minY = Math.min(line.Y0, Math.min(line.Y1, minY));
maxY = Math.max(line.Y0, Math.max(line.Y1, maxY));
}
minX -= 1;
maxX += 1;
minY -= 1;
maxY += 1;
BufferedImage bi = new BufferedImage((int) (maxX - minX), (int) (maxY - minY), BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
for (LineData line : lines) {
g.setColor(line.C);
g.drawLine(
(int) (line.X0 - minX),
(int) (line.Y0 - minY),
(int) (line.X1 - minX),
(int) (line.Y1 - minY)
);
}
return bi;
}
/**
* Draw a set of turtle lines.
* @param data Lines each with "tick x0 y0 x1 y1 r g b"
*/
public static void drawTurtle(String data) {
ImageFrame iframe = new ImageFrame(turtleToImage(data));
iframe.setTitle("draw-turtle");
iframe.setVisible(true);
}
}
| false | true | public static Image turtleToImage(String data) {
@SuppressWarnings("unused")
class LineData {
int Tick;
double X0;
double Y0;
double X1;
double Y1;
Color C;
LineData(int tick, double x0, double y0, double x1, double y1, Color c) {
Tick = tick;
X0 = x0;
Y0 = y0;
X1 = x1;
Y1 = y1;
C = c;
}
}
List<LineData> lines = new ArrayList<LineData>();
double minX = 0;
double maxX = 0;
double minY = 0;
double maxY = 0;
for (String line : data.split("\n")) {
String[] parts = line.split(" ");
if (parts.length != 8) continue;
lines.add(new LineData(
Integer.parseInt(parts[0]),
Double.parseDouble(parts[1]),
-1.0 * Double.parseDouble(parts[2]),
Double.parseDouble(parts[3]),
-1.0 * Double.parseDouble(parts[4]),
new Color(
Integer.parseInt(parts[5]),
Integer.parseInt(parts[6]),
Integer.parseInt(parts[7])
)
));
}
for (LineData line : lines) {
minX = Math.min(line.X0, Math.min(line.X1, minX));
maxX = Math.max(line.X0, Math.max(line.X1, maxX));
minY = Math.min(line.Y0, Math.min(line.Y1, minY));
maxY = Math.max(line.Y0, Math.max(line.Y1, maxY));
}
minX -= 1;
maxX += 1;
minY -= 1;
maxY += 1;
BufferedImage bi = new BufferedImage((int) (maxX - minX), (int) (maxY - minY), BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
for (LineData line : lines) {
g.setColor(line.C);
g.drawLine(
(int) (line.X0 - minX),
(int) (line.Y0 - minY),
(int) (line.X1 - minX),
(int) (line.Y1 - minY)
);
}
return bi;
}
| public static Image turtleToImage(String data) {
@SuppressWarnings("unused")
class LineData {
int Tick;
double X0;
double Y0;
double X1;
double Y1;
Color C;
LineData(int tick, double x0, double y0, double x1, double y1, Color c) {
Tick = tick;
X0 = x0;
Y0 = y0;
X1 = x1;
Y1 = y1;
C = c;
}
}
List<LineData> lines = new ArrayList<LineData>();
double minX = 0;
double maxX = 0;
double minY = 0;
double maxY = 0;
for (String line : data.split("\n")) {
String[] parts = line.trim().split(" ");
if (parts.length == 0) continue;
if (parts.length != 8) throw new IllegalArgumentException("Malformed turtle data with line: " + line);
lines.add(new LineData(
Integer.parseInt(parts[0]),
Double.parseDouble(parts[1]),
-1.0 * Double.parseDouble(parts[2]),
Double.parseDouble(parts[3]),
-1.0 * Double.parseDouble(parts[4]),
new Color(
Integer.parseInt(parts[5]),
Integer.parseInt(parts[6]),
Integer.parseInt(parts[7])
)
));
}
for (LineData line : lines) {
minX = Math.min(line.X0, Math.min(line.X1, minX));
maxX = Math.max(line.X0, Math.max(line.X1, maxX));
minY = Math.min(line.Y0, Math.min(line.Y1, minY));
maxY = Math.max(line.Y0, Math.max(line.Y1, maxY));
}
minX -= 1;
maxX += 1;
minY -= 1;
maxY += 1;
BufferedImage bi = new BufferedImage((int) (maxX - minX), (int) (maxY - minY), BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
for (LineData line : lines) {
g.setColor(line.C);
g.drawLine(
(int) (line.X0 - minX),
(int) (line.Y0 - minY),
(int) (line.X1 - minX),
(int) (line.Y1 - minY)
);
}
return bi;
}
|
diff --git a/src/com/android/mms/transaction/NotificationTransaction.java b/src/com/android/mms/transaction/NotificationTransaction.java
index 20bf0873..10f540e1 100644
--- a/src/com/android/mms/transaction/NotificationTransaction.java
+++ b/src/com/android/mms/transaction/NotificationTransaction.java
@@ -1,250 +1,262 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import static com.android.mms.transaction.TransactionState.FAILED;
import static com.android.mms.transaction.TransactionState.INITIALIZED;
import static com.android.mms.transaction.TransactionState.SUCCESS;
import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF;
import static com.google.android.mms.pdu.PduHeaders.STATUS_DEFERRED;
import static com.google.android.mms.pdu.PduHeaders.STATUS_RETRIEVED;
import static com.google.android.mms.pdu.PduHeaders.STATUS_UNRECOGNIZED;
import com.android.mms.MmsApp;
import com.android.mms.MmsConfig;
import com.android.mms.util.DownloadManager;
import com.android.mms.util.Recycler;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu.GenericPdu;
import com.google.android.mms.pdu.NotificationInd;
import com.google.android.mms.pdu.NotifyRespInd;
import com.google.android.mms.pdu.PduComposer;
import com.google.android.mms.pdu.PduHeaders;
import com.google.android.mms.pdu.PduParser;
import com.google.android.mms.pdu.PduPersister;
import android.database.sqlite.SqliteWrapper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Inbox;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.io.IOException;
/**
* The NotificationTransaction is responsible for handling multimedia
* message notifications (M-Notification.ind). It:
*
* <ul>
* <li>Composes the notification response (M-NotifyResp.ind).
* <li>Sends the notification response to the MMSC server.
* <li>Stores the notification indication.
* <li>Notifies the TransactionService about succesful completion.
* </ul>
*
* NOTE: This MMS client handles all notifications with a <b>deferred
* retrieval</b> response. The transaction service, upon succesful
* completion of this transaction, will trigger a retrieve transaction
* in case the client is in immediate retrieve mode.
*/
public class NotificationTransaction extends Transaction implements Runnable {
private static final String TAG = "NotificationTransaction";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private Uri mUri;
private NotificationInd mNotificationInd;
private String mContentLocation;
public NotificationTransaction(
Context context, int serviceId,
TransactionSettings connectionSettings, String uriString) {
super(context, serviceId, connectionSettings);
mUri = Uri.parse(uriString);
try {
mNotificationInd = (NotificationInd)
PduPersister.getPduPersister(context).load(mUri);
} catch (MmsException e) {
Log.e(TAG, "Failed to load NotificationInd from: " + uriString, e);
throw new IllegalArgumentException();
}
mId = new String(mNotificationInd.getTransactionId());
mContentLocation = new String(mNotificationInd.getContentLocation());
// Attach the transaction to the instance of RetryScheduler.
attach(RetryScheduler.getInstance(context));
}
/**
* This constructor is only used for test purposes.
*/
public NotificationTransaction(
Context context, int serviceId,
TransactionSettings connectionSettings, NotificationInd ind) {
super(context, serviceId, connectionSettings);
try {
mUri = PduPersister.getPduPersister(context).persist(
ind, Inbox.CONTENT_URI);
} catch (MmsException e) {
Log.e(TAG, "Failed to save NotificationInd in constructor.", e);
throw new IllegalArgumentException();
}
mNotificationInd = ind;
mId = new String(ind.getTransactionId());
}
/*
* (non-Javadoc)
* @see com.google.android.mms.pdu.Transaction#process()
*/
@Override
public void process() {
new Thread(this).start();
}
public void run() {
DownloadManager downloadManager = DownloadManager.getInstance();
boolean autoDownload = downloadManager.isAuto();
boolean dataSuspended = (MmsApp.getApplication().getTelephonyManager().getDataState() ==
TelephonyManager.DATA_SUSPENDED);
try {
if (LOCAL_LOGV) {
Log.v(TAG, "Notification transaction launched: " + this);
}
// By default, we set status to STATUS_DEFERRED because we
// should response MMSC with STATUS_DEFERRED when we cannot
// download a MM immediately.
int status = STATUS_DEFERRED;
// Don't try to download when data is suspended, as it will fail, so defer download
if (!autoDownload || dataSuspended) {
downloadManager.markState(mUri, DownloadManager.STATE_UNSTARTED);
sendNotifyRespInd(status);
return;
}
downloadManager.markState(mUri, DownloadManager.STATE_DOWNLOADING);
if (LOCAL_LOGV) {
Log.v(TAG, "Content-Location: " + mContentLocation);
}
byte[] retrieveConfData = null;
// We should catch exceptions here to response MMSC
// with STATUS_DEFERRED.
try {
retrieveConfData = getPdu(mContentLocation);
} catch (IOException e) {
mTransactionState.setState(FAILED);
}
if (retrieveConfData != null) {
GenericPdu pdu = new PduParser(retrieveConfData).parse();
if ((pdu == null) || (pdu.getMessageType() != MESSAGE_TYPE_RETRIEVE_CONF)) {
Log.e(TAG, "Invalid M-RETRIEVE.CONF PDU. " +
(pdu != null ? "message type: " + pdu.getMessageType() : "null pdu"));
mTransactionState.setState(FAILED);
status = STATUS_UNRECOGNIZED;
} else {
// Save the received PDU (must be a M-RETRIEVE.CONF).
PduPersister p = PduPersister.getPduPersister(mContext);
Uri uri = p.persist(pdu, Inbox.CONTENT_URI);
// Use local time instead of PDU time
- ContentValues values = new ContentValues(1);
+ ContentValues values = new ContentValues(2);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
+ Cursor c = mContext.getContentResolver().query(mUri,
+ null, null, null, null);
+ if (c != null) {
+ try {
+ if (c.moveToFirst()) {
+ int subId = c.getInt(c.getColumnIndex(Mms.SUB_ID));
+ values.put(Mms.SUB_ID, subId);
+ }
+ } finally {
+ c.close();
+ }
+ }
SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, values, null, null);
// We have successfully downloaded the new MM. Delete the
// M-NotifyResp.ind from Inbox.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
mUri, null, null);
// Notify observers with newly received MM.
mUri = uri;
status = STATUS_RETRIEVED;
}
}
if (LOCAL_LOGV) {
Log.v(TAG, "status=0x" + Integer.toHexString(status));
}
// Check the status and update the result state of this Transaction.
switch (status) {
case STATUS_RETRIEVED:
mTransactionState.setState(SUCCESS);
break;
case STATUS_DEFERRED:
// STATUS_DEFERRED, may be a failed immediate retrieval.
if (mTransactionState.getState() == INITIALIZED) {
mTransactionState.setState(SUCCESS);
}
break;
}
sendNotifyRespInd(status);
// Make sure this thread isn't over the limits in message count.
Recycler.getMmsRecycler().deleteOldMessagesInSameThreadAsMessage(mContext, mUri);
} catch (Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
} finally {
mTransactionState.setContentUri(mUri);
if (!autoDownload || dataSuspended) {
// Always mark the transaction successful for deferred
// download since any error here doesn't make sense.
mTransactionState.setState(SUCCESS);
}
if (mTransactionState.getState() != SUCCESS) {
mTransactionState.setState(FAILED);
Log.e(TAG, "NotificationTransaction failed.");
}
notifyObservers();
}
}
private void sendNotifyRespInd(int status) throws MmsException, IOException {
// Create the M-NotifyResp.ind
NotifyRespInd notifyRespInd = new NotifyRespInd(
PduHeaders.CURRENT_MMS_VERSION,
mNotificationInd.getTransactionId(),
status);
// Pack M-NotifyResp.ind and send it
if(MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, notifyRespInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, notifyRespInd).make());
}
}
@Override
public int getType() {
return NOTIFICATION_TRANSACTION;
}
}
| false | true | public void run() {
DownloadManager downloadManager = DownloadManager.getInstance();
boolean autoDownload = downloadManager.isAuto();
boolean dataSuspended = (MmsApp.getApplication().getTelephonyManager().getDataState() ==
TelephonyManager.DATA_SUSPENDED);
try {
if (LOCAL_LOGV) {
Log.v(TAG, "Notification transaction launched: " + this);
}
// By default, we set status to STATUS_DEFERRED because we
// should response MMSC with STATUS_DEFERRED when we cannot
// download a MM immediately.
int status = STATUS_DEFERRED;
// Don't try to download when data is suspended, as it will fail, so defer download
if (!autoDownload || dataSuspended) {
downloadManager.markState(mUri, DownloadManager.STATE_UNSTARTED);
sendNotifyRespInd(status);
return;
}
downloadManager.markState(mUri, DownloadManager.STATE_DOWNLOADING);
if (LOCAL_LOGV) {
Log.v(TAG, "Content-Location: " + mContentLocation);
}
byte[] retrieveConfData = null;
// We should catch exceptions here to response MMSC
// with STATUS_DEFERRED.
try {
retrieveConfData = getPdu(mContentLocation);
} catch (IOException e) {
mTransactionState.setState(FAILED);
}
if (retrieveConfData != null) {
GenericPdu pdu = new PduParser(retrieveConfData).parse();
if ((pdu == null) || (pdu.getMessageType() != MESSAGE_TYPE_RETRIEVE_CONF)) {
Log.e(TAG, "Invalid M-RETRIEVE.CONF PDU. " +
(pdu != null ? "message type: " + pdu.getMessageType() : "null pdu"));
mTransactionState.setState(FAILED);
status = STATUS_UNRECOGNIZED;
} else {
// Save the received PDU (must be a M-RETRIEVE.CONF).
PduPersister p = PduPersister.getPduPersister(mContext);
Uri uri = p.persist(pdu, Inbox.CONTENT_URI);
// Use local time instead of PDU time
ContentValues values = new ContentValues(1);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, values, null, null);
// We have successfully downloaded the new MM. Delete the
// M-NotifyResp.ind from Inbox.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
mUri, null, null);
// Notify observers with newly received MM.
mUri = uri;
status = STATUS_RETRIEVED;
}
}
if (LOCAL_LOGV) {
Log.v(TAG, "status=0x" + Integer.toHexString(status));
}
// Check the status and update the result state of this Transaction.
switch (status) {
case STATUS_RETRIEVED:
mTransactionState.setState(SUCCESS);
break;
case STATUS_DEFERRED:
// STATUS_DEFERRED, may be a failed immediate retrieval.
if (mTransactionState.getState() == INITIALIZED) {
mTransactionState.setState(SUCCESS);
}
break;
}
sendNotifyRespInd(status);
// Make sure this thread isn't over the limits in message count.
Recycler.getMmsRecycler().deleteOldMessagesInSameThreadAsMessage(mContext, mUri);
} catch (Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
} finally {
mTransactionState.setContentUri(mUri);
if (!autoDownload || dataSuspended) {
// Always mark the transaction successful for deferred
// download since any error here doesn't make sense.
mTransactionState.setState(SUCCESS);
}
if (mTransactionState.getState() != SUCCESS) {
mTransactionState.setState(FAILED);
Log.e(TAG, "NotificationTransaction failed.");
}
notifyObservers();
}
}
| public void run() {
DownloadManager downloadManager = DownloadManager.getInstance();
boolean autoDownload = downloadManager.isAuto();
boolean dataSuspended = (MmsApp.getApplication().getTelephonyManager().getDataState() ==
TelephonyManager.DATA_SUSPENDED);
try {
if (LOCAL_LOGV) {
Log.v(TAG, "Notification transaction launched: " + this);
}
// By default, we set status to STATUS_DEFERRED because we
// should response MMSC with STATUS_DEFERRED when we cannot
// download a MM immediately.
int status = STATUS_DEFERRED;
// Don't try to download when data is suspended, as it will fail, so defer download
if (!autoDownload || dataSuspended) {
downloadManager.markState(mUri, DownloadManager.STATE_UNSTARTED);
sendNotifyRespInd(status);
return;
}
downloadManager.markState(mUri, DownloadManager.STATE_DOWNLOADING);
if (LOCAL_LOGV) {
Log.v(TAG, "Content-Location: " + mContentLocation);
}
byte[] retrieveConfData = null;
// We should catch exceptions here to response MMSC
// with STATUS_DEFERRED.
try {
retrieveConfData = getPdu(mContentLocation);
} catch (IOException e) {
mTransactionState.setState(FAILED);
}
if (retrieveConfData != null) {
GenericPdu pdu = new PduParser(retrieveConfData).parse();
if ((pdu == null) || (pdu.getMessageType() != MESSAGE_TYPE_RETRIEVE_CONF)) {
Log.e(TAG, "Invalid M-RETRIEVE.CONF PDU. " +
(pdu != null ? "message type: " + pdu.getMessageType() : "null pdu"));
mTransactionState.setState(FAILED);
status = STATUS_UNRECOGNIZED;
} else {
// Save the received PDU (must be a M-RETRIEVE.CONF).
PduPersister p = PduPersister.getPduPersister(mContext);
Uri uri = p.persist(pdu, Inbox.CONTENT_URI);
// Use local time instead of PDU time
ContentValues values = new ContentValues(2);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
Cursor c = mContext.getContentResolver().query(mUri,
null, null, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
int subId = c.getInt(c.getColumnIndex(Mms.SUB_ID));
values.put(Mms.SUB_ID, subId);
}
} finally {
c.close();
}
}
SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, values, null, null);
// We have successfully downloaded the new MM. Delete the
// M-NotifyResp.ind from Inbox.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
mUri, null, null);
// Notify observers with newly received MM.
mUri = uri;
status = STATUS_RETRIEVED;
}
}
if (LOCAL_LOGV) {
Log.v(TAG, "status=0x" + Integer.toHexString(status));
}
// Check the status and update the result state of this Transaction.
switch (status) {
case STATUS_RETRIEVED:
mTransactionState.setState(SUCCESS);
break;
case STATUS_DEFERRED:
// STATUS_DEFERRED, may be a failed immediate retrieval.
if (mTransactionState.getState() == INITIALIZED) {
mTransactionState.setState(SUCCESS);
}
break;
}
sendNotifyRespInd(status);
// Make sure this thread isn't over the limits in message count.
Recycler.getMmsRecycler().deleteOldMessagesInSameThreadAsMessage(mContext, mUri);
} catch (Throwable t) {
Log.e(TAG, Log.getStackTraceString(t));
} finally {
mTransactionState.setContentUri(mUri);
if (!autoDownload || dataSuspended) {
// Always mark the transaction successful for deferred
// download since any error here doesn't make sense.
mTransactionState.setState(SUCCESS);
}
if (mTransactionState.getState() != SUCCESS) {
mTransactionState.setState(FAILED);
Log.e(TAG, "NotificationTransaction failed.");
}
notifyObservers();
}
}
|
diff --git a/ksoap2-base/src/main/java/org/ksoap2/SoapFault.java b/ksoap2-base/src/main/java/org/ksoap2/SoapFault.java
index 76eb2a3..99630a3 100644
--- a/ksoap2-base/src/main/java/org/ksoap2/SoapFault.java
+++ b/ksoap2-base/src/main/java/org/ksoap2/SoapFault.java
@@ -1,83 +1,85 @@
/* Copyright (c) 2003,2004, Stefan Haustein, Oberhausen, Rhld., Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE. */
package org.ksoap2;
import java.io.*;
import org.xmlpull.v1.*;
import org.kxml2.kdom.*;
/**
* Exception class encapsulating SOAP Faults
*/
public class SoapFault extends IOException {
/** The SOAP fault code */
public String faultcode;
/** The SOAP fault code */
public String faultstring;
/** The SOAP fault code */
public String faultactor;
/** A KDom Node holding the details of the fault */
public Node detail;
/** Fills the fault details from the given XML stream */
public void parse(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, SoapEnvelope.ENV, "Fault");
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("detail")) {
detail = new Node();
detail.parse(parser);
continue;
} else if (name.equals("faultcode"))
faultcode = parser.nextText();
else if (name.equals("faultstring"))
faultstring = parser.nextText();
else if (name.equals("faultactor"))
faultactor = parser.nextText();
else
throw new RuntimeException("unexpected tag:" + name);
parser.require(XmlPullParser.END_TAG, null, name);
}
+ parser.require(XmlPullParser.END_TAG, SoapEnvelope.ENV, "Fault");
+ parser.nextTag();
}
/** Writes the fault to the given XML stream */
public void write(XmlSerializer xw) throws IOException {
xw.startTag(SoapEnvelope.ENV, "Fault");
xw.startTag(null, "faultcode");
xw.text("" + faultcode);
xw.endTag(null, "faultcode");
xw.startTag(null, "faultstring");
xw.text("" + faultstring);
xw.endTag(null, "faultstring");
xw.startTag(null, "detail");
if (detail != null)
detail.write(xw);
xw.endTag(null, "detail");
xw.endTag(SoapEnvelope.ENV, "Fault");
}
/** Returns a simple string representation of the fault */
public String toString() {
return "SoapFault - faultcode: '" + faultcode + "' faultstring: '" + faultstring + "' faultactor: '" + faultactor + "' detail: " + detail;
}
}
| true | true | public void parse(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, SoapEnvelope.ENV, "Fault");
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("detail")) {
detail = new Node();
detail.parse(parser);
continue;
} else if (name.equals("faultcode"))
faultcode = parser.nextText();
else if (name.equals("faultstring"))
faultstring = parser.nextText();
else if (name.equals("faultactor"))
faultactor = parser.nextText();
else
throw new RuntimeException("unexpected tag:" + name);
parser.require(XmlPullParser.END_TAG, null, name);
}
}
| public void parse(XmlPullParser parser) throws IOException, XmlPullParserException {
parser.require(XmlPullParser.START_TAG, SoapEnvelope.ENV, "Fault");
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals("detail")) {
detail = new Node();
detail.parse(parser);
continue;
} else if (name.equals("faultcode"))
faultcode = parser.nextText();
else if (name.equals("faultstring"))
faultstring = parser.nextText();
else if (name.equals("faultactor"))
faultactor = parser.nextText();
else
throw new RuntimeException("unexpected tag:" + name);
parser.require(XmlPullParser.END_TAG, null, name);
}
parser.require(XmlPullParser.END_TAG, SoapEnvelope.ENV, "Fault");
parser.nextTag();
}
|
diff --git a/src/api/cli/Tester.java b/src/api/cli/Tester.java
index 0e6e68a..4eef42d 100644
--- a/src/api/cli/Tester.java
+++ b/src/api/cli/Tester.java
@@ -1,45 +1,45 @@
package api.cli;
import api.search.requests.RequestsSearch;
import api.soup.MySoup;
import api.util.CouldNotLoadException;
/**
* The Class Tester.
*
* @author Gwindow
*/
public class Tester {
private final static String UPDATE_SITE = "https://raw.github.com/Gwindow/WhatAndroid/gh-pages/index.html";
/**
* Instantiates a new tester.
*
* @throws CouldNotLoadException
* the could not load exception
*/
public Tester() throws CouldNotLoadException {
MySoup.setSite("what.cd");
- MySoup.login("login.php", "Gwindow", "t2ustUdE");
+ MySoup.login("login.php", "", "");
RequestsSearch rs = RequestsSearch.requestSearchFromSearchTerm("chopin");
for (int i = 0; i < rs.getResponse().getResults().size(); i++) {
System.out.println(rs.getResponse().getResults().get(i));
}
}
/**
* The main method.
*
* @param args
* the arguments
* @throws CouldNotLoadException
* the could not load exception
*/
public static void main(String[] args) throws CouldNotLoadException {
new Tester();
}
}
| true | true | public Tester() throws CouldNotLoadException {
MySoup.setSite("what.cd");
MySoup.login("login.php", "Gwindow", "t2ustUdE");
RequestsSearch rs = RequestsSearch.requestSearchFromSearchTerm("chopin");
for (int i = 0; i < rs.getResponse().getResults().size(); i++) {
System.out.println(rs.getResponse().getResults().get(i));
}
}
| public Tester() throws CouldNotLoadException {
MySoup.setSite("what.cd");
MySoup.login("login.php", "", "");
RequestsSearch rs = RequestsSearch.requestSearchFromSearchTerm("chopin");
for (int i = 0; i < rs.getResponse().getResults().size(); i++) {
System.out.println(rs.getResponse().getResults().get(i));
}
}
|
diff --git a/src/main/java/vle/web/VLEAnnotationController.java b/src/main/java/vle/web/VLEAnnotationController.java
index e44ae707..c11c1227 100644
--- a/src/main/java/vle/web/VLEAnnotationController.java
+++ b/src/main/java/vle/web/VLEAnnotationController.java
@@ -1,638 +1,638 @@
/**
*
*/
package vle.web;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import utils.SecurityUtils;
import vle.domain.annotation.Annotation;
import vle.domain.cRater.CRaterRequest;
import vle.domain.node.Node;
import vle.domain.peerreview.PeerReviewWork;
import vle.domain.user.UserInfo;
import vle.domain.webservice.crater.CRaterHttpClient;
import vle.domain.work.StepWork;
/**
* Controllers for handling Annotation GET and POST
* @author hirokiterashima
* @author geoffreykwan
*/
public class VLEAnnotationController extends HttpServlet {
private static final long serialVersionUID = 1L;
private boolean standAlone = true;
private boolean modeRetrieved = false;
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
/* check to see if we are in portal mode */
if(!this.modeRetrieved){
this.standAlone = !SecurityUtils.isPortalMode(request);
this.modeRetrieved = true;
}
/* make sure that this request is authenticated through the portal before proceeding */
if(this.standAlone || SecurityUtils.isAuthenticated(request)){
doPostJSON(request, response);
} else {
/* not authenticated send not authorized status */
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
/* check to see if we are in portal mode */
if(!this.modeRetrieved){
this.standAlone = !SecurityUtils.isPortalMode(request);
this.modeRetrieved = true;
}
/* make sure that this request is authenticated through the portal before proceeding */
if(this.standAlone || SecurityUtils.isAuthenticated(request)){
doGetJSON(request, response);
} else {
/* not authenticated send not authorized status */
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}
/**
* Handle GETing of Annotations.
* This includes GETing CRater Annotations, which involves POSTing to the
* CRater server (if needed).
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@SuppressWarnings("unchecked")
public void doGetJSON(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String requestedType = request.getParameter("type");
String fromWorkgroupIdStr = request.getParameter("fromWorkgroup");
String fromWorkgroupIdsStr = request.getParameter("fromWorkgroups");
String toWorkgroupIdStr = request.getParameter("toWorkgroup");
String runId = request.getParameter("runId");
String stepWorkIdStr = request.getParameter("stepWorkId");
String isStudentStr = request.getParameter("isStudent");
String annotationType = request.getParameter("annotationType");
String nodeStateIdStr = request.getParameter("nodeStateId");
String cRaterVerificationUrl = (String) request.getAttribute("cRaterVerificationUrl");
String cRaterScoringUrl = (String) request.getAttribute("cRaterScoringUrl");
String cRaterClientId = (String) request.getAttribute("cRaterClientId");
//this is only used when students retrieve flags
Vector<JSONObject> flaggedAnnotationsList = new Vector<JSONObject>();
//used to hold classmate workgroup ids to period ids
HashMap<Long, Long> classmateWorkgroupIdToPeriodIdMap = new HashMap<Long, Long>();
Long periodId = null;
Long longRunId = null;
if(runId != null) {
longRunId = Long.parseLong(runId);
}
Long stepWorkId = null;
if(stepWorkIdStr != null) {
stepWorkId = Long.parseLong(stepWorkIdStr);
}
boolean isStudent = false;
if(isStudentStr != null) {
isStudent = Boolean.parseBoolean(isStudentStr);
}
Long nodeStateId = null;
if(nodeStateIdStr != null) {
nodeStateId = Long.parseLong(nodeStateIdStr);
}
/*
* retrieval of periods is only required when students request flagged work
* because we only want students to see flagged work from their own period
*/
- if(requestedType.equals("flag") && isStudent) {
+ if((requestedType.equals("flag") || requestedType.equals("inappropriateFlag")) && isStudent) {
try {
//get the signed in student's user info and period id
String myUserInfoString = (String) request.getAttribute("myUserInfo");
JSONObject myUserInfo = new JSONObject(myUserInfoString);
periodId = myUserInfo.getLong("periodId");
//get the classmate user infos
String classmateUserInfosString = (String) request.getAttribute("classmateUserInfos");
JSONArray classmateUserInfos = new JSONArray(classmateUserInfosString);
//loop through all the classmate user infos
for(int x=0; x<classmateUserInfos.length(); x++) {
//get a classmate user info
JSONObject classmateUserInfo = classmateUserInfos.getJSONObject(x);
//get the workgroup id and period id of the classmate
long classmateWorkgroupId = classmateUserInfo.getLong("workgroupId");
long classmatePeriodId = classmateUserInfo.getLong("periodId");
//add the classmate workgroup id to period id entry into the map
classmateWorkgroupIdToPeriodIdMap.put(classmateWorkgroupId, classmatePeriodId);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// if requestedType is null, return all annotations
List<? extends Annotation> annotationList = null;
Annotation annotation = null;
if (requestedType == null ||
(requestedType.equals("annotation") && !"cRater".equals(annotationType))) {
if(fromWorkgroupIdStr != null && stepWorkId != null) {
//user is requesting an annotation they wrote themselves for a specific stepWork
UserInfo fromWorkgroup = UserInfo.getByWorkgroupId(new Long(fromWorkgroupIdStr));
StepWork stepWork = (StepWork) StepWork.getById(stepWorkId, StepWork.class);
annotation = Annotation.getByUserInfoAndStepWork(fromWorkgroup, stepWork, null);
} else if(fromWorkgroupIdsStr != null && toWorkgroupIdStr != null) {
/*
* user is requesting all annotations to toWorkgroup and from any fromWorkgroup
* in the list of fromWorkgroups
*/
UserInfo toWorkgroup = UserInfo.getOrCreateByWorkgroupId(new Long(toWorkgroupIdStr));
//split the fromWorkgroups
String[] split = fromWorkgroupIdsStr.split(",");
//create a String List out of the fromWorkgroups
List<String> fromWorkgroupIds = Arrays.asList(split);
//get the UserInfo objects for the fromWorkgroups
List<UserInfo> fromWorkgroups = UserInfo.getByWorkgroupIds(fromWorkgroupIds);
//get all the annotations that match
annotationList = Annotation.getByFromWorkgroupsAndToWorkgroup(fromWorkgroups, toWorkgroup, Annotation.class);
} else if (fromWorkgroupIdStr != null || toWorkgroupIdStr != null) {
UserInfo fromWorkgroup = null;
UserInfo toWorkgroup = null;
if (fromWorkgroupIdStr != null) {
fromWorkgroup = UserInfo.getByWorkgroupId(new Long(fromWorkgroupIdStr));
}
if (toWorkgroupIdStr != null) {
toWorkgroup = UserInfo.getByWorkgroupId(new Long(toWorkgroupIdStr));
}
annotationList = Annotation.getByFromWorkgroupAndToWorkgroup(fromWorkgroup, toWorkgroup, Annotation.class);
} else if(runId != null) {
//get all the annotations for the run id
annotationList = (List<Annotation>) Annotation.getByRunId(longRunId, Annotation.class);
} else {
annotationList = (List<Annotation>) Annotation.getList(Annotation.class);
}
- } else if (requestedType.equals("flag")) {
+ } else if (requestedType.equals("flag") || requestedType.equals("inappropriateFlag")) {
/*
* get the flags based on the paremeters that were passed in the request.
* this will return the flag annotations ordered from oldest to newest
*/
annotationList = Annotation.getByParamMap(request.getParameterMap());
}
// handle request for cRater annotation
if ("annotation".equals(requestedType) && "cRater".equals(annotationType)) {
annotation = getCRaterAnnotation(nodeStateId, runId, stepWorkId,
annotationType, cRaterScoringUrl, cRaterClientId);
}
JSONObject annotationsJSONObj = null;
if(annotationList != null) {
//a list of annotations will be returned
annotationsJSONObj = new JSONObject(); // all annotations
/*
* loop through all the annotations, the annotations are ordered
* from oldest to newest
*/
for (Annotation annotationObj : annotationList) {
try {
//get an annotation
JSONObject dataJSONObj = new JSONObject(annotationObj.getData());
//add the postTime
dataJSONObj.put("postTime", annotationObj.getPostTime().getTime());
/*
* if this is a student making the request we will add the stepWork data
* to each of the flags so they can see the work that was flagged
*/
if(requestedType.equals("flag") && isStudent) {
//get the stepWorkId of the work that was flagged
String flagStepWorkId = dataJSONObj.getString("stepWorkId");
//get the StepWork object
StepWork flagStepWork = StepWork.getByStepWorkId(new Long(flagStepWorkId));
//get the user info of the work that was flagged
UserInfo flaggedWorkUserInfo = flagStepWork.getUserInfo();
//get the workgroup id of the work that was flagged
Long flaggedWorkgroupId = flaggedWorkUserInfo.getWorkgroupId();
//get the period id of the work that was flagged
Long flaggedPeriodId = classmateWorkgroupIdToPeriodIdMap.get(flaggedWorkgroupId);
//check that the period of the flagged work is the same period that the signed in user is in
if(periodId != null && flaggedPeriodId != null && periodId.equals(flaggedPeriodId)) {
//get the data
JSONObject flagStepWorkData = new JSONObject(flagStepWork.getData());
//check if the flag value is set to "flagged" as opposed to "unflagged"
if(dataJSONObj.has("value") && dataJSONObj.getString("value").equals("flagged")) {
//add the data to the flag JSON object
dataJSONObj.put("data", flagStepWorkData);
//put the flag object into our list
flaggedAnnotationsList.add(dataJSONObj);
} else {
//remove the flag from the list because it was unflagged
/*
* loop through all the flagged annotations we have already obtained
* to remove the annotation that was unflagged
*/
Iterator<JSONObject> flaggedAnnotationsIterator = flaggedAnnotationsList.iterator();
while(flaggedAnnotationsIterator.hasNext()) {
//get an annotation
JSONObject nextFlaggedAnnotation = flaggedAnnotationsIterator.next();
//check if the annotation fields match
if(nextFlaggedAnnotation.has("toWorkgroup") && dataJSONObj.has("toWorkgroup") && nextFlaggedAnnotation.getString("toWorkgroup").equals(dataJSONObj.getString("toWorkgroup")) &&
nextFlaggedAnnotation.has("fromWorkgroup") && dataJSONObj.has("fromWorkgroup") && nextFlaggedAnnotation.getString("fromWorkgroup").equals(dataJSONObj.getString("fromWorkgroup")) &&
nextFlaggedAnnotation.has("nodeId") && dataJSONObj.has("nodeId") && nextFlaggedAnnotation.getString("nodeId").equals(dataJSONObj.getString("nodeId")) &&
nextFlaggedAnnotation.has("stepWorkId") && dataJSONObj.has("stepWorkId") && nextFlaggedAnnotation.getString("stepWorkId").equals(dataJSONObj.getString("stepWorkId")) &&
nextFlaggedAnnotation.has("runId") && dataJSONObj.has("runId") && nextFlaggedAnnotation.getString("runId").equals(dataJSONObj.getString("runId"))) {
flaggedAnnotationsIterator.remove();
}
}
}
}
} else {
//add the annotation to the JSON obj we will return
annotationsJSONObj.append("annotationsArray", dataJSONObj);
}
} catch (JSONException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error retrieving annotations");
e.printStackTrace();
}
}
/*
* the student is requesting the flags, we will now insert the json flag annotation
* objects into the annotationsJSONObj that will be returned as a response to the
* user
*/
- if(requestedType.equals("flag") && isStudent) {
+ if((requestedType.equals("flag") || requestedType.equals("inappropriateFlag")) && isStudent) {
//get all the stepwork ids that were flagged
//loop through all the flag annotations
for(JSONObject flagAnnotationDataJSONObj : flaggedAnnotationsList) {
try {
//get the run id, node id, and student id
String flaggedRunId = flagAnnotationDataJSONObj.getString("runId");
String flaggedNodeId = flagAnnotationDataJSONObj.getString("nodeId");
String flaggedToWorkgroup = flagAnnotationDataJSONObj.getString("toWorkgroup");
//get the Node and UserInfo objects
Node node = Node.getByNodeIdAndRunId(flaggedNodeId, flaggedRunId);
UserInfo studentWorkgroup = UserInfo.getByWorkgroupId(new Long(flaggedToWorkgroup));
/*
* get the step works the student did for the node. the list will be
* ordered from newest to oldest
*/
List<StepWork> stepWorks = StepWork.getByUserInfoAndNode(studentWorkgroup, node);
JSONObject latestStepWorkDataJSONObj = null;
//loop through all the step works the student did
for(int x=0; x<stepWorks.size(); x++) {
//get a step work
StepWork stepWork = stepWorks.get(x);
//get the json data from the step work
String stepWorkData = stepWork.getData();
//remember the newest step work data
latestStepWorkDataJSONObj = new JSONObject(stepWorkData);
//get the node states
JSONArray nodeStates = latestStepWorkDataJSONObj.getJSONArray("nodeStates");
//check if the node states is empty
if(nodeStates.length() > 0) {
/*
* node states is not empty so we have found the newest
* step work that contains actual work
*/
break;
}
}
//check if we found any step work data
if(latestStepWorkDataJSONObj != null) {
//put the data into the flag annotation object
flagAnnotationDataJSONObj.put("data", latestStepWorkDataJSONObj);
//put the flag object into the annotations array
annotationsJSONObj.append("annotationsArray", flagAnnotationDataJSONObj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
} else if(annotation != null) {
try {
//only one annotation will be returned
annotationsJSONObj = new JSONObject(annotation.getData());
} catch (JSONException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error retrieving annotations");
e.printStackTrace();
}
}
if(annotationsJSONObj != null) {
response.getWriter().write(annotationsJSONObj.toString());
} else {
// there was an error retrieving the annotation
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"error retrieving annotations");
}
}
/**
* Returns a CRater Annotation based on parameters, if exists. If not, makes a request to the
* CRater server to get automated feedback and saves it as an Annotation.
*
* Also updates/appends to an already-existing CRater Annotation if needed.
* @param request
* @param runId
* @param stepWorkIdStr
* @param annotationType
* @param cRaterScoringUrl
* @param cRaterClientId
* @param stepWorkId
* @return CRater annotation for the specified stepwork, or null if there was an error getting the CRater response
*/
public static Annotation getCRaterAnnotation(Long nodeStateId,
String runId, Long stepWorkId, String annotationType,
String cRaterScoringUrl, String cRaterClientId) {
// for identifying this response when sending to the CRater server.
String cRaterResponseId = stepWorkId.toString();
Annotation annotation = null;
//try to obtain the crater annotation if it exists
annotation = Annotation.getCRaterAnnotationByStepWorkId(stepWorkId);
if (annotation != null) {
// cRater annotation already exists, we are either getting it if it also exists for the
// specified nodestate or appending to the annotation array if it doesn't exist
JSONObject nodeStateCRaterAnnotation = annotation.getAnnotationForNodeStateId(nodeStateId);
if (nodeStateCRaterAnnotation != null) {
// do nothing...this stepwork has already been scored and saved in the annotation
// this will be returned to user later in this function
} else {
//this node state does not have a crater annotation yet so we will make it and add it to the array of annotations
try {
// make a request to CRater
StepWork stepWork = StepWork.getByStepWorkId(stepWorkId);
JSONObject nodeStateByTimestamp = stepWork.getNodeStateByTimestamp(nodeStateId);
String studentResponse = "";
//get the response
Object object = nodeStateByTimestamp.get("response");
if(object instanceof JSONArray) {
//the response is an array so we will obtain the first element
studentResponse = ((JSONArray) object).getString(0);
} else if(object instanceof String) {
//the response is a string
studentResponse = (String) object;
}
// get CRaterItemId from the StepWork and post to CRater server.
String cRaterItemId = stepWork.getCRaterItemId();
String cRaterResponseXML = CRaterHttpClient.getCRaterScoringResponse(cRaterScoringUrl, cRaterClientId, cRaterItemId, cRaterResponseId, studentResponse);
if(cRaterResponseXML != null) {
JSONObject cRaterResponseJSONObj = new JSONObject();
JSONObject studentNodeStateResponse = stepWork.getNodeStateByTimestamp(nodeStateId);
cRaterResponseJSONObj =
Annotation.createCRaterNodeStateAnnotation(
nodeStateId,
CRaterHttpClient.getScore(cRaterResponseXML),
studentNodeStateResponse,
cRaterResponseXML);
// append the cRaterResponse to the existing annotation for this stepwork.
annotation.appendNodeStateAnnotation(cRaterResponseJSONObj);
annotation.saveOrUpdate();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
// CRater annotation for this stepWork is null, so make a request to CRater to score the item.
try {
// make a request to CRater and insert new row in annotation.
StepWork stepWork = StepWork.getByStepWorkId(stepWorkId);
JSONObject nodeStateByTimestamp = stepWork.getNodeStateByTimestamp(nodeStateId);
String studentResponse = "";
//get the response
Object object = nodeStateByTimestamp.get("response");
if(object instanceof JSONArray) {
//the response is an array so we will obtain the first element
studentResponse = ((JSONArray) object).getString(0);
} else if(object instanceof String) {
//the response is a string
studentResponse = (String) object;
}
// get CRaterItemId from the StepWork and post to CRater server.
String cRaterItemId = stepWork.getCRaterItemId();
String cRaterResponseXML = CRaterHttpClient.getCRaterScoringResponse(cRaterScoringUrl, cRaterClientId, cRaterItemId, cRaterResponseId, studentResponse);
if (cRaterResponseXML != null) {
if(cRaterResponseXML.contains("<error code=")) {
//there was an error so we will not create Annotation or CRaterRequest objects
} else {
// create a new cRater annotation object based on CRater response
Calendar now = Calendar.getInstance();
Timestamp postTime = new Timestamp(now.getTimeInMillis());
Node node = stepWork.getNode();
String nodeId = node.getNodeId();
String type = annotationType;
Long workgroupId = stepWork.getUserInfo().getWorkgroupId();
String toWorkgroup = workgroupId.toString();
String fromWorkgroup = "-1"; // default for auto-scored items.
int score = CRaterHttpClient.getScore(cRaterResponseXML);
JSONObject studentResponseNodeState = stepWork.getNodeStateByTimestamp(nodeStateId);
String cRaterResponse = cRaterResponseXML;
JSONObject cRaterNodeStateAnnotation =
Annotation.createCRaterNodeStateAnnotation(nodeStateId, score, studentResponseNodeState, cRaterResponse);
JSONArray nodeStateAnnotationArray = new JSONArray();
nodeStateAnnotationArray.put(cRaterNodeStateAnnotation);
JSONObject dataJSONObj = new JSONObject();
try {
dataJSONObj.put("runId", runId);
dataJSONObj.put("nodeId", nodeId);
dataJSONObj.put("toWorkgroup", toWorkgroup);
dataJSONObj.put("fromWorkgroup", fromWorkgroup);
dataJSONObj.put("stepWorkId", stepWorkId);
dataJSONObj.put("type", type);
dataJSONObj.put("value", nodeStateAnnotationArray);
} catch (JSONException e) {
e.printStackTrace();
}
annotation = new Annotation(stepWork, null, new Long(runId), postTime, type, dataJSONObj.toString());
annotation.saveOrUpdate();
// update CRaterRequest table and mark this request as completed.
CRaterRequest cRaterRequest = CRaterRequest.getByStepWorkIdNodeStateId(stepWork,nodeStateId);
if(cRaterRequest != null) {
Calendar cRaterRequestCompletedTime = Calendar.getInstance();
cRaterRequest.setTimeCompleted(new Timestamp(cRaterRequestCompletedTime.getTimeInMillis()));
cRaterRequest.setcRaterResponse(cRaterResponse);
cRaterRequest.saveOrUpdate();
}
}
} else {
// there was an error connecting to the CRater servlet
// do nothing so this method will return null
// increment fail count
CRaterRequest cRaterRequest = CRaterRequest.getByStepWorkIdNodeStateId(stepWork, nodeStateId);
if(cRaterRequest != null) {
cRaterRequest.setFailCount(cRaterRequest.getFailCount()+1);
cRaterRequest.saveOrUpdate();
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return annotation;
}
/**
* Handles POST requests for annotations using JSON data storage
* @param request
* @param response
* @throws IOException
*/
private void doPostJSON(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//obtain the parameters
String runId = request.getParameter("runId");
String nodeId = request.getParameter("nodeId");
String toWorkgroup = request.getParameter("toWorkgroup");
String fromWorkgroup = request.getParameter("fromWorkgroup");
String type = request.getParameter("annotationType");
String value = request.getParameter("value");
String stepWorkId = request.getParameter("stepWorkId");
String action = request.getParameter("action");
String periodId = request.getParameter("periodId");
Calendar now = Calendar.getInstance();
Timestamp postTime = new Timestamp(now.getTimeInMillis());
StepWork stepWork = (StepWork) StepWork.getById(new Long(stepWorkId), StepWork.class);
UserInfo userInfo = UserInfo.getOrCreateByWorkgroupId(new Long(fromWorkgroup));
JSONObject annotationEntryJSONObj = new JSONObject();
try {
annotationEntryJSONObj.put("runId", runId);
annotationEntryJSONObj.put("nodeId", nodeId);
annotationEntryJSONObj.put("toWorkgroup", toWorkgroup);
annotationEntryJSONObj.put("fromWorkgroup", fromWorkgroup);
annotationEntryJSONObj.put("stepWorkId", stepWorkId);
annotationEntryJSONObj.put("type", type);
annotationEntryJSONObj.put("value", value);
} catch (JSONException e) {
e.printStackTrace();
}
Annotation annotation = Annotation.getByUserInfoAndStepWork(userInfo, stepWork, type);
if(annotation == null) {
//the annotation was not found so we will create it
annotation = new Annotation(type);
annotation.setUserInfo(userInfo);
annotation.setStepWork(stepWork);
}
//update the post time
annotation.setPostTime(postTime);
//update the data
annotation.setData(annotationEntryJSONObj.toString());
if(runId != null) {
//set the run id
annotation.setRunId(Long.parseLong(runId));
}
//propagate the row/object to the table
annotation.saveOrUpdate();
//check if this is a peer review annotation
if(action != null && action.equals("peerReviewAnnotate")) {
//set the annotation into the peerreviewwork table
PeerReviewWork.setPeerReviewAnnotation(new Long(runId), new Long(periodId), stepWork.getNode(), stepWork, userInfo, annotation);
}
response.getWriter().print(postTime.getTime());
}
}
| false | true | public void doGetJSON(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String requestedType = request.getParameter("type");
String fromWorkgroupIdStr = request.getParameter("fromWorkgroup");
String fromWorkgroupIdsStr = request.getParameter("fromWorkgroups");
String toWorkgroupIdStr = request.getParameter("toWorkgroup");
String runId = request.getParameter("runId");
String stepWorkIdStr = request.getParameter("stepWorkId");
String isStudentStr = request.getParameter("isStudent");
String annotationType = request.getParameter("annotationType");
String nodeStateIdStr = request.getParameter("nodeStateId");
String cRaterVerificationUrl = (String) request.getAttribute("cRaterVerificationUrl");
String cRaterScoringUrl = (String) request.getAttribute("cRaterScoringUrl");
String cRaterClientId = (String) request.getAttribute("cRaterClientId");
//this is only used when students retrieve flags
Vector<JSONObject> flaggedAnnotationsList = new Vector<JSONObject>();
//used to hold classmate workgroup ids to period ids
HashMap<Long, Long> classmateWorkgroupIdToPeriodIdMap = new HashMap<Long, Long>();
Long periodId = null;
Long longRunId = null;
if(runId != null) {
longRunId = Long.parseLong(runId);
}
Long stepWorkId = null;
if(stepWorkIdStr != null) {
stepWorkId = Long.parseLong(stepWorkIdStr);
}
boolean isStudent = false;
if(isStudentStr != null) {
isStudent = Boolean.parseBoolean(isStudentStr);
}
Long nodeStateId = null;
if(nodeStateIdStr != null) {
nodeStateId = Long.parseLong(nodeStateIdStr);
}
/*
* retrieval of periods is only required when students request flagged work
* because we only want students to see flagged work from their own period
*/
if(requestedType.equals("flag") && isStudent) {
try {
//get the signed in student's user info and period id
String myUserInfoString = (String) request.getAttribute("myUserInfo");
JSONObject myUserInfo = new JSONObject(myUserInfoString);
periodId = myUserInfo.getLong("periodId");
//get the classmate user infos
String classmateUserInfosString = (String) request.getAttribute("classmateUserInfos");
JSONArray classmateUserInfos = new JSONArray(classmateUserInfosString);
//loop through all the classmate user infos
for(int x=0; x<classmateUserInfos.length(); x++) {
//get a classmate user info
JSONObject classmateUserInfo = classmateUserInfos.getJSONObject(x);
//get the workgroup id and period id of the classmate
long classmateWorkgroupId = classmateUserInfo.getLong("workgroupId");
long classmatePeriodId = classmateUserInfo.getLong("periodId");
//add the classmate workgroup id to period id entry into the map
classmateWorkgroupIdToPeriodIdMap.put(classmateWorkgroupId, classmatePeriodId);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// if requestedType is null, return all annotations
List<? extends Annotation> annotationList = null;
Annotation annotation = null;
if (requestedType == null ||
(requestedType.equals("annotation") && !"cRater".equals(annotationType))) {
if(fromWorkgroupIdStr != null && stepWorkId != null) {
//user is requesting an annotation they wrote themselves for a specific stepWork
UserInfo fromWorkgroup = UserInfo.getByWorkgroupId(new Long(fromWorkgroupIdStr));
StepWork stepWork = (StepWork) StepWork.getById(stepWorkId, StepWork.class);
annotation = Annotation.getByUserInfoAndStepWork(fromWorkgroup, stepWork, null);
} else if(fromWorkgroupIdsStr != null && toWorkgroupIdStr != null) {
/*
* user is requesting all annotations to toWorkgroup and from any fromWorkgroup
* in the list of fromWorkgroups
*/
UserInfo toWorkgroup = UserInfo.getOrCreateByWorkgroupId(new Long(toWorkgroupIdStr));
//split the fromWorkgroups
String[] split = fromWorkgroupIdsStr.split(",");
//create a String List out of the fromWorkgroups
List<String> fromWorkgroupIds = Arrays.asList(split);
//get the UserInfo objects for the fromWorkgroups
List<UserInfo> fromWorkgroups = UserInfo.getByWorkgroupIds(fromWorkgroupIds);
//get all the annotations that match
annotationList = Annotation.getByFromWorkgroupsAndToWorkgroup(fromWorkgroups, toWorkgroup, Annotation.class);
} else if (fromWorkgroupIdStr != null || toWorkgroupIdStr != null) {
UserInfo fromWorkgroup = null;
UserInfo toWorkgroup = null;
if (fromWorkgroupIdStr != null) {
fromWorkgroup = UserInfo.getByWorkgroupId(new Long(fromWorkgroupIdStr));
}
if (toWorkgroupIdStr != null) {
toWorkgroup = UserInfo.getByWorkgroupId(new Long(toWorkgroupIdStr));
}
annotationList = Annotation.getByFromWorkgroupAndToWorkgroup(fromWorkgroup, toWorkgroup, Annotation.class);
} else if(runId != null) {
//get all the annotations for the run id
annotationList = (List<Annotation>) Annotation.getByRunId(longRunId, Annotation.class);
} else {
annotationList = (List<Annotation>) Annotation.getList(Annotation.class);
}
} else if (requestedType.equals("flag")) {
/*
* get the flags based on the paremeters that were passed in the request.
* this will return the flag annotations ordered from oldest to newest
*/
annotationList = Annotation.getByParamMap(request.getParameterMap());
}
// handle request for cRater annotation
if ("annotation".equals(requestedType) && "cRater".equals(annotationType)) {
annotation = getCRaterAnnotation(nodeStateId, runId, stepWorkId,
annotationType, cRaterScoringUrl, cRaterClientId);
}
JSONObject annotationsJSONObj = null;
if(annotationList != null) {
//a list of annotations will be returned
annotationsJSONObj = new JSONObject(); // all annotations
/*
* loop through all the annotations, the annotations are ordered
* from oldest to newest
*/
for (Annotation annotationObj : annotationList) {
try {
//get an annotation
JSONObject dataJSONObj = new JSONObject(annotationObj.getData());
//add the postTime
dataJSONObj.put("postTime", annotationObj.getPostTime().getTime());
/*
* if this is a student making the request we will add the stepWork data
* to each of the flags so they can see the work that was flagged
*/
if(requestedType.equals("flag") && isStudent) {
//get the stepWorkId of the work that was flagged
String flagStepWorkId = dataJSONObj.getString("stepWorkId");
//get the StepWork object
StepWork flagStepWork = StepWork.getByStepWorkId(new Long(flagStepWorkId));
//get the user info of the work that was flagged
UserInfo flaggedWorkUserInfo = flagStepWork.getUserInfo();
//get the workgroup id of the work that was flagged
Long flaggedWorkgroupId = flaggedWorkUserInfo.getWorkgroupId();
//get the period id of the work that was flagged
Long flaggedPeriodId = classmateWorkgroupIdToPeriodIdMap.get(flaggedWorkgroupId);
//check that the period of the flagged work is the same period that the signed in user is in
if(periodId != null && flaggedPeriodId != null && periodId.equals(flaggedPeriodId)) {
//get the data
JSONObject flagStepWorkData = new JSONObject(flagStepWork.getData());
//check if the flag value is set to "flagged" as opposed to "unflagged"
if(dataJSONObj.has("value") && dataJSONObj.getString("value").equals("flagged")) {
//add the data to the flag JSON object
dataJSONObj.put("data", flagStepWorkData);
//put the flag object into our list
flaggedAnnotationsList.add(dataJSONObj);
} else {
//remove the flag from the list because it was unflagged
/*
* loop through all the flagged annotations we have already obtained
* to remove the annotation that was unflagged
*/
Iterator<JSONObject> flaggedAnnotationsIterator = flaggedAnnotationsList.iterator();
while(flaggedAnnotationsIterator.hasNext()) {
//get an annotation
JSONObject nextFlaggedAnnotation = flaggedAnnotationsIterator.next();
//check if the annotation fields match
if(nextFlaggedAnnotation.has("toWorkgroup") && dataJSONObj.has("toWorkgroup") && nextFlaggedAnnotation.getString("toWorkgroup").equals(dataJSONObj.getString("toWorkgroup")) &&
nextFlaggedAnnotation.has("fromWorkgroup") && dataJSONObj.has("fromWorkgroup") && nextFlaggedAnnotation.getString("fromWorkgroup").equals(dataJSONObj.getString("fromWorkgroup")) &&
nextFlaggedAnnotation.has("nodeId") && dataJSONObj.has("nodeId") && nextFlaggedAnnotation.getString("nodeId").equals(dataJSONObj.getString("nodeId")) &&
nextFlaggedAnnotation.has("stepWorkId") && dataJSONObj.has("stepWorkId") && nextFlaggedAnnotation.getString("stepWorkId").equals(dataJSONObj.getString("stepWorkId")) &&
nextFlaggedAnnotation.has("runId") && dataJSONObj.has("runId") && nextFlaggedAnnotation.getString("runId").equals(dataJSONObj.getString("runId"))) {
flaggedAnnotationsIterator.remove();
}
}
}
}
} else {
//add the annotation to the JSON obj we will return
annotationsJSONObj.append("annotationsArray", dataJSONObj);
}
} catch (JSONException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error retrieving annotations");
e.printStackTrace();
}
}
/*
* the student is requesting the flags, we will now insert the json flag annotation
* objects into the annotationsJSONObj that will be returned as a response to the
* user
*/
if(requestedType.equals("flag") && isStudent) {
//get all the stepwork ids that were flagged
//loop through all the flag annotations
for(JSONObject flagAnnotationDataJSONObj : flaggedAnnotationsList) {
try {
//get the run id, node id, and student id
String flaggedRunId = flagAnnotationDataJSONObj.getString("runId");
String flaggedNodeId = flagAnnotationDataJSONObj.getString("nodeId");
String flaggedToWorkgroup = flagAnnotationDataJSONObj.getString("toWorkgroup");
//get the Node and UserInfo objects
Node node = Node.getByNodeIdAndRunId(flaggedNodeId, flaggedRunId);
UserInfo studentWorkgroup = UserInfo.getByWorkgroupId(new Long(flaggedToWorkgroup));
/*
* get the step works the student did for the node. the list will be
* ordered from newest to oldest
*/
List<StepWork> stepWorks = StepWork.getByUserInfoAndNode(studentWorkgroup, node);
JSONObject latestStepWorkDataJSONObj = null;
//loop through all the step works the student did
for(int x=0; x<stepWorks.size(); x++) {
//get a step work
StepWork stepWork = stepWorks.get(x);
//get the json data from the step work
String stepWorkData = stepWork.getData();
//remember the newest step work data
latestStepWorkDataJSONObj = new JSONObject(stepWorkData);
//get the node states
JSONArray nodeStates = latestStepWorkDataJSONObj.getJSONArray("nodeStates");
//check if the node states is empty
if(nodeStates.length() > 0) {
/*
* node states is not empty so we have found the newest
* step work that contains actual work
*/
break;
}
}
//check if we found any step work data
if(latestStepWorkDataJSONObj != null) {
//put the data into the flag annotation object
flagAnnotationDataJSONObj.put("data", latestStepWorkDataJSONObj);
//put the flag object into the annotations array
annotationsJSONObj.append("annotationsArray", flagAnnotationDataJSONObj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
} else if(annotation != null) {
try {
//only one annotation will be returned
annotationsJSONObj = new JSONObject(annotation.getData());
} catch (JSONException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error retrieving annotations");
e.printStackTrace();
}
}
if(annotationsJSONObj != null) {
response.getWriter().write(annotationsJSONObj.toString());
} else {
// there was an error retrieving the annotation
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"error retrieving annotations");
}
}
| public void doGetJSON(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String requestedType = request.getParameter("type");
String fromWorkgroupIdStr = request.getParameter("fromWorkgroup");
String fromWorkgroupIdsStr = request.getParameter("fromWorkgroups");
String toWorkgroupIdStr = request.getParameter("toWorkgroup");
String runId = request.getParameter("runId");
String stepWorkIdStr = request.getParameter("stepWorkId");
String isStudentStr = request.getParameter("isStudent");
String annotationType = request.getParameter("annotationType");
String nodeStateIdStr = request.getParameter("nodeStateId");
String cRaterVerificationUrl = (String) request.getAttribute("cRaterVerificationUrl");
String cRaterScoringUrl = (String) request.getAttribute("cRaterScoringUrl");
String cRaterClientId = (String) request.getAttribute("cRaterClientId");
//this is only used when students retrieve flags
Vector<JSONObject> flaggedAnnotationsList = new Vector<JSONObject>();
//used to hold classmate workgroup ids to period ids
HashMap<Long, Long> classmateWorkgroupIdToPeriodIdMap = new HashMap<Long, Long>();
Long periodId = null;
Long longRunId = null;
if(runId != null) {
longRunId = Long.parseLong(runId);
}
Long stepWorkId = null;
if(stepWorkIdStr != null) {
stepWorkId = Long.parseLong(stepWorkIdStr);
}
boolean isStudent = false;
if(isStudentStr != null) {
isStudent = Boolean.parseBoolean(isStudentStr);
}
Long nodeStateId = null;
if(nodeStateIdStr != null) {
nodeStateId = Long.parseLong(nodeStateIdStr);
}
/*
* retrieval of periods is only required when students request flagged work
* because we only want students to see flagged work from their own period
*/
if((requestedType.equals("flag") || requestedType.equals("inappropriateFlag")) && isStudent) {
try {
//get the signed in student's user info and period id
String myUserInfoString = (String) request.getAttribute("myUserInfo");
JSONObject myUserInfo = new JSONObject(myUserInfoString);
periodId = myUserInfo.getLong("periodId");
//get the classmate user infos
String classmateUserInfosString = (String) request.getAttribute("classmateUserInfos");
JSONArray classmateUserInfos = new JSONArray(classmateUserInfosString);
//loop through all the classmate user infos
for(int x=0; x<classmateUserInfos.length(); x++) {
//get a classmate user info
JSONObject classmateUserInfo = classmateUserInfos.getJSONObject(x);
//get the workgroup id and period id of the classmate
long classmateWorkgroupId = classmateUserInfo.getLong("workgroupId");
long classmatePeriodId = classmateUserInfo.getLong("periodId");
//add the classmate workgroup id to period id entry into the map
classmateWorkgroupIdToPeriodIdMap.put(classmateWorkgroupId, classmatePeriodId);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// if requestedType is null, return all annotations
List<? extends Annotation> annotationList = null;
Annotation annotation = null;
if (requestedType == null ||
(requestedType.equals("annotation") && !"cRater".equals(annotationType))) {
if(fromWorkgroupIdStr != null && stepWorkId != null) {
//user is requesting an annotation they wrote themselves for a specific stepWork
UserInfo fromWorkgroup = UserInfo.getByWorkgroupId(new Long(fromWorkgroupIdStr));
StepWork stepWork = (StepWork) StepWork.getById(stepWorkId, StepWork.class);
annotation = Annotation.getByUserInfoAndStepWork(fromWorkgroup, stepWork, null);
} else if(fromWorkgroupIdsStr != null && toWorkgroupIdStr != null) {
/*
* user is requesting all annotations to toWorkgroup and from any fromWorkgroup
* in the list of fromWorkgroups
*/
UserInfo toWorkgroup = UserInfo.getOrCreateByWorkgroupId(new Long(toWorkgroupIdStr));
//split the fromWorkgroups
String[] split = fromWorkgroupIdsStr.split(",");
//create a String List out of the fromWorkgroups
List<String> fromWorkgroupIds = Arrays.asList(split);
//get the UserInfo objects for the fromWorkgroups
List<UserInfo> fromWorkgroups = UserInfo.getByWorkgroupIds(fromWorkgroupIds);
//get all the annotations that match
annotationList = Annotation.getByFromWorkgroupsAndToWorkgroup(fromWorkgroups, toWorkgroup, Annotation.class);
} else if (fromWorkgroupIdStr != null || toWorkgroupIdStr != null) {
UserInfo fromWorkgroup = null;
UserInfo toWorkgroup = null;
if (fromWorkgroupIdStr != null) {
fromWorkgroup = UserInfo.getByWorkgroupId(new Long(fromWorkgroupIdStr));
}
if (toWorkgroupIdStr != null) {
toWorkgroup = UserInfo.getByWorkgroupId(new Long(toWorkgroupIdStr));
}
annotationList = Annotation.getByFromWorkgroupAndToWorkgroup(fromWorkgroup, toWorkgroup, Annotation.class);
} else if(runId != null) {
//get all the annotations for the run id
annotationList = (List<Annotation>) Annotation.getByRunId(longRunId, Annotation.class);
} else {
annotationList = (List<Annotation>) Annotation.getList(Annotation.class);
}
} else if (requestedType.equals("flag") || requestedType.equals("inappropriateFlag")) {
/*
* get the flags based on the paremeters that were passed in the request.
* this will return the flag annotations ordered from oldest to newest
*/
annotationList = Annotation.getByParamMap(request.getParameterMap());
}
// handle request for cRater annotation
if ("annotation".equals(requestedType) && "cRater".equals(annotationType)) {
annotation = getCRaterAnnotation(nodeStateId, runId, stepWorkId,
annotationType, cRaterScoringUrl, cRaterClientId);
}
JSONObject annotationsJSONObj = null;
if(annotationList != null) {
//a list of annotations will be returned
annotationsJSONObj = new JSONObject(); // all annotations
/*
* loop through all the annotations, the annotations are ordered
* from oldest to newest
*/
for (Annotation annotationObj : annotationList) {
try {
//get an annotation
JSONObject dataJSONObj = new JSONObject(annotationObj.getData());
//add the postTime
dataJSONObj.put("postTime", annotationObj.getPostTime().getTime());
/*
* if this is a student making the request we will add the stepWork data
* to each of the flags so they can see the work that was flagged
*/
if(requestedType.equals("flag") && isStudent) {
//get the stepWorkId of the work that was flagged
String flagStepWorkId = dataJSONObj.getString("stepWorkId");
//get the StepWork object
StepWork flagStepWork = StepWork.getByStepWorkId(new Long(flagStepWorkId));
//get the user info of the work that was flagged
UserInfo flaggedWorkUserInfo = flagStepWork.getUserInfo();
//get the workgroup id of the work that was flagged
Long flaggedWorkgroupId = flaggedWorkUserInfo.getWorkgroupId();
//get the period id of the work that was flagged
Long flaggedPeriodId = classmateWorkgroupIdToPeriodIdMap.get(flaggedWorkgroupId);
//check that the period of the flagged work is the same period that the signed in user is in
if(periodId != null && flaggedPeriodId != null && periodId.equals(flaggedPeriodId)) {
//get the data
JSONObject flagStepWorkData = new JSONObject(flagStepWork.getData());
//check if the flag value is set to "flagged" as opposed to "unflagged"
if(dataJSONObj.has("value") && dataJSONObj.getString("value").equals("flagged")) {
//add the data to the flag JSON object
dataJSONObj.put("data", flagStepWorkData);
//put the flag object into our list
flaggedAnnotationsList.add(dataJSONObj);
} else {
//remove the flag from the list because it was unflagged
/*
* loop through all the flagged annotations we have already obtained
* to remove the annotation that was unflagged
*/
Iterator<JSONObject> flaggedAnnotationsIterator = flaggedAnnotationsList.iterator();
while(flaggedAnnotationsIterator.hasNext()) {
//get an annotation
JSONObject nextFlaggedAnnotation = flaggedAnnotationsIterator.next();
//check if the annotation fields match
if(nextFlaggedAnnotation.has("toWorkgroup") && dataJSONObj.has("toWorkgroup") && nextFlaggedAnnotation.getString("toWorkgroup").equals(dataJSONObj.getString("toWorkgroup")) &&
nextFlaggedAnnotation.has("fromWorkgroup") && dataJSONObj.has("fromWorkgroup") && nextFlaggedAnnotation.getString("fromWorkgroup").equals(dataJSONObj.getString("fromWorkgroup")) &&
nextFlaggedAnnotation.has("nodeId") && dataJSONObj.has("nodeId") && nextFlaggedAnnotation.getString("nodeId").equals(dataJSONObj.getString("nodeId")) &&
nextFlaggedAnnotation.has("stepWorkId") && dataJSONObj.has("stepWorkId") && nextFlaggedAnnotation.getString("stepWorkId").equals(dataJSONObj.getString("stepWorkId")) &&
nextFlaggedAnnotation.has("runId") && dataJSONObj.has("runId") && nextFlaggedAnnotation.getString("runId").equals(dataJSONObj.getString("runId"))) {
flaggedAnnotationsIterator.remove();
}
}
}
}
} else {
//add the annotation to the JSON obj we will return
annotationsJSONObj.append("annotationsArray", dataJSONObj);
}
} catch (JSONException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error retrieving annotations");
e.printStackTrace();
}
}
/*
* the student is requesting the flags, we will now insert the json flag annotation
* objects into the annotationsJSONObj that will be returned as a response to the
* user
*/
if((requestedType.equals("flag") || requestedType.equals("inappropriateFlag")) && isStudent) {
//get all the stepwork ids that were flagged
//loop through all the flag annotations
for(JSONObject flagAnnotationDataJSONObj : flaggedAnnotationsList) {
try {
//get the run id, node id, and student id
String flaggedRunId = flagAnnotationDataJSONObj.getString("runId");
String flaggedNodeId = flagAnnotationDataJSONObj.getString("nodeId");
String flaggedToWorkgroup = flagAnnotationDataJSONObj.getString("toWorkgroup");
//get the Node and UserInfo objects
Node node = Node.getByNodeIdAndRunId(flaggedNodeId, flaggedRunId);
UserInfo studentWorkgroup = UserInfo.getByWorkgroupId(new Long(flaggedToWorkgroup));
/*
* get the step works the student did for the node. the list will be
* ordered from newest to oldest
*/
List<StepWork> stepWorks = StepWork.getByUserInfoAndNode(studentWorkgroup, node);
JSONObject latestStepWorkDataJSONObj = null;
//loop through all the step works the student did
for(int x=0; x<stepWorks.size(); x++) {
//get a step work
StepWork stepWork = stepWorks.get(x);
//get the json data from the step work
String stepWorkData = stepWork.getData();
//remember the newest step work data
latestStepWorkDataJSONObj = new JSONObject(stepWorkData);
//get the node states
JSONArray nodeStates = latestStepWorkDataJSONObj.getJSONArray("nodeStates");
//check if the node states is empty
if(nodeStates.length() > 0) {
/*
* node states is not empty so we have found the newest
* step work that contains actual work
*/
break;
}
}
//check if we found any step work data
if(latestStepWorkDataJSONObj != null) {
//put the data into the flag annotation object
flagAnnotationDataJSONObj.put("data", latestStepWorkDataJSONObj);
//put the flag object into the annotations array
annotationsJSONObj.append("annotationsArray", flagAnnotationDataJSONObj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
} else if(annotation != null) {
try {
//only one annotation will be returned
annotationsJSONObj = new JSONObject(annotation.getData());
} catch (JSONException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error retrieving annotations");
e.printStackTrace();
}
}
if(annotationsJSONObj != null) {
response.getWriter().write(annotationsJSONObj.toString());
} else {
// there was an error retrieving the annotation
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"error retrieving annotations");
}
}
|
diff --git a/src/balle/world/BasicWorld.java b/src/balle/world/BasicWorld.java
index 855df61..07292ba 100644
--- a/src/balle/world/BasicWorld.java
+++ b/src/balle/world/BasicWorld.java
@@ -1,136 +1,136 @@
package balle.world;
public class BasicWorld extends AbstractWorld {
private Snapshot prev = null;
public BasicWorld(boolean balleIsBlue) {
super(balleIsBlue);
}
@Override
public synchronized Snapshot getSnapshot() {
return prev;
}
private Coord subtractOrNull(Coord a, Coord b) {
if ((a == null) && (b == null))
return null;
else
return a.sub(b);
}
/**
* NOTE: DO ROBOTS ALWAYS MOVE FORWARD !? NO, treat angle of velocity
* different from angle the robot is facing.
*
*/
@Override
public void update(double yPosX, double yPosY, double yRad, double bPosX,
double bPosY, double bRad, double ballPosX, double ballPosY,
long timestamp) {
Robot ours = null;
Robot them = null;
FieldObject ball = null;
// Coordinates
Coord ourPosition, theirsPosition;
// Orientations
double ourOrientation, theirsOrientation;
// Adjust based on our color.
if (isBlue()) {
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
ourPosition = null;
else
ourPosition = new Coord(bPosX, bPosY);
ourOrientation = bRad;
if ((yPosX == UNKNOWN_VALUE) || (yPosY == UNKNOWN_VALUE))
theirsPosition = null;
else
theirsPosition = new Coord(yPosX, yPosY);
theirsOrientation = yRad;
} else {
if ((yPosX == UNKNOWN_VALUE) || (yPosY == UNKNOWN_VALUE))
ourPosition = null;
else
ourPosition = new Coord(yPosX, yPosY);
ourOrientation = yRad;
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
theirsPosition = null;
else
theirsPosition = new Coord(bPosX, bPosY);
theirsOrientation = bRad;
}
Coord ballPosition;
// Ball position
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
ballPosition = null;
else
ballPosition = new Coord(ballPosX, ballPosY);
Snapshot prev = getSnapshot();
// First case when there is no past snapshot (assume velocities are 0)
if (prev == null) {
if ((theirsPosition != null)
&& (theirsOrientation != UNKNOWN_VALUE))
them = new Robot(theirsPosition, new Velocity(0, 0, 1),
theirsOrientation);
if ((ourPosition != null) && (ourOrientation != UNKNOWN_VALUE))
ours = new Robot(ourPosition, new Velocity(0, 0, 1),
ourOrientation);
if (ballPosition != null)
ball = new FieldObject(ballPosition, new Velocity(0, 0, 1));
} else {
// change in time
long deltaT = timestamp - prev.getTimestamp();
// Special case when we get two inputs with the same timestamp:
if (deltaT == 0) {
// This will just keep the prev world in the memory, not doing
// anything
return;
}
if (ourPosition == null)
ourPosition = estimatedPosition(prev.getBalle(), deltaT);
if (theirsPosition == null)
theirsPosition = estimatedPosition(prev.getOpponent(), deltaT);
if (ballPosition == null)
ballPosition = estimatedPosition(prev.getBall(), deltaT);
// Change in position
Coord oursDPos, themDPos, ballDPos;
- oursDPos = subtractOrNull(ourPosition, prev.getBalle()
- .getPosition());
- themDPos = subtractOrNull(theirsPosition, prev.getOpponent()
- .getPosition());
- ballDPos = subtractOrNull(ballPosition, prev.getBall()
- .getPosition());
+ oursDPos = prev.getBalle() != null ? subtractOrNull(ourPosition,
+ prev.getBalle().getPosition()) : null;
+ themDPos = prev.getOpponent() != null ? subtractOrNull(
+ theirsPosition, prev.getOpponent().getPosition()) : null;
+ ballDPos = prev.getBall() == null ? subtractOrNull(ballPosition,
+ prev.getBall().getPosition()) : null;
// velocities
Velocity oursVel, themVel, ballVel;
oursVel = oursDPos != null ? new Velocity(oursDPos, deltaT) : null;
themVel = themDPos != null ? new Velocity(themDPos, deltaT) : null;
ballVel = ballDPos != null ? new Velocity(ballDPos, deltaT) : null;
// put it all together (almost)
them = new Robot(theirsPosition, themVel, theirsOrientation);
ours = new Robot(ourPosition, oursVel, ourOrientation);
ball = new FieldObject(ballPosition, ballVel);
}
synchronized (this) {
// pack into a snapshot
this.prev = new Snapshot(them, ours, ball, timestamp);
}
}
}
| true | true | public void update(double yPosX, double yPosY, double yRad, double bPosX,
double bPosY, double bRad, double ballPosX, double ballPosY,
long timestamp) {
Robot ours = null;
Robot them = null;
FieldObject ball = null;
// Coordinates
Coord ourPosition, theirsPosition;
// Orientations
double ourOrientation, theirsOrientation;
// Adjust based on our color.
if (isBlue()) {
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
ourPosition = null;
else
ourPosition = new Coord(bPosX, bPosY);
ourOrientation = bRad;
if ((yPosX == UNKNOWN_VALUE) || (yPosY == UNKNOWN_VALUE))
theirsPosition = null;
else
theirsPosition = new Coord(yPosX, yPosY);
theirsOrientation = yRad;
} else {
if ((yPosX == UNKNOWN_VALUE) || (yPosY == UNKNOWN_VALUE))
ourPosition = null;
else
ourPosition = new Coord(yPosX, yPosY);
ourOrientation = yRad;
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
theirsPosition = null;
else
theirsPosition = new Coord(bPosX, bPosY);
theirsOrientation = bRad;
}
Coord ballPosition;
// Ball position
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
ballPosition = null;
else
ballPosition = new Coord(ballPosX, ballPosY);
Snapshot prev = getSnapshot();
// First case when there is no past snapshot (assume velocities are 0)
if (prev == null) {
if ((theirsPosition != null)
&& (theirsOrientation != UNKNOWN_VALUE))
them = new Robot(theirsPosition, new Velocity(0, 0, 1),
theirsOrientation);
if ((ourPosition != null) && (ourOrientation != UNKNOWN_VALUE))
ours = new Robot(ourPosition, new Velocity(0, 0, 1),
ourOrientation);
if (ballPosition != null)
ball = new FieldObject(ballPosition, new Velocity(0, 0, 1));
} else {
// change in time
long deltaT = timestamp - prev.getTimestamp();
// Special case when we get two inputs with the same timestamp:
if (deltaT == 0) {
// This will just keep the prev world in the memory, not doing
// anything
return;
}
if (ourPosition == null)
ourPosition = estimatedPosition(prev.getBalle(), deltaT);
if (theirsPosition == null)
theirsPosition = estimatedPosition(prev.getOpponent(), deltaT);
if (ballPosition == null)
ballPosition = estimatedPosition(prev.getBall(), deltaT);
// Change in position
Coord oursDPos, themDPos, ballDPos;
oursDPos = subtractOrNull(ourPosition, prev.getBalle()
.getPosition());
themDPos = subtractOrNull(theirsPosition, prev.getOpponent()
.getPosition());
ballDPos = subtractOrNull(ballPosition, prev.getBall()
.getPosition());
// velocities
Velocity oursVel, themVel, ballVel;
oursVel = oursDPos != null ? new Velocity(oursDPos, deltaT) : null;
themVel = themDPos != null ? new Velocity(themDPos, deltaT) : null;
ballVel = ballDPos != null ? new Velocity(ballDPos, deltaT) : null;
// put it all together (almost)
them = new Robot(theirsPosition, themVel, theirsOrientation);
ours = new Robot(ourPosition, oursVel, ourOrientation);
ball = new FieldObject(ballPosition, ballVel);
}
synchronized (this) {
// pack into a snapshot
this.prev = new Snapshot(them, ours, ball, timestamp);
}
}
| public void update(double yPosX, double yPosY, double yRad, double bPosX,
double bPosY, double bRad, double ballPosX, double ballPosY,
long timestamp) {
Robot ours = null;
Robot them = null;
FieldObject ball = null;
// Coordinates
Coord ourPosition, theirsPosition;
// Orientations
double ourOrientation, theirsOrientation;
// Adjust based on our color.
if (isBlue()) {
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
ourPosition = null;
else
ourPosition = new Coord(bPosX, bPosY);
ourOrientation = bRad;
if ((yPosX == UNKNOWN_VALUE) || (yPosY == UNKNOWN_VALUE))
theirsPosition = null;
else
theirsPosition = new Coord(yPosX, yPosY);
theirsOrientation = yRad;
} else {
if ((yPosX == UNKNOWN_VALUE) || (yPosY == UNKNOWN_VALUE))
ourPosition = null;
else
ourPosition = new Coord(yPosX, yPosY);
ourOrientation = yRad;
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
theirsPosition = null;
else
theirsPosition = new Coord(bPosX, bPosY);
theirsOrientation = bRad;
}
Coord ballPosition;
// Ball position
if ((bPosX == UNKNOWN_VALUE) || (bPosY == UNKNOWN_VALUE))
ballPosition = null;
else
ballPosition = new Coord(ballPosX, ballPosY);
Snapshot prev = getSnapshot();
// First case when there is no past snapshot (assume velocities are 0)
if (prev == null) {
if ((theirsPosition != null)
&& (theirsOrientation != UNKNOWN_VALUE))
them = new Robot(theirsPosition, new Velocity(0, 0, 1),
theirsOrientation);
if ((ourPosition != null) && (ourOrientation != UNKNOWN_VALUE))
ours = new Robot(ourPosition, new Velocity(0, 0, 1),
ourOrientation);
if (ballPosition != null)
ball = new FieldObject(ballPosition, new Velocity(0, 0, 1));
} else {
// change in time
long deltaT = timestamp - prev.getTimestamp();
// Special case when we get two inputs with the same timestamp:
if (deltaT == 0) {
// This will just keep the prev world in the memory, not doing
// anything
return;
}
if (ourPosition == null)
ourPosition = estimatedPosition(prev.getBalle(), deltaT);
if (theirsPosition == null)
theirsPosition = estimatedPosition(prev.getOpponent(), deltaT);
if (ballPosition == null)
ballPosition = estimatedPosition(prev.getBall(), deltaT);
// Change in position
Coord oursDPos, themDPos, ballDPos;
oursDPos = prev.getBalle() != null ? subtractOrNull(ourPosition,
prev.getBalle().getPosition()) : null;
themDPos = prev.getOpponent() != null ? subtractOrNull(
theirsPosition, prev.getOpponent().getPosition()) : null;
ballDPos = prev.getBall() == null ? subtractOrNull(ballPosition,
prev.getBall().getPosition()) : null;
// velocities
Velocity oursVel, themVel, ballVel;
oursVel = oursDPos != null ? new Velocity(oursDPos, deltaT) : null;
themVel = themDPos != null ? new Velocity(themDPos, deltaT) : null;
ballVel = ballDPos != null ? new Velocity(ballDPos, deltaT) : null;
// put it all together (almost)
them = new Robot(theirsPosition, themVel, theirsOrientation);
ours = new Robot(ourPosition, oursVel, ourOrientation);
ball = new FieldObject(ballPosition, ballVel);
}
synchronized (this) {
// pack into a snapshot
this.prev = new Snapshot(them, ours, ball, timestamp);
}
}
|
diff --git a/src/web/org/openmrs/web/dwr/DWREncounterService.java b/src/web/org/openmrs/web/dwr/DWREncounterService.java
index 3d8c1e3c..c34eaff8 100644
--- a/src/web/org/openmrs/web/dwr/DWREncounterService.java
+++ b/src/web/org/openmrs/web/dwr/DWREncounterService.java
@@ -1,141 +1,148 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.dwr;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Encounter;
import org.openmrs.Location;
import org.openmrs.api.APIException;
import org.openmrs.api.EncounterService;
import org.openmrs.api.LocationService;
import org.openmrs.api.context.Context;
public class DWREncounterService {
private static final Log log = LogFactory.getLog(DWREncounterService.class);
public Vector findEncounters(String phrase, boolean includeVoided) throws APIException {
// List to return
// Object type gives ability to return error strings
Vector<Object> objectList = new Vector<Object>();
try {
EncounterService es = Context.getEncounterService();
List<Encounter> encs = new Vector<Encounter>();
if (phrase == null) {
objectList.add("Search phrase cannot be null");
return objectList;
}
if (phrase.matches("\\d+")) {
// user searched on a number. Insert concept with corresponding encounterId
Encounter e = es.getEncounter(Integer.valueOf(phrase));
if (e != null) {
if (!e.isVoided() || includeVoided == true)
encs.add(e);
}
}
if (phrase == null || phrase.equals("")) {
//TODO get all concepts for testing purposes?
} else {
- encs.addAll(es.getEncountersByPatient(phrase));
+ List<Encounter> encounters = es.getEncountersByPatient(phrase);
+ encs.addAll(encounters);
+ if (!encs.isEmpty() && !includeVoided) {
+ for (Encounter encounter : encounters) {
+ if (encounter.isVoided())
+ encs.remove(encounter);
+ }
+ }
}
if (encs.size() == 0) {
objectList.add("No matches found for <b>" + phrase + "</b>");
} else {
objectList = new Vector<Object>(encs.size());
for (Encounter e : encs) {
objectList.add(new EncounterListItem(e));
}
}
}
catch (Exception e) {
log.error("Error while searching for encounters", e);
objectList.add("Error while attempting to find encounter - " + e.getMessage());
}
return objectList;
}
public EncounterListItem getEncounter(Integer encounterId) {
EncounterService es = Context.getEncounterService();
Encounter e = es.getEncounter(encounterId);
return e == null ? null : new EncounterListItem(e);
}
@SuppressWarnings("unchecked")
public Vector findLocations(String searchValue) {
Vector locationList = new Vector();
try {
LocationService ls = Context.getLocationService();
List<Location> locations = ls.getLocations(searchValue);
locationList = new Vector(locations.size());
for (Location loc : locations) {
locationList.add(new LocationListItem(loc));
}
}
catch (Exception e) {
log.error(e);
locationList.add("Error while attempting to find locations - " + e.getMessage());
}
if (locationList.size() == 0) {
locationList.add("No locations found. Please search again.");
}
return locationList;
}
@SuppressWarnings("unchecked")
public Vector getLocations() {
Vector locationList = new Vector();
try {
LocationService ls = Context.getLocationService();
List<Location> locations = ls.getAllLocations();
locationList = new Vector(locations.size());
for (Location loc : locations) {
locationList.add(new LocationListItem(loc));
}
}
catch (Exception e) {
log.error("Error while attempting to get locations", e);
locationList.add("Error while attempting to get locations - " + e.getMessage());
}
return locationList;
}
public LocationListItem getLocation(Integer locationId) {
LocationService ls = Context.getLocationService();
Location l = ls.getLocation(locationId);
return l == null ? null : new LocationListItem(l);
}
}
| true | true | public Vector findEncounters(String phrase, boolean includeVoided) throws APIException {
// List to return
// Object type gives ability to return error strings
Vector<Object> objectList = new Vector<Object>();
try {
EncounterService es = Context.getEncounterService();
List<Encounter> encs = new Vector<Encounter>();
if (phrase == null) {
objectList.add("Search phrase cannot be null");
return objectList;
}
if (phrase.matches("\\d+")) {
// user searched on a number. Insert concept with corresponding encounterId
Encounter e = es.getEncounter(Integer.valueOf(phrase));
if (e != null) {
if (!e.isVoided() || includeVoided == true)
encs.add(e);
}
}
if (phrase == null || phrase.equals("")) {
//TODO get all concepts for testing purposes?
} else {
encs.addAll(es.getEncountersByPatient(phrase));
}
if (encs.size() == 0) {
objectList.add("No matches found for <b>" + phrase + "</b>");
} else {
objectList = new Vector<Object>(encs.size());
for (Encounter e : encs) {
objectList.add(new EncounterListItem(e));
}
}
}
catch (Exception e) {
log.error("Error while searching for encounters", e);
objectList.add("Error while attempting to find encounter - " + e.getMessage());
}
return objectList;
}
| public Vector findEncounters(String phrase, boolean includeVoided) throws APIException {
// List to return
// Object type gives ability to return error strings
Vector<Object> objectList = new Vector<Object>();
try {
EncounterService es = Context.getEncounterService();
List<Encounter> encs = new Vector<Encounter>();
if (phrase == null) {
objectList.add("Search phrase cannot be null");
return objectList;
}
if (phrase.matches("\\d+")) {
// user searched on a number. Insert concept with corresponding encounterId
Encounter e = es.getEncounter(Integer.valueOf(phrase));
if (e != null) {
if (!e.isVoided() || includeVoided == true)
encs.add(e);
}
}
if (phrase == null || phrase.equals("")) {
//TODO get all concepts for testing purposes?
} else {
List<Encounter> encounters = es.getEncountersByPatient(phrase);
encs.addAll(encounters);
if (!encs.isEmpty() && !includeVoided) {
for (Encounter encounter : encounters) {
if (encounter.isVoided())
encs.remove(encounter);
}
}
}
if (encs.size() == 0) {
objectList.add("No matches found for <b>" + phrase + "</b>");
} else {
objectList = new Vector<Object>(encs.size());
for (Encounter e : encs) {
objectList.add(new EncounterListItem(e));
}
}
}
catch (Exception e) {
log.error("Error while searching for encounters", e);
objectList.add("Error while attempting to find encounter - " + e.getMessage());
}
return objectList;
}
|
diff --git a/Rhythmus/src/com/kuna/rhythmus/BMSKeyData.java b/Rhythmus/src/com/kuna/rhythmus/BMSKeyData.java
index 61ee251..0250fc8 100644
--- a/Rhythmus/src/com/kuna/rhythmus/BMSKeyData.java
+++ b/Rhythmus/src/com/kuna/rhythmus/BMSKeyData.java
@@ -1,24 +1,19 @@
package com.kuna.rhythmus;
public class BMSKeyData implements Comparable<BMSKeyData> {
double beat;
int key;
double value;
double time;
int attr;
@Override
public int compareTo(BMSKeyData o) {
if (this.beat < o.beat)
return -1;
else if (this.beat > o.beat)
return 1;
- else {
- // if same? then BPM should be last argument
- if (o.key == 3 || o.key == 8)
- return 1;
- else
- return -1;
- }
+ else
+ return 0;
}
}
| true | true | public int compareTo(BMSKeyData o) {
if (this.beat < o.beat)
return -1;
else if (this.beat > o.beat)
return 1;
else {
// if same? then BPM should be last argument
if (o.key == 3 || o.key == 8)
return 1;
else
return -1;
}
}
| public int compareTo(BMSKeyData o) {
if (this.beat < o.beat)
return -1;
else if (this.beat > o.beat)
return 1;
else
return 0;
}
|
diff --git a/src/net/sradonia/bukkit/minecartmania/teleport/MinecartActionListener.java b/src/net/sradonia/bukkit/minecartmania/teleport/MinecartActionListener.java
index 0abf62b..a53263e 100644
--- a/src/net/sradonia/bukkit/minecartmania/teleport/MinecartActionListener.java
+++ b/src/net/sradonia/bukkit/minecartmania/teleport/MinecartActionListener.java
@@ -1,91 +1,93 @@
package net.sradonia.bukkit.minecartmania.teleport;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.util.Vector;
import com.afforess.minecartmaniacore.MinecartManiaMinecart;
import com.afforess.minecartmaniacore.event.MinecartActionEvent;
import com.afforess.minecartmaniacore.event.MinecartManiaListener;
import com.afforess.minecartmaniacore.utils.MinecartUtils;
public class MinecartActionListener extends MinecartManiaListener {
private final TeleporterList teleporters;
public MinecartActionListener(TeleporterList teleporters) {
this.teleporters = teleporters;
}
@Override
public void onMinecartActionEvent(MinecartActionEvent event) {
- if (!event.isActionTaken()) {
- Block blockAhead = event.getMinecart().getBlockTypeAhead();
+ if (event.isActionTaken())
+ return;
+ Block blockAhead = event.getMinecart().getBlockTypeAhead();
+ if (blockAhead != null) {
Material type = blockAhead.getType();
if (type.equals(Material.SIGN_POST) || type.equals(Material.WALL_SIGN)) {
// Minecart is going to crash into a sign...
Location signLocation = blockAhead.getLocation();
Teleporter teleporter = teleporters.search(signLocation);
if (teleporter != null) {
// ... which is a teleporter!
event.setActionTaken(true);
MinecartManiaMinecart minecart = event.getMinecart();
Location targetLocation = teleporter.getOther(signLocation);
if (targetLocation == null) {
// but we're missing the second waypoint...
if (minecart.hasPlayerPassenger()) {
minecart.getPlayerPassenger().sendMessage("You just crashed into an unconnected teleporter sign ;-)");
}
} else {
// search for minecart tracks around the target waypoint
Location trackLocation = findTrackAround(targetLocation);
if (trackLocation == null) {
if (minecart.hasPlayerPassenger()) {
minecart.getPlayerPassenger().sendMessage("Couldn't find tracks at target sign.");
}
} else {
// teleport minecart...
minecart.minecart.teleportTo(trackLocation);
// ...and set it's moving direction
double speed = minecart.minecart.getVelocity().length();
if (targetLocation.getX() > trackLocation.getX())
minecart.minecart.setVelocity(new Vector(-speed, 0, 0));
else if (targetLocation.getX() < trackLocation.getX())
minecart.minecart.setVelocity(new Vector(speed, 0, 0));
else if (targetLocation.getZ() > trackLocation.getZ())
minecart.minecart.setVelocity(new Vector(0, 0, -speed));
else if (targetLocation.getZ() < trackLocation.getZ())
minecart.minecart.setVelocity(new Vector(0, 0, speed));
}
}
}
}
}
}
public static Location findTrackAround(Location center) {
Block centerBlock = center.getBlock();
Block block;
block = centerBlock.getRelative(BlockFace.NORTH);
if (MinecartUtils.isMinecartTrack(block))
return block.getLocation();
block = centerBlock.getRelative(BlockFace.SOUTH);
if (MinecartUtils.isMinecartTrack(block))
return block.getLocation();
block = centerBlock.getRelative(BlockFace.EAST);
if (MinecartUtils.isMinecartTrack(block))
return block.getLocation();
block = centerBlock.getRelative(BlockFace.WEST);
if (MinecartUtils.isMinecartTrack(block))
return block.getLocation();
return null;
}
}
| true | true | public void onMinecartActionEvent(MinecartActionEvent event) {
if (!event.isActionTaken()) {
Block blockAhead = event.getMinecart().getBlockTypeAhead();
Material type = blockAhead.getType();
if (type.equals(Material.SIGN_POST) || type.equals(Material.WALL_SIGN)) {
// Minecart is going to crash into a sign...
Location signLocation = blockAhead.getLocation();
Teleporter teleporter = teleporters.search(signLocation);
if (teleporter != null) {
// ... which is a teleporter!
event.setActionTaken(true);
MinecartManiaMinecart minecart = event.getMinecart();
Location targetLocation = teleporter.getOther(signLocation);
if (targetLocation == null) {
// but we're missing the second waypoint...
if (minecart.hasPlayerPassenger()) {
minecart.getPlayerPassenger().sendMessage("You just crashed into an unconnected teleporter sign ;-)");
}
} else {
// search for minecart tracks around the target waypoint
Location trackLocation = findTrackAround(targetLocation);
if (trackLocation == null) {
if (minecart.hasPlayerPassenger()) {
minecart.getPlayerPassenger().sendMessage("Couldn't find tracks at target sign.");
}
} else {
// teleport minecart...
minecart.minecart.teleportTo(trackLocation);
// ...and set it's moving direction
double speed = minecart.minecart.getVelocity().length();
if (targetLocation.getX() > trackLocation.getX())
minecart.minecart.setVelocity(new Vector(-speed, 0, 0));
else if (targetLocation.getX() < trackLocation.getX())
minecart.minecart.setVelocity(new Vector(speed, 0, 0));
else if (targetLocation.getZ() > trackLocation.getZ())
minecart.minecart.setVelocity(new Vector(0, 0, -speed));
else if (targetLocation.getZ() < trackLocation.getZ())
minecart.minecart.setVelocity(new Vector(0, 0, speed));
}
}
}
}
}
}
| public void onMinecartActionEvent(MinecartActionEvent event) {
if (event.isActionTaken())
return;
Block blockAhead = event.getMinecart().getBlockTypeAhead();
if (blockAhead != null) {
Material type = blockAhead.getType();
if (type.equals(Material.SIGN_POST) || type.equals(Material.WALL_SIGN)) {
// Minecart is going to crash into a sign...
Location signLocation = blockAhead.getLocation();
Teleporter teleporter = teleporters.search(signLocation);
if (teleporter != null) {
// ... which is a teleporter!
event.setActionTaken(true);
MinecartManiaMinecart minecart = event.getMinecart();
Location targetLocation = teleporter.getOther(signLocation);
if (targetLocation == null) {
// but we're missing the second waypoint...
if (minecart.hasPlayerPassenger()) {
minecart.getPlayerPassenger().sendMessage("You just crashed into an unconnected teleporter sign ;-)");
}
} else {
// search for minecart tracks around the target waypoint
Location trackLocation = findTrackAround(targetLocation);
if (trackLocation == null) {
if (minecart.hasPlayerPassenger()) {
minecart.getPlayerPassenger().sendMessage("Couldn't find tracks at target sign.");
}
} else {
// teleport minecart...
minecart.minecart.teleportTo(trackLocation);
// ...and set it's moving direction
double speed = minecart.minecart.getVelocity().length();
if (targetLocation.getX() > trackLocation.getX())
minecart.minecart.setVelocity(new Vector(-speed, 0, 0));
else if (targetLocation.getX() < trackLocation.getX())
minecart.minecart.setVelocity(new Vector(speed, 0, 0));
else if (targetLocation.getZ() > trackLocation.getZ())
minecart.minecart.setVelocity(new Vector(0, 0, -speed));
else if (targetLocation.getZ() < trackLocation.getZ())
minecart.minecart.setVelocity(new Vector(0, 0, speed));
}
}
}
}
}
}
|
diff --git a/cipango-diameter/src/main/java/org/cipango/diameter/util/PrettyPrinter.java b/cipango-diameter/src/main/java/org/cipango/diameter/util/PrettyPrinter.java
index fd1548f..0a2f5c8 100644
--- a/cipango-diameter/src/main/java/org/cipango/diameter/util/PrettyPrinter.java
+++ b/cipango-diameter/src/main/java/org/cipango/diameter/util/PrettyPrinter.java
@@ -1,81 +1,82 @@
package org.cipango.diameter.util;
import org.cipango.diameter.AVP;
import org.cipango.diameter.AVPList;
import org.cipango.diameter.api.DiameterServletAnswer;
import org.cipango.diameter.base.Accounting;
import org.cipango.diameter.ims.Zh;
import org.cipango.diameter.node.DiameterMessage;
import org.cipango.diameter.node.DiameterRequest;
import org.cipango.diameter.node.Node;
import org.eclipse.jetty.util.StringUtil;
public class PrettyPrinter implements DiameterVisitor
{
private int _index;
private StringBuilder _buffer;
public void visit(DiameterMessage message)
{
_index = 0;
_buffer = new StringBuilder();
_buffer.append("[appId=").append(message.getApplicationId());
_buffer.append(",e2eId=").append(message.getEndToEndId());
_buffer.append(",hopId=").append(message.getHopByHopId()).append("] ");
_buffer.append(message.getCommand());
if (message instanceof DiameterServletAnswer)
_buffer.append(" / ").append(((DiameterServletAnswer) message).getResultCode());
_buffer.append(StringUtil.__LINE_SEPARATOR);
}
public void visit(AVP<?> avp)
{
if (!(avp.getValue() instanceof AVPList))
{
for (int i = 0; i < _index; i++)
_buffer.append(" ");
_buffer.append(avp.getType()).append(" = ");
if (avp.getValue() instanceof byte[])
{
byte[] tab = (byte[]) avp.getValue();
- if (tab[0] == '<' && tab[1] == '?' && tab[2] == 'x' && tab[3] == 'm' && tab[4] == 'l')
+ if (tab != null && tab.length > 5
+ && tab[0] == '<' && tab[1] == '?' && tab[2] == 'x' && tab[3] == 'm' && tab[4] == 'l')
_buffer.append(new String(tab));
else
_buffer.append(tab);
}
else
_buffer.append(avp.getValue());
_buffer.append(StringUtil.__LINE_SEPARATOR);
}
}
public void visitEnter(AVP<AVPList> avp)
{
_buffer.append(avp.getType() + " = ");
_buffer.append(StringUtil.__LINE_SEPARATOR);
_index++;
}
public void visitLeave(AVP<AVPList> avp)
{
_index--;
}
public String toString()
{
return _buffer.toString();
}
public static void main(String[] args)
{
DiameterMessage message = new DiameterRequest(new Node(), Accounting.ACR, Accounting.ACCOUNTING_ORDINAL, "foo");
message.getAVPs().add(Zh.ZH_APPLICATION_ID.getAVP());
PrettyPrinter pp = new PrettyPrinter();
message.accept(pp);
System.out.println(pp);
}
}
| true | true | public void visit(AVP<?> avp)
{
if (!(avp.getValue() instanceof AVPList))
{
for (int i = 0; i < _index; i++)
_buffer.append(" ");
_buffer.append(avp.getType()).append(" = ");
if (avp.getValue() instanceof byte[])
{
byte[] tab = (byte[]) avp.getValue();
if (tab[0] == '<' && tab[1] == '?' && tab[2] == 'x' && tab[3] == 'm' && tab[4] == 'l')
_buffer.append(new String(tab));
else
_buffer.append(tab);
}
else
_buffer.append(avp.getValue());
_buffer.append(StringUtil.__LINE_SEPARATOR);
}
}
| public void visit(AVP<?> avp)
{
if (!(avp.getValue() instanceof AVPList))
{
for (int i = 0; i < _index; i++)
_buffer.append(" ");
_buffer.append(avp.getType()).append(" = ");
if (avp.getValue() instanceof byte[])
{
byte[] tab = (byte[]) avp.getValue();
if (tab != null && tab.length > 5
&& tab[0] == '<' && tab[1] == '?' && tab[2] == 'x' && tab[3] == 'm' && tab[4] == 'l')
_buffer.append(new String(tab));
else
_buffer.append(tab);
}
else
_buffer.append(avp.getValue());
_buffer.append(StringUtil.__LINE_SEPARATOR);
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/util/TasksUiExtensionReader.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/util/TasksUiExtensionReader.java
index b203ea3ea..632dd4292 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/util/TasksUiExtensionReader.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/util/TasksUiExtensionReader.java
@@ -1,593 +1,595 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies 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:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.tasks.core.externalization.TaskListExternalizer;
import org.eclipse.mylyn.internal.tasks.ui.IDynamicSubMenuContributor;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.views.AbstractTaskListPresentation;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskListView;
import org.eclipse.mylyn.tasks.core.AbstractDuplicateDetector;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.AbstractTaskListMigrator;
import org.eclipse.mylyn.tasks.core.RepositoryTemplate;
import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylyn.tasks.ui.AbstractTaskRepositoryLinkProvider;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* @author Mik Kersten
* @author Shawn Minto
* @author Rob Elves
*/
public class TasksUiExtensionReader {
private static class ConnectorDescriptor {
IConfigurationElement element;
IConfigurationElement migratorElement;
AbstractRepositoryConnector repositoryConnector;
AbstractTaskListMigrator migrator;
private final String id;
public ConnectorDescriptor(IConfigurationElement element) {
this.element = element;
this.id = element.getAttribute(ATTR_ID);
}
public String getId() {
return id;
}
public String getConnectorKind() {
return (repositoryConnector != null) ? repositoryConnector.getConnectorKind() : null;
}
public IStatus createConnector() {
Assert.isTrue(repositoryConnector == null);
try {
Object connectorCore = element.createExecutableExtension(ATTR_CLASS);
if (connectorCore instanceof AbstractRepositoryConnector) {
repositoryConnector = (AbstractRepositoryConnector) connectorCore;
return Status.OK_STATUS;
} else {
return new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not load connector core " //$NON-NLS-1$
+ connectorCore.getClass().getCanonicalName());
}
} catch (Throwable e) {
return new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not load connector core", e); //$NON-NLS-1$
}
}
public IStatus createMigrator() {
Assert.isTrue(migrator == null);
try {
Object migratorObject = migratorElement.createExecutableExtension(ATTR_CLASS);
if (migratorObject instanceof AbstractTaskListMigrator) {
migrator = (AbstractTaskListMigrator) migratorObject;
return Status.OK_STATUS;
} else {
return new Status(
IStatus.ERROR,
TasksUiPlugin.ID_PLUGIN,
"Could not load task list migrator migrator: " + migratorObject.getClass().getCanonicalName() //$NON-NLS-1$
+ " must implement " + AbstractTaskListMigrator.class.getCanonicalName()); //$NON-NLS-1$
}
} catch (Throwable e) {
return new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load task list migrator extension", e); //$NON-NLS-1$
}
}
public String getPluginId() {
return element.getContributor().getName();
}
}
public static final String EXTENSION_REPOSITORIES = "org.eclipse.mylyn.tasks.ui.repositories"; //$NON-NLS-1$
public static final String EXTENSION_REPOSITORY_LINKS_PROVIDERS = "org.eclipse.mylyn.tasks.ui.projectLinkProviders"; //$NON-NLS-1$
public static final String EXTENSION_TEMPLATES = "org.eclipse.mylyn.tasks.core.templates"; //$NON-NLS-1$
public static final String EXTENSION_TMPL_REPOSITORY = "repository"; //$NON-NLS-1$
public static final String ELMNT_TMPL_LABEL = "label"; //$NON-NLS-1$
public static final String ELMNT_TMPL_URLREPOSITORY = "urlRepository"; //$NON-NLS-1$
public static final String ELMNT_TMPL_REPOSITORYKIND = "repositoryKind"; //$NON-NLS-1$
public static final String ELMNT_TMPL_CHARACTERENCODING = "characterEncoding"; //$NON-NLS-1$
public static final String ELMNT_TMPL_ANONYMOUS = "anonymous"; //$NON-NLS-1$
public static final String ELMNT_TMPL_VERSION = "version"; //$NON-NLS-1$
public static final String ELMNT_TMPL_URLNEWTASK = "urlNewTask"; //$NON-NLS-1$
public static final String ELMNT_TMPL_URLTASK = "urlTask"; //$NON-NLS-1$
public static final String ELMNT_TMPL_URLTASKQUERY = "urlTaskQuery"; //$NON-NLS-1$
public static final String ELMNT_TMPL_NEWACCOUNTURL = "urlNewAccount"; //$NON-NLS-1$
public static final String ELMNT_TMPL_ADDAUTO = "addAutomatically"; //$NON-NLS-1$
public static final String ELMNT_REPOSITORY_CONNECTOR = "connectorCore"; //$NON-NLS-1$
public static final String ELMNT_REPOSITORY_LINK_PROVIDER = "linkProvider"; //$NON-NLS-1$
public static final String ELMNT_REPOSITORY_UI = "connectorUi"; //$NON-NLS-1$
public static final String ELMNT_MIGRATOR = "taskListMigrator"; //$NON-NLS-1$
public static final String ATTR_BRANDING_ICON = "brandingIcon"; //$NON-NLS-1$
public static final String ATTR_OVERLAY_ICON = "overlayIcon"; //$NON-NLS-1$
public static final String ELMNT_TYPE = "type"; //$NON-NLS-1$
public static final String ELMNT_QUERY_PAGE = "queryPage"; //$NON-NLS-1$
public static final String ELMNT_SETTINGS_PAGE = "settingsPage"; //$NON-NLS-1$
public static final String EXTENSION_TASK_CONTRIBUTOR = "org.eclipse.mylyn.tasks.ui.actions"; //$NON-NLS-1$
public static final String ATTR_ACTION_CONTRIBUTOR_CLASS = "taskHandlerClass"; //$NON-NLS-1$
public static final String DYNAMIC_POPUP_ELEMENT = "dynamicPopupMenu"; //$NON-NLS-1$
public static final String ATTR_CLASS = "class"; //$NON-NLS-1$
public static final String ATTR_MENU_PATH = "menuPath"; //$NON-NLS-1$
public static final String EXTENSION_EDITORS = "org.eclipse.mylyn.tasks.ui.editors"; //$NON-NLS-1$
public static final String ELMNT_TASK_EDITOR_PAGE_FACTORY = "pageFactory"; //$NON-NLS-1$
public static final String EXTENSION_DUPLICATE_DETECTORS = "org.eclipse.mylyn.tasks.ui.duplicateDetectors"; //$NON-NLS-1$
public static final String ELMNT_DUPLICATE_DETECTOR = "detector"; //$NON-NLS-1$
public static final String ATTR_NAME = "name"; //$NON-NLS-1$
public static final String ATTR_KIND = "kind"; //$NON-NLS-1$
private static final String EXTENSION_PRESENTATIONS = "org.eclipse.mylyn.tasks.ui.presentations"; //$NON-NLS-1$
public static final String ELMNT_PRESENTATION = "presentation"; //$NON-NLS-1$
public static final String ATTR_ICON = "icon"; //$NON-NLS-1$
public static final String ATTR_PRIMARY = "primary"; //$NON-NLS-1$
public static final String ATTR_ID = "id"; //$NON-NLS-1$
private static boolean coreExtensionsRead = false;
/**
* Plug-in ids of connector extensions that failed to load.
*/
private static Set<String> disabledContributors = new HashSet<String>();
public static void initStartupExtensions(TaskListExternalizer taskListExternalizer) {
if (!coreExtensionsRead) {
IExtensionRegistry registry = Platform.getExtensionRegistry();
// NOTE: has to be read first, consider improving
initConnectorCores(taskListExternalizer, registry);
IExtensionPoint templatesExtensionPoint = registry.getExtensionPoint(EXTENSION_TEMPLATES);
IExtension[] templateExtensions = templatesExtensionPoint.getExtensions();
for (IExtension templateExtension : templateExtensions) {
IConfigurationElement[] elements = templateExtension.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (!isDisabled(element)) {
if (element.getName().equals(EXTENSION_TMPL_REPOSITORY)) {
readRepositoryTemplate(element);
}
}
}
}
IExtensionPoint presentationsExtensionPoint = registry.getExtensionPoint(EXTENSION_PRESENTATIONS);
IExtension[] presentations = presentationsExtensionPoint.getExtensions();
for (IExtension presentation : presentations) {
IConfigurationElement[] elements = presentation.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (!isDisabled(element)) {
readPresentation(element);
}
}
}
// NOTE: causes ..mylyn.context.ui to load
IExtensionPoint editorsExtensionPoint = registry.getExtensionPoint(EXTENSION_EDITORS);
IExtension[] editors = editorsExtensionPoint.getExtensions();
for (IExtension editor : editors) {
IConfigurationElement[] elements = editor.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (!isDisabled(element)) {
if (element.getName().equals(ELMNT_TASK_EDITOR_PAGE_FACTORY)) {
readTaskEditorPageFactory(element);
}
}
}
}
coreExtensionsRead = true;
}
}
private static void initConnectorCores(TaskListExternalizer taskListExternalizer, IExtensionRegistry registry) {
List<ConnectorDescriptor> descriptors = new ArrayList<ConnectorDescriptor>();
MultiStatus result = new MultiStatus(TasksUiPlugin.ID_PLUGIN, 0, "Repository connectors failed to load.", null); //$NON-NLS-1$
// read core and migrator extensions to check for id conflicts
Map<String, List<ConnectorDescriptor>> descriptorById = new LinkedHashMap<String, List<ConnectorDescriptor>>();
IExtensionPoint repositoriesExtensionPoint = registry.getExtensionPoint(EXTENSION_REPOSITORIES);
IExtension[] repositoryExtensions = repositoriesExtensionPoint.getExtensions();
for (IExtension repositoryExtension : repositoryExtensions) {
IConfigurationElement[] elements = repositoryExtension.getConfigurationElements();
ConnectorDescriptor descriptor = null;
IConfigurationElement migratorElement = null;
for (IConfigurationElement element : elements) {
if (element.getName().equals(ELMNT_REPOSITORY_CONNECTOR)) {
descriptor = new ConnectorDescriptor(element);
} else if (element.getName().equals(ELMNT_MIGRATOR)) {
migratorElement = element;
}
}
if (descriptor != null) {
descriptor.migratorElement = migratorElement;
descriptors.add(descriptor);
if (descriptor.getId() != null) {
add(descriptorById, descriptor.getId(), descriptor);
}
}
}
checkForConflicts(descriptors, result, descriptorById);
// create instances to check for connector kind conflicts
Map<String, List<ConnectorDescriptor>> descriptorByConnectorKind = new LinkedHashMap<String, List<ConnectorDescriptor>>();
for (ConnectorDescriptor descriptor : descriptors) {
IStatus status = descriptor.createConnector();
- if (status.isOK()) {
+ if (status.isOK() && descriptor.repositoryConnector != null) {
add(descriptorByConnectorKind, descriptor.getConnectorKind(), descriptor);
} else {
result.add(status);
}
}
checkForConflicts(descriptors, result, descriptorByConnectorKind);
// register connectors
List<AbstractTaskListMigrator> migrators = new ArrayList<AbstractTaskListMigrator>();
for (ConnectorDescriptor descriptor : descriptors) {
- TasksUiPlugin.getRepositoryManager().addRepositoryConnector(descriptor.repositoryConnector);
- if (descriptor.migratorElement != null) {
- IStatus status = descriptor.createMigrator();
- if (status.isOK()) {
- migrators.add(descriptor.migrator);
- } else {
- result.add(status);
+ if (descriptor.repositoryConnector != null) {
+ TasksUiPlugin.getRepositoryManager().addRepositoryConnector(descriptor.repositoryConnector);
+ if (descriptor.migratorElement != null) {
+ IStatus status = descriptor.createMigrator();
+ if (status.isOK() && descriptor.migrator != null) {
+ migrators.add(descriptor.migrator);
+ } else {
+ result.add(status);
+ }
}
}
}
if (!result.isOK()) {
StatusHandler.log(result);
}
taskListExternalizer.initialize(migrators);
}
private static boolean isDisabled(IConfigurationElement element) {
return disabledContributors.contains(element.getContributor().getName());
}
private static void checkForConflicts(List<ConnectorDescriptor> descriptors, MultiStatus result,
Map<String, List<ConnectorDescriptor>> descriptorById) {
for (Map.Entry<String, List<ConnectorDescriptor>> entry : descriptorById.entrySet()) {
if (entry.getValue().size() > 1) {
MultiStatus status = new MultiStatus(TasksUiPlugin.ID_PLUGIN, 0, NLS.bind(
"Connector ''{0}'' registered by multiple extensions.", entry.getKey()), null); //$NON-NLS-1$
for (ConnectorDescriptor descriptor : entry.getValue()) {
status.add(new Status(
IStatus.ERROR,
TasksUiPlugin.ID_PLUGIN,
NLS.bind(
"All extensions contributed by ''{0}'' have been disabled.", descriptor.getPluginId()), null)); //$NON-NLS-1$
disabledContributors.add(descriptor.getPluginId());
descriptors.remove(descriptor);
}
result.add(status);
}
}
}
private static void add(Map<String, List<ConnectorDescriptor>> descriptorById, String id,
ConnectorDescriptor descriptor) {
List<ConnectorDescriptor> list = descriptorById.get(id);
if (list == null) {
list = new ArrayList<ConnectorDescriptor>();
descriptorById.put(id, list);
}
list.add(descriptor);
}
public static void initWorkbenchUiExtensions() {
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint repositoriesExtensionPoint = registry.getExtensionPoint(EXTENSION_REPOSITORIES);
IExtension[] repositoryExtensions = repositoriesExtensionPoint.getExtensions();
for (IExtension repositoryExtension : repositoryExtensions) {
IConfigurationElement[] elements = repositoryExtension.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (!isDisabled(element)) {
if (element.getName().equals(ELMNT_REPOSITORY_UI)) {
readRepositoryConnectorUi(element);
}
}
}
}
IExtensionPoint linkProvidersExtensionPoint = registry.getExtensionPoint(EXTENSION_REPOSITORY_LINKS_PROVIDERS);
IExtension[] linkProvidersExtensions = linkProvidersExtensionPoint.getExtensions();
for (IExtension linkProvidersExtension : linkProvidersExtensions) {
IConfigurationElement[] elements = linkProvidersExtension.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (!isDisabled(element)) {
if (element.getName().equals(ELMNT_REPOSITORY_LINK_PROVIDER)) {
readLinkProvider(element);
}
}
}
}
IExtensionPoint duplicateDetectorsExtensionPoint = registry.getExtensionPoint(EXTENSION_DUPLICATE_DETECTORS);
IExtension[] dulicateDetectorsExtensions = duplicateDetectorsExtensionPoint.getExtensions();
for (IExtension dulicateDetectorsExtension : dulicateDetectorsExtensions) {
IConfigurationElement[] elements = dulicateDetectorsExtension.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (!isDisabled(element)) {
if (element.getName().equals(ELMNT_DUPLICATE_DETECTOR)) {
readDuplicateDetector(element);
}
}
}
}
IExtensionPoint extensionPoint = registry.getExtensionPoint(EXTENSION_TASK_CONTRIBUTOR);
IExtension[] extensions = extensionPoint.getExtensions();
for (IExtension extension : extensions) {
IConfigurationElement[] elements = extension.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (!isDisabled(element)) {
if (element.getName().equals(DYNAMIC_POPUP_ELEMENT)) {
readDynamicPopupContributor(element);
}
}
}
}
}
private static void readPresentation(IConfigurationElement element) {
try {
String name = element.getAttribute(ATTR_NAME);
String iconPath = element.getAttribute(ATTR_ICON);
ImageDescriptor imageDescriptor = AbstractUIPlugin.imageDescriptorFromPlugin( //
element.getContributor().getName(), iconPath);
AbstractTaskListPresentation presentation = (AbstractTaskListPresentation) element.createExecutableExtension(ATTR_CLASS);
presentation.setPluginId(element.getNamespaceIdentifier());
presentation.setImageDescriptor(imageDescriptor);
presentation.setName(name);
String primary = element.getAttribute(ATTR_PRIMARY);
if (primary != null && primary.equals("true")) { //$NON-NLS-1$
presentation.setPrimary(true);
}
TaskListView.addPresentation(presentation);
} catch (Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load presentation extension", e)); //$NON-NLS-1$
}
}
private static void readDuplicateDetector(IConfigurationElement element) {
try {
Object obj = element.createExecutableExtension(ATTR_CLASS);
if (obj instanceof AbstractDuplicateDetector) {
AbstractDuplicateDetector duplicateDetector = (AbstractDuplicateDetector) obj;
duplicateDetector.setName(element.getAttribute(ATTR_NAME));
duplicateDetector.setConnectorKind(element.getAttribute(ATTR_KIND));
TasksUiPlugin.getDefault().addDuplicateDetector(duplicateDetector);
} else {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load duplicate detector " + obj.getClass().getCanonicalName())); //$NON-NLS-1$
}
} catch (Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not load duplicate detector", e)); //$NON-NLS-1$
}
}
private static void readLinkProvider(IConfigurationElement element) {
try {
Object repositoryLinkProvider = element.createExecutableExtension(ATTR_CLASS);
if (repositoryLinkProvider instanceof AbstractTaskRepositoryLinkProvider) {
TasksUiPlugin.getDefault().addRepositoryLinkProvider(
(AbstractTaskRepositoryLinkProvider) repositoryLinkProvider);
} else {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load repository link provider " //$NON-NLS-1$
+ repositoryLinkProvider.getClass().getCanonicalName()));
}
} catch (Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load repository link provider", e)); //$NON-NLS-1$
}
}
private static void readTaskEditorPageFactory(IConfigurationElement element) {
String id = element.getAttribute(ATTR_ID);
if (id == null) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Editor page factory must specify id")); //$NON-NLS-1$
return;
}
try {
Object item = element.createExecutableExtension(ATTR_CLASS);
if (item instanceof AbstractTaskEditorPageFactory) {
AbstractTaskEditorPageFactory editorPageFactory = (AbstractTaskEditorPageFactory) item;
editorPageFactory.setId(id);
editorPageFactory.setPluginId(element.getNamespaceIdentifier());
TasksUiPlugin.getDefault().addTaskEditorPageFactory(editorPageFactory);
} else {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load editor page factory " + item.getClass().getCanonicalName() + " must implement " //$NON-NLS-1$ //$NON-NLS-2$
+ AbstractTaskEditorPageFactory.class.getCanonicalName()));
}
} catch (Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not load page editor factory", //$NON-NLS-1$
e));
}
}
private static void readRepositoryConnectorUi(IConfigurationElement element) {
try {
Object connectorUiObject = element.createExecutableExtension(ATTR_CLASS);
if (connectorUiObject instanceof AbstractRepositoryConnectorUi) {
AbstractRepositoryConnectorUi connectorUi = (AbstractRepositoryConnectorUi) connectorUiObject;
if (TasksUiPlugin.getConnector(connectorUi.getConnectorKind()) != null) {
TasksUiPlugin.getDefault().addRepositoryConnectorUi(connectorUi);
String iconPath = element.getAttribute(ATTR_BRANDING_ICON);
if (iconPath != null) {
ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(
element.getContributor().getName(), iconPath);
if (descriptor != null) {
TasksUiPlugin.getDefault().addBrandingIcon(connectorUi.getConnectorKind(),
CommonImages.getImage(descriptor));
}
}
String overlayIconPath = element.getAttribute(ATTR_OVERLAY_ICON);
if (overlayIconPath != null) {
ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(
element.getContributor().getName(), overlayIconPath);
if (descriptor != null) {
TasksUiPlugin.getDefault().addOverlayIcon(connectorUi.getConnectorKind(), descriptor);
}
}
} else {
StatusHandler.log(new Status(
IStatus.ERROR,
TasksUiPlugin.ID_PLUGIN,
NLS.bind(
"Ignoring connector ui for kind ''{0}'' without corresponding core contributed by ''{1}''.", connectorUi.getConnectorKind(), element.getContributor().getName()))); //$NON-NLS-1$
}
} else {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not load connector ui " //$NON-NLS-1$
+ connectorUiObject.getClass().getCanonicalName()));
}
} catch (Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Could not load connector ui", e)); //$NON-NLS-1$
}
}
private static void readRepositoryTemplate(IConfigurationElement element) {
boolean anonymous = false;
boolean addAuto = false;
String label = element.getAttribute(ELMNT_TMPL_LABEL);
String serverUrl = element.getAttribute(ELMNT_TMPL_URLREPOSITORY);
String repKind = element.getAttribute(ELMNT_TMPL_REPOSITORYKIND);
String version = element.getAttribute(ELMNT_TMPL_VERSION);
String newTaskUrl = element.getAttribute(ELMNT_TMPL_URLNEWTASK);
String taskPrefix = element.getAttribute(ELMNT_TMPL_URLTASK);
String taskQueryUrl = element.getAttribute(ELMNT_TMPL_URLTASKQUERY);
String newAccountUrl = element.getAttribute(ELMNT_TMPL_NEWACCOUNTURL);
String encoding = element.getAttribute(ELMNT_TMPL_CHARACTERENCODING);
addAuto = Boolean.parseBoolean(element.getAttribute(ELMNT_TMPL_ADDAUTO));
anonymous = Boolean.parseBoolean(element.getAttribute(ELMNT_TMPL_ANONYMOUS));
if (serverUrl != null && label != null && repKind != null
&& TasksUi.getRepositoryManager().getRepositoryConnector(repKind) != null) {
RepositoryTemplate template = new RepositoryTemplate(label, serverUrl, encoding, version, newTaskUrl,
taskPrefix, taskQueryUrl, newAccountUrl, anonymous, addAuto);
TasksUiPlugin.getRepositoryTemplateManager().addTemplate(repKind, template);
for (IConfigurationElement configElement : element.getChildren()) {
String name = configElement.getAttribute("name"); //$NON-NLS-1$
String value = configElement.getAttribute("value"); //$NON-NLS-1$
if (name != null && !name.equals("") && value != null) { //$NON-NLS-1$
template.addAttribute(name, value);
}
}
} else {
// TODO change error message to include hints about the cause of the error
StatusHandler.log(new Status(
IStatus.ERROR,
TasksUiPlugin.ID_PLUGIN,
"Could not load repository template extension contributed by " + element.getNamespaceIdentifier() + " with connectorKind " + repKind)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private static void readDynamicPopupContributor(IConfigurationElement element) {
try {
Object dynamicPopupContributor = element.createExecutableExtension(ATTR_CLASS);
String menuPath = element.getAttribute(ATTR_MENU_PATH);
if (dynamicPopupContributor instanceof IDynamicSubMenuContributor) {
TasksUiPlugin.getDefault().addDynamicPopupContributor(menuPath,
(IDynamicSubMenuContributor) dynamicPopupContributor);
} else {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load dynamic popup menu: " + dynamicPopupContributor.getClass().getCanonicalName() //$NON-NLS-1$
+ " must implement " + IDynamicSubMenuContributor.class.getCanonicalName())); //$NON-NLS-1$
}
} catch (Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load dynamic popup menu extension", e)); //$NON-NLS-1$
}
}
}
| false | true | private static void initConnectorCores(TaskListExternalizer taskListExternalizer, IExtensionRegistry registry) {
List<ConnectorDescriptor> descriptors = new ArrayList<ConnectorDescriptor>();
MultiStatus result = new MultiStatus(TasksUiPlugin.ID_PLUGIN, 0, "Repository connectors failed to load.", null); //$NON-NLS-1$
// read core and migrator extensions to check for id conflicts
Map<String, List<ConnectorDescriptor>> descriptorById = new LinkedHashMap<String, List<ConnectorDescriptor>>();
IExtensionPoint repositoriesExtensionPoint = registry.getExtensionPoint(EXTENSION_REPOSITORIES);
IExtension[] repositoryExtensions = repositoriesExtensionPoint.getExtensions();
for (IExtension repositoryExtension : repositoryExtensions) {
IConfigurationElement[] elements = repositoryExtension.getConfigurationElements();
ConnectorDescriptor descriptor = null;
IConfigurationElement migratorElement = null;
for (IConfigurationElement element : elements) {
if (element.getName().equals(ELMNT_REPOSITORY_CONNECTOR)) {
descriptor = new ConnectorDescriptor(element);
} else if (element.getName().equals(ELMNT_MIGRATOR)) {
migratorElement = element;
}
}
if (descriptor != null) {
descriptor.migratorElement = migratorElement;
descriptors.add(descriptor);
if (descriptor.getId() != null) {
add(descriptorById, descriptor.getId(), descriptor);
}
}
}
checkForConflicts(descriptors, result, descriptorById);
// create instances to check for connector kind conflicts
Map<String, List<ConnectorDescriptor>> descriptorByConnectorKind = new LinkedHashMap<String, List<ConnectorDescriptor>>();
for (ConnectorDescriptor descriptor : descriptors) {
IStatus status = descriptor.createConnector();
if (status.isOK()) {
add(descriptorByConnectorKind, descriptor.getConnectorKind(), descriptor);
} else {
result.add(status);
}
}
checkForConflicts(descriptors, result, descriptorByConnectorKind);
// register connectors
List<AbstractTaskListMigrator> migrators = new ArrayList<AbstractTaskListMigrator>();
for (ConnectorDescriptor descriptor : descriptors) {
TasksUiPlugin.getRepositoryManager().addRepositoryConnector(descriptor.repositoryConnector);
if (descriptor.migratorElement != null) {
IStatus status = descriptor.createMigrator();
if (status.isOK()) {
migrators.add(descriptor.migrator);
} else {
result.add(status);
}
}
}
if (!result.isOK()) {
StatusHandler.log(result);
}
taskListExternalizer.initialize(migrators);
}
| private static void initConnectorCores(TaskListExternalizer taskListExternalizer, IExtensionRegistry registry) {
List<ConnectorDescriptor> descriptors = new ArrayList<ConnectorDescriptor>();
MultiStatus result = new MultiStatus(TasksUiPlugin.ID_PLUGIN, 0, "Repository connectors failed to load.", null); //$NON-NLS-1$
// read core and migrator extensions to check for id conflicts
Map<String, List<ConnectorDescriptor>> descriptorById = new LinkedHashMap<String, List<ConnectorDescriptor>>();
IExtensionPoint repositoriesExtensionPoint = registry.getExtensionPoint(EXTENSION_REPOSITORIES);
IExtension[] repositoryExtensions = repositoriesExtensionPoint.getExtensions();
for (IExtension repositoryExtension : repositoryExtensions) {
IConfigurationElement[] elements = repositoryExtension.getConfigurationElements();
ConnectorDescriptor descriptor = null;
IConfigurationElement migratorElement = null;
for (IConfigurationElement element : elements) {
if (element.getName().equals(ELMNT_REPOSITORY_CONNECTOR)) {
descriptor = new ConnectorDescriptor(element);
} else if (element.getName().equals(ELMNT_MIGRATOR)) {
migratorElement = element;
}
}
if (descriptor != null) {
descriptor.migratorElement = migratorElement;
descriptors.add(descriptor);
if (descriptor.getId() != null) {
add(descriptorById, descriptor.getId(), descriptor);
}
}
}
checkForConflicts(descriptors, result, descriptorById);
// create instances to check for connector kind conflicts
Map<String, List<ConnectorDescriptor>> descriptorByConnectorKind = new LinkedHashMap<String, List<ConnectorDescriptor>>();
for (ConnectorDescriptor descriptor : descriptors) {
IStatus status = descriptor.createConnector();
if (status.isOK() && descriptor.repositoryConnector != null) {
add(descriptorByConnectorKind, descriptor.getConnectorKind(), descriptor);
} else {
result.add(status);
}
}
checkForConflicts(descriptors, result, descriptorByConnectorKind);
// register connectors
List<AbstractTaskListMigrator> migrators = new ArrayList<AbstractTaskListMigrator>();
for (ConnectorDescriptor descriptor : descriptors) {
if (descriptor.repositoryConnector != null) {
TasksUiPlugin.getRepositoryManager().addRepositoryConnector(descriptor.repositoryConnector);
if (descriptor.migratorElement != null) {
IStatus status = descriptor.createMigrator();
if (status.isOK() && descriptor.migrator != null) {
migrators.add(descriptor.migrator);
} else {
result.add(status);
}
}
}
}
if (!result.isOK()) {
StatusHandler.log(result);
}
taskListExternalizer.initialize(migrators);
}
|
diff --git a/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/QueryByExampleWidgetBuilder.java b/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/QueryByExampleWidgetBuilder.java
index 31a4349..ca30eca 100644
--- a/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/QueryByExampleWidgetBuilder.java
+++ b/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/QueryByExampleWidgetBuilder.java
@@ -1,127 +1,127 @@
// Metawidget
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package org.jboss.forge.scaffold.spring.metawidget.widgetbuilder;
import static org.metawidget.inspector.InspectionResultConstants.*;
import static org.metawidget.inspector.spring.SpringInspectionResultConstants.*;
import java.util.Map;
import org.metawidget.statically.javacode.JavaStatement;
import org.metawidget.statically.javacode.StaticJavaMetawidget;
import org.metawidget.statically.javacode.StaticJavaStub;
import org.metawidget.statically.javacode.StaticJavaWidget;
import org.metawidget.util.ClassUtils;
import org.metawidget.util.WidgetBuilderUtils;
import org.metawidget.util.simple.StringUtils;
import org.metawidget.widgetbuilder.iface.WidgetBuilder;
public class QueryByExampleWidgetBuilder
implements WidgetBuilder<StaticJavaWidget, StaticJavaMetawidget>
{
//
// Public methods
//
@Override
public StaticJavaWidget buildWidget(String elementName,
Map<String, String> attributes, StaticJavaMetawidget metawidget)
{
// Drill down
if(ENTITY.equals(elementName))
{
return null;
}
// Suppress
if(TRUE.equals(attributes.get(HIDDEN)))
{
return new StaticJavaStub();
}
String type = WidgetBuilderUtils.getActualClassOrType(attributes);
Class<?> clazz = ClassUtils.niceForName(type);
String name = attributes.get(NAME);
// String
if (String.class.equals(clazz))
{
StaticJavaStub toReturn = new StaticJavaStub();
toReturn.getChildren().add(
- new JavaStatement("String " + name + " = this.search.get" + StringUtils.capitalize(name) + "()"));
+ new JavaStatement("String " + name + " = search.get" + StringUtils.capitalize(name) + "()"));
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null && !\"\".equals(" + name + "))");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.like(root.<String>get(\"" + name + "\"), '%' + " + name
+ " + '%'))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// int Primitive
if(int.class.equals(clazz))
{
StaticJavaStub toReturn = new StaticJavaStub();
toReturn.getChildren().add(
new JavaStatement("int " + name + " = this.search.get" + StringUtils.capitalize(name) + "()"));
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != 0)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\"), " + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// LOOKUP
if (attributes.containsKey(LOOKUP))
{
StaticJavaStub toReturn = new StaticJavaStub();
JavaStatement getValue = new JavaStatement(ClassUtils.getSimpleName(type) + " " + name + " = this.search.get"
+ StringUtils.capitalize(name) + "()");
getValue.putImport(type);
toReturn.getChildren().add(getValue);
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\"), " + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// SPRING_LOOKUP
if (attributes.containsKey(SPRING_LOOKUP))
{
StaticJavaStub toReturn = new StaticJavaStub();
JavaStatement getValue = new JavaStatement(ClassUtils.getSimpleName(type) + " " + name + " = this.search.get"
+ StringUtils.capitalize(name) + "()");
getValue.putImport(type);
toReturn.getChildren().add(getValue);
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null && " + name + ".getId() != null)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\")," + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// Ignore N_TO_MANY relationships for now.
return new StaticJavaStub();
}
}
| true | true | public StaticJavaWidget buildWidget(String elementName,
Map<String, String> attributes, StaticJavaMetawidget metawidget)
{
// Drill down
if(ENTITY.equals(elementName))
{
return null;
}
// Suppress
if(TRUE.equals(attributes.get(HIDDEN)))
{
return new StaticJavaStub();
}
String type = WidgetBuilderUtils.getActualClassOrType(attributes);
Class<?> clazz = ClassUtils.niceForName(type);
String name = attributes.get(NAME);
// String
if (String.class.equals(clazz))
{
StaticJavaStub toReturn = new StaticJavaStub();
toReturn.getChildren().add(
new JavaStatement("String " + name + " = this.search.get" + StringUtils.capitalize(name) + "()"));
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null && !\"\".equals(" + name + "))");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.like(root.<String>get(\"" + name + "\"), '%' + " + name
+ " + '%'))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// int Primitive
if(int.class.equals(clazz))
{
StaticJavaStub toReturn = new StaticJavaStub();
toReturn.getChildren().add(
new JavaStatement("int " + name + " = this.search.get" + StringUtils.capitalize(name) + "()"));
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != 0)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\"), " + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// LOOKUP
if (attributes.containsKey(LOOKUP))
{
StaticJavaStub toReturn = new StaticJavaStub();
JavaStatement getValue = new JavaStatement(ClassUtils.getSimpleName(type) + " " + name + " = this.search.get"
+ StringUtils.capitalize(name) + "()");
getValue.putImport(type);
toReturn.getChildren().add(getValue);
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\"), " + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// SPRING_LOOKUP
if (attributes.containsKey(SPRING_LOOKUP))
{
StaticJavaStub toReturn = new StaticJavaStub();
JavaStatement getValue = new JavaStatement(ClassUtils.getSimpleName(type) + " " + name + " = this.search.get"
+ StringUtils.capitalize(name) + "()");
getValue.putImport(type);
toReturn.getChildren().add(getValue);
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null && " + name + ".getId() != null)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\")," + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// Ignore N_TO_MANY relationships for now.
return new StaticJavaStub();
}
| public StaticJavaWidget buildWidget(String elementName,
Map<String, String> attributes, StaticJavaMetawidget metawidget)
{
// Drill down
if(ENTITY.equals(elementName))
{
return null;
}
// Suppress
if(TRUE.equals(attributes.get(HIDDEN)))
{
return new StaticJavaStub();
}
String type = WidgetBuilderUtils.getActualClassOrType(attributes);
Class<?> clazz = ClassUtils.niceForName(type);
String name = attributes.get(NAME);
// String
if (String.class.equals(clazz))
{
StaticJavaStub toReturn = new StaticJavaStub();
toReturn.getChildren().add(
new JavaStatement("String " + name + " = search.get" + StringUtils.capitalize(name) + "()"));
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null && !\"\".equals(" + name + "))");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.like(root.<String>get(\"" + name + "\"), '%' + " + name
+ " + '%'))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// int Primitive
if(int.class.equals(clazz))
{
StaticJavaStub toReturn = new StaticJavaStub();
toReturn.getChildren().add(
new JavaStatement("int " + name + " = this.search.get" + StringUtils.capitalize(name) + "()"));
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != 0)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\"), " + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// LOOKUP
if (attributes.containsKey(LOOKUP))
{
StaticJavaStub toReturn = new StaticJavaStub();
JavaStatement getValue = new JavaStatement(ClassUtils.getSimpleName(type) + " " + name + " = this.search.get"
+ StringUtils.capitalize(name) + "()");
getValue.putImport(type);
toReturn.getChildren().add(getValue);
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\"), " + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// SPRING_LOOKUP
if (attributes.containsKey(SPRING_LOOKUP))
{
StaticJavaStub toReturn = new StaticJavaStub();
JavaStatement getValue = new JavaStatement(ClassUtils.getSimpleName(type) + " " + name + " = this.search.get"
+ StringUtils.capitalize(name) + "()");
getValue.putImport(type);
toReturn.getChildren().add(getValue);
JavaStatement ifNotEmpty = new JavaStatement("if (" + name + " != null && " + name + ".getId() != null)");
ifNotEmpty.getChildren().add(
new JavaStatement("predicatesList.add(builder.equal(root.get(\"" + name + "\")," + name + "))"));
toReturn.getChildren().add(ifNotEmpty);
return toReturn;
}
// Ignore N_TO_MANY relationships for now.
return new StaticJavaStub();
}
|
diff --git a/src/main/java/de/taimos/maven_redmine_plugin/model/DateDeserializer.java b/src/main/java/de/taimos/maven_redmine_plugin/model/DateDeserializer.java
index eaf4393..f6a500f 100644
--- a/src/main/java/de/taimos/maven_redmine_plugin/model/DateDeserializer.java
+++ b/src/main/java/de/taimos/maven_redmine_plugin/model/DateDeserializer.java
@@ -1,69 +1,72 @@
package de.taimos.maven_redmine_plugin.model;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
/**
* @author thoeger
*
*/
public class DateDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException, JsonProcessingException {
final String text = jp.getText();
return DateDeserializer.parse(text);
}
static Date parse(final String text) throws JsonParseException {
// BEWARE THIS IS UGLY CODE STYLE
Date parsed = null;
try {
// Redmine 2.x 2012-01-06T14:43:04Z
final SimpleDateFormat newDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
parsed = newDF.parse(text);
} catch (final ParseException e) {
- // cannot parse date so we try old format
+ // cannot parse date so we try other format
}
if (parsed == null) {
try {
// Redmine 2.x Date only 2012-01-06
final SimpleDateFormat newDF = new SimpleDateFormat("yyyy-MM-dd");
parsed = newDF.parse(text);
} catch (final ParseException e) {
- // cannot parse date so we try old format
+ // cannot parse date so we try other format
}
}
if (parsed == null) {
try {
// Redmine 1.x 2012/10/09 09:29:19 +0200
final SimpleDateFormat oldDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z");
parsed = oldDF.parse(text);
} catch (final ParseException e) {
- throw new RuntimeException("Cannot parse date");
+ // cannot parse date so we try other format
}
}
if (parsed == null) {
try {
// Redmine 1.x Date only 2012/10/09
final SimpleDateFormat oldDF = new SimpleDateFormat("yyyy/MM/dd");
parsed = oldDF.parse(text);
} catch (final ParseException e) {
- throw new RuntimeException("Cannot parse date");
+ // cannot parse date so we try other format
}
}
+ if (parsed == null) {
+ throw new RuntimeException("Cannot parse date");
+ }
return parsed;
}
}
| false | true | static Date parse(final String text) throws JsonParseException {
// BEWARE THIS IS UGLY CODE STYLE
Date parsed = null;
try {
// Redmine 2.x 2012-01-06T14:43:04Z
final SimpleDateFormat newDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
parsed = newDF.parse(text);
} catch (final ParseException e) {
// cannot parse date so we try old format
}
if (parsed == null) {
try {
// Redmine 2.x Date only 2012-01-06
final SimpleDateFormat newDF = new SimpleDateFormat("yyyy-MM-dd");
parsed = newDF.parse(text);
} catch (final ParseException e) {
// cannot parse date so we try old format
}
}
if (parsed == null) {
try {
// Redmine 1.x 2012/10/09 09:29:19 +0200
final SimpleDateFormat oldDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z");
parsed = oldDF.parse(text);
} catch (final ParseException e) {
throw new RuntimeException("Cannot parse date");
}
}
if (parsed == null) {
try {
// Redmine 1.x Date only 2012/10/09
final SimpleDateFormat oldDF = new SimpleDateFormat("yyyy/MM/dd");
parsed = oldDF.parse(text);
} catch (final ParseException e) {
throw new RuntimeException("Cannot parse date");
}
}
return parsed;
}
| static Date parse(final String text) throws JsonParseException {
// BEWARE THIS IS UGLY CODE STYLE
Date parsed = null;
try {
// Redmine 2.x 2012-01-06T14:43:04Z
final SimpleDateFormat newDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
parsed = newDF.parse(text);
} catch (final ParseException e) {
// cannot parse date so we try other format
}
if (parsed == null) {
try {
// Redmine 2.x Date only 2012-01-06
final SimpleDateFormat newDF = new SimpleDateFormat("yyyy-MM-dd");
parsed = newDF.parse(text);
} catch (final ParseException e) {
// cannot parse date so we try other format
}
}
if (parsed == null) {
try {
// Redmine 1.x 2012/10/09 09:29:19 +0200
final SimpleDateFormat oldDF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z");
parsed = oldDF.parse(text);
} catch (final ParseException e) {
// cannot parse date so we try other format
}
}
if (parsed == null) {
try {
// Redmine 1.x Date only 2012/10/09
final SimpleDateFormat oldDF = new SimpleDateFormat("yyyy/MM/dd");
parsed = oldDF.parse(text);
} catch (final ParseException e) {
// cannot parse date so we try other format
}
}
if (parsed == null) {
throw new RuntimeException("Cannot parse date");
}
return parsed;
}
|
diff --git a/modules/radiotv/src/main/java/dk/statsbiblioteket/doms/radiotv/extractor/transcoder/Util.java b/modules/radiotv/src/main/java/dk/statsbiblioteket/doms/radiotv/extractor/transcoder/Util.java
index 9587308..22f7b26 100644
--- a/modules/radiotv/src/main/java/dk/statsbiblioteket/doms/radiotv/extractor/transcoder/Util.java
+++ b/modules/radiotv/src/main/java/dk/statsbiblioteket/doms/radiotv/extractor/transcoder/Util.java
@@ -1,201 +1,201 @@
/* File: $Id$
* Revision: $Revision$
* Author: $Author$
* Date: $Date$
*
* Copyright 2004-2009 Det Kongelige Bibliotek and Statsbiblioteket, Denmark
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package dk.statsbiblioteket.doms.radiotv.extractor.transcoder;
import dk.statsbiblioteket.doms.radiotv.extractor.Constants;
import org.apache.log4j.Logger;
import javax.servlet.ServletConfig;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
private static Logger log = Logger.getLogger(Util.class);
/**
* Pattern for extracting a uuid of a doms object from url-decoded
* permanent url.
*/
public static final String UUID_STRING = ".*uuid:(.*)";
public static final Pattern UUID_PATTERN = Pattern.compile(UUID_STRING);
private Util(){}
public static String getDemuxFilename(TranscodeRequest request) {
return request.getPid()+"_first.ts";
}
/**
* Gets the uuid from a shard url
* @param shardUrl
* @return
* @throws UnsupportedEncodingException
*/
public static String getUuid(String shardUrl) throws UnsupportedEncodingException {
String urlS = URLDecoder.decode(shardUrl, "UTF-8");
Matcher m = UUID_PATTERN.matcher(urlS);
if (m.matches()) {
return m.group(1);
} else return null;
}
/**
* Converts a shard url to a doms url
* e.g. http://www.statsbiblioteket.dk/doms/shard/uuid:ef8ea1b2-aaa8-412a-a247-af682bb57d25
* to <DOMS_SERVER>/fedora/objects/uuid%3Aef8ea1b2-aaa8-412a-a247-af682bb57d25/datastreams/SHARD_METADATA/conteny
*
* @param pid
* @return
*/
public static URL getDomsUrl(String pid, ServletConfig config) throws ProcessorException {
String urlS = Util.getInitParameter(config, Constants.DOMS_LOCATION) + "/objects/uuid:"+pid+"/datastreams/SHARD_METADATA/content";
try {
return new URL(urlS);
} catch (MalformedURLException e) {
throw new ProcessorException(e);
}
}
public static String getFinalFilename(TranscodeRequest request) {
return request.getPid() + ".mp4";
}
public static File getTempDir(ServletConfig config) {
return new File(getInitParameter(config, Constants.TEMP_DIR_INIT_PARAM));
}
public static File getFinalDir(ServletConfig config) {
return new File(Util.getInitParameter(config, Constants.FINAL_DIR_INIT_PARAM));
}
public static File getDemuxFile(TranscodeRequest request, ServletConfig config) {
return new File(getTempDir(config), getDemuxFilename(request));
}
public static File getIntialFinalFile(TranscodeRequest request, ServletConfig config) {
return new File(getTempDir(config), getFinalFilename(request));
}
public static File getFinalFinalFile(TranscodeRequest request, ServletConfig config) {
return new File(getFinalDir(config), getFinalFilename(request));
}
public static File getFlashFile(TranscodeRequest request, ServletConfig config) {
return new File(getFinalDir(config), request.getPid() + ".flv");
}
public static File getLockFile(TranscodeRequest request, ServletConfig config) {
return new File(getTempDir(config), getLockFileName(request));
}
public static String getLockFileName(TranscodeRequest request) {
return request.getPid() + "." + request.getServiceType() + ".lck";
}
public static File[] getAllLockFiles(ServletConfig config) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".lck");
}
};
return (getTempDir(config)).listFiles(filter);
}
public static void unlockRequest(TranscodeRequest request) {
synchronized (request) {
if (request.getThePool() != null && request.getLockObject() != null) {
try {
log.info("Unlocking request '" + request.getPid() + "' from '" + request.getLockObject() + "'");
request.getThePool().returnObject(request.getLockObject());
request.setLockObject(null);
request.setThePool(null);
} catch (Exception e) {
log.error(e);
}
}
}
}
public static String getStreamId(TranscodeRequest request, ServletConfig config) throws ProcessorException {
File outputFile = OutputFileUtil.getExistingMediaOutputFile(request, config);
String filename = getRelativePath(new File(Util.getInitParameter(config, Constants.FINAL_DIR_INIT_PARAM)), outputFile);
if (filename.endsWith(".mp4")) {
return "mp4:" + filename;
} else if (filename.endsWith(".mp3")) {
return "mp3:" + filename;
} else if (filename.endsWith(".flv")) {
return "flv:" + filename;
} else return null;
}
public static String getRelativePath(File parent, File child) throws ProcessorException {
try {
String parentS = parent.getCanonicalPath();
String childS = child.getCanonicalPath();
if (!childS.startsWith(parentS)) {
throw new ProcessorException(parentS + " is not a parent of " + childS);
}
String result = childS.replaceFirst(parentS, "");
- if (result.startsWith(File.separator)) {
- result.replaceFirst(File.separator, "");
+ while (result.startsWith(File.separator)) {
+ result = result.replaceFirst(File.separator, "");
}
return result;
} catch (IOException e) {
throw new ProcessorException(e);
}
}
public static int getQueuePosition(TranscodeRequest request, ServletConfig config) {
return ProcessorChainThreadPool.getInstance(config).getPosition(request);
}
public static String getInitParameter(ServletConfig config, String paramName) {
if (config.getServletContext() != null && config.getServletContext().getInitParameter(paramName) != null) {
return config.getServletContext().getInitParameter(paramName);
} else {
return config.getInitParameter(paramName);
}
}
public static String getAudioBitrate(ServletConfig config) {
return getInitParameter(config, Constants.AUDIO_BITRATE);
}
public static String getVideoBitrate(ServletConfig config) {
return getInitParameter(config, Constants.VIDEO_BITRATE);
}
public static String getPrimarySnapshotSuffix(ServletConfig config) {
return getInitParameter(config, Constants.SNAPSHOT_PRIMARY_FORMAT);
}
}
| true | true | public static String getRelativePath(File parent, File child) throws ProcessorException {
try {
String parentS = parent.getCanonicalPath();
String childS = child.getCanonicalPath();
if (!childS.startsWith(parentS)) {
throw new ProcessorException(parentS + " is not a parent of " + childS);
}
String result = childS.replaceFirst(parentS, "");
if (result.startsWith(File.separator)) {
result.replaceFirst(File.separator, "");
}
return result;
} catch (IOException e) {
throw new ProcessorException(e);
}
}
| public static String getRelativePath(File parent, File child) throws ProcessorException {
try {
String parentS = parent.getCanonicalPath();
String childS = child.getCanonicalPath();
if (!childS.startsWith(parentS)) {
throw new ProcessorException(parentS + " is not a parent of " + childS);
}
String result = childS.replaceFirst(parentS, "");
while (result.startsWith(File.separator)) {
result = result.replaceFirst(File.separator, "");
}
return result;
} catch (IOException e) {
throw new ProcessorException(e);
}
}
|
diff --git a/src/de/schildbach/pte/AbstractHafasProvider.java b/src/de/schildbach/pte/AbstractHafasProvider.java
index d59f44c..ba1ea4f 100644
--- a/src/de/schildbach/pte/AbstractHafasProvider.java
+++ b/src/de/schildbach/pte/AbstractHafasProvider.java
@@ -1,963 +1,972 @@
/*
* Copyright 2010 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.schildbach.pte;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import de.schildbach.pte.dto.Connection;
import de.schildbach.pte.dto.GetConnectionDetailsResult;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.LocationType;
import de.schildbach.pte.dto.NearbyStationsResult;
import de.schildbach.pte.dto.QueryConnectionsResult;
import de.schildbach.pte.dto.QueryConnectionsResult.Status;
import de.schildbach.pte.dto.Station;
import de.schildbach.pte.util.Color;
import de.schildbach.pte.util.ParserUtils;
import de.schildbach.pte.util.XmlPullUtil;
/**
* @author Andreas Schildbach
*/
public abstract class AbstractHafasProvider implements NetworkProvider
{
private static final String DEFAULT_ENCODING = "ISO-8859-1";
private final String apiUri;
private static final String prod = "hafas";
private final String accessId;
public AbstractHafasProvider(final String apiUri, final String accessId)
{
this.apiUri = apiUri;
this.accessId = accessId;
}
protected String[] splitNameAndPlace(final String name)
{
return new String[] { null, name };
}
private final String wrap(final String request)
{
return "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" //
+ "<ReqC ver=\"1.1\" prod=\"" + prod + "\" lang=\"DE\"" + (accessId != null ? " accessId=\"" + accessId + "\"" : "") + ">" //
+ request //
+ "</ReqC>";
}
private static final Location parseStation(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Station".equals(type))
{
final String name = pp.getAttributeValue(null, "name").trim();
final int id = Integer.parseInt(pp.getAttributeValue(null, "externalStationNr"));
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.STATION, id, y, x, null, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parsePoi(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Poi".equals(type))
{
String name = pp.getAttributeValue(null, "name").trim();
if (name.equals("unknown"))
name = null;
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.POI, 0, y, x, null, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parseAddress(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Address".equals(type))
{
String name = pp.getAttributeValue(null, "name").trim();
if (name.equals("unknown"))
name = null;
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.ADDRESS, 0, y, x, null, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parseReqLoc(final XmlPullParser pp)
{
final String type = pp.getName();
if ("ReqLoc".equals(type))
{
XmlPullUtil.requireAttr(pp, "type", "ADR");
final String name = pp.getAttributeValue(null, "output").trim();
return new Location(LocationType.ADDRESS, 0, null, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
public List<Location> autocompleteStations(final CharSequence constraint) throws IOException
{
final String request = "<LocValReq id=\"req\" maxNr=\"20\"><ReqLoc match=\"" + constraint + "\" type=\"ALLTYPE\"/></LocValReq>";
// System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request), 3);
final List<Location> results = new ArrayList<Location>();
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "LocValRes");
XmlPullUtil.requireAttr(pp, "id", "req");
XmlPullUtil.enter(pp);
while (pp.getEventType() == XmlPullParser.START_TAG)
{
final String tag = pp.getName();
if ("Station".equals(tag))
results.add(parseStation(pp));
else if ("Poi".equals(tag))
results.add(parsePoi(pp));
else if ("Address".equals(tag))
results.add(parseAddress(pp));
else if ("ReqLoc".equals(tag))
/* results.add(parseReqLoc(pp)) */;
else
System.out.println("cannot handle tag: " + tag);
XmlPullUtil.next(pp);
}
XmlPullUtil.exit(pp);
return results;
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep,
final String products, final WalkSpeed walkSpeed) throws IOException
{
if (from.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(from.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(autocompletes, null, null);
from = autocompletes.get(0);
}
if (via != null && via.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(via.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, autocompletes, null);
via = autocompletes.get(0);
}
if (to.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(to.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, null, autocompletes);
to = autocompletes.get(0);
}
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm");
final String request = "<ConReq>" //
+ "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" //
+ (via != null ? "<Via>" + location(via) + "</Via>" : "") //
+ "<Dest>" + location(to) + "</Dest>" //
+ "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" //
+ "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" //
+ "</ConReq>";
return queryConnections(request, from, via, to);
}
public QueryConnectionsResult queryMoreConnections(final String context) throws IOException
{
final String request = "<ConScrReq scr=\"F\" nrCons=\"4\">" //
+ "<ConResCtxt>" + context + "</ConResCtxt>" //
+ "</ConScrReq>";
return queryConnections(request, null, null, null);
}
private QueryConnectionsResult queryConnections(final String request, final Location from, final Location via, final Location to)
throws IOException
{
// System.out.println(request);
// ParserUtils.printXml(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request), 3);
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp, "ResC");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("F1")) // Spool: Error reading the spoolfile
return new QueryConnectionsResult(Status.SERVICE_DOWN);
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.enter(pp, "ConRes");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
- if (code.equals("K9380"))
+ if (code.equals("K9380") || code.equals("K895")) // Departure/Arrival are too near
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.UNRESOLVABLE_ADDRESS;
+ if (code.equals("K9240")) // Internal error
+ return new QueryConnectionsResult(Status.SERVICE_DOWN);
+ if (code.equals("K9260")) // Departure station does not exist
+ return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
+ if (code.equals("K891")) // No route found (try entering an intermediate station)
+ return QueryConnectionsResult.NO_CONNECTIONS;
+ if (code.equals("K899")) // An error occurred
+ return new QueryConnectionsResult(Status.SERVICE_DOWN);
+ // if (code.equals("K1:890")) // Unsuccessful or incomplete search (direction: forward)
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String context = XmlPullUtil.text(pp);
XmlPullUtil.enter(pp, "ConnectionList");
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "Overview");
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location departure = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Departure");
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location arrival = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Arrival");
XmlPullUtil.exit(pp, "Overview");
XmlPullUtil.enter(pp, "ConSectionList");
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionDeparture = parseLocation(pp);
XmlPullUtil.enter(pp, "Dep");
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
Location destination = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "JourneyAttributeList");
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp, "JourneyAttribute");
XmlPullUtil.require(pp, "Attribute");
final String attrName = pp.getAttributeValue(null, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
destination = new Location(LocationType.ANY, 0, null, attributeVariants.get("NORMAL"));
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.enter(pp, "Duration");
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionArrival = parseLocation(pp);
XmlPullUtil.enter(pp, "Arr");
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, destination, departureTime, departurePos, sectionDeparture.id, sectionDeparture.name,
arrivalTime, arrivalPos, sectionArrival.id, sectionArrival.name, null));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure,
sectionArrival.id, sectionArrival.name));
}
else
{
parts.add(new Connection.Footway(min, sectionDeparture.id, sectionDeparture.name, sectionArrival.id, sectionArrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, departure.id, departure.name, arrival.id, arrival.name,
parts, null));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, context, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
private final Location parseLocation(final XmlPullParser pp) throws XmlPullParserException, IOException
{
Location location;
if (pp.getName().equals("Station"))
location = parseStation(pp);
else if (pp.getName().equals("Poi"))
location = parsePoi(pp);
else if (pp.getName().equals("Address"))
location = parseAddress(pp);
else
throw new IllegalStateException("cannot parse: " + pp.getName());
XmlPullUtil.next(pp);
return location;
}
private final Map<String, String> parseAttributeVariants(final XmlPullParser pp) throws XmlPullParserException, IOException
{
final Map<String, String> attributeVariants = new HashMap<String, String>();
while (XmlPullUtil.test(pp, "AttributeVariant"))
{
final String type = XmlPullUtil.attr(pp, "type");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
final String value = XmlPullUtil.text(pp).trim();
XmlPullUtil.exit(pp);
attributeVariants.put(type, value);
}
return attributeVariants;
}
private static final Pattern P_TIME = Pattern.compile("(\\d+)d(\\d+):(\\d{2}):(\\d{2})");
private Date parseTime(final Calendar currentDate, final String str)
{
final Matcher m = P_TIME.matcher(str);
if (m.matches())
{
final Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, currentDate.get(Calendar.YEAR));
c.set(Calendar.MONTH, currentDate.get(Calendar.MONTH));
c.set(Calendar.DAY_OF_MONTH, currentDate.get(Calendar.DAY_OF_MONTH));
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(2)));
c.set(Calendar.MINUTE, Integer.parseInt(m.group(3)));
c.set(Calendar.SECOND, Integer.parseInt(m.group(4)));
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(m.group(1)));
return c.getTime();
}
else
{
throw new IllegalArgumentException("cannot parse duration: " + str);
}
}
private static final Pattern P_DURATION = Pattern.compile("(\\d+):(\\d{2})");
private final int parseDuration(final String str)
{
final Matcher m = P_DURATION.matcher(str);
if (m.matches())
return Integer.parseInt(m.group(1)) * 60 + Integer.parseInt(m.group(2));
else
throw new IllegalArgumentException("cannot parse duration: " + str);
}
private static final String location(final Location location)
{
if (location.type == LocationType.STATION && location.id != 0)
return "<Station externalId=\"" + location.id + "\" />";
if (location.type == LocationType.POI && location.hasLocation())
return "<Poi type=\"WGS84\" x=\"" + location.lon + "\" y=\"" + location.lat + "\" />";
if (location.type == LocationType.ADDRESS && location.hasLocation())
return "<Address type=\"WGS84\" x=\"" + location.lon + "\" y=\"" + location.lat + "\" />";
throw new IllegalArgumentException("cannot handle: " + location.toDebugString());
}
protected static final String locationId(final Location location)
{
final StringBuilder builder = new StringBuilder();
builder.append("A=").append(locationType(location));
if (location.hasLocation())
builder.append("@X=" + location.lon + "@Y=" + location.lat);
if (location.name != null)
builder.append("@G=" + location.name);
if (location.type == LocationType.STATION && location.id != 0)
builder.append("@L=").append(location.id);
return builder.toString();
}
protected static final int locationType(final Location location)
{
if (location.type == LocationType.STATION)
return 1;
if (location.type == LocationType.POI)
return 4;
if (location.type == LocationType.ADDRESS && location.hasLocation())
return 16;
if (location.type == LocationType.ADDRESS && location.name != null)
return 2;
if (location.type == LocationType.ANY)
return 255;
throw new IllegalArgumentException(location.type.toString());
}
private static final Pattern P_LINE_S = Pattern.compile("S\\d+");
private static final Pattern P_LINE_SN = Pattern.compile("SN\\d*");
private final String _normalizeLine(final String type, final String name, final String longCategory)
{
final String normalizedType = type.split(" ", 2)[0];
final String normalizedName = normalizeWhitespace(name);
if ("EN".equals(normalizedType)) // EuroNight
return "I" + normalizedName;
if ("EC".equals(normalizedType)) // EuroCity
return "I" + normalizedName;
if ("ICE".equals(normalizedType)) // InterCityExpress
return "I" + normalizedName;
if ("IC".equals(normalizedType)) // InterCity
return "I" + normalizedName;
if ("ICN".equals(normalizedType)) // IC-Neigezug
return "I" + normalizedName;
if ("CNL".equals(normalizedType)) // CityNightLine
return "I" + normalizedName;
if ("OEC".equals(normalizedType)) // ÖBB EuroCity
return "I" + normalizedName;
if ("OIC".equals(normalizedType)) // ÖBB InterCity
return "I" + normalizedName;
if ("TGV".equals(normalizedType)) // Train à grande vit.
return "I" + normalizedName;
if ("THA".equals(normalizedType)) // Thalys
return "I" + normalizedName;
if ("THALYS".equals(normalizedType)) // THALYS
return "I" + normalizedName;
if ("ES".equals(normalizedType)) // Eurostar Italia
return "I" + normalizedName;
if ("EST".equals(normalizedType)) // Eurostar
return "I" + normalizedName;
if ("X2".equals(normalizedType)) // X2000 Neigezug, Schweden
return "I" + normalizedName;
if ("RJ".equals(normalizedType)) // Railjet
return "I" + normalizedName;
if ("AVE".equals(normalizedType)) // Alta Velocidad ES
return "I" + normalizedName;
if ("ARC".equals(normalizedType)) // Arco, Spanien
return "I" + normalizedName;
if ("ALS".equals(normalizedType)) // Alaris, Spanien
return "I" + normalizedName;
if ("TAL".equals(normalizedType)) // Talgo, Spanien
return "I" + normalizedName;
if ("NZ".equals(normalizedType)) // Nacht-Zug
return "I" + normalizedName;
if ("FYR".equals(normalizedType)) // Fyra, Amsterdam-Schiphol-Rotterdam
return "I" + normalizedName;
if ("R".equals(normalizedType)) // Regio
return "R" + normalizedName;
if ("D".equals(normalizedType)) // Schnellzug
return "R" + normalizedName;
if ("E".equals(normalizedType)) // Eilzug
return "R" + normalizedName;
if ("RE".equals(normalizedType)) // RegioExpress
return "R" + normalizedName;
if ("IR".equals(normalizedType)) // InterRegio
return "R" + normalizedName;
if ("IRE".equals(normalizedType)) // InterRegioExpress
return "R" + normalizedName;
if ("ATZ".equals(normalizedType)) // Autotunnelzug
return "R" + normalizedName;
if ("EXT".equals(normalizedType)) // Extrazug
return "R" + normalizedName;
if ("S".equals(normalizedType)) // S-Bahn
return "S" + normalizedName;
if (P_LINE_S.matcher(normalizedType).matches()) // diverse S-Bahnen
return "S" + normalizedType;
if (P_LINE_SN.matcher(normalizedType).matches()) // Nacht-S-Bahn
return "S" + normalizedType;
if ("SPR".equals(normalizedType)) // Sprinter, Niederlande
return "S" + normalizedName;
if ("Met".equals(normalizedType)) // Metro
return "U" + normalizedName;
if ("M".equals(normalizedType)) // Metro
return "U" + normalizedName;
if ("Métro".equals(normalizedType))
return "U" + normalizedName;
if ("Tram".equals(normalizedType)) // Tram
return "T" + normalizedName;
if ("T".equals(normalizedType)) // Tram
return "T" + normalizedName;
if ("Tramway".equals(normalizedType))
return "T" + normalizedName;
if ("BUS".equals(normalizedType)) // Bus
return "B" + normalizedName;
if ("Bus".equals(normalizedType)) // Niederflurbus
return "B" + normalizedName;
if ("NFB".equals(normalizedType)) // Niederflur-Bus
return "B" + normalizedName;
if ("N".equals(normalizedType)) // Nachtbus
return "B" + normalizedName;
if ("Tro".equals(normalizedType)) // Trolleybus
return "B" + normalizedName;
if ("Taxi".equals(normalizedType)) // Taxi
return "B" + normalizedName;
if ("TX".equals(normalizedType)) // Taxi
return "B" + normalizedName;
if ("BAT".equals(normalizedType)) // Schiff
return "F" + normalizedName;
if ("LB".equals(normalizedType)) // Luftseilbahn
return "C" + normalizedName;
if ("FUN".equals(normalizedType)) // Standseilbahn
return "C" + normalizedName;
if ("Fun".equals(normalizedType)) // Funiculaire
return "C" + normalizedName;
if ("L".equals(normalizedType))
return "?" + normalizedName;
if ("P".equals(normalizedType))
return "?" + normalizedName;
if ("CR".equals(normalizedType))
return "?" + normalizedName;
if ("TRN".equals(normalizedType))
return "?" + normalizedName;
throw new IllegalStateException("cannot normalize type '" + normalizedType + "' (" + type + ") name '" + normalizedName + "' longCategory '"
+ longCategory + "'");
}
private final static Pattern P_WHITESPACE = Pattern.compile("\\s+");
private final String normalizeWhitespace(final String str)
{
return P_WHITESPACE.matcher(str).replaceAll("");
}
public GetConnectionDetailsResult getConnectionDetails(String connectionUri) throws IOException
{
throw new UnsupportedOperationException();
}
private final static Pattern P_NEARBY_COARSE = Pattern.compile("<tr class=\"(zebra[^\"]*)\">(.*?)</tr>", Pattern.DOTALL);
private final static Pattern P_NEARBY_FINE_COORDS = Pattern
.compile("REQMapRoute0\\.Location0\\.X=(-?\\d+)&(?:amp;)?REQMapRoute0\\.Location0\\.Y=(-?\\d+)&");
private final static Pattern P_NEARBY_FINE_LOCATION = Pattern.compile("[\\?&]input=(\\d+)&[^\"]*\">([^<]*)<");
protected abstract String nearbyStationUri(String stationId);
public NearbyStationsResult nearbyStations(final String stationId, final int lat, final int lon, final int maxDistance, final int maxStations)
throws IOException
{
if (stationId == null)
throw new IllegalArgumentException("stationId must be given");
final List<Station> stations = new ArrayList<Station>();
final String uri = nearbyStationUri(stationId);
final CharSequence page = ParserUtils.scrape(uri);
String oldZebra = null;
final Matcher mCoarse = P_NEARBY_COARSE.matcher(page);
while (mCoarse.find())
{
final String zebra = mCoarse.group(1);
if (oldZebra != null && zebra.equals(oldZebra))
throw new IllegalArgumentException("missed row? last:" + zebra);
else
oldZebra = zebra;
final Matcher mFineLocation = P_NEARBY_FINE_LOCATION.matcher(mCoarse.group(2));
if (mFineLocation.find())
{
int parsedLon = 0;
int parsedLat = 0;
final int parsedId = Integer.parseInt(mFineLocation.group(1));
final String parsedName = ParserUtils.resolveEntities(mFineLocation.group(2));
final Matcher mFineCoords = P_NEARBY_FINE_COORDS.matcher(mCoarse.group(2));
if (mFineCoords.find())
{
parsedLon = Integer.parseInt(mFineCoords.group(1));
parsedLat = Integer.parseInt(mFineCoords.group(2));
}
final String[] nameAndPlace = splitNameAndPlace(parsedName);
stations.add(new Station(parsedId, nameAndPlace[0], nameAndPlace[1], parsedName, parsedLat, parsedLon, 0, null, null));
}
else
{
throw new IllegalArgumentException("cannot parse '" + mCoarse.group(2) + "' on " + uri);
}
}
if (maxStations == 0 || maxStations >= stations.size())
return new NearbyStationsResult(stations);
else
return new NearbyStationsResult(stations.subList(0, maxStations));
}
protected static final Pattern P_NORMALIZE_LINE = Pattern.compile("([A-Za-zÄÖÜäöüßáàâéèêíìîóòôúùû/-]+)[\\s-]*(.*)");
protected final String normalizeLine(final String type, final String line)
{
final Matcher m = P_NORMALIZE_LINE.matcher(line);
final String strippedLine = m.matches() ? m.group(1) + m.group(2) : line;
final char normalizedType = normalizeType(type);
if (normalizedType != 0)
return normalizedType + strippedLine;
throw new IllegalStateException("cannot normalize type '" + type + "' line '" + line + "'");
}
protected abstract char normalizeType(String type);
protected final char normalizeCommonTypes(final String ucType)
{
// Intercity
if (ucType.equals("EC")) // EuroCity
return 'I';
if (ucType.equals("EN")) // EuroNight
return 'I';
if (ucType.equals("ICE")) // InterCityExpress
return 'I';
if (ucType.equals("IC")) // InterCity
return 'I';
if (ucType.equals("EN")) // EuroNight
return 'I';
if (ucType.equals("CNL")) // CityNightLine
return 'I';
if (ucType.equals("OEC")) // ÖBB-EuroCity
return 'I';
if (ucType.equals("OIC")) // ÖBB-InterCity
return 'I';
if (ucType.equals("RJ")) // RailJet, Österreichische Bundesbahnen
return 'I';
if (ucType.equals("THA")) // Thalys
return 'I';
if (ucType.equals("TGV")) // Train à Grande Vitesse
return 'I';
if (ucType.equals("DNZ")) // Berlin-Saratov, Berlin-Moskva, Connections only?
return 'I';
if (ucType.equals("AIR")) // Generic Flight
return 'I';
if (ucType.equals("ECB")) // EC, Verona-München
return 'I';
if (ucType.equals("INZ")) // Nacht
return 'I';
if (ucType.equals("RHI")) // ICE
return 'I';
if (ucType.equals("RHT")) // TGV
return 'I';
if (ucType.equals("TGD")) // TGV
return 'I';
if (ucType.equals("IRX")) // IC
return 'I';
// Regional Germany
if (ucType.equals("ZUG")) // Generic Train
return 'R';
if (ucType.equals("R")) // Generic Regional Train
return 'R';
if (ucType.equals("DPN")) // Dritter Personen Nahverkehr
return 'R';
if (ucType.equals("RB")) // RegionalBahn
return 'R';
if (ucType.equals("RE")) // RegionalExpress
return 'R';
if (ucType.equals("IR")) // Interregio
return 'R';
if (ucType.equals("IRE")) // Interregio Express
return 'R';
if (ucType.equals("HEX")) // Harz-Berlin-Express, Veolia
return 'R';
if (ucType.equals("WFB")) // Westfalenbahn
return 'R';
if (ucType.equals("RT")) // RegioTram
return 'R';
if (ucType.equals("REX")) // RegionalExpress, Österreich
return 'R';
// Regional Poland
if (ucType.equals("OS")) // Chop-Cierna nas Tisou
return 'R';
if (ucType.equals("SP")) // Polen
return 'R';
// Suburban Trains
if (ucType.equals("S")) // Generic S-Bahn
return 'S';
// Subway
if (ucType.equals("U")) // Generic U-Bahn
return 'U';
// Tram
if (ucType.equals("STR")) // Generic Tram
return 'T';
// Bus
if (ucType.equals("BUS")) // Generic Bus
return 'B';
if (ucType.equals("AST")) // Anruf-Sammel-Taxi
return 'B';
if (ucType.equals("RUF")) // Rufbus
return 'B';
if (ucType.equals("SEV")) // Schienen-Ersatz-Verkehr
return 'B';
if (ucType.equals("BUSSEV")) // Schienen-Ersatz-Verkehr
return 'B';
if (ucType.equals("BSV")) // Bus SEV
return 'B';
if (ucType.equals("FB")) // Luxemburg-Saarbrücken
return 'B';
// Ferry
if (ucType.equals("SCH")) // Schiff
return 'F';
if (ucType.equals("AS")) // SyltShuttle, eigentlich Autoreisezug
return 'F';
return 0;
}
private static final Pattern P_CONNECTION_ID = Pattern.compile("co=(C\\d+-\\d+)&");
protected static String extractConnectionId(final String link)
{
final Matcher m = P_CONNECTION_ID.matcher(link);
if (m.find())
return m.group(1);
else
throw new IllegalArgumentException("cannot extract id from " + link);
}
private static final Map<Character, int[]> LINES = new HashMap<Character, int[]>();
static
{
LINES.put('I', new int[] { Color.WHITE, Color.RED, Color.RED });
LINES.put('R', new int[] { Color.GRAY, Color.WHITE });
LINES.put('S', new int[] { Color.parseColor("#006e34"), Color.WHITE });
LINES.put('U', new int[] { Color.parseColor("#003090"), Color.WHITE });
LINES.put('T', new int[] { Color.parseColor("#cc0000"), Color.WHITE });
LINES.put('B', new int[] { Color.parseColor("#993399"), Color.WHITE });
LINES.put('F', new int[] { Color.BLUE, Color.WHITE });
LINES.put('?', new int[] { Color.DKGRAY, Color.WHITE });
}
public int[] lineColors(final String line)
{
if (line.length() == 0)
return null;
return LINES.get(line.charAt(0));
}
private void assertResC(final XmlPullParser pp) throws XmlPullParserException, IOException
{
if (!XmlPullUtil.jumpToStartTag(pp, null, "ResC"))
throw new IOException("cannot find <ResC />");
}
}
| false | true | private QueryConnectionsResult queryConnections(final String request, final Location from, final Location via, final Location to)
throws IOException
{
// System.out.println(request);
// ParserUtils.printXml(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request), 3);
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp, "ResC");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("F1")) // Spool: Error reading the spoolfile
return new QueryConnectionsResult(Status.SERVICE_DOWN);
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.enter(pp, "ConRes");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("K9380"))
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.UNRESOLVABLE_ADDRESS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String context = XmlPullUtil.text(pp);
XmlPullUtil.enter(pp, "ConnectionList");
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "Overview");
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location departure = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Departure");
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location arrival = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Arrival");
XmlPullUtil.exit(pp, "Overview");
XmlPullUtil.enter(pp, "ConSectionList");
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionDeparture = parseLocation(pp);
XmlPullUtil.enter(pp, "Dep");
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
Location destination = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "JourneyAttributeList");
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp, "JourneyAttribute");
XmlPullUtil.require(pp, "Attribute");
final String attrName = pp.getAttributeValue(null, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
destination = new Location(LocationType.ANY, 0, null, attributeVariants.get("NORMAL"));
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.enter(pp, "Duration");
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionArrival = parseLocation(pp);
XmlPullUtil.enter(pp, "Arr");
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, destination, departureTime, departurePos, sectionDeparture.id, sectionDeparture.name,
arrivalTime, arrivalPos, sectionArrival.id, sectionArrival.name, null));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure,
sectionArrival.id, sectionArrival.name));
}
else
{
parts.add(new Connection.Footway(min, sectionDeparture.id, sectionDeparture.name, sectionArrival.id, sectionArrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, departure.id, departure.name, arrival.id, arrival.name,
parts, null));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, context, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
| private QueryConnectionsResult queryConnections(final String request, final Location from, final Location via, final Location to)
throws IOException
{
// System.out.println(request);
// ParserUtils.printXml(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request), 3);
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp, "ResC");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("F1")) // Spool: Error reading the spoolfile
return new QueryConnectionsResult(Status.SERVICE_DOWN);
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.enter(pp, "ConRes");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("K9380") || code.equals("K895")) // Departure/Arrival are too near
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.UNRESOLVABLE_ADDRESS;
if (code.equals("K9240")) // Internal error
return new QueryConnectionsResult(Status.SERVICE_DOWN);
if (code.equals("K9260")) // Departure station does not exist
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K891")) // No route found (try entering an intermediate station)
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K899")) // An error occurred
return new QueryConnectionsResult(Status.SERVICE_DOWN);
// if (code.equals("K1:890")) // Unsuccessful or incomplete search (direction: forward)
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String context = XmlPullUtil.text(pp);
XmlPullUtil.enter(pp, "ConnectionList");
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "Overview");
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location departure = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Departure");
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location arrival = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Arrival");
XmlPullUtil.exit(pp, "Overview");
XmlPullUtil.enter(pp, "ConSectionList");
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionDeparture = parseLocation(pp);
XmlPullUtil.enter(pp, "Dep");
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
Location destination = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "JourneyAttributeList");
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp, "JourneyAttribute");
XmlPullUtil.require(pp, "Attribute");
final String attrName = pp.getAttributeValue(null, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
destination = new Location(LocationType.ANY, 0, null, attributeVariants.get("NORMAL"));
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.enter(pp, "Duration");
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionArrival = parseLocation(pp);
XmlPullUtil.enter(pp, "Arr");
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, destination, departureTime, departurePos, sectionDeparture.id, sectionDeparture.name,
arrivalTime, arrivalPos, sectionArrival.id, sectionArrival.name, null));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure,
sectionArrival.id, sectionArrival.name));
}
else
{
parts.add(new Connection.Footway(min, sectionDeparture.id, sectionDeparture.name, sectionArrival.id, sectionArrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, departure.id, departure.name, arrival.id, arrival.name,
parts, null));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, context, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
|
diff --git a/src/com/nloko/android/syncmypix/SyncResultsActivity.java b/src/com/nloko/android/syncmypix/SyncResultsActivity.java
index 0fdab3a..26f11dc 100644
--- a/src/com/nloko/android/syncmypix/SyncResultsActivity.java
+++ b/src/com/nloko/android/syncmypix/SyncResultsActivity.java
@@ -1,1441 +1,1442 @@
//
// SyncResultsActivity.java is part of SyncMyPix
//
// Authors:
// Neil Loknath <[email protected]>
//
// Copyright (c) 2009 Neil Loknath
//
// SyncMyPix is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SyncMyPix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SyncMyPix. If not, see <http://www.gnu.org/licenses/>.
//
package com.nloko.android.syncmypix;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import com.nloko.android.Log;
import com.nloko.android.PhotoCache;
import com.nloko.android.ThumbnailCache;
import com.nloko.android.Utils;
import com.nloko.android.ThumbnailCache.ImageListener;
import com.nloko.android.ThumbnailCache.ImageProvider;
import com.nloko.android.syncmypix.SyncMyPix.Results;
import com.nloko.android.syncmypix.SyncMyPix.ResultsDescription;
import com.nloko.android.syncmypix.SyncMyPix.Sync;
import com.nloko.android.syncmypix.contactutils.ContactUtils;
import com.nloko.android.syncmypix.graphics.CropImage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.provider.Contacts.People;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
public class SyncResultsActivity extends Activity {
private ContactUtils mContactUtils;
private SyncMyPixDbHelper mDbHelper;
private ListView mListview;
private Handler mMainHandler;
private DownloadImageHandler mDownloadHandler;
private ThumbnailHandler mThumbnailHandler;
private InitializeResultsThread mInitResultsThread;
private Bitmap mContactImage;
private final ThumbnailCache mCache = new ThumbnailCache();
private PhotoCache mSdCache;
private ProgressBar mProgress;
private ImageButton mDeleteButton;
private ImageButton mHelpButton;
private ImageButton mHomeButton;
private Uri mUriOfSelected = null;
private final int MENU_FILTER = 1;
private final int MENU_FILTER_ALL = 2;
private final int MENU_FILTER_NOTFOUND = 3;
private final int MENU_FILTER_UPDATED = 4;
private final int MENU_FILTER_SKIPPED = 5;
private final int MENU_FILTER_ERROR = 6;
// dialogs
private final int ZOOM_PIC = 1;
private final int UPDATE_CONTACT = 3;
private final int HELP_DIALOG = 4;
private final int DELETE_DIALOG = 5;
private final int DELETING = 6;
private static final String TAG = "SyncResults";
private final int CONTEXTMENU_CROP = 3;
private final int CONTEXTMENU_SELECT_CONTACT = 4;
private final int CONTEXTMENU_VIEW_CONTACT = 5;
private final int CONTEXTMENU_UNLINK = 6;
private final int PICK_CONTACT = 6;
private final int REQUEST_CROP_PHOTO = 7;
private final String[] mProjection = {
Results._ID,
Results.NAME,
Results.DESCRIPTION,
Results.PIC_URL,
Results.CONTACT_ID,
Sync.DATE_STARTED,
Sync.DATE_COMPLETED };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
mContactUtils = new ContactUtils();
mSdCache = new PhotoCache(getApplicationContext());
Bitmap defaultImage = BitmapFactory.decodeResource(getResources(), R.drawable.default_face);
//mCache.setDefaultImage(Bitmap.createScaledBitmap(defaultImage, 40, 40, false));
mCache.setDefaultImage(defaultImage);
mDbHelper = new SyncMyPixDbHelper(getApplicationContext());
Cursor cursor = managedQuery(Results.CONTENT_URI, mProjection, null, null, Results.DEFAULT_SORT_ORDER);
mProgress = (ProgressBar) findViewById(R.id.progress);
mProgress.setVisibility(View.VISIBLE);
mListview = (ListView) findViewById(R.id.resultList);
final SimpleCursorAdapter adapter = new ResultsListAdapter(
this,
R.layout.resultslistitem,
cursor,
new String[] {Results.NAME, Results.DESCRIPTION },
new int[] { R.id.text1, R.id.text2 } );
mListview.setAdapter(adapter);
mCache.setImageProvider(new ImageProvider() {
public boolean onImageRequired(String url) {
if (mThumbnailHandler != null) {
//Log.d(TAG, "reloading thumbnail");
Message msg = mThumbnailHandler.obtainMessage();
msg.obj = url;
mThumbnailHandler.sendMessage(msg);
return true;
}
return false;
}
});
mCache.setImageListener(new ImageListener() {
public void onImageReady(final String url) {
+ if (mListview == null) return;
final ImageView image = (ImageView) mListview.findViewWithTag(url);
// Log.d(TAG, "onImageReady updating image");
runOnUiThread(new Runnable() {
public void run() {
if (mListview == null) return;
if (mCache != null && image != null) {
image.setImageBitmap(mCache.get(url));
} else {
// HACK sometimes the view can't be found, probably already recycled
((SimpleCursorAdapter)mListview.getAdapter()).notifyDataSetChanged();
}
mListview.invalidateViews();
}
});
}
});
mListview.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
return false;
}
});
mListview.setOnItemClickListener(new OnItemClickListener () {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Cursor cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
cursor.moveToPosition(position);
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
if (url != null) {
//setProgressBarIndeterminateVisibility(true);
mProgress.setVisibility(View.VISIBLE);
Message msg = mDownloadHandler.obtainMessage();
msg.what = ZOOM_PIC;
msg.obj = url;
mDownloadHandler.sendMessage(msg);
}
}
});
mListview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
int position = ((AdapterContextMenuInfo)menuInfo).position;
Cursor cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
if (cursor.moveToPosition(position)) {
String id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
String name = cursor.getString(cursor.getColumnIndex(Results.NAME));
if (url != null) {
menu.setHeaderTitle(name);
if (id != null) {
menu.add(0, CONTEXTMENU_VIEW_CONTACT, Menu.NONE, R.string.syncresults_menu_viewsynced);
menu.add(0, CONTEXTMENU_CROP, Menu.NONE, R.string.syncresults_menu_crop);
menu.add(0, CONTEXTMENU_UNLINK, Menu.NONE, R.string.syncresults_menu_unlink);
}
menu.add(0, CONTEXTMENU_SELECT_CONTACT, Menu.NONE, R.string.syncresults_menu_addpicture);
}
}
}
});
mHomeButton = (ImageButton) findViewById(R.id.home);
mHomeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
finish();
}
});
mHelpButton = (ImageButton) findViewById(R.id.help);
mHelpButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.help_link)));
startActivity(i);
}
});
mDeleteButton = (ImageButton) findViewById(R.id.delete);
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DELETE_DIALOG);
}
});
mMainHandler = new MainHandler(this);
}
private static class MainHandler extends Handler
{
private final WeakReference<SyncResultsActivity> mActivity;
private final static int UNKNOWN_HOST_ERROR = 2;
private final static int MANUAL_LINK_ERROR = 3;
public MainHandler(SyncResultsActivity activity)
{
super();
mActivity = new WeakReference<SyncResultsActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
SyncResultsActivity activity = mActivity.get();
if (activity != null) {
Bitmap bitmap = (Bitmap) msg.obj;
if (bitmap != null) {
activity.mContactImage = bitmap;
activity.showDialog(activity.ZOOM_PIC);
}
activity.mProgress.setVisibility(View.INVISIBLE);
handleWhat(msg);
}
}
private void handleWhat(Message msg) {
SyncResultsActivity activity = mActivity.get();
if (activity != null) {
switch (msg.what) {
case UNKNOWN_HOST_ERROR:
Toast.makeText(activity.getApplicationContext(), R.string.syncresults_networkerror, Toast.LENGTH_LONG).show();
break;
case MANUAL_LINK_ERROR:
Toast.makeText(activity.getApplicationContext(), R.string.syncresults_manuallinkerror, Toast.LENGTH_LONG).show();
break;
}
}
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
Log.d(TAG, "FINALIZED");
}
@Override
protected void onPause() {
super.onPause();
// save battery life by killing downloader thread
if (mCache != null) {
mCache.togglePauseOnDownloader(true);
mCache.empty();
}
// if (mThumbnailHandler != null) {
// mThumbnailHandler.stopRunning();
// }
if (mDownloadHandler != null) {
mDownloadHandler.stopRunning();
}
if (mInitResultsThread != null) {
mInitResultsThread.stopRunning();
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (mCache != null) {
mCache.empty();
}
}
@Override
protected void onResume() {
super.onResume();
HandlerThread downloadThread = new HandlerThread("ImageDownload");
downloadThread.start();
mDownloadHandler = new DownloadImageHandler(this, downloadThread.getLooper());
if (mInitResultsThread == null) {
mInitResultsThread = new InitializeResultsThread(this);
mInitResultsThread.start();
}
if (mThumbnailHandler == null) {
HandlerThread thumbnailThread = new HandlerThread("Thumbnail");
thumbnailThread.start();
mThumbnailHandler = new ThumbnailHandler(this, thumbnailThread.getLooper());
}
mCache.togglePauseOnDownloader(false);
NotificationManager notifyManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notifyManager.cancel(R.string.syncservice_stopped);
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
if (mThumbnailHandler != null) {
mThumbnailHandler.stopRunning();
}
mCache.destroy();
if (mSdCache != null) {
mSdCache.releaseResources();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item;
SubMenu options = menu.addSubMenu(0, MENU_FILTER, 0, R.string.syncresults_filterButton);
options.add(0, MENU_FILTER_ALL, 0, "All");
options.add(0, MENU_FILTER_ERROR, 0, "Errors");
options.add(0, MENU_FILTER_NOTFOUND, 0, "Not found");
options.add(0, MENU_FILTER_SKIPPED, 0, "Skipped");
options.add(0, MENU_FILTER_UPDATED, 0, "Updated");
options.setIcon(android.R.drawable.ic_menu_sort_alphabetically);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
SimpleCursorAdapter adapter = (SimpleCursorAdapter)mListview.getAdapter();
switch (item.getItemId()) {
case MENU_FILTER_ALL:
adapter.getFilter().filter(null);
return true;
case MENU_FILTER_ERROR:
adapter.getFilter().filter("'" + ResultsDescription.ERROR.getDescription(getApplicationContext()) + "'," +
"'" + ResultsDescription.DOWNLOAD_FAILED.getDescription(getApplicationContext()) + "'");
return true;
case MENU_FILTER_NOTFOUND:
adapter.getFilter().filter("'" + ResultsDescription.NOTFOUND.getDescription(getApplicationContext()) + "'");
return true;
case MENU_FILTER_UPDATED:
adapter.getFilter().filter("'" + ResultsDescription.UPDATED.getDescription(getApplicationContext()) + "'," +
"'" + ResultsDescription.MULTIPLEPROCESSED.getDescription(getApplicationContext()) + "'");
return true;
case MENU_FILTER_SKIPPED:
adapter.getFilter().filter("'" + ResultsDescription.SKIPPED_EXISTS.getDescription(getApplicationContext()) + "'," +
"'" + ResultsDescription.SKIPPED_UNCHANGED.getDescription(getApplicationContext()) + "'," +
"'" + ResultsDescription.SKIPPED_MULTIPLEFOUND.getDescription(getApplicationContext()) + "'");
return true;
}
return false;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
int position;
Cursor cursor;
Intent intent;
String id;
switch (item.getItemId()) {
case CONTEXTMENU_VIEW_CONTACT:
position = ((AdapterContextMenuInfo)menuInfo).position;
cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
if (cursor.moveToPosition(position)) {
id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
if (id != null) {
intent = new Intent(Intent.ACTION_VIEW, Uri.withAppendedPath(mContactUtils.getContentUri(), id));
startActivity(intent);
}
}
return true;
case CONTEXTMENU_SELECT_CONTACT:
position = ((AdapterContextMenuInfo)menuInfo).position;
mUriOfSelected = getResultsUriFromListPosition(position);
intent = new Intent(Intent.ACTION_PICK, mContactUtils.getContentUri());
startActivityForResult(intent, PICK_CONTACT);
return true;
case CONTEXTMENU_CROP:
position = ((AdapterContextMenuInfo)menuInfo).position;
mUriOfSelected = getResultsUriFromListPosition(position);
cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
if (cursor.moveToPosition(position)) {
id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
updateContactWithSelection(Uri.withAppendedPath(mContactUtils.getContentUri(), id));
//crop(id);
}
return true;
case CONTEXTMENU_UNLINK:
position = ((AdapterContextMenuInfo)menuInfo).position;
mUriOfSelected = getResultsUriFromListPosition(position);
cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
if (cursor.moveToPosition(position)) {
id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
unlink(id, true);
}
return true;
}
return super.onContextItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
Uri contactData;
switch (requestCode) {
case PICK_CONTACT:
contactData = data.getData();
updateContactWithSelection(contactData);
break;
case REQUEST_CROP_PHOTO:
if (mUriOfSelected == null) {
break;
}
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(mUriOfSelected,
new String[] { Results.CONTACT_ID, Results.PIC_URL, Results.LOOKUP_KEY },
null,
null,
null);
ResultsListAdapter adapter = (ResultsListAdapter)mListview.getAdapter();
if (cursor.moveToFirst()) {
String id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
String lookup = cursor.getString(cursor.getColumnIndex(Results.LOOKUP_KEY));
Bitmap bitmap = (Bitmap) data.getParcelableExtra("data");
if (bitmap != null) {
byte[] bytes = Utils.bitmapToPNG(bitmap);
mContactUtils.updatePhoto(getContentResolver(), bytes, id);
mDbHelper.updateHashes(id, lookup, null, bytes);
mCache.add(url, bitmap);
adapter.notifyDataSetChanged();
}
}
cursor.close();
break;
}
}
private Uri getResultsUriFromListPosition(int pos)
{
Cursor cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
if (cursor != null && cursor.moveToPosition(pos)) {
String id = cursor.getString(cursor.getColumnIndex(Results._ID));
return Uri.withAppendedPath(Results.CONTENT_URI, id);
}
return null;
}
private void crop(String id)
{
// launch cropping activity
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClass(getApplicationContext(), CropImage.class);
intent.setData(Uri.withAppendedPath(People.CONTENT_URI, id));
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 96);
intent.putExtra("outputY", 96);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CROP_PHOTO);
}
private void updateContactWithSelection(Uri contact)
{
// hopefully, no users will ever see this message
// SyncMyPix has been getting killed by Android under
// low memory conditions.
// Work has been done to try to prevent this ie. override onLowMemory,
// free resources, ensure proper garbage collection.
if (contact == null || mUriOfSelected == null) {
Toast.makeText(getApplicationContext(),
R.string.syncresults_addpicture_error,
Toast.LENGTH_LONG).show();
return;
}
final ContentResolver resolver = getContentResolver();
final Uri contactUri = contact;
final List<String> segments = contactUri.getPathSegments();
final String contactId = segments.get(segments.size() - 1);
final String lookup = mContactUtils.getLookup(resolver, contactUri);
Cursor cursor = resolver.query(mUriOfSelected,
new String[] { Results._ID,
Results.CONTACT_ID,
Results.PIC_URL,
Results.FRIEND_ID,
Sync.SOURCE },
null,
null,
null);
if (cursor.moveToFirst()) {
if (!mContactUtils.isContactUpdatable(resolver, contactId)) {
Toast.makeText(getApplicationContext(),
R.string.syncresults_contactunlinkableerror,
Toast.LENGTH_LONG).show();
return;
}
showDialog(UPDATE_CONTACT);
final long id = cursor.getLong(cursor.getColumnIndex(Results._ID));
final String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
final String friendId = cursor.getString(cursor.getColumnIndex(Results.FRIEND_ID));
final String source = cursor.getString(cursor.getColumnIndex(Sync.SOURCE));
final String oldContactId = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
final PhotoCache sdCache = mSdCache;
Thread thread = new Thread(new Runnable() {
public void run() {
try {
String filename = Uri.parse(url).getLastPathSegment();
InputStream friend = sdCache.get(filename);
if (friend == null) {
friend = Utils.downloadPictureAsStream(url);
}
if (friend != null) {
byte[] bytes = Utils.getByteArrayFromInputStream(friend);
friend.close();
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
sdCache.add(filename, bytes);
Log.d(TAG, contactUri.toString());
unlink(contactId);
if (oldContactId != null) {
unlink(oldContactId, true);
}
String origHash = Utils.getMd5Hash(bytes);
bytes = Utils.bitmapToPNG(bitmap);
String dbHash = Utils.getMd5Hash(bytes);
mContactUtils.updatePhoto(resolver, bytes, contactId);
mDbHelper.updateHashes(contactId, lookup, origHash, dbHash);
if (friendId != null && !friendId.equals("")) {
mDbHelper.updateLink(contactId, lookup, friendId, source);
}
mCache.add(url, bitmap);
ContentValues values = new ContentValues();
values.put(Results.DESCRIPTION, ResultsDescription.UPDATED.getDescription(getApplicationContext()));
values.put(Results.CONTACT_ID, Long.parseLong(contactId));
resolver.update(Uri.withAppendedPath(Results.CONTENT_URI, Long.toString(id)),
values,
null,
null);
runOnUiThread(new Runnable() {
public void run() {
crop(contactId);
}
});
} else {
mMainHandler.sendEmptyMessage(MainHandler.MANUAL_LINK_ERROR);
}
} catch (UnknownHostException ex) {
ex.printStackTrace();
mMainHandler.sendEmptyMessage(MainHandler.UNKNOWN_HOST_ERROR);
} catch (Exception e) {
e.printStackTrace();
mMainHandler.sendEmptyMessage(MainHandler.MANUAL_LINK_ERROR);
}
finally {
runOnUiThread(new Runnable() {
public void run() {
dismissDialog(UPDATE_CONTACT);
}
});
}
}
});
thread.start();
}
cursor.close();
}
private void unlink(String id)
{
unlink(id, false);
}
private void unlink(String id, boolean purge)
{
if (id == null) {
return;
}
final ContentResolver resolver = getContentResolver();
ContentValues values = new ContentValues();
values.put(Results.DESCRIPTION, ResultsDescription.NOTFOUND.getDescription(getApplicationContext()));
values.putNull(Results.CONTACT_ID);
resolver.update(Results.CONTENT_URI,
values,
Results.CONTACT_ID + "=" + id,
null);
if (purge) {
mDbHelper.deletePicture(id);
resolver.delete(Uri.withAppendedPath(SyncMyPix.Contacts.CONTENT_URI, id), null, null);
}
}
private Dialog showZoomDialog()
{
Dialog zoomedDialog = new Dialog(SyncResultsActivity.this);
zoomedDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
zoomedDialog.setContentView(R.layout.zoomedpic);
zoomedDialog.setCancelable(true);
final ImageView image = (ImageView)zoomedDialog.findViewById(R.id.image);
final int padding = 15;
final int width = mContactImage.getWidth();
final int height = mContactImage.getHeight();
int newWidth = width;
int newHeight = height;
final int windowHeight = getWindowManager().getDefaultDisplay().getHeight();
final int windowWidth = getWindowManager().getDefaultDisplay().getWidth();
boolean scale = false;
float ratio;
if (newHeight >= windowHeight) {
ratio = (float)newWidth / (float)newHeight;
newHeight = windowHeight - padding;
newWidth = Math.round(ratio * (float)newHeight);
scale = true;
}
if (newWidth >= windowWidth) {
ratio = (float)newHeight / (float)newWidth;
newWidth = windowWidth - padding;
newHeight = Math.round(ratio * (float)newWidth);
scale = true;
}
image.setImageBitmap(mContactImage);
if (scale) {
Matrix m = new Matrix();
m.postScale((float)newWidth / (float)width, (float)newHeight / (float)height);
image.setImageMatrix(m);
zoomedDialog.getWindow().setLayout(newWidth, newHeight);
}
zoomedDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
removeDialog(ZOOM_PIC);
}
});
return zoomedDialog;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case ZOOM_PIC:
if (mContactImage != null) {
return showZoomDialog();
}
break;
case UPDATE_CONTACT:
ProgressDialog sync = new ProgressDialog(this);
sync.setCancelable(false);
sync.setMessage(getString(R.string.syncresults_syncDialog));
sync.setProgressStyle(ProgressDialog.STYLE_SPINNER);
return sync;
case DELETE_DIALOG:
AlertDialog.Builder deleteBuilder = new AlertDialog.Builder(this);
deleteBuilder.setTitle(R.string.syncresults_deleteDialog)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.syncresults_deleteDialog_msg)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
removeDialog(DELETE_DIALOG);
showDialog(DELETING);
mDbHelper.deleteAllPictures(new DbHelperNotifier() {
public void onUpdateComplete() {
runOnUiThread(new Runnable() {
public void run() {
dismissDialog(DELETING);
Toast.makeText(getApplicationContext(),
R.string.syncresults_deleted,
Toast.LENGTH_LONG).show();
finish();
}
});
}
});
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
removeDialog(DELETE_DIALOG);
}
});
AlertDialog delete = deleteBuilder.create();
return delete;
case DELETING:
ProgressDialog deleting = new ProgressDialog(this);
deleting.setCancelable(false);
deleting.setMessage(getString(R.string.syncresults_deletingDialog));
deleting.setProgressStyle(ProgressDialog.STYLE_SPINNER);
return deleting;
}
return super.onCreateDialog(id);
}
private static class InitializeResultsThread extends Thread
{
private boolean running = true;
private Cursor cursor;
private final WeakReference<SyncResultsActivity> mActivity;
InitializeResultsThread (SyncResultsActivity activity)
{
mActivity = new WeakReference<SyncResultsActivity>(activity);
}
private void ensureQuery()
{
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return;
}
cursor = activity.getContentResolver().query(Results.CONTENT_URI,
new String[] { Sync.UPDATED,
Sync.SKIPPED,
Sync.NOT_FOUND },
null,
null,
null);
}
private void closeQuery()
{
if (cursor != null) {
cursor.close();
}
}
public void stopRunning ()
{
synchronized(this) {
running = false;
closeQuery();
}
}
private void hideDialog()
{
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
public void run() {
activity.mProgress.setVisibility(View.INVISIBLE);
}
});
}
public void run()
{
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return;
}
final int updated, skipped, notFound;
synchronized(this) {
if (running) {
ensureQuery();
if (cursor.moveToFirst()) {
updated = cursor.getInt(cursor.getColumnIndex(Sync.UPDATED));
skipped = cursor.getInt(cursor.getColumnIndex(Sync.SKIPPED));
notFound = cursor.getInt(cursor.getColumnIndex(Sync.NOT_FOUND));
} else {
updated = 0;
skipped = 0;
notFound = 0;
}
} else {
hideDialog();
return;
}
}
final TextView text1 = (TextView) activity.findViewById(R.id.updated);
final TextView text2 = (TextView) activity.findViewById(R.id.skipped);
final TextView text3 = (TextView) activity.findViewById(R.id.notfound);
final TextView label1 = (TextView) activity.findViewById(R.id.updatedLabel);
final TextView label2 = (TextView) activity.findViewById(R.id.skippedLabel);
final TextView label3 = (TextView) activity.findViewById(R.id.notfoundLabel);
activity.runOnUiThread(new Runnable() {
public void run() {
CharSequence s = activity.getString(R.string.syncresults_updated);
label1.setText(String.format(s.toString(), activity.getString(R.string.app_name)));
text1.setText(Integer.toString(updated));
text2.setText(Integer.toString(skipped));
text3.setText(Integer.toString(notFound));
label1.setVisibility(View.VISIBLE);
label2.setVisibility(View.VISIBLE);
label3.setVisibility(View.VISIBLE);
//activity.removeDialog(activity.LOADING_DIALOG);
activity.mProgress.setVisibility(View.INVISIBLE);
}
});
}
}
private static class ThumbnailHandler extends Handler
{
private final int LOAD_ALL = 1;
private final WeakReference<SyncResultsActivity> mActivity;
private boolean running = true;
private boolean mLoading = false;
private static class WorkerThread extends Thread {
// create a structure to queue
private final class Work {
public String contactId;
public String url;
public Work(String contactId, String url) {
this.contactId = contactId;
this.url = url;
}
}
private final BlockingQueue<Work> mQueue = new LinkedBlockingQueue<Work>();
private final WeakReference<SyncResultsActivity> mActivity;
private boolean running = true;
public WorkerThread(SyncResultsActivity activity) {
mActivity = new WeakReference<SyncResultsActivity>(activity);
}
public void stopRunning() {
running = false;
interrupt();
}
public void queueWork(String contactId, String url) {
try {
mQueue.put(new Work(contactId, url));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private String queryContact(String url)
{
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return null;
}
final ContentResolver resolver = activity.getContentResolver();
if (resolver == null) {
return null;
}
final String where = Results.PIC_URL + "='" + url + "'";
String[] projection = {
Results._ID,
Results.CONTACT_ID,
Results.PIC_URL };
Cursor cursor = null;
String id = null;
try {
cursor = resolver.query(Results.CONTENT_URI,
projection,
where,
null,
Results.DEFAULT_SORT_ORDER);
if (cursor.moveToNext()) {
id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
}
} catch (Exception ex) {
Log.e(TAG, android.util.Log.getStackTraceString(ex));
} finally {
if (cursor != null) {
cursor.close();
}
}
return id;
}
private void update(String contactId, String url)
{
if (contactId == null || url == null) {
return;
}
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return;
}
if (activity.mCache.contains(url)) {
return;
}
final ContentResolver resolver = activity.getContentResolver();
if (resolver == null) {
return;
}
final ContactUtils utils = activity.mContactUtils;
if (utils == null) {
return;
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(utils.getPhoto(resolver, contactId));
if (bitmap != null) {
//Log.d(TAG, "ThumbnailHandler updated cache " + url);
activity.mCache.add(url, bitmap);
// // HACK to force notifyDatasetUpdated() to be honoured
// ContentValues values = new ContentValues();
// values.put(Results.PIC_URL, url);
// //synchronized(this) {
// resolver.update(Results.CONTENT_URI,
// values,
// Results.CONTACT_ID + "=" + contactId,
// null);
// //}
}
} catch (Exception ex) {
Log.e(TAG, android.util.Log.getStackTraceString(ex));
} finally {
// activity.runOnUiThread(new Runnable() {
//
// public void run() {
// // TODO Auto-generated method stub
// ((SimpleCursorAdapter)activity.mListview.getAdapter()).notifyDataSetChanged();
// }
//
// });
}
}
public void run() {
while(running) {
try {
Work w = mQueue.take();
if (w != null && w.contactId == null) {
w.contactId = queryContact(w.url);
}
update(w.contactId, w.url);
} catch (InterruptedException e) {
Log.d(TAG, "INTERRUPTED!");
}
}
}
}
// use a pool to support extremely popular people
private static final int MAX_THREADS = 3;
private int mThreadIndex = 0;
private final List<WorkerThread> mThreadPool = new ArrayList<WorkerThread>();
ThumbnailHandler(SyncResultsActivity activity, Looper looper)
{
super(looper);
mActivity = new WeakReference<SyncResultsActivity>(activity);
initThreadPool(activity);
//init();
}
private void initThreadPool(SyncResultsActivity activity)
{
for (int i=0; i < MAX_THREADS; i++) {
WorkerThread thread = new WorkerThread(activity);
thread.start();
mThreadPool.add(thread);
}
}
private void init()
{
Message msg = obtainMessage();
msg.what = LOAD_ALL;
sendMessage(msg);
}
public boolean isLoading()
{
return mLoading;
}
private void loadAll()
{
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return;
}
final ContentResolver resolver = activity.getContentResolver();
if (resolver == null) {
return;
}
mLoading = true;
String[] projection = {
Results._ID,
Results.CONTACT_ID,
Results.PIC_URL };
Cursor cursor = null;
try {
cursor = resolver.query(Results.CONTENT_URI,
projection,
null,
null,
Results.DEFAULT_SORT_ORDER);
while(running && cursor.moveToNext()) {
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
url = url != null ? url.trim() : null;
String id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
queueWork(id, url);
}
} catch (Exception ex) {
Log.e(TAG, android.util.Log.getStackTraceString(ex));
} finally {
if (cursor != null) {
cursor.close();
}
//((SimpleCursorAdapter)activity.mListview.getAdapter()).notifyDataSetChanged();
mLoading = false;
}
}
public void stopRunning()
{
synchronized(this) {
getLooper().quit();
running = false;
for (WorkerThread thread : mThreadPool) {
if (thread != null) {
thread.stopRunning();
}
}
}
}
private void queueWork(String url) {
queueWork(null, url);
}
private void queueWork(String contactId, String url) {
if (mThreadIndex == mThreadPool.size()) {
mThreadIndex = 0;
}
WorkerThread thread = mThreadPool.get(mThreadIndex++);
if (thread != null) {
thread.queueWork(contactId, url);
}
}
@Override
public void handleMessage(Message msg)
{
if (!running || mLoading) {
return;
} else if (msg.what == LOAD_ALL) {
loadAll();
return;
}
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return;
}
String url = (String) msg.obj;
if (url == null) {
return;
}
queueWork(url);
}
}
private static class DownloadImageHandler extends Handler
{
private final WeakReference<SyncResultsActivity> mActivity;
private boolean running = true;
DownloadImageHandler(SyncResultsActivity activity, Looper looper)
{
super(looper);
mActivity = new WeakReference<SyncResultsActivity>(activity);
}
public void stopRunning()
{
synchronized(this) {
getLooper().quit();
running = false;
}
}
@Override
public void handleMessage(Message msg)
{
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return;
}
final Handler handler = activity.mMainHandler;
if (handler == null) {
return;
}
final SyncMyPixPreferences prefs = new SyncMyPixPreferences(activity.getApplicationContext());
String url = (String) msg.obj;
if (url != null) {
try {
InputStream friend = null;
String filename = Uri.parse(url).getLastPathSegment();
if (activity.mSdCache != null) {
friend = activity.mSdCache.get(filename);
}
// cache miss
if (friend == null) {
friend = Utils.downloadPictureAsStream(url);
}
synchronized(this) {
if (running && friend != null) {
byte[] bytes = Utils.getByteArrayFromInputStream(friend);
friend.close();
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
if (prefs.getCache()) {
activity.mSdCache.add(filename, bytes);
}
Message mainMsg = handler.obtainMessage();
mainMsg.obj = bitmap;
mainMsg.what = msg.what;
handler.sendMessage(mainMsg);
if (!activity.mCache.contains(url)) {
activity.mCache.add(url, bitmap, true);
}
}
}
} catch (UnknownHostException ex) {
ex.printStackTrace();
handler.sendEmptyMessage(MainHandler.UNKNOWN_HOST_ERROR);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static class ResultsListAdapter extends SimpleCursorAdapter
{
public static final class Viewholder {
public String url;
public ImageView image;
public TextView name;
public TextView status;
}
private final WeakReference<SyncResultsActivity> mActivity;
private Bitmap mNeutralFace;
private Bitmap mSadFace;
public ResultsListAdapter(SyncResultsActivity context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
mActivity = new WeakReference<SyncResultsActivity>(context);
// pre-scale images
mNeutralFace = BitmapFactory.decodeResource(context.getResources(), R.drawable.neutral_face);
//mNeutralFace = Bitmap.createScaledBitmap(mNeutralFace, 40, 40, false);
mSadFace = BitmapFactory.decodeResource(context.getResources(), R.drawable.sad_face);
//mSadFace = Bitmap.createScaledBitmap(mSadFace, 40, 40, false);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// use a Viewholder to cache the ImageView and avoid unnecessary findViewById calls
View view = super.newView(context, cursor, parent);
Viewholder holder = new Viewholder();
holder.image = (ImageView) view.findViewById(R.id.contactImage);
holder.name = (TextView) view.findViewById(R.id.text1);
holder.status = (TextView) view.findViewById(R.id.text2);
view.setTag(holder);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Viewholder holder = (Viewholder) view.getTag();
// if (holder == null) {
// return;
// } else {
// view.setTag("");
// }
// do all the binding myself since 1.5 throws a ClassCastException due to Viewholder
//super.bindView(view, context, cursor);
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return;
}
Viewholder holder = (Viewholder) view.getTag();
if (holder == null) {
return;
}
long id = cursor.getLong(cursor.getColumnIndex(Results.CONTACT_ID));
String name = cursor.getString(cursor.getColumnIndex(Results.NAME));
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
url = url != null ? url.trim() : null;
String description = cursor.getString(cursor.getColumnIndex(Results.DESCRIPTION));
holder.name.setText(name);
holder.status.setText(description);
holder.url = url;
// this finds the right view to load the image into
// due to Android object recycling
ImageView image = holder.image;
image.setTag(url);
if (id > 0 && !activity.mCache.contains(url)) {
//if (!activity.mThumbnailHandler.isLoading()) {
//Log.d(TAG, "bindView attempting to load into cache " + url);
Message msg = activity.mThumbnailHandler.obtainMessage();
msg.obj = url;
activity.mThumbnailHandler.sendMessage(msg);
//}
image.setImageBitmap(activity.mCache.getDefaultImage());
} else if (activity.mCache.contains(url)) {
//Log.d(TAG, id + " bindView attempting to get from cache " + url);
image.setImageBitmap(activity.mCache.get(url));
} else if (description.equals(ResultsDescription.NOTFOUND.getDescription(context.getApplicationContext()))) {
image.setImageBitmap(mNeutralFace);
} else {
image.setImageBitmap(mSadFace);
}
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
final SyncResultsActivity activity = mActivity.get();
if (activity == null) {
return null;
}
final ContentResolver resolver = activity.getContentResolver();
if (resolver == null) {
return null;
}
String where = null;
if (constraint != null) {
where = Results.DESCRIPTION + " IN (" + constraint + ")";
}
return resolver.query(Results.CONTENT_URI,
activity.mProjection,
where,
null,
null);
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
mContactUtils = new ContactUtils();
mSdCache = new PhotoCache(getApplicationContext());
Bitmap defaultImage = BitmapFactory.decodeResource(getResources(), R.drawable.default_face);
//mCache.setDefaultImage(Bitmap.createScaledBitmap(defaultImage, 40, 40, false));
mCache.setDefaultImage(defaultImage);
mDbHelper = new SyncMyPixDbHelper(getApplicationContext());
Cursor cursor = managedQuery(Results.CONTENT_URI, mProjection, null, null, Results.DEFAULT_SORT_ORDER);
mProgress = (ProgressBar) findViewById(R.id.progress);
mProgress.setVisibility(View.VISIBLE);
mListview = (ListView) findViewById(R.id.resultList);
final SimpleCursorAdapter adapter = new ResultsListAdapter(
this,
R.layout.resultslistitem,
cursor,
new String[] {Results.NAME, Results.DESCRIPTION },
new int[] { R.id.text1, R.id.text2 } );
mListview.setAdapter(adapter);
mCache.setImageProvider(new ImageProvider() {
public boolean onImageRequired(String url) {
if (mThumbnailHandler != null) {
//Log.d(TAG, "reloading thumbnail");
Message msg = mThumbnailHandler.obtainMessage();
msg.obj = url;
mThumbnailHandler.sendMessage(msg);
return true;
}
return false;
}
});
mCache.setImageListener(new ImageListener() {
public void onImageReady(final String url) {
final ImageView image = (ImageView) mListview.findViewWithTag(url);
// Log.d(TAG, "onImageReady updating image");
runOnUiThread(new Runnable() {
public void run() {
if (mListview == null) return;
if (mCache != null && image != null) {
image.setImageBitmap(mCache.get(url));
} else {
// HACK sometimes the view can't be found, probably already recycled
((SimpleCursorAdapter)mListview.getAdapter()).notifyDataSetChanged();
}
mListview.invalidateViews();
}
});
}
});
mListview.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
return false;
}
});
mListview.setOnItemClickListener(new OnItemClickListener () {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Cursor cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
cursor.moveToPosition(position);
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
if (url != null) {
//setProgressBarIndeterminateVisibility(true);
mProgress.setVisibility(View.VISIBLE);
Message msg = mDownloadHandler.obtainMessage();
msg.what = ZOOM_PIC;
msg.obj = url;
mDownloadHandler.sendMessage(msg);
}
}
});
mListview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
int position = ((AdapterContextMenuInfo)menuInfo).position;
Cursor cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
if (cursor.moveToPosition(position)) {
String id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
String name = cursor.getString(cursor.getColumnIndex(Results.NAME));
if (url != null) {
menu.setHeaderTitle(name);
if (id != null) {
menu.add(0, CONTEXTMENU_VIEW_CONTACT, Menu.NONE, R.string.syncresults_menu_viewsynced);
menu.add(0, CONTEXTMENU_CROP, Menu.NONE, R.string.syncresults_menu_crop);
menu.add(0, CONTEXTMENU_UNLINK, Menu.NONE, R.string.syncresults_menu_unlink);
}
menu.add(0, CONTEXTMENU_SELECT_CONTACT, Menu.NONE, R.string.syncresults_menu_addpicture);
}
}
}
});
mHomeButton = (ImageButton) findViewById(R.id.home);
mHomeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
finish();
}
});
mHelpButton = (ImageButton) findViewById(R.id.help);
mHelpButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.help_link)));
startActivity(i);
}
});
mDeleteButton = (ImageButton) findViewById(R.id.delete);
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DELETE_DIALOG);
}
});
mMainHandler = new MainHandler(this);
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
mContactUtils = new ContactUtils();
mSdCache = new PhotoCache(getApplicationContext());
Bitmap defaultImage = BitmapFactory.decodeResource(getResources(), R.drawable.default_face);
//mCache.setDefaultImage(Bitmap.createScaledBitmap(defaultImage, 40, 40, false));
mCache.setDefaultImage(defaultImage);
mDbHelper = new SyncMyPixDbHelper(getApplicationContext());
Cursor cursor = managedQuery(Results.CONTENT_URI, mProjection, null, null, Results.DEFAULT_SORT_ORDER);
mProgress = (ProgressBar) findViewById(R.id.progress);
mProgress.setVisibility(View.VISIBLE);
mListview = (ListView) findViewById(R.id.resultList);
final SimpleCursorAdapter adapter = new ResultsListAdapter(
this,
R.layout.resultslistitem,
cursor,
new String[] {Results.NAME, Results.DESCRIPTION },
new int[] { R.id.text1, R.id.text2 } );
mListview.setAdapter(adapter);
mCache.setImageProvider(new ImageProvider() {
public boolean onImageRequired(String url) {
if (mThumbnailHandler != null) {
//Log.d(TAG, "reloading thumbnail");
Message msg = mThumbnailHandler.obtainMessage();
msg.obj = url;
mThumbnailHandler.sendMessage(msg);
return true;
}
return false;
}
});
mCache.setImageListener(new ImageListener() {
public void onImageReady(final String url) {
if (mListview == null) return;
final ImageView image = (ImageView) mListview.findViewWithTag(url);
// Log.d(TAG, "onImageReady updating image");
runOnUiThread(new Runnable() {
public void run() {
if (mListview == null) return;
if (mCache != null && image != null) {
image.setImageBitmap(mCache.get(url));
} else {
// HACK sometimes the view can't be found, probably already recycled
((SimpleCursorAdapter)mListview.getAdapter()).notifyDataSetChanged();
}
mListview.invalidateViews();
}
});
}
});
mListview.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
return false;
}
});
mListview.setOnItemClickListener(new OnItemClickListener () {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Cursor cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
cursor.moveToPosition(position);
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
if (url != null) {
//setProgressBarIndeterminateVisibility(true);
mProgress.setVisibility(View.VISIBLE);
Message msg = mDownloadHandler.obtainMessage();
msg.what = ZOOM_PIC;
msg.obj = url;
mDownloadHandler.sendMessage(msg);
}
}
});
mListview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
int position = ((AdapterContextMenuInfo)menuInfo).position;
Cursor cursor = ((SimpleCursorAdapter)mListview.getAdapter()).getCursor();
if (cursor.moveToPosition(position)) {
String id = cursor.getString(cursor.getColumnIndex(Results.CONTACT_ID));
String url = cursor.getString(cursor.getColumnIndex(Results.PIC_URL));
String name = cursor.getString(cursor.getColumnIndex(Results.NAME));
if (url != null) {
menu.setHeaderTitle(name);
if (id != null) {
menu.add(0, CONTEXTMENU_VIEW_CONTACT, Menu.NONE, R.string.syncresults_menu_viewsynced);
menu.add(0, CONTEXTMENU_CROP, Menu.NONE, R.string.syncresults_menu_crop);
menu.add(0, CONTEXTMENU_UNLINK, Menu.NONE, R.string.syncresults_menu_unlink);
}
menu.add(0, CONTEXTMENU_SELECT_CONTACT, Menu.NONE, R.string.syncresults_menu_addpicture);
}
}
}
});
mHomeButton = (ImageButton) findViewById(R.id.home);
mHomeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
finish();
}
});
mHelpButton = (ImageButton) findViewById(R.id.help);
mHelpButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.help_link)));
startActivity(i);
}
});
mDeleteButton = (ImageButton) findViewById(R.id.delete);
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DELETE_DIALOG);
}
});
mMainHandler = new MainHandler(this);
}
|
diff --git a/src/main/java/com/financial/pyramid/web/TabsController.java b/src/main/java/com/financial/pyramid/web/TabsController.java
index 3a188c5..13a91c1 100644
--- a/src/main/java/com/financial/pyramid/web/TabsController.java
+++ b/src/main/java/com/financial/pyramid/web/TabsController.java
@@ -1,151 +1,154 @@
package com.financial.pyramid.web;
import com.financial.pyramid.domain.Contact;
import com.financial.pyramid.domain.News;
import com.financial.pyramid.domain.User;
import com.financial.pyramid.domain.Video;
import com.financial.pyramid.service.*;
import com.financial.pyramid.settings.Setting;
import com.financial.pyramid.utils.Session;
import com.financial.pyramid.web.form.AuthenticationForm;
import com.financial.pyramid.web.form.InvitationForm;
import com.financial.pyramid.web.form.PageForm;
import com.financial.pyramid.web.form.QueryForm;
import com.financial.pyramid.web.tree.BinaryTree;
import com.financial.pyramid.web.tree.BinaryTreeWidget;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* User: Danil
* Date: 05.06.13
* Time: 23:03
*/
@Controller
@RequestMapping("/pyramid")
public class TabsController extends AbstractController {
@Autowired
protected VideoService videoService;
@Autowired
protected NewsService newsService;
@Autowired
protected SettingsService settingsService;
@Autowired
protected UserService userService;
@Autowired
protected ContactService contactService;
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(ModelMap model) {
return "/tabs/home";
}
@RequestMapping(value = "/training", method = RequestMethod.GET)
public String training(ModelMap model) {
List<Video> videos = videoService.find();
Video video = videos != null && videos.size() > 0 ? videos.get(0) : null;
String defaultVideo = settingsService.getProperty(Setting.YOU_TUBE_VIDEO_URL, video != null ? video.getExternalId() : null);
model.addAttribute("defaultVideo", defaultVideo);
model.addAttribute("videos", videos);
return "/tabs/training";
}
@RequestMapping(value = "/news", method = RequestMethod.GET)
public String news(ModelMap model, @RequestParam(value = "page", defaultValue = "1") Integer page) {
PageForm<News> newsForm = new PageForm<News>();
QueryForm form = new QueryForm();
form.setSort("date");
form.setOrder("desc");
form.setPage(page);
int total = newsService.find().size();
List<News> list = newsService.findByQuery(form);
newsForm.setPage(page);
newsForm.setRows(list);
newsForm.setTotal(total);
model.addAttribute("newsForm", newsForm);
return "/tabs/news";
}
@RequestMapping(value = "/office", method = RequestMethod.GET)
public String office(ModelMap model, HttpSession session, HttpServletRequest request) {
Authentication authentication = Session.getAuthentication();
if (authentication.getPrincipal() instanceof UserDetails) {
User currentUser = (User) authentication.getDetails();
User user = userService.findById(currentUser.getId());
BinaryTree tree = userService.getBinaryTree(currentUser.getEmail());
BinaryTreeWidget widget = new BinaryTreeWidget(tree);
widget.setStubText(localizationService.translate("user.add"));
while (tree != null) {
widget.addUserToWidget(tree);
if (tree.isChild()) {
tree = tree.getLeft() != null ? tree.getLeft() : tree.getRight();
} else {
while (tree.itIsRight() || (tree.isParent() && !tree.getParent().isRight())) {
tree = tree.getParent();
}
tree = tree.isParent() ? tree.getParent().getRight() : null;
}
}
- Calendar c = Calendar.getInstance();
- int daysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
+ int daysLeft = 0;
+ int daysMonth = 0;
+ Date activationStartDate = user.getAccount().getDateActivated();
Date activationEndDate = user.getAccount().getDateExpired();
Double earningsAmount = user.getAccount().getEarningsSum();
double earningsSum = new BigDecimal(earningsAmount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
- int daysLeft = 0;
+ if (activationStartDate != null){
+ daysMonth = Days.daysBetween(new DateTime(activationStartDate), new DateTime(activationEndDate)).getDays();
+ }
if (activationEndDate != null) {
daysLeft = Days.daysBetween(new DateTime(), new DateTime(activationEndDate)).getDays();
}
model.addAttribute("daysLeft", daysLeft);
- model.addAttribute("monthDays", daysInMonth);
+ model.addAttribute("monthDays", daysMonth);
model.addAttribute("earningsSum", earningsSum);
model.addAttribute("userBinaryTree", widget.getRootElement());
model.addAttribute("invitation", new InvitationForm());
return "/tabs/user/private-office";
}
model.addAttribute("authentication", new AuthenticationForm());
return "/tabs/login";
}
@RequestMapping(value = "/about", method = RequestMethod.GET)
public String about(ModelMap model) {
return "/tabs/about";
}
@RequestMapping(value = "/contacts", method = RequestMethod.GET)
public String contacts(ModelMap model) {
List<Contact> contacts = contactService.findAll();
String address = settingsService.getProperty(Setting.CONTACTS_ADDRESS);
String phones = settingsService.getProperty(Setting.CONTACTS_PHONES);
String mapUrl = settingsService.getProperty(Setting.CONTACTS_MAP_URL);
String fullMapUrl = settingsService.getProperty(Setting.CONTACTS_MAP_HREF);
model.addAttribute("address", address);
model.addAttribute("phones", phones);
model.addAttribute("mapUrl", mapUrl);
model.addAttribute("showFullMapUrl", fullMapUrl);
model.addAttribute("contacts", contacts);
return "/tabs/contacts";
}
}
| false | true | public String office(ModelMap model, HttpSession session, HttpServletRequest request) {
Authentication authentication = Session.getAuthentication();
if (authentication.getPrincipal() instanceof UserDetails) {
User currentUser = (User) authentication.getDetails();
User user = userService.findById(currentUser.getId());
BinaryTree tree = userService.getBinaryTree(currentUser.getEmail());
BinaryTreeWidget widget = new BinaryTreeWidget(tree);
widget.setStubText(localizationService.translate("user.add"));
while (tree != null) {
widget.addUserToWidget(tree);
if (tree.isChild()) {
tree = tree.getLeft() != null ? tree.getLeft() : tree.getRight();
} else {
while (tree.itIsRight() || (tree.isParent() && !tree.getParent().isRight())) {
tree = tree.getParent();
}
tree = tree.isParent() ? tree.getParent().getRight() : null;
}
}
Calendar c = Calendar.getInstance();
int daysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
Date activationEndDate = user.getAccount().getDateExpired();
Double earningsAmount = user.getAccount().getEarningsSum();
double earningsSum = new BigDecimal(earningsAmount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
int daysLeft = 0;
if (activationEndDate != null) {
daysLeft = Days.daysBetween(new DateTime(), new DateTime(activationEndDate)).getDays();
}
model.addAttribute("daysLeft", daysLeft);
model.addAttribute("monthDays", daysInMonth);
model.addAttribute("earningsSum", earningsSum);
model.addAttribute("userBinaryTree", widget.getRootElement());
model.addAttribute("invitation", new InvitationForm());
return "/tabs/user/private-office";
}
model.addAttribute("authentication", new AuthenticationForm());
return "/tabs/login";
}
| public String office(ModelMap model, HttpSession session, HttpServletRequest request) {
Authentication authentication = Session.getAuthentication();
if (authentication.getPrincipal() instanceof UserDetails) {
User currentUser = (User) authentication.getDetails();
User user = userService.findById(currentUser.getId());
BinaryTree tree = userService.getBinaryTree(currentUser.getEmail());
BinaryTreeWidget widget = new BinaryTreeWidget(tree);
widget.setStubText(localizationService.translate("user.add"));
while (tree != null) {
widget.addUserToWidget(tree);
if (tree.isChild()) {
tree = tree.getLeft() != null ? tree.getLeft() : tree.getRight();
} else {
while (tree.itIsRight() || (tree.isParent() && !tree.getParent().isRight())) {
tree = tree.getParent();
}
tree = tree.isParent() ? tree.getParent().getRight() : null;
}
}
int daysLeft = 0;
int daysMonth = 0;
Date activationStartDate = user.getAccount().getDateActivated();
Date activationEndDate = user.getAccount().getDateExpired();
Double earningsAmount = user.getAccount().getEarningsSum();
double earningsSum = new BigDecimal(earningsAmount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if (activationStartDate != null){
daysMonth = Days.daysBetween(new DateTime(activationStartDate), new DateTime(activationEndDate)).getDays();
}
if (activationEndDate != null) {
daysLeft = Days.daysBetween(new DateTime(), new DateTime(activationEndDate)).getDays();
}
model.addAttribute("daysLeft", daysLeft);
model.addAttribute("monthDays", daysMonth);
model.addAttribute("earningsSum", earningsSum);
model.addAttribute("userBinaryTree", widget.getRootElement());
model.addAttribute("invitation", new InvitationForm());
return "/tabs/user/private-office";
}
model.addAttribute("authentication", new AuthenticationForm());
return "/tabs/login";
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
index f85629e67..f867c3197 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
@@ -1,284 +1,284 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies 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:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.DatePicker;
import org.eclipse.mylyn.internal.provisional.commons.ui.DateSelectionDialog;
import org.eclipse.mylyn.internal.provisional.commons.ui.WorkbenchUtil;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.DateRange;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil;
import org.eclipse.mylyn.internal.tasks.core.WeekDateRange;
import org.eclipse.mylyn.tasks.core.IRepositoryElement;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.swt.widgets.Shell;
/**
* @author Rob Elves
* @author Mik Kersten
*/
public class ScheduleTaskMenuContributor implements IDynamicSubMenuContributor {
private AbstractTask singleTaskSelection;
private final List<IRepositoryElement> taskListElementsToSchedule = new ArrayList<IRepositoryElement>();
public MenuManager getSubMenuManager(final List<IRepositoryElement> selectedElements) {
singleTaskSelection = null;
taskListElementsToSchedule.clear();
final MenuManager subMenuManager = new MenuManager(Messages.ScheduleTaskMenuContributor_Schedule_for);
if (selectedElements.size() == 1) {
IRepositoryElement selectedElement = selectedElements.get(0);
if (selectedElement instanceof ITask) {
singleTaskSelection = (AbstractTask) selectedElement;
}
}
for (IRepositoryElement selectedElement : selectedElements) {
if (selectedElement instanceof ITask) {
taskListElementsToSchedule.add(selectedElement);
}
}
if (selectionIncludesCompletedTasks()) {
Action action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Cannot_schedule_completed_tasks);
action.setEnabled(false);
subMenuManager.add(action);
return subMenuManager;
}
WeekDateRange week = TaskActivityUtil.getCurrentWeek();
int days = 0;
for (DateRange day : week.getDaysOfWeek()) {
if (day.includes(TaskActivityUtil.getCalendar())) {
days++;
// Today
Action action = createDateSelectionAction(day, CommonImages.SCHEDULE_DAY);
subMenuManager.add(action);
// Special case: Over scheduled tasks always 'scheduled' for today
if (singleTaskSelection != null && isPastReminder(singleTaskSelection)) {
action.setChecked(true);
}
} else if (day.after(TaskActivityUtil.getCalendar())) {
days++;
// Week Days
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
}
// Next week days
int toAdd = 7 - days;
WeekDateRange nextWeek = TaskActivityUtil.getNextWeek();
for (int x = 0; x < toAdd; x++) {
int next = TasksUiPlugin.getTaskActivityManager().getWeekStartDay() + x;
if (next > Calendar.SATURDAY) {
next = x;
}
DateRange day = nextWeek.getDayOfWeek(next);
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
// This Week
Action action = createDateSelectionAction(week, CommonImages.SCHEDULE_WEEK);
subMenuManager.add(action);
// Special case: This Week holds previous weeks' scheduled tasks
if (isThisWeek(singleTaskSelection)) {
// Tasks scheduled for 'someday' float into this week
action.setChecked(true);
}
// Next Week
action = createDateSelectionAction(week.next(), null);
subMenuManager.add(action);
// Two Weeks
action = createDateSelectionAction(week.next().next(), null);
subMenuManager.add(action);
if (singleTaskSelection != null && getScheduledForDate(singleTaskSelection) != null) {
// Update Two Weeks
DateRange range = getScheduledForDate(singleTaskSelection);
if (range.equals(TaskActivityUtil.getNextWeek().next())
|| TaskActivityUtil.getNextWeek().next().includes(range)) {
action.setChecked(true);
}
// Future
if (getScheduledForDate(singleTaskSelection).after(week.next().next().getEndDate())
&& !(getScheduledForDate(singleTaskSelection) instanceof WeekDateRange)) {
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(Messages.ScheduleTaskMenuContributor_Future);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
// Date Selection Dialog
action = new Action() {
@Override
public void run() {
Calendar theCalendar = TaskActivityUtil.getCalendar();
if (getScheduledForDate(singleTaskSelection) != null) {
theCalendar.setTime(getScheduledForDate(singleTaskSelection).getStartDate().getTime());
}
Shell shell = null;
- if (subMenuManager != null && subMenuManager.getMenu() != null) {
+ if (subMenuManager != null && subMenuManager.getMenu() != null && subMenuManager.getMenu().isDisposed()) {
// we should try to use the same shell that the menu was created with
// so that it shows up on top of that shell correctly
shell = subMenuManager.getMenu().getShell();
}
if (shell == null) {
shell = WorkbenchUtil.getShell();
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(shell, theCalendar,
DatePicker.TITLE_DIALOG, false, TasksUiPlugin.getDefault().getPreferenceStore().getInt(
ITasksUiPreferenceConstants.PLANNING_ENDHOUR));
int result = reminderDialog.open();
if (result == Window.OK) {
DateRange range = null;
if (reminderDialog.getDate() != null) {
range = TaskActivityUtil.getDayOf(reminderDialog.getDate());
}
setScheduledDate(range);
}
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Choose_Date_);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
setScheduledDate(null);
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Not_Scheduled);
action.setChecked(false);
if (singleTaskSelection != null) {
if (getScheduledForDate(singleTaskSelection) == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
private boolean isThisWeek(AbstractTask task) {
return task != null && task.getScheduledForDate() != null
&& task.getScheduledForDate() instanceof WeekDateRange
&& task.getScheduledForDate().isBefore(TaskActivityUtil.getCurrentWeek());
}
private boolean selectionIncludesCompletedTasks() {
if (singleTaskSelection instanceof AbstractTask) {
if ((singleTaskSelection).isCompleted()) {
return true;
}
}
if (taskListElementsToSchedule.size() > 0) {
for (IRepositoryElement task : taskListElementsToSchedule) {
if (task instanceof AbstractTask) {
if (((AbstractTask) task).isCompleted()) {
return true;
}
}
}
}
return false;
}
private Action createDateSelectionAction(final DateRange dateContainer, ImageDescriptor imageDescriptor) {
Action action = new Action() {
@Override
public void run() {
setScheduledDate(dateContainer);
}
};
action.setText(dateContainer.toString());
action.setImageDescriptor(imageDescriptor);
action.setEnabled(canSchedule());
DateRange scheduledDate = getScheduledForDate(singleTaskSelection);
if (scheduledDate != null) {
action.setChecked(dateContainer.equals(scheduledDate));
}
return action;
}
private boolean canSchedule() {
if (taskListElementsToSchedule.size() == 0) {
return true;
} else if (singleTaskSelection instanceof ITask) {
return ((!(singleTaskSelection).isCompleted()) || taskListElementsToSchedule.size() > 0);
} else {
return taskListElementsToSchedule.size() > 0;
}
}
protected void setScheduledDate(DateRange dateContainer) {
for (IRepositoryElement element : taskListElementsToSchedule) {
if (element instanceof AbstractTask) {
AbstractTask task = (AbstractTask) element;
if (dateContainer != null) {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, dateContainer);
} else {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, null);
}
}
}
}
protected DateRange getScheduledForDate(final AbstractTask selectedTask) {
if (selectedTask != null) {
return selectedTask.getScheduledForDate();
}
return null;
}
private boolean isPastReminder(AbstractTask task) {
return TasksUiPlugin.getTaskActivityManager().isPastReminder(task);
}
}
| true | true | public MenuManager getSubMenuManager(final List<IRepositoryElement> selectedElements) {
singleTaskSelection = null;
taskListElementsToSchedule.clear();
final MenuManager subMenuManager = new MenuManager(Messages.ScheduleTaskMenuContributor_Schedule_for);
if (selectedElements.size() == 1) {
IRepositoryElement selectedElement = selectedElements.get(0);
if (selectedElement instanceof ITask) {
singleTaskSelection = (AbstractTask) selectedElement;
}
}
for (IRepositoryElement selectedElement : selectedElements) {
if (selectedElement instanceof ITask) {
taskListElementsToSchedule.add(selectedElement);
}
}
if (selectionIncludesCompletedTasks()) {
Action action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Cannot_schedule_completed_tasks);
action.setEnabled(false);
subMenuManager.add(action);
return subMenuManager;
}
WeekDateRange week = TaskActivityUtil.getCurrentWeek();
int days = 0;
for (DateRange day : week.getDaysOfWeek()) {
if (day.includes(TaskActivityUtil.getCalendar())) {
days++;
// Today
Action action = createDateSelectionAction(day, CommonImages.SCHEDULE_DAY);
subMenuManager.add(action);
// Special case: Over scheduled tasks always 'scheduled' for today
if (singleTaskSelection != null && isPastReminder(singleTaskSelection)) {
action.setChecked(true);
}
} else if (day.after(TaskActivityUtil.getCalendar())) {
days++;
// Week Days
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
}
// Next week days
int toAdd = 7 - days;
WeekDateRange nextWeek = TaskActivityUtil.getNextWeek();
for (int x = 0; x < toAdd; x++) {
int next = TasksUiPlugin.getTaskActivityManager().getWeekStartDay() + x;
if (next > Calendar.SATURDAY) {
next = x;
}
DateRange day = nextWeek.getDayOfWeek(next);
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
// This Week
Action action = createDateSelectionAction(week, CommonImages.SCHEDULE_WEEK);
subMenuManager.add(action);
// Special case: This Week holds previous weeks' scheduled tasks
if (isThisWeek(singleTaskSelection)) {
// Tasks scheduled for 'someday' float into this week
action.setChecked(true);
}
// Next Week
action = createDateSelectionAction(week.next(), null);
subMenuManager.add(action);
// Two Weeks
action = createDateSelectionAction(week.next().next(), null);
subMenuManager.add(action);
if (singleTaskSelection != null && getScheduledForDate(singleTaskSelection) != null) {
// Update Two Weeks
DateRange range = getScheduledForDate(singleTaskSelection);
if (range.equals(TaskActivityUtil.getNextWeek().next())
|| TaskActivityUtil.getNextWeek().next().includes(range)) {
action.setChecked(true);
}
// Future
if (getScheduledForDate(singleTaskSelection).after(week.next().next().getEndDate())
&& !(getScheduledForDate(singleTaskSelection) instanceof WeekDateRange)) {
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(Messages.ScheduleTaskMenuContributor_Future);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
// Date Selection Dialog
action = new Action() {
@Override
public void run() {
Calendar theCalendar = TaskActivityUtil.getCalendar();
if (getScheduledForDate(singleTaskSelection) != null) {
theCalendar.setTime(getScheduledForDate(singleTaskSelection).getStartDate().getTime());
}
Shell shell = null;
if (subMenuManager != null && subMenuManager.getMenu() != null) {
// we should try to use the same shell that the menu was created with
// so that it shows up on top of that shell correctly
shell = subMenuManager.getMenu().getShell();
}
if (shell == null) {
shell = WorkbenchUtil.getShell();
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(shell, theCalendar,
DatePicker.TITLE_DIALOG, false, TasksUiPlugin.getDefault().getPreferenceStore().getInt(
ITasksUiPreferenceConstants.PLANNING_ENDHOUR));
int result = reminderDialog.open();
if (result == Window.OK) {
DateRange range = null;
if (reminderDialog.getDate() != null) {
range = TaskActivityUtil.getDayOf(reminderDialog.getDate());
}
setScheduledDate(range);
}
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Choose_Date_);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
setScheduledDate(null);
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Not_Scheduled);
action.setChecked(false);
if (singleTaskSelection != null) {
if (getScheduledForDate(singleTaskSelection) == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
| public MenuManager getSubMenuManager(final List<IRepositoryElement> selectedElements) {
singleTaskSelection = null;
taskListElementsToSchedule.clear();
final MenuManager subMenuManager = new MenuManager(Messages.ScheduleTaskMenuContributor_Schedule_for);
if (selectedElements.size() == 1) {
IRepositoryElement selectedElement = selectedElements.get(0);
if (selectedElement instanceof ITask) {
singleTaskSelection = (AbstractTask) selectedElement;
}
}
for (IRepositoryElement selectedElement : selectedElements) {
if (selectedElement instanceof ITask) {
taskListElementsToSchedule.add(selectedElement);
}
}
if (selectionIncludesCompletedTasks()) {
Action action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Cannot_schedule_completed_tasks);
action.setEnabled(false);
subMenuManager.add(action);
return subMenuManager;
}
WeekDateRange week = TaskActivityUtil.getCurrentWeek();
int days = 0;
for (DateRange day : week.getDaysOfWeek()) {
if (day.includes(TaskActivityUtil.getCalendar())) {
days++;
// Today
Action action = createDateSelectionAction(day, CommonImages.SCHEDULE_DAY);
subMenuManager.add(action);
// Special case: Over scheduled tasks always 'scheduled' for today
if (singleTaskSelection != null && isPastReminder(singleTaskSelection)) {
action.setChecked(true);
}
} else if (day.after(TaskActivityUtil.getCalendar())) {
days++;
// Week Days
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
}
// Next week days
int toAdd = 7 - days;
WeekDateRange nextWeek = TaskActivityUtil.getNextWeek();
for (int x = 0; x < toAdd; x++) {
int next = TasksUiPlugin.getTaskActivityManager().getWeekStartDay() + x;
if (next > Calendar.SATURDAY) {
next = x;
}
DateRange day = nextWeek.getDayOfWeek(next);
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
// This Week
Action action = createDateSelectionAction(week, CommonImages.SCHEDULE_WEEK);
subMenuManager.add(action);
// Special case: This Week holds previous weeks' scheduled tasks
if (isThisWeek(singleTaskSelection)) {
// Tasks scheduled for 'someday' float into this week
action.setChecked(true);
}
// Next Week
action = createDateSelectionAction(week.next(), null);
subMenuManager.add(action);
// Two Weeks
action = createDateSelectionAction(week.next().next(), null);
subMenuManager.add(action);
if (singleTaskSelection != null && getScheduledForDate(singleTaskSelection) != null) {
// Update Two Weeks
DateRange range = getScheduledForDate(singleTaskSelection);
if (range.equals(TaskActivityUtil.getNextWeek().next())
|| TaskActivityUtil.getNextWeek().next().includes(range)) {
action.setChecked(true);
}
// Future
if (getScheduledForDate(singleTaskSelection).after(week.next().next().getEndDate())
&& !(getScheduledForDate(singleTaskSelection) instanceof WeekDateRange)) {
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(Messages.ScheduleTaskMenuContributor_Future);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
// Date Selection Dialog
action = new Action() {
@Override
public void run() {
Calendar theCalendar = TaskActivityUtil.getCalendar();
if (getScheduledForDate(singleTaskSelection) != null) {
theCalendar.setTime(getScheduledForDate(singleTaskSelection).getStartDate().getTime());
}
Shell shell = null;
if (subMenuManager != null && subMenuManager.getMenu() != null && subMenuManager.getMenu().isDisposed()) {
// we should try to use the same shell that the menu was created with
// so that it shows up on top of that shell correctly
shell = subMenuManager.getMenu().getShell();
}
if (shell == null) {
shell = WorkbenchUtil.getShell();
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(shell, theCalendar,
DatePicker.TITLE_DIALOG, false, TasksUiPlugin.getDefault().getPreferenceStore().getInt(
ITasksUiPreferenceConstants.PLANNING_ENDHOUR));
int result = reminderDialog.open();
if (result == Window.OK) {
DateRange range = null;
if (reminderDialog.getDate() != null) {
range = TaskActivityUtil.getDayOf(reminderDialog.getDate());
}
setScheduledDate(range);
}
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Choose_Date_);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
setScheduledDate(null);
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Not_Scheduled);
action.setChecked(false);
if (singleTaskSelection != null) {
if (getScheduledForDate(singleTaskSelection) == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
|
diff --git a/src/org/apache/ws/security/message/WSSecEncrypt.java b/src/org/apache/ws/security/message/WSSecEncrypt.java
index 031b53b67..7eee1908f 100644
--- a/src/org/apache/ws/security/message/WSSecEncrypt.java
+++ b/src/org/apache/ws/security/message/WSSecEncrypt.java
@@ -1,762 +1,763 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.ws.security.message;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.SOAPConstants;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSEncryptionPart;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.message.token.Reference;
import org.apache.ws.security.message.token.SecurityTokenReference;
import org.apache.ws.security.util.Base64;
import org.apache.ws.security.util.WSSecurityUtil;
import org.apache.xml.security.encryption.EncryptedData;
import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.encryption.XMLEncryptionException;
import org.apache.xml.security.keys.KeyInfo;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Vector;
/**
* Encrypts a parts of a message according to WS Specification, X509 profile,
* and adds the encryption data.
*
* @author Davanum Srinivas ([email protected]).
* @author Werner Dittmann ([email protected]).
*/
public class WSSecEncrypt extends WSSecEncryptedKey {
private static Log log = LogFactory.getLog(WSSecEncrypt.class.getName());
private static Log tlog = LogFactory.getLog("org.apache.ws.security.TIME");
protected String symEncAlgo = WSConstants.AES_128;
protected String encCanonAlgo = null;
protected byte[] embeddedKey = null;
protected String embeddedKeyName = null;
protected boolean useKeyIdentifier;
/**
* Symmetric key used in the EncrytpedKey.
*/
protected SecretKey symmetricKey = null;
/**
* SecurityTokenReference to be inserted into EncryptedData/keyInfo element.
*/
protected SecurityTokenReference securityTokenReference = null;
/**
* Indicates whether to encrypt the symmetric key into an EncryptedKey
* or not.
*/
private boolean encryptSymmKey = true;
/**
* Custom reference value
*/
private String customReferenceValue;
/**
* Constructor.
*/
public WSSecEncrypt() {
}
/**
* Sets the key to use during embedded encryption.
*
* <p/>
*
* @param key
* to use during encryption. The key must fit the selected
* symmetrical encryption algorithm
*/
public void setKey(byte[] key) {
this.embeddedKey = key;
}
/**
* Sets the algorithm to encode the symmetric key.
*
* Default is the <code>WSConstants.KEYTRANSPORT_RSA15</code> algorithm.
*
* @param keyEnc
* specifies the key encoding algorithm.
* @see WSConstants#KEYTRANSPORT_RSA15
* @see WSConstants#KEYTRANSPORT_RSAOEP
*/
public void setKeyEnc(String keyEnc) {
keyEncAlgo = keyEnc;
}
/**
* Set the key name for EMBEDDED_KEYNAME
*
* @param embeddedKeyName
*/
public void setEmbeddedKeyName(String embeddedKeyName) {
this.embeddedKeyName = embeddedKeyName;
}
/**
* Set this true if a key identifier must be used in the KeyInfo
*
* @param useKeyIdentifier
*/
public void setUseKeyIdentifier(boolean useKeyIdentifier) {
this.useKeyIdentifier = useKeyIdentifier;
}
/**
* Set the name of the symmetric encryption algorithm to use.
*
* This encryption algorithm is used to encrypt the data. If the algorithm
* is not set then AES128 is used. Refer to WSConstants which algorithms are
* supported.
*
* @param algo
* Is the name of the encryption algorithm
* @see WSConstants#TRIPLE_DES
* @see WSConstants#AES_128
* @see WSConstants#AES_192
* @see WSConstants#AES_256
*/
public void setSymmetricEncAlgorithm(String algo) {
symEncAlgo = algo;
}
/**
* Set the name of an optional canonicalization algorithm to use before
* encryption.
*
* This c14n algorithm is used to serialize the data before encryption. If
* the algorithm is not set then a standard serialization is used (provided
* by XMLCipher, usually a XMLSerializer according to DOM 3 specification).
*
* @param algo
* Is the name of the canonicalization algorithm
*/
public void setEncCanonicalization(String algo) {
encCanonAlgo = algo;
}
/**
* Get the name of symmetric encryption algorithm to use.
*
* The name of the encryption algorithm to encrypt the data, i.e. the SOAP
* Body. Refer to WSConstants which algorithms are supported.
*
* @return the name of the currently selected symmetric encryption algorithm
* @see WSConstants#TRIPLE_DES
* @see WSConstants#AES_128
* @see WSConstants#AES_192
* @see WSConstants#AES_256
*/
public String getSymmetricEncAlgorithm() {
return symEncAlgo;
}
/**
* Returns if Key Identifiers should be used in KeyInfo
* @return
*/
public boolean getUseKeyIdentifier() {
return useKeyIdentifier;
}
/**
* Initialize a WSSec Encrypt.
*
* The method prepares and initializes a WSSec Encrypt structure after the
* relevant information was set. After preparation of the token references
* can be added and encrypted.
*
* </p>
*
* This method does not add any element to the security header. This must be
* done explicitly.
*
* @param doc
* The SOAP envelope as <code>Document</code>
* @param crypto
* An instance of the Crypto API to handle keystore and
* certificates
* @throws WSSecurityException
*/
public void prepare(Document doc, Crypto crypto) throws WSSecurityException {
document = doc;
/*
* If no external key (symmetricalKey) was set generate an encryption
* key (session key) for this Encrypt element. This key will be
* encrypted using the public key of the receiver
*/
if(this.ephemeralKey == null) {
if (symmetricKey == null) {
KeyGenerator keyGen = getKeyGenerator();
this.symmetricKey = keyGen.generateKey();
}
this.ephemeralKey = this.symmetricKey.getEncoded();
}
if (this.symmetricKey == null) {
this.symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo,
this.ephemeralKey);
}
/*
* Get the certificate that contains the public key for the public key
* algorithm that will encrypt the generated symmetric (session) key.
*/
if(this.encryptSymmKey) {
X509Certificate remoteCert = null;
if (useThisCert != null) {
remoteCert = useThisCert;
} else {
X509Certificate[] certs = crypto.getCertificates(user);
if (certs == null || certs.length <= 0) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"invalidX509Data", new Object[] { "for Encryption" });
}
remoteCert = certs[0];
}
prepareInternal(this.ephemeralKey, remoteCert, crypto);
}
}
/**
* Builds the SOAP envelope with encrypted Body and adds encrypted key.
*
* This is a convenience method and for backward compatibility. The method
* calls the single function methods in order to perform a <i>one shot
* encryption</i>. This method is compatible with the build method of the
* previous version with the exception of the additional WSSecHeader
* parameter.
*
* @param doc
* the SOAP envelope as <code>Document</code> with plain text
* Body
* @param crypto
* an instance of the Crypto API to handle keystore and
* Certificates
* @param secHeader
* the security header element to hold the encrypted key element.
* @return the SOAP envelope with encrypted Body as <code>Document
* </code>
* @throws WSSecurityException
*/
public Document build(Document doc, Crypto crypto, WSSecHeader secHeader)
throws WSSecurityException {
doDebug = log.isDebugEnabled();
if (keyIdentifierType == WSConstants.EMBEDDED_KEYNAME
|| keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
return buildEmbedded(doc, crypto, secHeader);
}
if (doDebug) {
log.debug("Beginning Encryption...");
}
prepare(doc, crypto);
SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope);
if (parts == null) {
parts = new Vector();
WSEncryptionPart encP = new WSEncryptionPart(soapConstants
.getBodyQName().getLocalPart(), soapConstants
.getEnvelopeURI(), "Content");
parts.add(encP);
}
Element refs = encryptForInternalRef(null, parts);
addInternalRefElement(refs);
prependToHeader(secHeader);
if (bstToken != null) {
prependBSTElementToHeader(secHeader);
}
log.debug("Encryption complete.");
return doc;
}
/**
* Encrypt one or more parts or elements of the message (internal).
*
* This method takes a vector of <code>WSEncryptionPart</code> object that
* contain information about the elements to encrypt. The method call the
* encryption method, takes the reference information generated during
* encryption and add this to the <code>xenc:Reference</code> element.
* This method can be called after <code>prepare()</code> and can be
* called multiple times to encrypt a number of parts or elements.
*
* </p>
*
* The method generates a <code>xenc:Reference</code> element that <i>must</i>
* be added to this token. See <code>addInternalRefElement()</code>.
*
* </p>
*
* If the <code>dataRef</code> parameter is <code>null</code> the method
* creates and initializes a new Reference element.
*
* @param dataRef
* A <code>xenc:Reference</code> element or <code>null</code>
* @param references
* A vector containing WSEncryptionPart objects
* @return Returns the updated <code>xenc:Reference</code> element
* @throws WSSecurityException
*/
public Element encryptForInternalRef(Element dataRef, Vector references)
throws WSSecurityException {
Vector encDataRefs = doEncryption(document, this.symmetricKey,
references);
Element referenceList = dataRef;
if (referenceList == null) {
referenceList = document.createElementNS(WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":ReferenceList");
}
createDataRefList(document, referenceList, encDataRefs);
return referenceList;
}
/**
* Encrypt one or more parts or elements of the message (external).
*
* This method takes a vector of <code>WSEncryptionPart</code> object that
* contain information about the elements to encrypt. The method call the
* encryption method, takes the reference information generated during
* encryption and add this to the <code>xenc:Reference</code> element.
* This method can be called after <code>prepare()</code> and can be
* called multiple times to encrypt a number of parts or elements.
*
* </p>
*
* The method generates a <code>xenc:Reference</code> element that <i>must</i>
* be added to the SecurityHeader. See <code>addExternalRefElement()</code>.
*
* </p>
*
* If the <code>dataRef</code> parameter is <code>null</code> the method
* creates and initializes a new Reference element.
*
* @param dataRef
* A <code>xenc:Reference</code> element or <code>null</code>
* @param references
* A vector containing WSEncryptionPart objects
* @return Returns the updated <code>xenc:Reference</code> element
* @throws WSSecurityException
*/
public Element encryptForExternalRef(Element dataRef, Vector references)
throws WSSecurityException {
Vector encDataRefs = doEncryption(document, this.symmetricKey,
references);
Element referenceList = dataRef;
if (referenceList == null) {
referenceList = document.createElementNS(WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":ReferenceList");
}
createDataRefList(document, referenceList, encDataRefs);
return referenceList;
}
/**
* Adds the internal Reference element to this Encrypt data.
*
* The reference element <i>must</i> be created by the
* <code>encryptForInternalRef()</code> method. The reference element is
* added to the <code>EncryptedKey</code> element of this encrypt block.
*
* @param dataRef
* The internal <code>enc:Reference</code> element
*/
public void addInternalRefElement(Element dataRef) {
WSSecurityUtil.appendChildElement(document, encryptedKeyElement, dataRef);
}
/**
* Adds (prepends) the external Reference element to the Security header.
*
* The reference element <i>must</i> be created by the
* <code>encryptForExternalRef() </code> method. The method prepends the
* reference element in the SecurityHeader.
*
* @param dataRef
* The external <code>enc:Reference</code> element
* @param secHeader
* The security header.
*/
public void addExternalRefElement(Element dataRef, WSSecHeader secHeader) {
WSSecurityUtil.prependChildElement(document, secHeader
.getSecurityHeader(), dataRef, false);
}
private Vector doEncryption(Document doc, SecretKey secretKey,
Vector references) throws WSSecurityException {
KeyInfo keyInfo = null;
// Prepare KeyInfo if useKeyIdentifier is set
if ( useKeyIdentifier &&
keyIdentifierType == WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER) {
keyInfo = new KeyInfo(document);
SecurityTokenReference secToken = new SecurityTokenReference(document);
if(this.customReferenceValue != null) {
secToken.setKeyIdentifierEncKeySHA1(this.customReferenceValue);
} else {
secToken.setKeyIdentifierEncKeySHA1(getSHA1(encryptedEphemeralKey));
}
keyInfo.addUnknownElement(secToken.getElement());
}
return doEncryption(doc, secretKey, keyInfo, references);
}
private Vector doEncryption(Document doc, SecretKey secretKey,
KeyInfo keyInfo, Vector references) throws WSSecurityException {
XMLCipher xmlCipher = null;
try {
xmlCipher = XMLCipher.getInstance(symEncAlgo);
} catch (XMLEncryptionException e3) {
throw new WSSecurityException(
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3);
}
Vector encDataRef = new Vector();
boolean cloneKeyInfo = false;
for (int part = 0; part < references.size(); part++) {
WSEncryptionPart encPart = (WSEncryptionPart) references.get(part);
String idToEnc = encPart.getId();
String elemName = encPart.getName();
String nmSpace = encPart.getNamespace();
String modifier = encPart.getEncModifier();
/*
* Third step: get the data to encrypt.
*
*/
Element body = null;
if (idToEnc != null) {
body = WSSecurityUtil.findElementById(document
.getDocumentElement(), idToEnc, WSConstants.WSU_NS);
if (body == null) {
body = WSSecurityUtil.findElementById(document
.getDocumentElement(), idToEnc, null);
}
} else {
body = (Element) WSSecurityUtil.findElement(document, elemName,
nmSpace);
}
if (body == null) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"noEncElement", new Object[] { "{" + nmSpace + "}"
+ elemName });
}
boolean content = modifier.equals("Content") ? true : false;
String xencEncryptedDataId = "EncDataId-" + body.hashCode();
encPart.setEncId(xencEncryptedDataId);
cloneKeyInfo = true;
if(keyInfo == null) {
keyInfo = new KeyInfo(document);
SecurityTokenReference secToken = new SecurityTokenReference(document);
Reference ref = new Reference(document);
ref.setURI("#" + encKeyId);
secToken.setReference(ref);
keyInfo.addUnknownElement(secToken.getElement());
}
/*
* Forth step: encrypt data, and set necessary attributes in
* xenc:EncryptedData
*/
try {
if (modifier.equals("Header")) {
Element elem = doc.createElementNS(WSConstants.WSSE11_NS,"wsse11:"+WSConstants.ENCRYPTED_HEADER);
+ WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
String wsuPrefix = WSSecurityUtil.setNamespace(elem,
WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
elem.setAttributeNS(WSConstants.WSU_NS, wsuPrefix + ":Id", "EncHeader-" + body.hashCode());
NamedNodeMap map = body.getAttributes();
for (int i = 0 ; i < map.getLength() ; i++) {
Attr attr = (Attr)map.item(i);
if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
|| attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
String soapEnvPrefix = WSSecurityUtil.setNamespace(elem,
attr.getNamespaceURI(), "soapevn");
elem.setAttributeNS(attr.getNamespaceURI(), soapEnvPrefix +":"+attr.getLocalName(), attr.getValue());
}
}
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, body, content);
Element encDataElem = WSSecurityUtil.findElementById(document
.getDocumentElement(), xencEncryptedDataId, null);
Node clone = encDataElem.cloneNode(true);
elem.appendChild(clone);
encDataElem.getParentNode().appendChild(elem);
encDataElem.getParentNode().removeChild(encDataElem);
} else {
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, body, content);
}
if(cloneKeyInfo) {
keyInfo = new KeyInfo((Element) keyInfo.getElement()
.cloneNode(true), null);
}
} catch (Exception e2) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENC_DEC, null, null, e2);
}
encDataRef.add(new String("#" + xencEncryptedDataId));
}
return encDataRef;
}
private Document buildEmbedded(Document doc, Crypto crypto,
WSSecHeader secHeader) throws WSSecurityException {
doDebug = log.isDebugEnabled();
if (doDebug) {
log.debug("Beginning Encryption embedded...");
}
envelope = doc.getDocumentElement();
envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:"
+ WSConstants.ENC_PREFIX, WSConstants.ENC_NS);
/*
* Second step: generate a symmetric key from the specified key
* (password) for this algorithm, and set the cipher into encryption
* mode.
*/
if (this.symmetricKey == null) {
if (embeddedKey == null) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"noKeySupplied");
}
this.symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo,
embeddedKey);
}
KeyInfo keyInfo = null;
if (this.keyIdentifierType == WSConstants.EMBEDDED_KEYNAME) {
keyInfo = new KeyInfo(doc);
keyInfo
.addKeyName(embeddedKeyName == null ? user
: embeddedKeyName);
} else if (this.keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
/*
* This means that we want to embed a <wsse:SecurityTokenReference>
* into keyInfo element. If we need this functionality, this.secRef
* MUST be set before calling the build(doc, crypto) method. So if
* secRef is null then throw an exception.
*/
if (this.securityTokenReference == null) {
throw new WSSecurityException(
WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"You must set keyInfo element, if the keyIdentifier "
+ "== EMBED_SECURITY_TOKEN_REF");
} else {
keyInfo = new KeyInfo(doc);
Element tmpE = securityTokenReference.getElement();
tmpE.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:"
+ tmpE.getPrefix(), tmpE.getNamespaceURI());
keyInfo.addUnknownElement(securityTokenReference.getElement());
}
}
SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope);
if (parts == null) {
parts = new Vector();
WSEncryptionPart encP = new WSEncryptionPart(soapConstants
.getBodyQName().getLocalPart(), soapConstants
.getEnvelopeURI(), "Content");
parts.add(encP);
}
Vector encDataRefs = doEncryption(doc, this.symmetricKey, keyInfo,
parts);
/*
* At this point data is encrypted with the symmetric key and can be
* referenced via the above Id
*/
/*
* Now we need to setup the wsse:Security header block 1) get (or
* create) the wsse:Security header block 2) The last step sets up the
* reference list that pints to the encrypted data
*/
Element wsseSecurity = secHeader.getSecurityHeader();
Element referenceList = doc.createElementNS(WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":ReferenceList");
referenceList = createDataRefList(doc, referenceList, encDataRefs);
WSSecurityUtil.prependChildElement(doc, wsseSecurity, referenceList,
true);
return doc;
}
private KeyGenerator getKeyGenerator() throws WSSecurityException {
KeyGenerator keyGen = null;
try {
/*
* Assume AES as default, so initialize it
*/
keyGen = KeyGenerator.getInstance("AES");
if (symEncAlgo.equalsIgnoreCase(WSConstants.TRIPLE_DES)) {
keyGen = KeyGenerator.getInstance("DESede");
} else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_128)) {
keyGen.init(128);
} else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_192)) {
keyGen.init(192);
} else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_256)) {
keyGen.init(256);
} else {
return null;
}
} catch (NoSuchAlgorithmException e) {
throw new WSSecurityException(
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e);
}
return keyGen;
}
/**
* Create DOM subtree for <code>xenc:EncryptedKey</code>
*
* @param doc
* the SOAP envelope parent document
* @param keyTransportAlgo
* specifies which algorithm to use to encrypt the symmetric key
* @return an <code>xenc:EncryptedKey</code> element
*/
public static Element createDataRefList(Document doc,
Element referenceList, Vector encDataRefs) {
for (int i = 0; i < encDataRefs.size(); i++) {
String dataReferenceUri = (String) encDataRefs.get(i);
Element dataReference = doc.createElementNS(WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":DataReference");
dataReference.setAttributeNS(null, "URI", dataReferenceUri);
referenceList.appendChild(dataReference);
}
return referenceList;
}
/**
* @return The symmetric key
*/
public SecretKey getSymmetricKey() {
return symmetricKey;
}
/**
* Set the symmetric key to be used for encryption
*
* @param key
*/
public void setSymmetricKey(SecretKey key) {
this.symmetricKey = key;
}
/**
* @return Return the SecurityTokenRefernce
*/
public SecurityTokenReference getSecurityTokenReference() {
return securityTokenReference;
}
/**
* @param reference
*/
public void setSecurityTokenReference(SecurityTokenReference reference) {
securityTokenReference = reference;
}
public boolean isEncryptSymmKey() {
return encryptSymmKey;
}
public void setEncryptSymmKey(boolean encryptSymmKey) {
this.encryptSymmKey = encryptSymmKey;
}
private String getSHA1(byte[] input) throws WSSecurityException {
try {
MessageDigest sha = null;
sha = MessageDigest.getInstance("SHA-1");
sha.reset();
sha.update(input);
byte[] data = sha.digest();
return Base64.encode(data);
} catch (NoSuchAlgorithmException e) {
throw new WSSecurityException(
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e);
}
}
public void setCustomReferenceValue(String customReferenceValue) {
this.customReferenceValue = customReferenceValue;
}
}
| true | true | private Vector doEncryption(Document doc, SecretKey secretKey,
KeyInfo keyInfo, Vector references) throws WSSecurityException {
XMLCipher xmlCipher = null;
try {
xmlCipher = XMLCipher.getInstance(symEncAlgo);
} catch (XMLEncryptionException e3) {
throw new WSSecurityException(
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3);
}
Vector encDataRef = new Vector();
boolean cloneKeyInfo = false;
for (int part = 0; part < references.size(); part++) {
WSEncryptionPart encPart = (WSEncryptionPart) references.get(part);
String idToEnc = encPart.getId();
String elemName = encPart.getName();
String nmSpace = encPart.getNamespace();
String modifier = encPart.getEncModifier();
/*
* Third step: get the data to encrypt.
*
*/
Element body = null;
if (idToEnc != null) {
body = WSSecurityUtil.findElementById(document
.getDocumentElement(), idToEnc, WSConstants.WSU_NS);
if (body == null) {
body = WSSecurityUtil.findElementById(document
.getDocumentElement(), idToEnc, null);
}
} else {
body = (Element) WSSecurityUtil.findElement(document, elemName,
nmSpace);
}
if (body == null) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"noEncElement", new Object[] { "{" + nmSpace + "}"
+ elemName });
}
boolean content = modifier.equals("Content") ? true : false;
String xencEncryptedDataId = "EncDataId-" + body.hashCode();
encPart.setEncId(xencEncryptedDataId);
cloneKeyInfo = true;
if(keyInfo == null) {
keyInfo = new KeyInfo(document);
SecurityTokenReference secToken = new SecurityTokenReference(document);
Reference ref = new Reference(document);
ref.setURI("#" + encKeyId);
secToken.setReference(ref);
keyInfo.addUnknownElement(secToken.getElement());
}
/*
* Forth step: encrypt data, and set necessary attributes in
* xenc:EncryptedData
*/
try {
if (modifier.equals("Header")) {
Element elem = doc.createElementNS(WSConstants.WSSE11_NS,"wsse11:"+WSConstants.ENCRYPTED_HEADER);
String wsuPrefix = WSSecurityUtil.setNamespace(elem,
WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
elem.setAttributeNS(WSConstants.WSU_NS, wsuPrefix + ":Id", "EncHeader-" + body.hashCode());
NamedNodeMap map = body.getAttributes();
for (int i = 0 ; i < map.getLength() ; i++) {
Attr attr = (Attr)map.item(i);
if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
|| attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
String soapEnvPrefix = WSSecurityUtil.setNamespace(elem,
attr.getNamespaceURI(), "soapevn");
elem.setAttributeNS(attr.getNamespaceURI(), soapEnvPrefix +":"+attr.getLocalName(), attr.getValue());
}
}
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, body, content);
Element encDataElem = WSSecurityUtil.findElementById(document
.getDocumentElement(), xencEncryptedDataId, null);
Node clone = encDataElem.cloneNode(true);
elem.appendChild(clone);
encDataElem.getParentNode().appendChild(elem);
encDataElem.getParentNode().removeChild(encDataElem);
} else {
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, body, content);
}
if(cloneKeyInfo) {
keyInfo = new KeyInfo((Element) keyInfo.getElement()
.cloneNode(true), null);
}
} catch (Exception e2) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENC_DEC, null, null, e2);
}
encDataRef.add(new String("#" + xencEncryptedDataId));
}
| private Vector doEncryption(Document doc, SecretKey secretKey,
KeyInfo keyInfo, Vector references) throws WSSecurityException {
XMLCipher xmlCipher = null;
try {
xmlCipher = XMLCipher.getInstance(symEncAlgo);
} catch (XMLEncryptionException e3) {
throw new WSSecurityException(
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3);
}
Vector encDataRef = new Vector();
boolean cloneKeyInfo = false;
for (int part = 0; part < references.size(); part++) {
WSEncryptionPart encPart = (WSEncryptionPart) references.get(part);
String idToEnc = encPart.getId();
String elemName = encPart.getName();
String nmSpace = encPart.getNamespace();
String modifier = encPart.getEncModifier();
/*
* Third step: get the data to encrypt.
*
*/
Element body = null;
if (idToEnc != null) {
body = WSSecurityUtil.findElementById(document
.getDocumentElement(), idToEnc, WSConstants.WSU_NS);
if (body == null) {
body = WSSecurityUtil.findElementById(document
.getDocumentElement(), idToEnc, null);
}
} else {
body = (Element) WSSecurityUtil.findElement(document, elemName,
nmSpace);
}
if (body == null) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"noEncElement", new Object[] { "{" + nmSpace + "}"
+ elemName });
}
boolean content = modifier.equals("Content") ? true : false;
String xencEncryptedDataId = "EncDataId-" + body.hashCode();
encPart.setEncId(xencEncryptedDataId);
cloneKeyInfo = true;
if(keyInfo == null) {
keyInfo = new KeyInfo(document);
SecurityTokenReference secToken = new SecurityTokenReference(document);
Reference ref = new Reference(document);
ref.setURI("#" + encKeyId);
secToken.setReference(ref);
keyInfo.addUnknownElement(secToken.getElement());
}
/*
* Forth step: encrypt data, and set necessary attributes in
* xenc:EncryptedData
*/
try {
if (modifier.equals("Header")) {
Element elem = doc.createElementNS(WSConstants.WSSE11_NS,"wsse11:"+WSConstants.ENCRYPTED_HEADER);
WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
String wsuPrefix = WSSecurityUtil.setNamespace(elem,
WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
elem.setAttributeNS(WSConstants.WSU_NS, wsuPrefix + ":Id", "EncHeader-" + body.hashCode());
NamedNodeMap map = body.getAttributes();
for (int i = 0 ; i < map.getLength() ; i++) {
Attr attr = (Attr)map.item(i);
if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
|| attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
String soapEnvPrefix = WSSecurityUtil.setNamespace(elem,
attr.getNamespaceURI(), "soapevn");
elem.setAttributeNS(attr.getNamespaceURI(), soapEnvPrefix +":"+attr.getLocalName(), attr.getValue());
}
}
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, body, content);
Element encDataElem = WSSecurityUtil.findElementById(document
.getDocumentElement(), xencEncryptedDataId, null);
Node clone = encDataElem.cloneNode(true);
elem.appendChild(clone);
encDataElem.getParentNode().appendChild(elem);
encDataElem.getParentNode().removeChild(encDataElem);
} else {
xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
EncryptedData encData = xmlCipher.getEncryptedData();
encData.setId(xencEncryptedDataId);
encData.setKeyInfo(keyInfo);
xmlCipher.doFinal(doc, body, content);
}
if(cloneKeyInfo) {
keyInfo = new KeyInfo((Element) keyInfo.getElement()
.cloneNode(true), null);
}
} catch (Exception e2) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENC_DEC, null, null, e2);
}
encDataRef.add(new String("#" + xencEncryptedDataId));
}
|
diff --git a/src/uk/org/ponder/beanutil/BeanUtil.java b/src/uk/org/ponder/beanutil/BeanUtil.java
index c1572fc..0df3c67 100644
--- a/src/uk/org/ponder/beanutil/BeanUtil.java
+++ b/src/uk/org/ponder/beanutil/BeanUtil.java
@@ -1,108 +1,108 @@
/*
* Created on Aug 4, 2005
*/
package uk.org.ponder.beanutil;
import java.util.Iterator;
import java.util.Map;
import uk.org.ponder.saxalizer.MethodAnalyser;
import uk.org.ponder.saxalizer.SAXalizerMappingContext;
import uk.org.ponder.util.UniversalRuntimeException;
/**
* @author Antranig Basman ([email protected])
*
*/
public class BeanUtil {
/**
* The String prefix used for the ID of a freshly created entity to an
* "obstinate" BeanLocator following the standard OTP system. The text
* following the prefix is arbitrary. Custom OTP systems might use a different
* prefix.
*/
public static String NEW_ENTITY_PREFIX = "new ";
public static void copyBeans(Map source, WriteableBeanLocator target) {
for (Iterator sit = source.keySet().iterator(); sit.hasNext();) {
String name = (String) sit.next();
Object bean = source.get(name);
target.set(name, bean);
}
}
public static void censorNullBean(String beanname, Object beanvalue) {
if (beanvalue == null) {
throw UniversalRuntimeException.accumulate(new BeanNotFoundException(),
"No bean with name " + beanname
+ " could be found in RSAC or application context");
}
}
public static Object navigateOne(Object moveobj, String path,
SAXalizerMappingContext mappingcontext) {
if (path == null || path.equals("")) {
return moveobj;
}
if (moveobj == null) {
throw UniversalRuntimeException.accumulate(
new IllegalArgumentException(),
"Null value encounted in bean path at component " + path);
}
else {
PropertyAccessor pa = MethodAnalyser.getPropertyAccessor(moveobj,
mappingcontext);
return pa.getProperty(moveobj, path);
}
}
public static Object navigate(Object rootobj, String path,
SAXalizerMappingContext mappingcontext) {
if (path == null || path.equals("")) {
return rootobj;
}
String[] components = PathUtil.splitPath(path);
Object moveobj = rootobj;
for (int comp = 0; comp < components.length; ++comp) {
if (moveobj == null) {
throw UniversalRuntimeException.accumulate(
new IllegalArgumentException(),
"Null value encounted in bean path at component "
+ (comp == 0 ? "<root>"
: components[comp - 1] + " while traversing for "
+ components[comp]));
}
else {
- moveobj = navigateOne(moveobj, path, mappingcontext);
+ moveobj = navigateOne(moveobj, components[comp], mappingcontext);
}
}
return moveobj;
}
/**
* Given a string representing an EL expression beginning #{ and ending },
* strip these off returning the bare expression. If the bracketing characters
* are not present, return null.
*/
public static String stripEL(String el) {
if (el == null) {
return null;
}
else if (el.startsWith("#{") && el.endsWith("}")) {
return el.substring(2, el.length() - 1);
}
else
return null;
}
public static String stripELNoisy(String el) {
String stripped = stripEL(el);
if (stripped == null) {
throw new IllegalArgumentException("EL expression \"" + el
+ "\" is not bracketed with #{..}");
}
return stripped;
}
}
| true | true | public static Object navigate(Object rootobj, String path,
SAXalizerMappingContext mappingcontext) {
if (path == null || path.equals("")) {
return rootobj;
}
String[] components = PathUtil.splitPath(path);
Object moveobj = rootobj;
for (int comp = 0; comp < components.length; ++comp) {
if (moveobj == null) {
throw UniversalRuntimeException.accumulate(
new IllegalArgumentException(),
"Null value encounted in bean path at component "
+ (comp == 0 ? "<root>"
: components[comp - 1] + " while traversing for "
+ components[comp]));
}
else {
moveobj = navigateOne(moveobj, path, mappingcontext);
}
}
return moveobj;
}
| public static Object navigate(Object rootobj, String path,
SAXalizerMappingContext mappingcontext) {
if (path == null || path.equals("")) {
return rootobj;
}
String[] components = PathUtil.splitPath(path);
Object moveobj = rootobj;
for (int comp = 0; comp < components.length; ++comp) {
if (moveobj == null) {
throw UniversalRuntimeException.accumulate(
new IllegalArgumentException(),
"Null value encounted in bean path at component "
+ (comp == 0 ? "<root>"
: components[comp - 1] + " while traversing for "
+ components[comp]));
}
else {
moveobj = navigateOne(moveobj, components[comp], mappingcontext);
}
}
return moveobj;
}
|
diff --git a/src/com/jme/animation/SpatialTransformer.java b/src/com/jme/animation/SpatialTransformer.java
index 3fdb43772..4fbad4ba5 100755
--- a/src/com/jme/animation/SpatialTransformer.java
+++ b/src/com/jme/animation/SpatialTransformer.java
@@ -1,829 +1,832 @@
/*
* Copyright (c) 2003-2006 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme.animation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import com.jme.math.Quaternion;
import com.jme.math.TransformQuaternion;
import com.jme.math.Vector3f;
import com.jme.renderer.CloneCreator;
import com.jme.scene.Controller;
import com.jme.scene.Spatial;
import com.jme.util.LoggingSystem;
import java.util.logging.Level;
/**
* Started Date: Jul 9, 2004 <br>
* <br>
*
* This class animates spatials by interpolating between various
* transformations. The user defines objects to be transformed and what
* rotation/translation/scale to give each object at various points in time. The
* user must call interpolateMissing() before using the controller in order to
* interpolate unspecified translation/rotation/scale.
*
*
* @author Jack Lindamood
* @author Philip Wainwright (bugfixes)
*/
public class SpatialTransformer extends Controller {
private static final long serialVersionUID = 1L;
/** Number of objects this transformer changes. */
private int numObjects;
/** Refrences to the objects that will be changed. */
public Spatial[] toChange;
/** Used internally by update specifying how to change each object. */
private TransformQuaternion[] pivots;
/**
* parentIndexes[i] states that toChange[i]'s parent is
* toChange[parentIndex[i]].
*/
public int[] parentIndexes;
/** Interpolated array of keyframe states */
public ArrayList keyframes;
/** Current time in the animation */
private float curTime;
/** Time previous to curTime */
private PointInTime beginPointTime;
/** Time after curTime */
private PointInTime endPointTime;
/** Used internally in update to flag that a pivot has been updated */
private boolean[] haveChanged;
private float delta;
private final static Vector3f unSyncbeginPos = new Vector3f();
private final static Vector3f unSyncendPos = new Vector3f();
private final static Quaternion unSyncbeginRot = new Quaternion();
private final static Quaternion unSyncendRot = new Quaternion();
/**
* Constructs a new SpatialTransformer that will operate on
* <code>numObjects</code> Spatials
*
* @param numObjects
* The number of spatials to change
*/
public SpatialTransformer(int numObjects) {
this.numObjects = numObjects;
toChange = new Spatial[numObjects];
pivots = new TransformQuaternion[numObjects];
parentIndexes = new int[numObjects];
haveChanged = new boolean[numObjects];
Arrays.fill(parentIndexes, -1);
for (int i = 0; i < numObjects; i++)
pivots[i] = new TransformQuaternion();
keyframes = new ArrayList();
}
public void update(float time) {
if (!isActive()) return;
curTime += time * getSpeed();
setBeginAndEnd();
Arrays.fill(haveChanged, false);
delta = endPointTime.time - beginPointTime.time;
if (delta != 0f) delta = (curTime - beginPointTime.time) / delta;
for (int i = 0; i < numObjects; i++) {
updatePivot(i);
pivots[i].applyToSpatial(toChange[i]);
}
}
/**
* Called by update, and itself recursivly. Will, when completed, change
* toChange[objIndex] by pivots[objIndex]
*
* @param objIndex
* The index to update.
*/
private void updatePivot(int objIndex) {
if (haveChanged[objIndex])
return;
else
haveChanged[objIndex] = true;
int parentIndex = parentIndexes[objIndex];
if (parentIndex != -1) {
updatePivot(parentIndex);
}
pivots[objIndex].interpolateTransforms(beginPointTime.look[objIndex],
endPointTime.look[objIndex], delta);
if (parentIndex != -1)
pivots[objIndex].combineWithParent(pivots[parentIndex]);
}
/**
* overridden by SpatialTransformer to always set a time inside the first
* and the last keyframe's time in the animation.
* @author Kai Rabien (hevee)
*/
public void setMinTime(float minTime) {
if(keyframes != null && keyframes.size() > 0){
float firstFrame = ((PointInTime)keyframes.get(0)).time;
float lastFrame = ((PointInTime)keyframes.get(keyframes.size() - 1)).time;
if(minTime < firstFrame) minTime = firstFrame;
if(minTime > lastFrame) minTime = lastFrame;
}
curTime = minTime;
super.setMinTime(minTime);
}
/**
* overridden by SpatialTransformer to always set a time inside the first
* and the last keyframe's time in the animation
* @author Kai Rabien (hevee)
*/
public void setMaxTime(float maxTime) {
if(keyframes != null && keyframes.size() > 0){
float firstFrame = ((PointInTime)keyframes.get(0)).time;
float lastFrame = ((PointInTime)keyframes.get(keyframes.size() - 1)).time;
if(maxTime < firstFrame) maxTime = firstFrame;
if(maxTime > lastFrame) maxTime = lastFrame;
}
super.setMaxTime(maxTime);
}
/**
* Sets the new animation boundaries for this controller. This will start at
* newBeginTime and proceed in the direction of newEndTime (either forwards
* or backwards). If both are the same, then the animation is set to their
* time and turned off, otherwise the animation is turned on to start the
* animation acording to the repeat type. If either BeginTime or EndTime are
* invalid times (less than 0 or greater than the maximum set keyframe time)
* then a warning is set and nothing happens. <br>
* It is suggested that this function be called if new animation boundaries
* need to be set, instead of setMinTime and setMaxTime directly.
*
* @param newBeginTime
* The starting time
* @param newEndTime
* The ending time
*/
public void setNewAnimationTimes(float newBeginTime, float newEndTime) {
if (newBeginTime < 0
|| newBeginTime > ((PointInTime) keyframes
.get(keyframes.size() - 1)).time) {
LoggingSystem.getLogger().log(Level.WARNING,
"Attempt to set invalid begintime:" + newBeginTime);
return;
}
if (newEndTime < 0
|| newEndTime > ((PointInTime) keyframes
.get(keyframes.size() - 1)).time) {
LoggingSystem.getLogger().log(Level.WARNING,
"Attempt to set invalid endtime:" + newEndTime);
return;
}
setMinTime(newBeginTime);
setMaxTime(newEndTime);
setActive(true);
if (newBeginTime <= newEndTime) { // Moving forward
curTime = newBeginTime;
if (newBeginTime == newEndTime) {
update(0);
setActive(false);
}
} else { // Moving backwards
curTime = newEndTime;
}
}
/**
* Gets the current time in the animation
* @param morph
* The new mesh to morph
*/
public float getCurTime(){return curTime;}
/**
* Sets the current time in the animation
* @param time
* The time this Controller should continue at
*/
public void setCurTime(float time){ curTime = time;}
/**
* Called in update for calculating the correct beginPointTime and
* endPointTime, and changing curTime if neccessary.
* @author Kai Rabien (hevee)
*/
private void setBeginAndEnd() {
float minTime = getMinTime();
float maxTime = getMaxTime();
if(getSpeed() > 0){
if(curTime >= maxTime){
if(getRepeatType() == RT_WRAP){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = curTime - maxTime;
curTime = minTime + overshoot;
} else if (getRepeatType() == RT_CLAMP){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = beginPointTime;
curTime = maxTime;
} else if(getRepeatType() == RT_CYCLE){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = curTime - maxTime;
curTime = maxTime - overshoot;
setSpeed(- getSpeed());
}
} else if(curTime <= minTime){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
curTime = minTime;
} else{//curTime is inside minTime and maxTime
int[] is = findIndicesBeforeAfter(curTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
}
} else if(getSpeed() < 0){
if(curTime <= minTime){
if(getRepeatType() == RT_WRAP){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = minTime - curTime;
curTime = maxTime - overshoot;
} else if (getRepeatType() == RT_CLAMP){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = beginPointTime;
curTime = minTime;
} else if(getRepeatType() == RT_CYCLE){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = minTime - curTime;
curTime = minTime + overshoot;
setSpeed(- getSpeed());
}
} else if(curTime >= maxTime){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
curTime = maxTime;
} else{//curTime is inside minTime and maxTime
int[] is = findIndicesBeforeAfter(curTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
}
+ } else {
+ beginPointTime = ((PointInTime) keyframes.get(0));
+ endPointTime = ((PointInTime) keyframes.get(0));
}
}
/**
* Finds indices i in keyframes such that <code>
* keyframes.get(i[0]).time < giventime <= keyframes.get(i[1]).time </code>
* if no keyframe was found before or after <code>giventime</code>, the
* corresponding value will clamp to <code>0</code> resp.
* <code>keyframes.size() - 1</code>
* @author Kai Rabien (hevee)
*/
int[] findIndicesBeforeAfter(float giventime){
int[] ret = new int[]{0, keyframes.size() - 1};
for (int i = 0; i < keyframes.size(); i++){
float curFrameTime = ((PointInTime) keyframes.get(i)).time;
if (curFrameTime >= giventime) {
ret[1] = i;
return ret;
} else
ret[0] = i;
}
return ret;
}
/**
* Sets an object to animate. The object's index is <code>index</code> and
* it's parent index is <code>parentIndex</code>. A parent index of -1
* indicates it has no parent.
*
* @param objChange
* The spatial that will be updated by this SpatialTransformer.
* @param index
* The index of that spatial in this transformer's array
* @param parentIndex
* The parentIndex in this transformer's array for this Spatial
*/
public void setObject(Spatial objChange, int index, int parentIndex) {
toChange[index] = objChange;
pivots[index].setTranslation(objChange.getLocalTranslation());
pivots[index].setScale(objChange.getLocalScale());
pivots[index].setRotationQuaternion(objChange.getLocalRotation());
parentIndexes[index] = parentIndex;
}
/**
* Returns the keyframe for <code>time</code>. If one doens't exist, a
* new one is created, and <code>getMaxTime()</code> will be
* set to <code>Math.max(time, getMaxTime())</code>.
* @param time
* The time to look for.
* @return The keyframe refrencing <code>time</code>.
*/
private PointInTime findTime(float time) {
for (int i = 0; i < keyframes.size(); i++) {
if (((PointInTime) keyframes.get(i)).time == time){
setMinTime(Math.min(time, getMinTime()));
setMaxTime(Math.max(time, getMaxTime()));
return (PointInTime) keyframes.get(i);
}
if (((PointInTime) keyframes.get(i)).time > time) {
PointInTime t = new PointInTime(time);
keyframes.add(i, t);
setMinTime(Math.min(time, getMinTime()));
setMaxTime(Math.max(time, getMaxTime()));
return t;
}
}
PointInTime t = new PointInTime(time);
keyframes.add(t);
setMinTime(Math.min(time, getMinTime()));
setMaxTime(Math.max(time, getMaxTime()));
return t;
}
/**
* Sets object with index <code>indexInST</code> to rotate by
* <code>rot</code> at time <code>time</code>.
*
* @param indexInST
* The index of the spatial to change
* @param time
* The time for the spatial to take this rotation
* @param rot
* The rotation to take
*/
public void setRotation(int indexInST, float time, Quaternion rot) {
PointInTime toAdd = findTime(time);
toAdd.setRotation(indexInST, rot);
}
/**
* Sets object with index <code>indexInST</code> to translate by
* <code>position</code> at time <code>time</code>.
*
* @param indexInST
* The index of the spatial to change
* @param time
* The time for the spatial to take this translation
* @param position
* The position to take
*/
public void setPosition(int indexInST, float time, Vector3f position) {
PointInTime toAdd = findTime(time);
toAdd.setTranslation(indexInST, position);
}
/**
* Sets object with index <code>indexInST</code> to scale by
* <code>scale</code> at time <code>time</code>.
*
* @param indexInST
* The index of the spatial to change
* @param time
* The time for the spatial to take this scale
* @param scale
* The scale to take
*/
public void setScale(int indexInST, float time, Vector3f scale) {
PointInTime toAdd = findTime(time);
toAdd.setScale(indexInST, scale);
}
/**
* This must be called one time, once all translations/rotations/scales have
* been set. It will interpolate unset values to make the animation look
* correct. Tail and head values are assumed to be the identity.
*/
public void interpolateMissing() {
if (keyframes.size() != 1) {
fillTrans();
fillRots();
fillScales();
}
for (int objIndex = 0; objIndex < numObjects; objIndex++)
pivots[objIndex].applyToSpatial(toChange[objIndex]);
}
/**
* Called by interpolateMissing(), it will interpolate missing scale values.
*/
private void fillScales() {
for (int objIndex = 0; objIndex < numObjects; objIndex++) {
// 1) Find first non-null scale of objIndex <code>objIndex</code>
int start;
for (start = 0; start < keyframes.size(); start++) {
if (((PointInTime) keyframes.get(start)).usedScale
.get(objIndex)) break;
}
if (start == keyframes.size()) { // if they are all null then fill
// with identity
for (int i = 0; i < keyframes.size(); i++)
{
pivots[objIndex].getScale( // pull original translation
((PointInTime) keyframes.get(i)).look[objIndex]
.getScale()); // ...into object translation.
}
continue; // we're done so lets break
}
if (start != 0) { // if there -are- null elements at the begining,
// then fill with first non-null
((PointInTime) keyframes.get(start)).look[objIndex]
.getScale(unSyncbeginPos);
for (int i = 0; i < start; i++)
((PointInTime) keyframes.get(i)).look[objIndex]
.setScale(unSyncbeginPos);
}
int lastgood = start;
for (int i = start + 1; i < keyframes.size(); i++) {
if (((PointInTime) keyframes.get(i)).usedScale.get(objIndex)) {
fillScale(objIndex, lastgood, i); // fills gaps
lastgood = i;
}
}
if (lastgood != keyframes.size() - 1) { // Make last ones equal to
// last good
((PointInTime) keyframes.get(keyframes.size() - 1)).look[objIndex]
.setScale(((PointInTime) keyframes.get(lastgood)).look[objIndex]
.getScale(null));
}
((PointInTime) keyframes.get(lastgood)).look[objIndex]
.getScale(unSyncbeginPos);
for (int i = lastgood + 1; i < keyframes.size(); i++) {
((PointInTime) keyframes.get(i)).look[objIndex]
.setScale(unSyncbeginPos);
}
}
}
/**
* Interpolates unspecified scale values for objectIndex from start to end.
*
* @param objectIndex
* Index to interpolate.
* @param startScaleIndex
* Starting scale index.
* @param endScaleIndex
* Ending scale index.
*/
private void fillScale(int objectIndex, int startScaleIndex,
int endScaleIndex) {
((PointInTime) keyframes.get(startScaleIndex)).look[objectIndex]
.getScale(unSyncbeginPos);
((PointInTime) keyframes.get(endScaleIndex)).look[objectIndex]
.getScale(unSyncendPos);
float startTime = ((PointInTime) keyframes.get(startScaleIndex)).time;
float endTime = ((PointInTime) keyframes.get(endScaleIndex)).time;
float delta = endTime - startTime;
Vector3f tempVec = new Vector3f();
for (int i = startScaleIndex + 1; i < endScaleIndex; i++) {
float thisTime = ((PointInTime) keyframes.get(i)).time;
tempVec.interpolate(unSyncbeginPos, unSyncendPos,
(thisTime - startTime) / delta);
((PointInTime) keyframes.get(i)).look[objectIndex]
.setScale(tempVec);
}
}
/**
* Called by interpolateMissing(), it will interpolate missing rotation
* values.
*/
private void fillRots() {
for (int joint = 0; joint < numObjects; joint++) {
// 1) Find first non-null rotation of joint <code>joint</code>
int start;
for (start = 0; start < keyframes.size(); start++) {
if (((PointInTime) keyframes.get(start)).usedRot.get(joint))
break;
}
if (start == keyframes.size()) { // if they are all null then fill
// with identity
for (int i = 0; i < keyframes.size(); i++)
pivots[joint].getRotation( // pull original rotation
((PointInTime) keyframes.get(i)).look[joint]
.getRotation()); // ...into object rotation.
continue; // we're done so lets break
}
if (start != 0) { // if there -are- null elements at the begining,
// then fill with first non-null
((PointInTime) keyframes.get(start)).look[joint]
.getRotation(unSyncbeginRot);
for (int i = 0; i < start; i++)
((PointInTime) keyframes.get(i)).look[joint]
.setRotationQuaternion(unSyncbeginRot);
}
int lastgood = start;
for (int i = start + 1; i < keyframes.size(); i++) {
if (((PointInTime) keyframes.get(i)).usedRot.get(joint)) {
fillQuats(joint, lastgood, i); // fills gaps
lastgood = i;
}
}
// fillQuats(joint,lastgood,keyframes.size()-1); // fills tail
((PointInTime) keyframes.get(lastgood)).look[joint]
.getRotation(unSyncbeginRot);
for (int i = lastgood + 1; i < keyframes.size(); i++) {
((PointInTime) keyframes.get(i)).look[joint]
.setRotationQuaternion(unSyncbeginRot);
}
}
}
/**
* Interpolates unspecified rot values for objectIndex from start to end.
*
* @param objectIndex
* Index to interpolate.
* @param startRotIndex
* Starting rot index.
* @param endRotIndex
* Ending rot index.
*/
private void fillQuats(int objectIndex, int startRotIndex, int endRotIndex) {
((PointInTime) keyframes.get(startRotIndex)).look[objectIndex]
.getRotation(unSyncbeginRot);
((PointInTime) keyframes.get(endRotIndex)).look[objectIndex]
.getRotation(unSyncendRot);
float startTime = ((PointInTime) keyframes.get(startRotIndex)).time;
float endTime = ((PointInTime) keyframes.get(endRotIndex)).time;
float delta = endTime - startTime;
Quaternion tempQuat = new Quaternion();
for (int i = startRotIndex + 1; i < endRotIndex; i++) {
float thisTime = ((PointInTime) keyframes.get(i)).time;
tempQuat.slerp(unSyncbeginRot, unSyncendRot, (thisTime - startTime)
/ delta);
((PointInTime) keyframes.get(i)).look[objectIndex]
.setRotationQuaternion(tempQuat);
}
}
/**
* Called by interpolateMissing(), it will interpolate missing translation
* values.
*/
private void fillTrans() {
for (int objIndex = 0; objIndex < numObjects; objIndex++) {
// 1) Find first non-null translation of objIndex
// <code>objIndex</code>
int start;
for (start = 0; start < keyframes.size(); start++) {
if (((PointInTime) keyframes.get(start)).usedTrans
.get(objIndex)) break;
}
if (start == keyframes.size()) { // if they are all null then fill
// with identity
for (int i = 0; i < keyframes.size(); i++)
pivots[objIndex].getTranslation( // pull original translation
((PointInTime) keyframes.get(i)).look[objIndex]
.getTranslation()); // ...into object translation.
continue; // we're done so lets break
}
if (start != 0) { // if there -are- null elements at the begining,
// then fill with first non-null
((PointInTime) keyframes.get(start)).look[objIndex]
.getTranslation(unSyncbeginPos);
for (int i = 0; i < start; i++)
((PointInTime) keyframes.get(i)).look[objIndex]
.setTranslation(unSyncbeginPos);
}
int lastgood = start;
for (int i = start + 1; i < keyframes.size(); i++) {
if (((PointInTime) keyframes.get(i)).usedTrans.get(objIndex)) {
fillVecs(objIndex, lastgood, i); // fills gaps
lastgood = i;
}
}
if (lastgood != keyframes.size() - 1) { // Make last ones equal to
// last good
((PointInTime) keyframes.get(keyframes.size() - 1)).look[objIndex]
.setTranslation(((PointInTime) keyframes.get(lastgood)).look[objIndex]
.getTranslation(null));
}
((PointInTime) keyframes.get(lastgood)).look[objIndex]
.getTranslation(unSyncbeginPos);
for (int i = lastgood + 1; i < keyframes.size(); i++) {
((PointInTime) keyframes.get(i)).look[objIndex]
.setTranslation(unSyncbeginPos);
}
}
}
/**
* Interpolates unspecified translation values for objectIndex from start to
* end.
*
* @param objectIndex
* Index to interpolate.
* @param startPosIndex
* Starting translation index.
* @param endPosIndex
* Ending translation index.
*/
private void fillVecs(int objectIndex, int startPosIndex, int endPosIndex) {
((PointInTime) keyframes.get(startPosIndex)).look[objectIndex]
.getTranslation(unSyncbeginPos);
((PointInTime) keyframes.get(endPosIndex)).look[objectIndex]
.getTranslation(unSyncendPos);
float startTime = ((PointInTime) keyframes.get(startPosIndex)).time;
float endTime = ((PointInTime) keyframes.get(endPosIndex)).time;
float delta = endTime - startTime;
Vector3f tempVec = new Vector3f();
for (int i = startPosIndex + 1; i < endPosIndex; i++) {
float thisTime = ((PointInTime) keyframes.get(i)).time;
tempVec.interpolate(unSyncbeginPos, unSyncendPos,
(thisTime - startTime) / delta);
((PointInTime) keyframes.get(i)).look[objectIndex]
.setTranslation(tempVec);
}
}
/**
* Returns the number of Objects used by this SpatialTransformer
*
* @return The number of objects.
*/
public int getNumObjects() {
return numObjects;
}
public Controller putClone(Controller store, CloneCreator properties) {
if (!properties.isSet("spatialcontroller")) return null;
SpatialTransformer toReturn = new SpatialTransformer(this.numObjects);
super.putClone(toReturn, properties);
toReturn.numObjects = this.numObjects;
System.arraycopy(this.toChange, 0, toReturn.toChange, 0,
toChange.length);
System.arraycopy(this.pivots, 0, toReturn.pivots, 0, pivots.length);
toReturn.parentIndexes = this.parentIndexes;
toReturn.keyframes = this.keyframes;
toReturn.curTime = this.curTime;
toReturn.haveChanged = this.haveChanged;
properties.queueSpatialTransformer(toReturn);
return toReturn;
}
/**
* Defines a point in time where at time <code>time</code>, ohject
* <code>toChange[i]</code> will assume transformation
* <code>look[i]</code>. BitSet's used* specify if the transformation
* value was specified by the user, or interpolated
*/
public class PointInTime {
/** Bit i is true if look[i].rotation was user defined. */
public BitSet usedRot;
/** Bit i is true if look[i].translation was user defined. */
public BitSet usedTrans;
/** Bit i is true if look[i].scale was user defined. */
public BitSet usedScale;
/** The time of this TransformationMatrix. */
public float time;
/** toChange[i] looks like look[i] at time. */
public TransformQuaternion[] look;
/**
* Constructs a new PointInTime with the time <code>time</code>
*
* @param time
* The the for this PointInTime.
*/
PointInTime(float time) {
look = new TransformQuaternion[numObjects];
usedRot = new BitSet(numObjects);
usedTrans = new BitSet(numObjects);
usedScale = new BitSet(numObjects);
for (int i = 0; i < look.length; i++)
look[i] = new TransformQuaternion();
this.time = time;
}
/**
* Sets the rotation for objIndex and sets usedRot to true for that
* index
*
* @param objIndex
* The object to take the rotation at this point in time.
* @param rot
* The rotation to take.
*/
void setRotation(int objIndex, Quaternion rot) {
look[objIndex].setRotationQuaternion(rot);
usedRot.set(objIndex);
}
/**
* Sets the translation for objIndex and sets usedTrans to true for that
* index
*
* @param objIndex
* The object to take the translation at this point in time.
* @param trans
* The translation to take.
*/
void setTranslation(int objIndex, Vector3f trans) {
look[objIndex].setTranslation(trans);
usedTrans.set(objIndex);
}
/**
* Sets the scale for objIndex and sets usedScale to true for that index
*
* @param objIndex
* The object to take the scale at this point in time.
* @param scale
* The scale to take.
*/
void setScale(int objIndex, Vector3f scale) {
look[objIndex].setScale(scale);
usedScale.set(objIndex);
}
}
}
| true | true | private void setBeginAndEnd() {
float minTime = getMinTime();
float maxTime = getMaxTime();
if(getSpeed() > 0){
if(curTime >= maxTime){
if(getRepeatType() == RT_WRAP){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = curTime - maxTime;
curTime = minTime + overshoot;
} else if (getRepeatType() == RT_CLAMP){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = beginPointTime;
curTime = maxTime;
} else if(getRepeatType() == RT_CYCLE){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = curTime - maxTime;
curTime = maxTime - overshoot;
setSpeed(- getSpeed());
}
} else if(curTime <= minTime){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
curTime = minTime;
} else{//curTime is inside minTime and maxTime
int[] is = findIndicesBeforeAfter(curTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
}
} else if(getSpeed() < 0){
if(curTime <= minTime){
if(getRepeatType() == RT_WRAP){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = minTime - curTime;
curTime = maxTime - overshoot;
} else if (getRepeatType() == RT_CLAMP){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = beginPointTime;
curTime = minTime;
} else if(getRepeatType() == RT_CYCLE){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = minTime - curTime;
curTime = minTime + overshoot;
setSpeed(- getSpeed());
}
} else if(curTime >= maxTime){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
curTime = maxTime;
} else{//curTime is inside minTime and maxTime
int[] is = findIndicesBeforeAfter(curTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
}
}
}
| private void setBeginAndEnd() {
float minTime = getMinTime();
float maxTime = getMaxTime();
if(getSpeed() > 0){
if(curTime >= maxTime){
if(getRepeatType() == RT_WRAP){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = curTime - maxTime;
curTime = minTime + overshoot;
} else if (getRepeatType() == RT_CLAMP){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = beginPointTime;
curTime = maxTime;
} else if(getRepeatType() == RT_CYCLE){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = curTime - maxTime;
curTime = maxTime - overshoot;
setSpeed(- getSpeed());
}
} else if(curTime <= minTime){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
curTime = minTime;
} else{//curTime is inside minTime and maxTime
int[] is = findIndicesBeforeAfter(curTime);
int beginIndex = is[0];
int endIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
}
} else if(getSpeed() < 0){
if(curTime <= minTime){
if(getRepeatType() == RT_WRAP){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = minTime - curTime;
curTime = maxTime - overshoot;
} else if (getRepeatType() == RT_CLAMP){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[1];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = beginPointTime;
curTime = minTime;
} else if(getRepeatType() == RT_CYCLE){
int[] is = findIndicesBeforeAfter(minTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
float overshoot = minTime - curTime;
curTime = minTime + overshoot;
setSpeed(- getSpeed());
}
} else if(curTime >= maxTime){
int[] is = findIndicesBeforeAfter(maxTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
curTime = maxTime;
} else{//curTime is inside minTime and maxTime
int[] is = findIndicesBeforeAfter(curTime);
int beginIndex = is[1];
int endIndex = is[0];
beginPointTime = ((PointInTime) keyframes.get(beginIndex));
endPointTime = ((PointInTime) keyframes.get(endIndex));
}
} else {
beginPointTime = ((PointInTime) keyframes.get(0));
endPointTime = ((PointInTime) keyframes.get(0));
}
}
|
diff --git a/src/anim/AnimStateMachine.java b/src/anim/AnimStateMachine.java
index 3590b2e..e5bd928 100644
--- a/src/anim/AnimStateMachine.java
+++ b/src/anim/AnimStateMachine.java
@@ -1,115 +1,114 @@
/**
*
*/
package anim;
import java.util.EnumMap;
import org.newdawn.slick.Animation;
import util.Direction;
import entities.Entity;
/**
* A state machine for handling animation transitions
* @author Mullings
*
*/
public class AnimStateMachine {
private EnumMap<AnimationState, Animation> animMap;
protected AnimationState currentState;
public AnimStateMachine() {
animMap = new EnumMap<AnimationState, Animation>(AnimationState.class);
}
public void addAnimation(AnimationState type, Animation animation) {
animMap.put(type, animation);
}
public void update(Entity entity) {
if (currentState == null) return;
if (currentState == AnimationState.FALL && animMap.get(AnimationState.START_JUMP) != null) {
animMap.get(AnimationState.START_JUMP).restart();
}
switch(currentState) {
case JUMP:
case RISE:
if (entity.getPhysicsBody().getLinearVelocity().y >= 0) {
play(AnimationState.FALL);
-// System.out.println("JUMP => FALL");
}
break;
case HOOKING:
case FALL:
if (entity.isTouching(Direction.DOWN)) {
play(AnimationState.IDLE);
-// System.out.println("FALL => IDLE");
}
if (entity.getPhysicsBody().getLinearVelocity().y < 0) {
play(AnimationState.RISE);
-// System.out.println("JUMP => FALL");
}
break;
case IDLE:
case RUN:
if (!entity.isTouching(Direction.DOWN)) {
if (entity.getPhysicsBody().getLinearVelocity().y >= 0) {
play(AnimationState.FALL);
-// System.out.println("JUMP => FALL");
} else {
- play(AnimationState.JUMP);
+ play(AnimationState.RISE);
+ }
+ } else {
+ if (entity.getPhysicsBody().getLinearVelocity().x == 0) {
+ play(AnimationState.IDLE);
}
-// System.out.println("IDLE/RUN => FALL");
}
break;
}
}
public boolean play(AnimationState state) {
if (currentState == null || currentState.canChangeTo(state)) {
currentState = state;
return true;
}
return false;
}
public AnimationState getCurrentState() {
return currentState;
}
public Animation getCurrentAnimation() {
if (currentState != null) {
if (currentState.transitionsFrom() == null )
return animMap.get(currentState);
Animation transition = animMap.get(currentState.transitionsFrom());
if (transition.isStopped()) {
return animMap.get(currentState);
} else {
return animMap.get(currentState.transitionsFrom());
}
}
return null;
}
public void setFrames(AnimationState as, int numFrames, int durPerFrame) {
for (int i = 0; i < numFrames; i++) {
Animation a = animMap.get(as);
a.setDuration(i, durPerFrame);
animMap.put(as, a);
}
for (int i = numFrames; i < animMap.get(as).getFrameCount(); i++) {
Animation a = animMap.get(as);
a.setDuration(i, 0);
animMap.put(as, a);
}
}
}
| false | true | public void update(Entity entity) {
if (currentState == null) return;
if (currentState == AnimationState.FALL && animMap.get(AnimationState.START_JUMP) != null) {
animMap.get(AnimationState.START_JUMP).restart();
}
switch(currentState) {
case JUMP:
case RISE:
if (entity.getPhysicsBody().getLinearVelocity().y >= 0) {
play(AnimationState.FALL);
// System.out.println("JUMP => FALL");
}
break;
case HOOKING:
case FALL:
if (entity.isTouching(Direction.DOWN)) {
play(AnimationState.IDLE);
// System.out.println("FALL => IDLE");
}
if (entity.getPhysicsBody().getLinearVelocity().y < 0) {
play(AnimationState.RISE);
// System.out.println("JUMP => FALL");
}
break;
case IDLE:
case RUN:
if (!entity.isTouching(Direction.DOWN)) {
if (entity.getPhysicsBody().getLinearVelocity().y >= 0) {
play(AnimationState.FALL);
// System.out.println("JUMP => FALL");
} else {
play(AnimationState.JUMP);
}
// System.out.println("IDLE/RUN => FALL");
}
break;
}
}
| public void update(Entity entity) {
if (currentState == null) return;
if (currentState == AnimationState.FALL && animMap.get(AnimationState.START_JUMP) != null) {
animMap.get(AnimationState.START_JUMP).restart();
}
switch(currentState) {
case JUMP:
case RISE:
if (entity.getPhysicsBody().getLinearVelocity().y >= 0) {
play(AnimationState.FALL);
}
break;
case HOOKING:
case FALL:
if (entity.isTouching(Direction.DOWN)) {
play(AnimationState.IDLE);
}
if (entity.getPhysicsBody().getLinearVelocity().y < 0) {
play(AnimationState.RISE);
}
break;
case IDLE:
case RUN:
if (!entity.isTouching(Direction.DOWN)) {
if (entity.getPhysicsBody().getLinearVelocity().y >= 0) {
play(AnimationState.FALL);
} else {
play(AnimationState.RISE);
}
} else {
if (entity.getPhysicsBody().getLinearVelocity().x == 0) {
play(AnimationState.IDLE);
}
}
break;
}
}
|
diff --git a/src/com/gildorymrp/gildorym/RollCommand.java b/src/com/gildorymrp/gildorym/RollCommand.java
index bb5d4ef..9ec1b40 100644
--- a/src/com/gildorymrp/gildorym/RollCommand.java
+++ b/src/com/gildorymrp/gildorym/RollCommand.java
@@ -1,61 +1,64 @@
package com.gildorymrp.gildorym;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class RollCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Integer amount = 1;
Integer maxRoll = 20;
Integer plus = 0;
String rollString = args[0];
+ String secondHalf;
if (rollString.contains("d")) {
amount = Integer.parseInt(rollString.split("d")[0]);
+ secondHalf = rollString.split("d")[1];
+ } else {
+ secondHalf = args[0];
}
if (amount >= 100) {
sender.sendMessage(ChatColor.RED + "You can't roll that many times!");
return true;
}
- String secondHalf = rollString.split("d")[1];
if (rollString.contains("+")) {
plus = Integer.parseInt(secondHalf.split("+")[1]);
maxRoll = Integer.parseInt(secondHalf.split("+")[0]);
} else {
maxRoll = Integer.parseInt(secondHalf);
}
Set<Integer> rolls = new HashSet<Integer>();
Random random = new Random();
for (int i = 0; i < amount; i++) {
- rolls.add(random.nextInt(maxRoll));
+ rolls.add(random.nextInt(maxRoll) + 1);
}
String output = ChatColor.GRAY + "(";
Integer rollTotal = 0;
for (Integer roll : rolls) {
output += roll;
output += "+";
rollTotal += roll;
}
output += plus + ") = " + rollTotal;
if (sender instanceof Player) {
for (Player player : ((Player) sender).getWorld().getPlayers()) {
if (player.getLocation().distance(((Player) sender).getLocation()) <= 16) {
player.sendMessage(output);
}
}
} else {
sender.sendMessage(output);
}
return true;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Integer amount = 1;
Integer maxRoll = 20;
Integer plus = 0;
String rollString = args[0];
if (rollString.contains("d")) {
amount = Integer.parseInt(rollString.split("d")[0]);
}
if (amount >= 100) {
sender.sendMessage(ChatColor.RED + "You can't roll that many times!");
return true;
}
String secondHalf = rollString.split("d")[1];
if (rollString.contains("+")) {
plus = Integer.parseInt(secondHalf.split("+")[1]);
maxRoll = Integer.parseInt(secondHalf.split("+")[0]);
} else {
maxRoll = Integer.parseInt(secondHalf);
}
Set<Integer> rolls = new HashSet<Integer>();
Random random = new Random();
for (int i = 0; i < amount; i++) {
rolls.add(random.nextInt(maxRoll));
}
String output = ChatColor.GRAY + "(";
Integer rollTotal = 0;
for (Integer roll : rolls) {
output += roll;
output += "+";
rollTotal += roll;
}
output += plus + ") = " + rollTotal;
if (sender instanceof Player) {
for (Player player : ((Player) sender).getWorld().getPlayers()) {
if (player.getLocation().distance(((Player) sender).getLocation()) <= 16) {
player.sendMessage(output);
}
}
} else {
sender.sendMessage(output);
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Integer amount = 1;
Integer maxRoll = 20;
Integer plus = 0;
String rollString = args[0];
String secondHalf;
if (rollString.contains("d")) {
amount = Integer.parseInt(rollString.split("d")[0]);
secondHalf = rollString.split("d")[1];
} else {
secondHalf = args[0];
}
if (amount >= 100) {
sender.sendMessage(ChatColor.RED + "You can't roll that many times!");
return true;
}
if (rollString.contains("+")) {
plus = Integer.parseInt(secondHalf.split("+")[1]);
maxRoll = Integer.parseInt(secondHalf.split("+")[0]);
} else {
maxRoll = Integer.parseInt(secondHalf);
}
Set<Integer> rolls = new HashSet<Integer>();
Random random = new Random();
for (int i = 0; i < amount; i++) {
rolls.add(random.nextInt(maxRoll) + 1);
}
String output = ChatColor.GRAY + "(";
Integer rollTotal = 0;
for (Integer roll : rolls) {
output += roll;
output += "+";
rollTotal += roll;
}
output += plus + ") = " + rollTotal;
if (sender instanceof Player) {
for (Player player : ((Player) sender).getWorld().getPlayers()) {
if (player.getLocation().distance(((Player) sender).getLocation()) <= 16) {
player.sendMessage(output);
}
}
} else {
sender.sendMessage(output);
}
return true;
}
|
diff --git a/app/controllers/Application.java b/app/controllers/Application.java
index d44eebd..e69647a 100644
--- a/app/controllers/Application.java
+++ b/app/controllers/Application.java
@@ -1,27 +1,27 @@
package controllers;
import helpers.FedexServicesHelper;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import play.mvc.Controller;
public class Application extends Controller {
public static void index(){
render();
}
public static void getShippingRate(String zipCode,String jsoncallback) throws SAXException, IOException, ParserConfigurationException {
String rate = FedexServicesHelper.getShippingRateFor(zipCode);
if(jsoncallback!=null && jsoncallback.trim().length()>0){
response.contentType="application/x-javascript";
- renderTemplate("Application/index.jsonp",jsoncallback,rate);
+ renderTemplate("Application/shippingRate.jsonp",jsoncallback,rate);
}else{
render(rate);
}
}
}
| true | true | public static void getShippingRate(String zipCode,String jsoncallback) throws SAXException, IOException, ParserConfigurationException {
String rate = FedexServicesHelper.getShippingRateFor(zipCode);
if(jsoncallback!=null && jsoncallback.trim().length()>0){
response.contentType="application/x-javascript";
renderTemplate("Application/index.jsonp",jsoncallback,rate);
}else{
render(rate);
}
}
| public static void getShippingRate(String zipCode,String jsoncallback) throws SAXException, IOException, ParserConfigurationException {
String rate = FedexServicesHelper.getShippingRateFor(zipCode);
if(jsoncallback!=null && jsoncallback.trim().length()>0){
response.contentType="application/x-javascript";
renderTemplate("Application/shippingRate.jsonp",jsoncallback,rate);
}else{
render(rate);
}
}
|
diff --git a/mbt/src/org/tigris/mbt/generators/CodeGenerator.java b/mbt/src/org/tigris/mbt/generators/CodeGenerator.java
index 275d7a0..8bd69ff 100644
--- a/mbt/src/org/tigris/mbt/generators/CodeGenerator.java
+++ b/mbt/src/org/tigris/mbt/generators/CodeGenerator.java
@@ -1,59 +1,63 @@
package org.tigris.mbt.generators;
/**
* Will generate code using a template. The code generated will contain all
* lables/names defined by the vertices and edges. This enables the user to
* write templates for a multitude of scripting or programming languages.<br>
* <br>
* There is 2 variables in the template that will be replaced as follows:<br>
* <strong>{LABEL}</strong> Will be replace by the actual name of the edge or
* vertex.<br>
* <strong>{EDGE_VERTEX}</strong> Will be replace by the word 'Edge' or
* 'Vertex'.<br>
* <br>
* <strong>Below is an example of a template.</strong>
*
* <pre>
* /**
* * This method implements the {EDGE_VERTEX} '{LABEL}'
* * /
* public void {LABEL}()
* {
* log.info( "{EDGE_VERTEX}: {LABEL}" );
* throw new RuntimeException( "Not implemented" );
* }
* </pre>
*/
public class CodeGenerator extends ListGenerator {
String[] template; // {HEADER, BODY, FOOTER}
private boolean first = true;
public CodeGenerator() {
super();
}
public CodeGenerator(String[] template) {
setTemplate(template);
}
public void setTemplate(String[] template) {
this.template = template;
}
public String[] getNext() {
String[] retur = super.getNext();
+ if ( retur[0].isEmpty() ) {
+ retur[1] = "";
+ return retur;
+ }
retur[0] = (first && template[0].length() > 0 ? template[0] + "\n" : "")
+ // HEADER
template[1] // BODY
.replaceAll("\\{LABEL\\}", retur[0]).replaceAll("\\{EDGE_VERTEX\\}", retur[1])
+ (!hasNext() && template[2].length() > 0 ? "\n" + template[2] : ""); // FOOTER
retur[1] = "";
first = false;
return retur;
}
public String toString() {
return "CODE";
}
}
| true | true | public String[] getNext() {
String[] retur = super.getNext();
retur[0] = (first && template[0].length() > 0 ? template[0] + "\n" : "")
+ // HEADER
template[1] // BODY
.replaceAll("\\{LABEL\\}", retur[0]).replaceAll("\\{EDGE_VERTEX\\}", retur[1])
+ (!hasNext() && template[2].length() > 0 ? "\n" + template[2] : ""); // FOOTER
retur[1] = "";
first = false;
return retur;
}
| public String[] getNext() {
String[] retur = super.getNext();
if ( retur[0].isEmpty() ) {
retur[1] = "";
return retur;
}
retur[0] = (first && template[0].length() > 0 ? template[0] + "\n" : "")
+ // HEADER
template[1] // BODY
.replaceAll("\\{LABEL\\}", retur[0]).replaceAll("\\{EDGE_VERTEX\\}", retur[1])
+ (!hasNext() && template[2].length() > 0 ? "\n" + template[2] : ""); // FOOTER
retur[1] = "";
first = false;
return retur;
}
|
diff --git a/src/main/java/org/elasticsearch/shell/jline/JLineConsole.java b/src/main/java/org/elasticsearch/shell/jline/JLineConsole.java
index f8a1728..ddab0fb 100644
--- a/src/main/java/org/elasticsearch/shell/jline/JLineConsole.java
+++ b/src/main/java/org/elasticsearch/shell/jline/JLineConsole.java
@@ -1,86 +1,86 @@
/*
* Licensed to Luca Cavanna (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.shell.jline;
import jline.console.ConsoleReader;
import jline.console.completer.Completer;
import jline.internal.ShutdownHooks;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Singleton;
import org.elasticsearch.common.inject.name.Named;
import org.elasticsearch.shell.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
@Singleton
public class JLineConsole implements Console {
private final ConsoleReader reader;
private final PrintStream out;
@Inject
JLineConsole(@Named("appName") String appName, @Named("shellInput") InputStream in, @Named("shellOutput") PrintStream out, Completer completer) {
this.out = out;
try {
this.reader = new ConsoleReader(appName, in, out, null);
reader.setBellEnabled(false);
reader.addCompleter(completer);
- //TODO add a real shutdown hooks (e.g. shutdown all running client nodes etc.)
+ //TODO add a real shutdown hook (e.g. shutdown all running client nodes etc.)
ShutdownHooks.add(new ShutdownHooks.Task() {
@Override
public void run() throws Exception {
JLineConsole.this.out.println("bye");
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void print(String message) {
out.print(message);
}
public void println() {
out.println();
}
public void println(String message) {
out.println(message);
}
public String readLine(String prompt) throws Exception {
return reader.readLine(prompt);
}
public PrintStream getOut() {
return out;
}
@Override
public void shutdown() {
reader.shutdown();
}
}
| true | true | JLineConsole(@Named("appName") String appName, @Named("shellInput") InputStream in, @Named("shellOutput") PrintStream out, Completer completer) {
this.out = out;
try {
this.reader = new ConsoleReader(appName, in, out, null);
reader.setBellEnabled(false);
reader.addCompleter(completer);
//TODO add a real shutdown hooks (e.g. shutdown all running client nodes etc.)
ShutdownHooks.add(new ShutdownHooks.Task() {
@Override
public void run() throws Exception {
JLineConsole.this.out.println("bye");
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
| JLineConsole(@Named("appName") String appName, @Named("shellInput") InputStream in, @Named("shellOutput") PrintStream out, Completer completer) {
this.out = out;
try {
this.reader = new ConsoleReader(appName, in, out, null);
reader.setBellEnabled(false);
reader.addCompleter(completer);
//TODO add a real shutdown hook (e.g. shutdown all running client nodes etc.)
ShutdownHooks.add(new ShutdownHooks.Task() {
@Override
public void run() throws Exception {
JLineConsole.this.out.println("bye");
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/main/java/com/ning/http/client/providers/NettyAsyncHttpProvider.java b/src/main/java/com/ning/http/client/providers/NettyAsyncHttpProvider.java
index 8e5248aa1..5ec3bb45f 100644
--- a/src/main/java/com/ning/http/client/providers/NettyAsyncHttpProvider.java
+++ b/src/main/java/com/ning/http/client/providers/NettyAsyncHttpProvider.java
@@ -1,987 +1,991 @@
/*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.http.client.providers;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHandler.STATE;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.ByteArrayPart;
import com.ning.http.client.Cookie;
import com.ning.http.client.FilePart;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.MaxRedirectException;
import com.ning.http.client.Part;
import com.ning.http.client.ProgressAsyncHandler;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.RequestType;
import com.ning.http.client.Response;
import com.ning.http.client.StringPart;
import com.ning.http.client.logging.LogManager;
import com.ning.http.client.logging.Logger;
import com.ning.http.multipart.ByteArrayPartSource;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.multipart.PartSource;
import com.ning.http.util.AuthenticatorUtils;
import com.ning.http.util.SslUtils;
import com.ning.http.util.UTF8UrlEncoder;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferOutputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelFutureProgressListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DefaultFileRegion;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.FileRegion;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultCookie;
import org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedFile;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.HashedWheelTimer;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.jboss.netty.channel.Channels.pipeline;
public class NettyAsyncHttpProvider extends IdleStateHandler implements AsyncHttpProvider<HttpResponse> {
private final Logger log = LogManager.getLogger(NettyAsyncHttpProvider.class);
private final ClientBootstrap bootstrap;
private final static int MAX_BUFFERED_BYTES = 8192;
private final AsyncHttpClientConfig config;
private final ConcurrentHashMap<String, Channel> connectionsPool = new ConcurrentHashMap<String, Channel>();
private final AtomicInteger activeConnectionsCount = new AtomicInteger();
private final ConcurrentHashMap<String, AtomicInteger> connectionsPerHost = new ConcurrentHashMap<String, AtomicInteger>();
private final AtomicBoolean isClose = new AtomicBoolean(false);
private final NioClientSocketChannelFactory socketChannelFactory;
private final ChannelGroup openChannels = new DefaultChannelGroup("asyncHttpClient");
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
super(new HashedWheelTimer(), 0, 0, config.getIdleConnectionTimeoutInMs(), TimeUnit.MILLISECONDS) ;
socketChannelFactory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
config.executorService());
bootstrap = new ClientBootstrap(socketChannelFactory);
this.config = config;
}
void configure(final boolean useSSL, final ConnectListener<?> cl){
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
if (useSSL){
try{
SSLEngine sslEngine = config.getSSLEngine();
if (sslEngine == null){
sslEngine = SslUtils.getSSLEngine();
}
pipeline.addLast("ssl", new SslHandler(sslEngine));
} catch (Throwable ex){
cl.future().abort(ex);
}
}
pipeline.addLast("codec", new HttpClientCodec());
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
}
private Channel lookupInCache(URI uri) {
Channel channel = connectionsPool.remove(getBaseUrl(uri));
if (channel != null) {
/**
* The Channel will eventually be closed by Netty and will becomes invalid.
* We might suffer a memory leak if we don't scan for closed channel. The
* AsyncHttpClientConfig.reaper() will always make sure those are cleared.
*/
if (channel.isOpen()) {
channel.setReadable(true);
} else {
return null;
}
}
return channel;
}
/**
* Non Blocking connect.
*/
private final static class ConnectListener<T> implements ChannelFutureListener {
private final AsyncHttpClientConfig config;
private final NettyResponseFuture<T> future;
private final HttpRequest nettyRequest;
private ConnectListener(AsyncHttpClientConfig config,
NettyResponseFuture<T> future,
HttpRequest nettyRequest) {
this.config = config;
this.future = future;
this.nettyRequest = nettyRequest;
}
public NettyResponseFuture<T> future() {
return future;
}
public final void operationComplete(ChannelFuture f) throws Exception {
try {
executeRequest(f.getChannel(), config, future, nettyRequest);
} catch (ConnectException ex){
future.abort(ex);
}
}
public static class Builder<T> {
private final Logger log = LogManager.getLogger(Builder.class);
private final AsyncHttpClientConfig config;
private final Request request;
private final AsyncHandler<T> asyncHandler;
private NettyResponseFuture<T> future;
public Builder(AsyncHttpClientConfig config, Request request, AsyncHandler<T> asyncHandler) {
this.config = config;
this.request = request;
this.asyncHandler = asyncHandler;
this.future = null;
}
public Builder(AsyncHttpClientConfig config, Request request, AsyncHandler<T> asyncHandler, NettyResponseFuture<T> future) {
this.config = config;
this.request = request;
this.asyncHandler = asyncHandler;
this.future = future;
}
public ConnectListener<T> build() throws IOException {
URI uri = createUri(request.getRawUrl());
HttpRequest nettyRequest = buildRequest(config,request,uri);
log.debug("Executing the doConnect operation: %s", asyncHandler);
if (future == null){
future = new NettyResponseFuture<T>(uri, request, asyncHandler,
nettyRequest, config.getRequestTimeoutInMs());
}
return new ConnectListener<T>(config, future, nettyRequest);
}
}
}
private final static <T> void executeRequest(final Channel channel,
final AsyncHttpClientConfig config,
final NettyResponseFuture<T> future,
final HttpRequest nettyRequest) throws ConnectException {
if (!channel.isConnected()){
String url = channel.getRemoteAddress() != null ? channel.getRemoteAddress().toString() : null;
if (url == null) {
try {
url = future.getURI().toString();
} catch (MalformedURLException e) {
// ignored
}
}
throw new ConnectException(String.format("Connection refused to %s", url));
}
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(future);
/**
* Currently it is impossible to write the headers and the FIle using a single I/O operation.
* I've filled NETTY-XXX as an enhancement.
*/
channel.write(nettyRequest).addListener(new ProgressListener(true,future.getAsyncHandler()));
if (future.getRequest().getFile() != null) {
final File file = future.getRequest().getFile();
RandomAccessFile raf;
long fileLength = 0;
try {
raf = new RandomAccessFile(file, "r");
fileLength = raf.length();
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) != null) {
writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
writeFuture.addListener(new ProgressListener(false,future.getAsyncHandler()));
} else {
final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
writeFuture = channel.write(region);
writeFuture.addListener(new ProgressListener(false,future.getAsyncHandler()) {
public void operationComplete(ChannelFuture cf) {
region.releaseExternalResources();
super.operationComplete(cf);
}
});
}
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
try{
future.setReaperFuture(config.reaper().schedule(new Callable<Object>() {
public Object call() {
if (!future.isDone() && !future.isCancelled()) {
future.abort(new TimeoutException());
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(ClosedEvent.class);
}
return null;
}
}, config.getRequestTimeoutInMs(), TimeUnit.MILLISECONDS));
} catch (RejectedExecutionException ex){
future.abort(ex);
}
}
private final static HttpRequest buildRequest(AsyncHttpClientConfig config,Request request, URI uri) throws IOException{
return construct(config, request, new HttpMethod(request.getType().toString()), uri);
}
private final static URI createUri(String u) {
URI uri = URI.create(u);
final String scheme = uri.getScheme().toLowerCase();
if (scheme == null || !scheme.equals("http") && !scheme.equals("https")) {
throw new IllegalArgumentException("The URI scheme, of the URI " + u
+ ", must be equal (ignoring case) to 'http'");
}
String path = uri.getPath();
if (path == null) {
throw new IllegalArgumentException("The URI path, of the URI " + uri
+ ", must be non-null");
} else if (path.length() > 0 && path.charAt(0) != '/') {
throw new IllegalArgumentException("The URI path, of the URI " + uri
+ ". must start with a '/'");
} else if (path.length() == 0 ) {
return URI.create(u + "/");
}
return uri;
}
@SuppressWarnings("deprecation")
private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri) throws IOException {
String host = uri.getHost();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
StringBuilder path = new StringBuilder(uri.getPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
HttpRequest nettyRequest;
if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, uri.toString());
} else {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
- nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + getPort(uri));
+ if (uri.getPort() == -1) {
+ nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
+ } else {
+ nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
+ }
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
Realm realm = request.getRealm();
if (realm != null) {
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
default:
throw new IllegalStateException("Invalie AuthType");
}
}
String ka = config.getKeepAlive() ? "keep-alive" : "close";
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, ka);
if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest.setHeader("Proxy-Connection", ka);
}
if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
RequestType type = request.getType();
if (RequestType.POST.equals(type) || RequestType.PUT.equals(type)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8"));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(bytes, 0, length));
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes("UTF-8")));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE,"application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (file.isHidden() || !file.exists() || !file.isFile()) {
throw new IOException(String.format("File %s is not a file, is hidden or doesn't exist",file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, new RandomAccessFile(file, "r").length());
}
}
if (nettyRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE) == null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=utf-8");
}
return nettyRequest;
}
public void close() {
isClose.set(true);
connectionsPool.clear();
openChannels.close();
this.releaseExternalResources();
config.reaper().shutdown();
config.executorService().shutdown();
socketChannelFactory.releaseExternalResources();
bootstrap.releaseExternalResources();
}
/* @Override */
public Response prepareResponse(final HttpResponseStatus status,
final HttpResponseHeaders headers,
final Collection<HttpResponseBodyPart> bodyParts) {
return new NettyAsyncResponse(status,headers,bodyParts);
}
/* @Override */
public <T> Future<T> execute(final Request request, final AsyncHandler<T> asyncHandler) throws IOException {
return doConnect(request,asyncHandler, null);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f) throws IOException {
doConnect(request,f.getAsyncHandler(),f);
}
private <T> Future<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f) throws IOException{
if (isClose.get()){
throw new IOException("Closed");
}
if (config.getMaxTotalConnections() != -1 && activeConnectionsCount.getAndIncrement() >= config.getMaxTotalConnections()) {
activeConnectionsCount.decrementAndGet();
throw new IOException("Too many connections");
}
URI uri = createUri(request.getUrl());
log.debug("Lookup cache: %s", uri);
Channel channel = lookupInCache(uri);
if (channel != null && channel.isOpen()) {
if (channel.isConnected()) {
// Decrement the count as this is not a new connection.
if (config.getMaxConnectionPerHost() == -1) {
activeConnectionsCount.decrementAndGet();
}
HttpRequest nettyRequest = buildRequest(config,request,uri);
if (f == null) {
f = new NettyResponseFuture<T>(uri, request, asyncHandler,
nettyRequest, config.getRequestTimeoutInMs());
}
try {
executeRequest(channel, config,f,nettyRequest);
return f;
} catch (ConnectException ex) {
// The connection failed because the channel got remotly closed
// Let continue the normal processing.
connectionsPool.remove(channel);
}
} else {
connectionsPool.remove(channel);
}
}
ConnectListener<T> c = new ConnectListener.Builder<T>(config, request, asyncHandler,f).build();
configure(uri.getScheme().compareToIgnoreCase("https") == 0, c);
ChannelFuture channelFuture;
try{
if (config.getProxyServer() == null && request.getProxyServer() == null) {
channelFuture = bootstrap.connect(new InetSocketAddress(uri.getHost(), getPort(uri)));
} else {
ProxyServer proxy = (request.getProxyServer() == null ? config.getProxyServer() : request.getProxyServer());
channelFuture = bootstrap.connect(new InetSocketAddress(proxy.getHost(), proxy.getPort()));
}
bootstrap.setOption("connectTimeout", config.getConnectionTimeoutInMs());
} catch (Throwable t){
if (config.getMaxTotalConnections() != -1) {
activeConnectionsCount.decrementAndGet();
}
log.error(t);
c.future().abort(t.getCause());
return c.future();
}
channelFuture.addListener(c);
openChannels.add(channelFuture.getChannel());
return c.future();
}
@Override
protected void channelIdle(ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
closeChannel(ctx);
for (Entry<String,Channel> e: connectionsPool.entrySet()) {
if (e.getValue().equals(ctx.getChannel())) {
connectionsPool.remove(e.getKey());
if (config.getMaxTotalConnections() != -1) {
activeConnectionsCount.decrementAndGet();
}
break;
}
}
future.abort(new IOException("No response received. Connection timed out after " + config.getIdleConnectionTimeoutInMs()));
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
// Discard in memory bytes if the HttpContent.interrupt() has been invoked.
if (ctx.getAttachment() instanceof DiscardEvent) {
ctx.getChannel().setReadable(false);
return;
} else if ( !(ctx.getAttachment() instanceof NettyResponseFuture<?>)) {
// The IdleStateHandler times out and he is calling us.
// We already closed the channel in IdleStateHandler#channelIdle
// so we have nothing to do
return;
}
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
HttpRequest nettyRequest = future.getNettyRequest();
AsyncHandler<?> handler = future.getAsyncHandler();
try{
if (e.getMessage() instanceof HttpResponse) {
HttpResponse response = (HttpResponse) e.getMessage();
// Required if there is some trailing headers.
future.setHttpResponse(response);
String ka = response.getHeader(HttpHeaders.Names.CONNECTION);
future.setKeepAlive(ka == null || ka.toLowerCase().equals("keep-alive"));
String wwwAuth = response.getHeader(HttpHeaders.Names.WWW_AUTHENTICATE);
Request request = future.getRequest();
if (response.getStatus().getCode() == 401
&& wwwAuth != null
&& future.getRequest().getRealm() != null
&& !future.isInDigestAuth()) {
Realm realm = new Realm.RealmBuilder().clone(request.getRealm())
.parseWWWAuthenticateHeader(wwwAuth)
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getType().toString())
.setScheme(Realm.AuthScheme.DIGEST)
.build();
// If authentication fail, we don't want to end up here again.
future.setInDigestAuth(true);
log.debug("Sending authentication to %s", request.getUrl());
//Cache our current connection so we don't have to re-open it.
markAsDoneAndCacheConnection(future, ctx.getChannel(), false);
RequestBuilder builder = new RequestBuilder(future.getRequest());
execute(builder.setRealm(realm).build(),future);
return;
}
if (config.isRedirectEnabled()
&& (response.getStatus().getCode() == 302 || response.getStatus().getCode() == 301) ){
if (future.incrementAndGetCurrentRedirectCount() < config.getMaxRedirects()) {
String location = response.getHeader(HttpHeaders.Names.LOCATION);
if (location.startsWith("/")) {
location = getBaseUrl(future.getURI()) + location;
}
URI uri = createUri(location);
RequestBuilder builder = new RequestBuilder(future.getRequest());
future.setURI(uri);
closeChannel(ctx);
String newUrl = uri.toString();
log.debug("Redirecting to %s", newUrl);
execute(builder.setUrl(newUrl).build(),future);
return;
} else {
throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects());
}
}
if (log.isDebugEnabled()){
log.debug("Status: %s", response.getStatus());
log.debug("Version: %s", response.getProtocolVersion());
log.debug("\"");
if (!response.getHeaderNames().isEmpty()) {
for (String name : response.getHeaderNames()) {
log.debug("Header: %s = %s", name, response.getHeaders(name));
}
log.debug("\"");
}
}
if (updateStatusAndInterrupt(handler, new ResponseStatus(future.getURI(),response, this))) {
finishUpdate(future, ctx);
return;
} else if (updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(),response, this))) {
finishUpdate(future, ctx);
return;
} else if (!response.isChunked()) {
if (response.getContent().readableBytes() != 0) {
updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(),response, this));
}
finishUpdate(future, ctx);
return;
}
if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
markAsDoneAndCacheConnection(future, ctx.getChannel(), true);
}
} else if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (handler != null) {
if (chunk.isLast() || updateBodyAndInterrupt(handler, new ResponseBodyPart(future.getURI(),null, this,chunk))) {
if (chunk instanceof DefaultHttpChunkTrailer) {
updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(),
future.getHttpResponse(), this, (HttpChunkTrailer) chunk));
}
finishUpdate(future, ctx);
}
}
}
} catch (Exception t){
try {
future.abort(t);
} finally {
finishUpdate(future,ctx);
throw t;
}
}
}
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
log.debug("Channel closed: %s", e.getState());
if (!isClose.get() && ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
if (future!= null && !future.isDone() && !future.isCancelled()){
try {
future.getAsyncHandler().onThrowable(new IOException("No response received. Connection timed out"));
} catch (Throwable t) {
log.error(t);
}
}
connectionsPool.remove(ctx.getChannel());
}
ctx.sendUpstream(e);
}
private void markAsDoneAndCacheConnection(final NettyResponseFuture<?> future, final Channel channel, boolean releaseFuture) throws MalformedURLException {
if (future.getKeepAlive()){
AtomicInteger connectionPerHost = connectionsPerHost.get(getBaseUrl(future.getURI()));
if (connectionPerHost == null) {
connectionPerHost = new AtomicInteger(1);
connectionsPerHost.put(getBaseUrl(future.getURI()),connectionPerHost);
}
if (config.getMaxConnectionPerHost() == -1 || connectionPerHost.getAndIncrement() < config.getMaxConnectionPerHost()) {
connectionsPool.put(getBaseUrl(future.getURI()), channel);
} else {
connectionPerHost.decrementAndGet();
log.warn("Maximum connections per hosts reached " + config.getMaxConnectionPerHost());
}
} else if (config.getMaxTotalConnections() != -1) {
activeConnectionsCount.decrementAndGet();
}
if (releaseFuture)
future.done();
}
private String getBaseUrl(URI uri){
String url = uri.getScheme() + "://" + uri.getAuthority();
int port = uri.getPort();
if (port == -1) {
port = getPort(uri);
url += ":" + port;
}
return url;
}
private static int getPort(URI uri) {
int port = uri.getPort();
if (port == -1)
port = uri.getScheme().equals("http")? 80: 443 ;
return port;
}
private void finishUpdate(NettyResponseFuture<?> future, ChannelHandlerContext ctx) throws IOException {
closeChannel(ctx);
markAsDoneAndCacheConnection(future, ctx.getChannel(), true);
}
private void closeChannel(ChannelHandlerContext ctx) {
// Catch any unexpected exception when marking the channel.
ctx.setAttachment(new DiscardEvent());
try{
ctx.getChannel().setReadable(false);
} catch (Exception ex){
log.debug(ex);
}
}
@SuppressWarnings("unchecked")
private final boolean updateStatusAndInterrupt(AsyncHandler handler, HttpResponseStatus c) throws Exception {
return handler.onStatusReceived(c) != STATE.CONTINUE;
}
@SuppressWarnings("unchecked")
private final boolean updateHeadersAndInterrupt(AsyncHandler handler, HttpResponseHeaders c) throws Exception {
return handler.onHeadersReceived(c) != STATE.CONTINUE;
}
@SuppressWarnings("unchecked")
private final boolean updateBodyAndInterrupt(AsyncHandler handler, HttpResponseBodyPart c) throws Exception {
return handler.onBodyPartReceived(c) != STATE.CONTINUE;
}
//Simple marker for stopping publishing bytes.
private final static class DiscardEvent {
}
//Simple marker for closed events
private final static class ClosedEvent {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
Channel ch = e.getChannel();
Throwable cause = e.getCause();
if (log.isDebugEnabled())
log.debug("I/O Exception during read or doConnect: ", cause);
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
if (future!= null){
try {
future.getAsyncHandler().onThrowable(cause);
} catch (Throwable t) {
log.error(t);
}
}
}
if (log.isDebugEnabled()){
log.debug(e.toString());
log.debug(ch.toString());
}
}
private final static int computeAndSetContentLength(Request request, HttpRequest r) {
int lenght = (int) request.getLength();
if (lenght == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) {
lenght = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH));
}
if (lenght != -1) {
r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(lenght));
}
return lenght;
}
/**
* This is quite ugly as our internal names are duplicated, but we build on top of HTTP Client implementation.
* @param params
* @param methodParams
* @return
* @throws java.io.FileNotFoundException
*/
private final static MultipartRequestEntity createMultipartRequestEntity(List<Part> params, FluentStringsMap methodParams) throws FileNotFoundException {
com.ning.http.multipart.Part[] parts = new com.ning.http.multipart.Part[params.size()];
int i = 0;
for (Part part : params) {
if (part instanceof StringPart) {
parts[i] = new com.ning.http.multipart.StringPart(part.getName(),
((StringPart) part).getValue(),
"UTF-8");
} else if (part instanceof FilePart) {
parts[i] = new com.ning.http.multipart.FilePart(part.getName(),
((FilePart) part).getFile(),
((FilePart) part).getMimeType(),
((FilePart) part).getCharSet());
} else if (part instanceof ByteArrayPart) {
PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(), ((ByteArrayPart) part).getData());
parts[i] = new com.ning.http.multipart.FilePart(part.getName(),
source,
((ByteArrayPart) part).getMimeType(),
((ByteArrayPart) part).getCharSet());
} else if (part == null) {
throw new NullPointerException("Part cannot be null");
} else {
throw new IllegalArgumentException(String.format("Unsupported part type for multipart parameter %s",
part.getName()));
}
++i;
}
return new MultipartRequestEntity(parts, methodParams);
}
// TODO: optimize; better use segmented-buffer to avoid reallocs (expand-by-doubling)
private static byte[] readFully(InputStream in, int[] lengthWrapper) throws IOException
{
// just in case available() returns bogus (or -1), allocate non-trivial chunk
byte[] b = new byte[Math.max(512, in.available())];
int offset = 0;
while (true) {
int left = b.length - offset;
int count = in.read(b, offset, left);
if (count < 0) { // EOF
break;
}
offset += count;
if (count == left) { // full buffer, need to expand
b = doubleUp(b);
}
}
// wish Java had Tuple return type...
lengthWrapper[0] = offset;
return b;
}
private static byte[] doubleUp(byte[] b)
{
// TODO: in Java 1.6, we would use Arrays.copyOf(), but for now we only rely on 1.5:
int len = b.length;
byte[] b2 = new byte[len+len];
System.arraycopy(b,0,b2,0,len);
return b2;
}
private static class ProgressListener implements ChannelFutureProgressListener {
private final boolean notifyHeaders;
private final AsyncHandler asyncHandler;
public ProgressListener(boolean notifyHeaders, AsyncHandler asyncHandler) {
this.notifyHeaders = notifyHeaders;
this.asyncHandler = asyncHandler;
}
public void operationComplete(ChannelFuture cf) {
if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
if (notifyHeaders) {
ProgressAsyncHandler.class.cast(asyncHandler).onHeaderWriteCompleted();
} else {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteCompleted();
}
}
}
public void operationProgressed(ChannelFuture cf, long amount, long current, long total) {
if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteProgess(amount,current,total);
}
}
}
}
| true | true | private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri) throws IOException {
String host = uri.getHost();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
StringBuilder path = new StringBuilder(uri.getPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
HttpRequest nettyRequest;
if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, uri.toString());
} else {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + getPort(uri));
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
Realm realm = request.getRealm();
if (realm != null) {
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
default:
throw new IllegalStateException("Invalie AuthType");
}
}
String ka = config.getKeepAlive() ? "keep-alive" : "close";
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, ka);
if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest.setHeader("Proxy-Connection", ka);
}
if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
RequestType type = request.getType();
if (RequestType.POST.equals(type) || RequestType.PUT.equals(type)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8"));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(bytes, 0, length));
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes("UTF-8")));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE,"application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (file.isHidden() || !file.exists() || !file.isFile()) {
throw new IOException(String.format("File %s is not a file, is hidden or doesn't exist",file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, new RandomAccessFile(file, "r").length());
}
}
if (nettyRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE) == null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=utf-8");
}
return nettyRequest;
}
| private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri) throws IOException {
String host = uri.getHost();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
StringBuilder path = new StringBuilder(uri.getPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
HttpRequest nettyRequest;
if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, uri.toString());
} else {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
Realm realm = request.getRealm();
if (realm != null) {
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
default:
throw new IllegalStateException("Invalie AuthType");
}
}
String ka = config.getKeepAlive() ? "keep-alive" : "close";
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, ka);
if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest.setHeader("Proxy-Connection", ka);
}
if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
RequestType type = request.getType();
if (RequestType.POST.equals(type) || RequestType.PUT.equals(type)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8"));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(bytes, 0, length));
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes("UTF-8")));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE,"application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (file.isHidden() || !file.exists() || !file.isFile()) {
throw new IOException(String.format("File %s is not a file, is hidden or doesn't exist",file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, new RandomAccessFile(file, "r").length());
}
}
if (nettyRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE) == null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=utf-8");
}
return nettyRequest;
}
|
diff --git a/src/com/android/camera/PhotoMenu.java b/src/com/android/camera/PhotoMenu.java
index db49efbf1..0bfc075cb 100644
--- a/src/com/android/camera/PhotoMenu.java
+++ b/src/com/android/camera/PhotoMenu.java
@@ -1,305 +1,285 @@
/*
* Copyright (C) 2012 The Android Open Source Project
* Copyright (C) 2013 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera;
import android.content.Context;
import android.content.res.Resources;
import android.hardware.Camera.Parameters;
import android.view.LayoutInflater;
import com.android.camera.ui.AbstractSettingPopup;
import com.android.camera.ui.CountdownTimerPopup;
import com.android.camera.ui.ListPrefSettingPopup;
import com.android.camera.ui.MoreSettingPopup;
import com.android.camera.ui.PieItem;
import com.android.camera.ui.PieItem.OnClickListener;
import com.android.camera.ui.PieRenderer;
import com.android.gallery3d.R;
import java.util.Locale;
public class PhotoMenu extends PieController
implements MoreSettingPopup.Listener,
CountdownTimerPopup.Listener,
ListPrefSettingPopup.Listener {
private static String TAG = "CAM_photomenu";
private final String mSettingOff;
private PhotoUI mUI;
private String[] mOtherKeys;
private AbstractSettingPopup mPopup;
private static final int POPUP_NONE = 0;
private static final int POPUP_FIRST_LEVEL = 1;
private static final int POPUP_SECOND_LEVEL = 2;
private int mPopupStatus;
private CameraActivity mActivity;
public PhotoMenu(CameraActivity activity, PhotoUI ui, PieRenderer pie) {
super(activity, pie);
mUI = ui;
mSettingOff = activity.getString(R.string.setting_off_value);
mActivity = activity;
}
public void initialize(PreferenceGroup group) {
super.initialize(group);
mPopup = null;
mPopupStatus = POPUP_NONE;
PieItem item = null;
final Resources res = mActivity.getResources();
Locale locale = res.getConfiguration().locale;
// the order is from left to right in the menu
// hdr
if (group.findPreference(CameraSettings.KEY_CAMERA_HDR) != null) {
item = makeSwitchItem(CameraSettings.KEY_CAMERA_HDR, true);
mRenderer.addItem(item);
}
// exposure compensation
if (group.findPreference(CameraSettings.KEY_EXPOSURE) != null) {
item = makeItem(CameraSettings.KEY_EXPOSURE);
item.setLabel(res.getString(R.string.pref_exposure_label));
mRenderer.addItem(item);
}
// more settings
PieItem more = makeItem(R.drawable.ic_settings_holo_light);
more.setLabel(res.getString(R.string.camera_menu_settings_label));
mRenderer.addItem(more);
// flash
if (group.findPreference(CameraSettings.KEY_FLASH_MODE) != null) {
item = makeItem(CameraSettings.KEY_FLASH_MODE);
item.setLabel(res.getString(R.string.pref_camera_flashmode_label));
mRenderer.addItem(item);
}
// camera switcher
if (group.findPreference(CameraSettings.KEY_CAMERA_ID) != null) {
item = makeSwitchItem(CameraSettings.KEY_CAMERA_ID, false);
final PieItem fitem = item;
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
// Find the index of next camera.
ListPreference pref = mPreferenceGroup
.findPreference(CameraSettings.KEY_CAMERA_ID);
if (pref != null) {
int index = pref.findIndexOfValue(pref.getValue());
CharSequence[] values = pref.getEntryValues();
index = (index + 1) % values.length;
pref.setValueIndex(index);
mListener.onCameraPickerClicked(index);
}
updateItem(fitem, CameraSettings.KEY_CAMERA_ID);
}
});
mRenderer.addItem(item);
}
// location
if (group.findPreference(CameraSettings.KEY_RECORD_LOCATION) != null) {
item = makeSwitchItem(CameraSettings.KEY_RECORD_LOCATION, true);
more.addItem(item);
if (mActivity.isSecureCamera()) {
// Prevent location preference from getting changed in secure camera mode
item.setEnabled(false);
}
}
// countdown timer
final ListPreference ctpref = group.findPreference(CameraSettings.KEY_TIMER);
final ListPreference beeppref =
group.findPreference(CameraSettings.KEY_TIMER_SOUND_EFFECTS);
item = makeItem(R.drawable.ic_timer);
item.setLabel(res.getString(R.string.pref_camera_timer_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
CountdownTimerPopup timerPopup =
(CountdownTimerPopup) mActivity.getLayoutInflater().inflate(
R.layout.countdown_setting_popup, null, false);
timerPopup.initialize(ctpref, beeppref);
timerPopup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = timerPopup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
// image size
final ListPreference sizePref = group.findPreference(CameraSettings.KEY_PICTURE_SIZE);
if (sizePref != null) {
item = makeItem(R.drawable.ic_imagesize);
item.setLabel(res.getString(
R.string.pref_camera_picturesize_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
ListPrefSettingPopup popup =
(ListPrefSettingPopup) mActivity.getLayoutInflater().inflate(
R.layout.list_pref_setting_popup, null, false);
popup.initialize(sizePref);
popup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = popup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
- // Storage location
- if (group.findPreference(CameraSettings.KEY_STORAGE) != null) {
- item = makeItem(R.drawable.stat_notify_sdcard);
- final ListPreference storagePref = group.findPreference(CameraSettings.KEY_STORAGE);
- item.setLabel(res.getString(R.string.pref_camera_storage_title).toUpperCase(locale));
- item.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(PieItem item) {
- LayoutInflater inflater = mActivity.getLayoutInflater();
- ListPrefSettingPopup popup = (ListPrefSettingPopup) inflater.inflate(
- R.layout.list_pref_setting_popup, null, false);
- popup.initialize(storagePref);
- popup.setSettingChangedListener(PhotoMenu.this);
- mUI.dismissPopup();
- mPopup = popup;
- mPopupStatus = POPUP_SECOND_LEVEL;
- mUI.showPopup(mPopup);
- }
- });
- more.addItem(item);
- }
// white balance
if (group.findPreference(CameraSettings.KEY_WHITE_BALANCE) != null) {
item = makeItem(CameraSettings.KEY_WHITE_BALANCE);
item.setLabel(res.getString(R.string.pref_camera_whitebalance_label));
more.addItem(item);
}
// scene mode
final ListPreference scenePref = group.findPreference(CameraSettings.KEY_SCENE_MODE);
if (scenePref != null) {
item = makeItem(R.drawable.ic_sce);
item.setLabel(res.getString(R.string.pref_camera_scenemode_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
LayoutInflater inflater = mActivity.getLayoutInflater();
ListPrefSettingPopup popup = (ListPrefSettingPopup) inflater.inflate(
R.layout.list_pref_setting_popup, null, false);
popup.initialize(scenePref);
popup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = popup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
// extra settings popup
mOtherKeys = new String[] {
+ CameraSettings.KEY_STORAGE,
CameraSettings.KEY_FOCUS_MODE,
CameraSettings.KEY_FOCUS_TIME,
CameraSettings.KEY_POWER_SHUTTER,
CameraSettings.KEY_ISO_MODE,
CameraSettings.KEY_JPEG,
CameraSettings.KEY_COLOR_EFFECT,
CameraSettings.KEY_BURST_MODE
};
item = makeItem(R.drawable.ic_settings_holo_light);
item.setLabel(res.getString(R.string.camera_menu_more_label).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
if (mPopup == null || mPopupStatus != POPUP_FIRST_LEVEL) {
LayoutInflater inflater = mActivity.getLayoutInflater();
MoreSettingPopup popup = (MoreSettingPopup) inflater.inflate(
R.layout.more_setting_popup, null, false);
popup.initialize(mPreferenceGroup, mOtherKeys);
popup.setSettingChangedListener(PhotoMenu.this);
mPopup = popup;
mPopupStatus = POPUP_FIRST_LEVEL;
}
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
@Override
// Hit when an item in a popup gets selected
public void onListPrefChanged(ListPreference pref) {
if (mPopup != null) {
if (mPopupStatus == POPUP_SECOND_LEVEL) {
mUI.dismissPopup();
}
}
onSettingChanged(pref);
}
public void popupDismissed() {
// the popup gets dismissed
if (mPopup != null) {
if (mPopupStatus == POPUP_SECOND_LEVEL) {
mPopup = null;
}
}
}
// Return true if the preference has the specified key but not the value.
private static boolean notSame(ListPreference pref, String key, String value) {
return (key.equals(pref.getKey()) && !value.equals(pref.getValue()));
}
private void setPreference(String key, String value) {
ListPreference pref = mPreferenceGroup.findPreference(key);
if (pref != null && !value.equals(pref.getValue())) {
pref.setValue(value);
reloadPreferences();
}
}
@Override
public void onSettingChanged(ListPreference pref) {
// Reset the scene mode if HDR is set to on. Reset HDR if scene mode is
// set to non-auto.
if (notSame(pref, CameraSettings.KEY_CAMERA_HDR, mSettingOff)) {
setPreference(CameraSettings.KEY_SCENE_MODE, Parameters.SCENE_MODE_AUTO);
} else if (notSame(pref, CameraSettings.KEY_SCENE_MODE, Parameters.SCENE_MODE_AUTO)) {
setPreference(CameraSettings.KEY_CAMERA_HDR, mSettingOff);
}
super.onSettingChanged(pref);
}
@Override
// Hit when an item in the first-level popup gets selected, then bring up
// the second-level popup
public void onPreferenceClicked(ListPreference pref) {
if (mPopupStatus != POPUP_FIRST_LEVEL) return;
LayoutInflater inflater = mActivity.getLayoutInflater();
ListPrefSettingPopup basic = (ListPrefSettingPopup) inflater.inflate(
R.layout.list_pref_setting_popup, null, false);
basic.initialize(pref);
basic.setSettingChangedListener(this);
mUI.dismissPopup();
mPopup = basic;
mUI.showPopup(mPopup);
mPopupStatus = POPUP_SECOND_LEVEL;
}
}
| false | true | public void initialize(PreferenceGroup group) {
super.initialize(group);
mPopup = null;
mPopupStatus = POPUP_NONE;
PieItem item = null;
final Resources res = mActivity.getResources();
Locale locale = res.getConfiguration().locale;
// the order is from left to right in the menu
// hdr
if (group.findPreference(CameraSettings.KEY_CAMERA_HDR) != null) {
item = makeSwitchItem(CameraSettings.KEY_CAMERA_HDR, true);
mRenderer.addItem(item);
}
// exposure compensation
if (group.findPreference(CameraSettings.KEY_EXPOSURE) != null) {
item = makeItem(CameraSettings.KEY_EXPOSURE);
item.setLabel(res.getString(R.string.pref_exposure_label));
mRenderer.addItem(item);
}
// more settings
PieItem more = makeItem(R.drawable.ic_settings_holo_light);
more.setLabel(res.getString(R.string.camera_menu_settings_label));
mRenderer.addItem(more);
// flash
if (group.findPreference(CameraSettings.KEY_FLASH_MODE) != null) {
item = makeItem(CameraSettings.KEY_FLASH_MODE);
item.setLabel(res.getString(R.string.pref_camera_flashmode_label));
mRenderer.addItem(item);
}
// camera switcher
if (group.findPreference(CameraSettings.KEY_CAMERA_ID) != null) {
item = makeSwitchItem(CameraSettings.KEY_CAMERA_ID, false);
final PieItem fitem = item;
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
// Find the index of next camera.
ListPreference pref = mPreferenceGroup
.findPreference(CameraSettings.KEY_CAMERA_ID);
if (pref != null) {
int index = pref.findIndexOfValue(pref.getValue());
CharSequence[] values = pref.getEntryValues();
index = (index + 1) % values.length;
pref.setValueIndex(index);
mListener.onCameraPickerClicked(index);
}
updateItem(fitem, CameraSettings.KEY_CAMERA_ID);
}
});
mRenderer.addItem(item);
}
// location
if (group.findPreference(CameraSettings.KEY_RECORD_LOCATION) != null) {
item = makeSwitchItem(CameraSettings.KEY_RECORD_LOCATION, true);
more.addItem(item);
if (mActivity.isSecureCamera()) {
// Prevent location preference from getting changed in secure camera mode
item.setEnabled(false);
}
}
// countdown timer
final ListPreference ctpref = group.findPreference(CameraSettings.KEY_TIMER);
final ListPreference beeppref =
group.findPreference(CameraSettings.KEY_TIMER_SOUND_EFFECTS);
item = makeItem(R.drawable.ic_timer);
item.setLabel(res.getString(R.string.pref_camera_timer_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
CountdownTimerPopup timerPopup =
(CountdownTimerPopup) mActivity.getLayoutInflater().inflate(
R.layout.countdown_setting_popup, null, false);
timerPopup.initialize(ctpref, beeppref);
timerPopup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = timerPopup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
// image size
final ListPreference sizePref = group.findPreference(CameraSettings.KEY_PICTURE_SIZE);
if (sizePref != null) {
item = makeItem(R.drawable.ic_imagesize);
item.setLabel(res.getString(
R.string.pref_camera_picturesize_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
ListPrefSettingPopup popup =
(ListPrefSettingPopup) mActivity.getLayoutInflater().inflate(
R.layout.list_pref_setting_popup, null, false);
popup.initialize(sizePref);
popup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = popup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
// Storage location
if (group.findPreference(CameraSettings.KEY_STORAGE) != null) {
item = makeItem(R.drawable.stat_notify_sdcard);
final ListPreference storagePref = group.findPreference(CameraSettings.KEY_STORAGE);
item.setLabel(res.getString(R.string.pref_camera_storage_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
LayoutInflater inflater = mActivity.getLayoutInflater();
ListPrefSettingPopup popup = (ListPrefSettingPopup) inflater.inflate(
R.layout.list_pref_setting_popup, null, false);
popup.initialize(storagePref);
popup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = popup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
// white balance
if (group.findPreference(CameraSettings.KEY_WHITE_BALANCE) != null) {
item = makeItem(CameraSettings.KEY_WHITE_BALANCE);
item.setLabel(res.getString(R.string.pref_camera_whitebalance_label));
more.addItem(item);
}
// scene mode
final ListPreference scenePref = group.findPreference(CameraSettings.KEY_SCENE_MODE);
if (scenePref != null) {
item = makeItem(R.drawable.ic_sce);
item.setLabel(res.getString(R.string.pref_camera_scenemode_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
LayoutInflater inflater = mActivity.getLayoutInflater();
ListPrefSettingPopup popup = (ListPrefSettingPopup) inflater.inflate(
R.layout.list_pref_setting_popup, null, false);
popup.initialize(scenePref);
popup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = popup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
// extra settings popup
mOtherKeys = new String[] {
CameraSettings.KEY_FOCUS_MODE,
CameraSettings.KEY_FOCUS_TIME,
CameraSettings.KEY_POWER_SHUTTER,
CameraSettings.KEY_ISO_MODE,
CameraSettings.KEY_JPEG,
CameraSettings.KEY_COLOR_EFFECT,
CameraSettings.KEY_BURST_MODE
};
item = makeItem(R.drawable.ic_settings_holo_light);
item.setLabel(res.getString(R.string.camera_menu_more_label).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
if (mPopup == null || mPopupStatus != POPUP_FIRST_LEVEL) {
LayoutInflater inflater = mActivity.getLayoutInflater();
MoreSettingPopup popup = (MoreSettingPopup) inflater.inflate(
R.layout.more_setting_popup, null, false);
popup.initialize(mPreferenceGroup, mOtherKeys);
popup.setSettingChangedListener(PhotoMenu.this);
mPopup = popup;
mPopupStatus = POPUP_FIRST_LEVEL;
}
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
| public void initialize(PreferenceGroup group) {
super.initialize(group);
mPopup = null;
mPopupStatus = POPUP_NONE;
PieItem item = null;
final Resources res = mActivity.getResources();
Locale locale = res.getConfiguration().locale;
// the order is from left to right in the menu
// hdr
if (group.findPreference(CameraSettings.KEY_CAMERA_HDR) != null) {
item = makeSwitchItem(CameraSettings.KEY_CAMERA_HDR, true);
mRenderer.addItem(item);
}
// exposure compensation
if (group.findPreference(CameraSettings.KEY_EXPOSURE) != null) {
item = makeItem(CameraSettings.KEY_EXPOSURE);
item.setLabel(res.getString(R.string.pref_exposure_label));
mRenderer.addItem(item);
}
// more settings
PieItem more = makeItem(R.drawable.ic_settings_holo_light);
more.setLabel(res.getString(R.string.camera_menu_settings_label));
mRenderer.addItem(more);
// flash
if (group.findPreference(CameraSettings.KEY_FLASH_MODE) != null) {
item = makeItem(CameraSettings.KEY_FLASH_MODE);
item.setLabel(res.getString(R.string.pref_camera_flashmode_label));
mRenderer.addItem(item);
}
// camera switcher
if (group.findPreference(CameraSettings.KEY_CAMERA_ID) != null) {
item = makeSwitchItem(CameraSettings.KEY_CAMERA_ID, false);
final PieItem fitem = item;
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
// Find the index of next camera.
ListPreference pref = mPreferenceGroup
.findPreference(CameraSettings.KEY_CAMERA_ID);
if (pref != null) {
int index = pref.findIndexOfValue(pref.getValue());
CharSequence[] values = pref.getEntryValues();
index = (index + 1) % values.length;
pref.setValueIndex(index);
mListener.onCameraPickerClicked(index);
}
updateItem(fitem, CameraSettings.KEY_CAMERA_ID);
}
});
mRenderer.addItem(item);
}
// location
if (group.findPreference(CameraSettings.KEY_RECORD_LOCATION) != null) {
item = makeSwitchItem(CameraSettings.KEY_RECORD_LOCATION, true);
more.addItem(item);
if (mActivity.isSecureCamera()) {
// Prevent location preference from getting changed in secure camera mode
item.setEnabled(false);
}
}
// countdown timer
final ListPreference ctpref = group.findPreference(CameraSettings.KEY_TIMER);
final ListPreference beeppref =
group.findPreference(CameraSettings.KEY_TIMER_SOUND_EFFECTS);
item = makeItem(R.drawable.ic_timer);
item.setLabel(res.getString(R.string.pref_camera_timer_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
CountdownTimerPopup timerPopup =
(CountdownTimerPopup) mActivity.getLayoutInflater().inflate(
R.layout.countdown_setting_popup, null, false);
timerPopup.initialize(ctpref, beeppref);
timerPopup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = timerPopup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
// image size
final ListPreference sizePref = group.findPreference(CameraSettings.KEY_PICTURE_SIZE);
if (sizePref != null) {
item = makeItem(R.drawable.ic_imagesize);
item.setLabel(res.getString(
R.string.pref_camera_picturesize_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
ListPrefSettingPopup popup =
(ListPrefSettingPopup) mActivity.getLayoutInflater().inflate(
R.layout.list_pref_setting_popup, null, false);
popup.initialize(sizePref);
popup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = popup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
// white balance
if (group.findPreference(CameraSettings.KEY_WHITE_BALANCE) != null) {
item = makeItem(CameraSettings.KEY_WHITE_BALANCE);
item.setLabel(res.getString(R.string.pref_camera_whitebalance_label));
more.addItem(item);
}
// scene mode
final ListPreference scenePref = group.findPreference(CameraSettings.KEY_SCENE_MODE);
if (scenePref != null) {
item = makeItem(R.drawable.ic_sce);
item.setLabel(res.getString(R.string.pref_camera_scenemode_title).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
LayoutInflater inflater = mActivity.getLayoutInflater();
ListPrefSettingPopup popup = (ListPrefSettingPopup) inflater.inflate(
R.layout.list_pref_setting_popup, null, false);
popup.initialize(scenePref);
popup.setSettingChangedListener(PhotoMenu.this);
mUI.dismissPopup();
mPopup = popup;
mPopupStatus = POPUP_SECOND_LEVEL;
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
// extra settings popup
mOtherKeys = new String[] {
CameraSettings.KEY_STORAGE,
CameraSettings.KEY_FOCUS_MODE,
CameraSettings.KEY_FOCUS_TIME,
CameraSettings.KEY_POWER_SHUTTER,
CameraSettings.KEY_ISO_MODE,
CameraSettings.KEY_JPEG,
CameraSettings.KEY_COLOR_EFFECT,
CameraSettings.KEY_BURST_MODE
};
item = makeItem(R.drawable.ic_settings_holo_light);
item.setLabel(res.getString(R.string.camera_menu_more_label).toUpperCase(locale));
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(PieItem item) {
if (mPopup == null || mPopupStatus != POPUP_FIRST_LEVEL) {
LayoutInflater inflater = mActivity.getLayoutInflater();
MoreSettingPopup popup = (MoreSettingPopup) inflater.inflate(
R.layout.more_setting_popup, null, false);
popup.initialize(mPreferenceGroup, mOtherKeys);
popup.setSettingChangedListener(PhotoMenu.this);
mPopup = popup;
mPopupStatus = POPUP_FIRST_LEVEL;
}
mUI.showPopup(mPopup);
}
});
more.addItem(item);
}
|
diff --git a/test/Regex.java b/test/Regex.java
index 22108dde..f6741397 100644
--- a/test/Regex.java
+++ b/test/Regex.java
@@ -1,96 +1,96 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex {
private static void expect(boolean v) {
if (! v) throw new RuntimeException();
}
private static Matcher getMatcher(String regex, String string) {
return Pattern.compile(regex).matcher(string);
}
private static void expectMatch(String regex, String string) {
expect(getMatcher(regex, string).matches());
}
private static void expectNoMatch(String regex, String string) {
expect(!getMatcher(regex, string).matches());
}
private static void expectGroups(String regex, String string,
String... groups) {
Matcher matcher = getMatcher(regex, string);
expect(matcher.matches());
expect(matcher.groupCount() == groups.length);
for (int i = 1; i <= groups.length; ++i) {
if (groups[i - 1] == null) {
expect(matcher.group(i) == null);
} else {
expect(groups[i - 1].equals(matcher.group(i)));
}
}
}
private static void expectFind(String regex, String string,
String... matches)
{
Matcher matcher = getMatcher(regex, string);
int i = 0;
while (i < matches.length) {
expect(matcher.find());
expect(matches[i++].equals(matcher.group()));
}
expect(!matcher.find());
}
private static void expectSplit(String regex, String string,
String... list)
{
String[] array = Pattern.compile(regex).split(string);
expect(array.length == list.length);
for (int i = 0; i < list.length; ++ i) {
expect(list[i].equals(array[i]));
}
}
public static void main(String[] args) {
expectMatch("a(bb)?a", "abba");
expectNoMatch("a(bb)?a", "abbba");
expectNoMatch("a(bb)?a", "abbaa");
expectGroups("a(a*?)(a?)(a??)(a+)(a*)a", "aaaaaa", "", "a", "", "aaa", "");
expectMatch("...", "abc");
expectNoMatch(".", "\n");
expectGroups("a(bb)*a", "abbbba", "bb");
expectGroups("a(bb)?(bb)+a", "abba", null, "bb");
expectFind(" +", "Hello , world! ", " ", " ", " ");
expectMatch("[0-9A-Fa-f]+", "08ef");
expectNoMatch("[0-9A-Fa-f]+", "08@ef");
expectGroups("(?:a)", "a");
expectGroups("a|(b|c)", "a", (String)null);
expectGroups("a|(b|c)", "c", "c");
expectGroups("(?=a)a", "a");
- expectGroups(".*(o)(?<=[A-Z][a-z]*)", "Hello", "o");
+ expectGroups(".*(o)(?<=[A-Z][a-z]{1,4})", "Hello", "o");
expectNoMatch("(?!a).", "a");
expectMatch("[\\d]", "0");
expectMatch("\\0777", "?7");
expectMatch("\\a", "\007");
expectMatch("\\\\", "\\");
expectMatch("\\x4A", "J");
expectMatch("\\x61", "a");
expectMatch("\\078", "\0078");
expectSplit("(?<=\\w)(?=\\W)|(?<=\\W)(?=\\w)", "a + b * x",
"a", " + ", "b", " * ", "x");
expectMatch("[0-9[def]]", "f");
expectNoMatch("[a-z&&[^d-f]]", "f");
expectSplit("^H", "Hello\nHobbes!", "", "ello\nHobbes!");
expectSplit("o.*?$", "Hello\r\nHobbes!", "Hello\r\nH");
expectSplit("\\b", "a+ b + c\nd", "", "a", "+ ", "b", " + ", "c", "\n", "d");
expectSplit("\\B", "Hi Cal!", "H", "i C", "a", "l!");
expectMatch("a{2,5}", "aaaa");
expectGroups("a??(a{2,5}?)", "aaaa", "aaaa");
expectGroups("a??(a{3}?)", "aaaa", "aaa");
expectNoMatch("a(a{3}?)", "aaaaa");
expectMatch("a(a{3,}?)", "aaaaa");
}
}
| true | true | public static void main(String[] args) {
expectMatch("a(bb)?a", "abba");
expectNoMatch("a(bb)?a", "abbba");
expectNoMatch("a(bb)?a", "abbaa");
expectGroups("a(a*?)(a?)(a??)(a+)(a*)a", "aaaaaa", "", "a", "", "aaa", "");
expectMatch("...", "abc");
expectNoMatch(".", "\n");
expectGroups("a(bb)*a", "abbbba", "bb");
expectGroups("a(bb)?(bb)+a", "abba", null, "bb");
expectFind(" +", "Hello , world! ", " ", " ", " ");
expectMatch("[0-9A-Fa-f]+", "08ef");
expectNoMatch("[0-9A-Fa-f]+", "08@ef");
expectGroups("(?:a)", "a");
expectGroups("a|(b|c)", "a", (String)null);
expectGroups("a|(b|c)", "c", "c");
expectGroups("(?=a)a", "a");
expectGroups(".*(o)(?<=[A-Z][a-z]*)", "Hello", "o");
expectNoMatch("(?!a).", "a");
expectMatch("[\\d]", "0");
expectMatch("\\0777", "?7");
expectMatch("\\a", "\007");
expectMatch("\\\\", "\\");
expectMatch("\\x4A", "J");
expectMatch("\\x61", "a");
expectMatch("\\078", "\0078");
expectSplit("(?<=\\w)(?=\\W)|(?<=\\W)(?=\\w)", "a + b * x",
"a", " + ", "b", " * ", "x");
expectMatch("[0-9[def]]", "f");
expectNoMatch("[a-z&&[^d-f]]", "f");
expectSplit("^H", "Hello\nHobbes!", "", "ello\nHobbes!");
expectSplit("o.*?$", "Hello\r\nHobbes!", "Hello\r\nH");
expectSplit("\\b", "a+ b + c\nd", "", "a", "+ ", "b", " + ", "c", "\n", "d");
expectSplit("\\B", "Hi Cal!", "H", "i C", "a", "l!");
expectMatch("a{2,5}", "aaaa");
expectGroups("a??(a{2,5}?)", "aaaa", "aaaa");
expectGroups("a??(a{3}?)", "aaaa", "aaa");
expectNoMatch("a(a{3}?)", "aaaaa");
expectMatch("a(a{3,}?)", "aaaaa");
}
| public static void main(String[] args) {
expectMatch("a(bb)?a", "abba");
expectNoMatch("a(bb)?a", "abbba");
expectNoMatch("a(bb)?a", "abbaa");
expectGroups("a(a*?)(a?)(a??)(a+)(a*)a", "aaaaaa", "", "a", "", "aaa", "");
expectMatch("...", "abc");
expectNoMatch(".", "\n");
expectGroups("a(bb)*a", "abbbba", "bb");
expectGroups("a(bb)?(bb)+a", "abba", null, "bb");
expectFind(" +", "Hello , world! ", " ", " ", " ");
expectMatch("[0-9A-Fa-f]+", "08ef");
expectNoMatch("[0-9A-Fa-f]+", "08@ef");
expectGroups("(?:a)", "a");
expectGroups("a|(b|c)", "a", (String)null);
expectGroups("a|(b|c)", "c", "c");
expectGroups("(?=a)a", "a");
expectGroups(".*(o)(?<=[A-Z][a-z]{1,4})", "Hello", "o");
expectNoMatch("(?!a).", "a");
expectMatch("[\\d]", "0");
expectMatch("\\0777", "?7");
expectMatch("\\a", "\007");
expectMatch("\\\\", "\\");
expectMatch("\\x4A", "J");
expectMatch("\\x61", "a");
expectMatch("\\078", "\0078");
expectSplit("(?<=\\w)(?=\\W)|(?<=\\W)(?=\\w)", "a + b * x",
"a", " + ", "b", " * ", "x");
expectMatch("[0-9[def]]", "f");
expectNoMatch("[a-z&&[^d-f]]", "f");
expectSplit("^H", "Hello\nHobbes!", "", "ello\nHobbes!");
expectSplit("o.*?$", "Hello\r\nHobbes!", "Hello\r\nH");
expectSplit("\\b", "a+ b + c\nd", "", "a", "+ ", "b", " + ", "c", "\n", "d");
expectSplit("\\B", "Hi Cal!", "H", "i C", "a", "l!");
expectMatch("a{2,5}", "aaaa");
expectGroups("a??(a{2,5}?)", "aaaa", "aaaa");
expectGroups("a??(a{3}?)", "aaaa", "aaa");
expectNoMatch("a(a{3}?)", "aaaaa");
expectMatch("a(a{3,}?)", "aaaaa");
}
|
diff --git a/src/main/java/tachyon/client/FileOutStream.java b/src/main/java/tachyon/client/FileOutStream.java
index 674af8d8cf..2db178a69b 100644
--- a/src/main/java/tachyon/client/FileOutStream.java
+++ b/src/main/java/tachyon/client/FileOutStream.java
@@ -1,250 +1,245 @@
/*
* 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 tachyon.client;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import tachyon.Constants;
import tachyon.UnderFileSystem;
/**
* <code>FileOutStream</code> implementation of TachyonFile. It can only be gotten by
* calling the methods in <code>tachyon.client.TachyonFile</code>, but can not be initialized by
* the client code.
*/
public class FileOutStream extends OutStream {
private final Logger LOG = Logger.getLogger(Constants.LOGGER_TYPE);
private final long BLOCK_CAPACITY;
private BlockOutStream mCurrentBlockOutStream;
private long mCurrentBlockId;
private long mCurrentBlockLeftByte;
private List<BlockOutStream> mPreviousBlockOutStreams;
private long mCachedBytes;
private OutputStream mCheckpointOutputStream = null;
private String mUnderFsFile = null;
private boolean mClosed = false;
private boolean mCancel = false;
FileOutStream(TachyonFile file, WriteType opType) throws IOException {
super(file, opType);
BLOCK_CAPACITY = file.getBlockSizeByte();
// TODO Support and test append.
mCurrentBlockOutStream = null;
mCurrentBlockId = -1;
mCurrentBlockLeftByte = 0;
mPreviousBlockOutStreams = new ArrayList<BlockOutStream>();
mCachedBytes = 0;
if (WRITE_TYPE.isThrough()) {
mUnderFsFile = TFS.createAndGetUserUnderfsTempFolder() + "/" + FILE.FID;
UnderFileSystem underfsClient = UnderFileSystem.get(mUnderFsFile);
if (BLOCK_CAPACITY > Integer.MAX_VALUE) {
throw new IOException("BLOCK_CAPCAITY (" + BLOCK_CAPACITY + ") can not bigger than "
+ Integer.MAX_VALUE);
}
mCheckpointOutputStream = underfsClient.create(mUnderFsFile, (int) BLOCK_CAPACITY);
}
}
private void getNextBlock() throws IOException {
if (mCurrentBlockId != -1) {
if (mCurrentBlockLeftByte != 0) {
throw new IOException("The current block still has space left, no need to get new block");
}
mPreviousBlockOutStreams.add(mCurrentBlockOutStream);
}
if (WRITE_TYPE.isCache()) {
mCurrentBlockId = TFS.getBlockIdBasedOnOffset(FILE.FID, mCachedBytes);
mCurrentBlockLeftByte = BLOCK_CAPACITY;
mCurrentBlockOutStream =
new BlockOutStream(FILE, WRITE_TYPE, (int) (mCachedBytes / BLOCK_CAPACITY));
}
}
@Override
public void write(int b) throws IOException {
if (WRITE_TYPE.isCache()) {
try {
if (mCurrentBlockId == -1 || mCurrentBlockLeftByte == 0) {
getNextBlock();
}
// TODO Cache the exception here.
mCurrentBlockOutStream.write(b);
mCurrentBlockLeftByte --;
mCachedBytes ++;
} catch (IOException ioe) {
if (WRITE_TYPE.isMustCache()) {
LOG.error(ioe.getMessage());
throw new IOException("Fail to cache: " + WRITE_TYPE);
} else {
LOG.warn("Fail to cache for: " + ioe.getMessage());
}
}
}
if (WRITE_TYPE.isThrough()) {
mCheckpointOutputStream.write(b);
}
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (WRITE_TYPE.isCache()) {
try {
int tLen = len;
int tOff = off;
while (tLen > 0) {
if (mCurrentBlockLeftByte == 0) {
getNextBlock();
}
if (mCurrentBlockLeftByte > tLen) {
mCurrentBlockOutStream.write(b, tOff, tLen);
mCurrentBlockLeftByte -= tLen;
mCachedBytes += tLen;
tOff += tLen;
tLen = 0;
} else {
mCurrentBlockOutStream.write(b, tOff, (int) mCurrentBlockLeftByte);
tOff += mCurrentBlockLeftByte;
tLen -= mCurrentBlockLeftByte;
mCachedBytes += mCurrentBlockLeftByte;
mCurrentBlockLeftByte = 0;
}
}
} catch (IOException ioe) {
if (WRITE_TYPE.isMustCache()) {
LOG.error(ioe.getMessage());
throw new IOException("Fail to cache: " + WRITE_TYPE);
} else {
LOG.warn("Fail to cache for: " + ioe.getMessage());
}
}
}
if (WRITE_TYPE.isThrough()) {
mCheckpointOutputStream.write(b, off, len);
}
}
public void write(ByteBuffer buf) throws IOException {
write(buf.array(), buf.position(), buf.limit() - buf.position());
}
public void write(ArrayList<ByteBuffer> bufs) throws IOException {
for (int k = 0; k < bufs.size(); k ++) {
write(bufs.get(k));
}
}
@Override
public void flush() throws IOException {
// We only flush the checkpoint output stream.
// TODO flushing for RAMFS block streams.
mCheckpointOutputStream.flush();
}
@Override
public void close() throws IOException {
if (!mClosed) {
if (mCurrentBlockOutStream != null) {
mPreviousBlockOutStreams.add(mCurrentBlockOutStream);
}
Boolean canComplete = false;
if (WRITE_TYPE.isThrough()) {
if (mCancel) {
mCheckpointOutputStream.close();
UnderFileSystem underFsClient = UnderFileSystem.get(mUnderFsFile);
underFsClient.delete(mUnderFsFile, false);
} else {
mCheckpointOutputStream.flush();
mCheckpointOutputStream.close();
TFS.addCheckpoint(FILE.FID);
canComplete = true;
}
}
if (WRITE_TYPE.isCache()) {
try {
if(mCancel){
for (BlockOutStream bos : mPreviousBlockOutStreams) {
bos.cancel();
}
}else {
for (BlockOutStream bos : mPreviousBlockOutStreams) {
bos.close();
}
canComplete = true;
}
} catch (IOException ioe) {
if (WRITE_TYPE.isMustCache()) {
LOG.error(ioe.getMessage());
throw new IOException("Fail to cache: " + WRITE_TYPE);
} else {
LOG.warn("Fail to cache for: " + ioe.getMessage());
}
}
}
if (canComplete) {
- if (WRITE_TYPE.isThrough()) {
- mCheckpointOutputStream.flush();
- mCheckpointOutputStream.close();
- TFS.addCheckpoint(FILE.FID);
- TFS.completeFile(FILE.FID);
- } else if (WRITE_TYPE.isAsync()) {
+ if (WRITE_TYPE.isAsync()) {
TFS.asyncCheckpoint(FILE.FID);
- TFS.completeFile(FILE.FID);
}
+ TFS.completeFile(FILE.FID);
}
}
mClosed = true;
}
@Override
public void cancel() throws IOException {
mCancel = true;
close();
}
}
| false | true | public void close() throws IOException {
if (!mClosed) {
if (mCurrentBlockOutStream != null) {
mPreviousBlockOutStreams.add(mCurrentBlockOutStream);
}
Boolean canComplete = false;
if (WRITE_TYPE.isThrough()) {
if (mCancel) {
mCheckpointOutputStream.close();
UnderFileSystem underFsClient = UnderFileSystem.get(mUnderFsFile);
underFsClient.delete(mUnderFsFile, false);
} else {
mCheckpointOutputStream.flush();
mCheckpointOutputStream.close();
TFS.addCheckpoint(FILE.FID);
canComplete = true;
}
}
if (WRITE_TYPE.isCache()) {
try {
if(mCancel){
for (BlockOutStream bos : mPreviousBlockOutStreams) {
bos.cancel();
}
}else {
for (BlockOutStream bos : mPreviousBlockOutStreams) {
bos.close();
}
canComplete = true;
}
} catch (IOException ioe) {
if (WRITE_TYPE.isMustCache()) {
LOG.error(ioe.getMessage());
throw new IOException("Fail to cache: " + WRITE_TYPE);
} else {
LOG.warn("Fail to cache for: " + ioe.getMessage());
}
}
}
if (canComplete) {
if (WRITE_TYPE.isThrough()) {
mCheckpointOutputStream.flush();
mCheckpointOutputStream.close();
TFS.addCheckpoint(FILE.FID);
TFS.completeFile(FILE.FID);
} else if (WRITE_TYPE.isAsync()) {
TFS.asyncCheckpoint(FILE.FID);
TFS.completeFile(FILE.FID);
}
}
}
mClosed = true;
}
| public void close() throws IOException {
if (!mClosed) {
if (mCurrentBlockOutStream != null) {
mPreviousBlockOutStreams.add(mCurrentBlockOutStream);
}
Boolean canComplete = false;
if (WRITE_TYPE.isThrough()) {
if (mCancel) {
mCheckpointOutputStream.close();
UnderFileSystem underFsClient = UnderFileSystem.get(mUnderFsFile);
underFsClient.delete(mUnderFsFile, false);
} else {
mCheckpointOutputStream.flush();
mCheckpointOutputStream.close();
TFS.addCheckpoint(FILE.FID);
canComplete = true;
}
}
if (WRITE_TYPE.isCache()) {
try {
if(mCancel){
for (BlockOutStream bos : mPreviousBlockOutStreams) {
bos.cancel();
}
}else {
for (BlockOutStream bos : mPreviousBlockOutStreams) {
bos.close();
}
canComplete = true;
}
} catch (IOException ioe) {
if (WRITE_TYPE.isMustCache()) {
LOG.error(ioe.getMessage());
throw new IOException("Fail to cache: " + WRITE_TYPE);
} else {
LOG.warn("Fail to cache for: " + ioe.getMessage());
}
}
}
if (canComplete) {
if (WRITE_TYPE.isAsync()) {
TFS.asyncCheckpoint(FILE.FID);
}
TFS.completeFile(FILE.FID);
}
}
mClosed = true;
}
|
diff --git a/src/main/java/net/rymate/bchatmanager/bChatManager.java b/src/main/java/net/rymate/bchatmanager/bChatManager.java
index 72ea13b..23d8307 100644
--- a/src/main/java/net/rymate/bchatmanager/bChatManager.java
+++ b/src/main/java/net/rymate/bchatmanager/bChatManager.java
@@ -1,194 +1,194 @@
package net.rymate.bchatmanager;
import net.milkbowl.vault.chat.Chat;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.configuration.file.YamlConfiguration;
import net.rymate.bchatmanager.metrics.Metrics;
import java.io.IOException;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
/**
* Main class
*
* @author rymate
*/
public class bChatManager extends JavaPlugin {
public static Chat chat = null;
private bChatListener listener;
public YamlConfiguration config;
public void onEnable() {
//setup the config
setupConfig();
//Chatlistener - can you hear me?
this.listener = new bChatListener(this);
this.getServer().getPluginManager().registerEvents(listener, this);
//Vault chat hooks
setupChat();
//setup the Metrics
Metrics metrics;
try {
metrics = new Metrics(this);
metrics.start();
} catch (IOException ex) {
Logger.getLogger(bChatManager.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("[bChatManager] Enabled!");
}
private void setupConfig() {
File configFile = new File(this.getDataFolder() + File.separator + "config.yml");
try {
if (!configFile.exists()) {
this.saveDefaultConfig();
}
} catch (Exception ex) {
Logger.getLogger(bChatManager.class.getName()).log(Level.SEVERE, null, ex);
}
config = new YamlConfiguration();
config.loadConfiguration(configFile);
}
/*
* Code to setup the Chat variable in Vault. Allows me to hook to all the prefix plugins.
*/
private boolean setupChat() {
RegisteredServiceProvider<Chat> chatProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.chat.Chat.class);
if (chatProvider != null) {
chat = chatProvider.getProvider();
}
return (chat != null);
}
//
// Begin methods from Functions.java
//
public String replacePlayerPlaceholders(Player player, String format) {
String worldName = player.getWorld().getName();
return format.replace("%prefix", chat.getPlayerPrefix(player))
.replace("%suffix", chat.getPlayerSuffix(player))
.replace("%world", worldName)
.replace("%player", player.getName())
.replace("%displayname", player.getDisplayName())
.replace("%group", chat.getPrimaryGroup(player));
}
public String colorize(String string) {
if (string == null) {
return "";
}
return string.replaceAll("&([a-z0-9])", "\u00A7$1");
}
public List<Player> getLocalRecipients(Player sender, String message, double range) {
Location playerLocation = sender.getLocation();
List<Player> recipients = new LinkedList<Player>();
double squaredDistance = Math.pow(range, 2);
for (Player recipient : getServer().getOnlinePlayers()) {
// Recipient are not from same world
if (!recipient.getWorld().equals(sender.getWorld())) {
continue;
}
if (playerLocation.distanceSquared(recipient.getLocation()) > squaredDistance) {
continue;
}
recipients.add(recipient);
}
return recipients;
}
public List<Player> getSpies() {
List<Player> recipients = new LinkedList<Player>();
for (Player recipient : this.getServer().getOnlinePlayers()) {
if (recipient.hasPermission("bchatmanager.spy")) {
recipients.add(recipient);
}
}
return recipients;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if ((command.getName().equals("me")) && (config.getBoolean("toggles.control-me", true))) {
String meFormat = config.getString("formats.me-format", "* %player %message");
Double chatRange = config.getDouble("other.chat-range", 100);
boolean rangedMode = config.getBoolean("toggles.ranged-mode", false);
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Ya need to type something after it :P");
return false;
}
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You are not an in-game player!");
return true;
}
Player player = (Player) sender;
int i;
StringBuilder me = new StringBuilder();
for (i = 0; i < args.length; i++) {
me.append(args[i]);
me.append(" ");
}
String meMessage = me.toString();
String message = meFormat;
message = colorize(message);
if (sender.hasPermission("bchatmanager.chat.color")) {
- meMessage = f.colorize(meMessage);
+ meMessage = colorize(meMessage);
}
message = message.replace("%message", meMessage).replace("%displayname", "%1$s");
message = replacePlayerPlaceholders(player, message);
if (rangedMode) {
List<Player> pl = getLocalRecipients(player, message, chatRange);
for (int j = 0; j < pl.size(); j++) {
pl.get(j).sendMessage(message);
}
sender.sendMessage(message);
System.out.println(message);
} else {
getServer().broadcastMessage(message);
}
return true;
}
if ((command.getName().equals("bchatreload"))) {
if (!(sender instanceof Player)) {
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Plugin reloaded!");
return true;
}
if (sender.hasPermission("bchatmanager.reload")) {
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Wtf, you can't do this!");
return true;
}
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Plugin reloaded!");
return true;
}
return true;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if ((command.getName().equals("me")) && (config.getBoolean("toggles.control-me", true))) {
String meFormat = config.getString("formats.me-format", "* %player %message");
Double chatRange = config.getDouble("other.chat-range", 100);
boolean rangedMode = config.getBoolean("toggles.ranged-mode", false);
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Ya need to type something after it :P");
return false;
}
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You are not an in-game player!");
return true;
}
Player player = (Player) sender;
int i;
StringBuilder me = new StringBuilder();
for (i = 0; i < args.length; i++) {
me.append(args[i]);
me.append(" ");
}
String meMessage = me.toString();
String message = meFormat;
message = colorize(message);
if (sender.hasPermission("bchatmanager.chat.color")) {
meMessage = f.colorize(meMessage);
}
message = message.replace("%message", meMessage).replace("%displayname", "%1$s");
message = replacePlayerPlaceholders(player, message);
if (rangedMode) {
List<Player> pl = getLocalRecipients(player, message, chatRange);
for (int j = 0; j < pl.size(); j++) {
pl.get(j).sendMessage(message);
}
sender.sendMessage(message);
System.out.println(message);
} else {
getServer().broadcastMessage(message);
}
return true;
}
if ((command.getName().equals("bchatreload"))) {
if (!(sender instanceof Player)) {
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Plugin reloaded!");
return true;
}
if (sender.hasPermission("bchatmanager.reload")) {
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Wtf, you can't do this!");
return true;
}
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Plugin reloaded!");
return true;
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if ((command.getName().equals("me")) && (config.getBoolean("toggles.control-me", true))) {
String meFormat = config.getString("formats.me-format", "* %player %message");
Double chatRange = config.getDouble("other.chat-range", 100);
boolean rangedMode = config.getBoolean("toggles.ranged-mode", false);
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "Ya need to type something after it :P");
return false;
}
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You are not an in-game player!");
return true;
}
Player player = (Player) sender;
int i;
StringBuilder me = new StringBuilder();
for (i = 0; i < args.length; i++) {
me.append(args[i]);
me.append(" ");
}
String meMessage = me.toString();
String message = meFormat;
message = colorize(message);
if (sender.hasPermission("bchatmanager.chat.color")) {
meMessage = colorize(meMessage);
}
message = message.replace("%message", meMessage).replace("%displayname", "%1$s");
message = replacePlayerPlaceholders(player, message);
if (rangedMode) {
List<Player> pl = getLocalRecipients(player, message, chatRange);
for (int j = 0; j < pl.size(); j++) {
pl.get(j).sendMessage(message);
}
sender.sendMessage(message);
System.out.println(message);
} else {
getServer().broadcastMessage(message);
}
return true;
}
if ((command.getName().equals("bchatreload"))) {
if (!(sender instanceof Player)) {
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Plugin reloaded!");
return true;
}
if (sender.hasPermission("bchatmanager.reload")) {
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Wtf, you can't do this!");
return true;
}
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
sender.sendMessage(ChatColor.AQUA + "[bChatManager] Plugin reloaded!");
return true;
}
return true;
}
|
diff --git a/jdt-patch/e36/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java b/jdt-patch/e36/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java
index 78985b2..b0b1874 100644
--- a/jdt-patch/e36/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java
+++ b/jdt-patch/e36/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java
@@ -1,995 +1,995 @@
/*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler;
import org.codehaus.jdt.groovy.integration.LanguageSupportFactory;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.*;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.parser.*;
import org.eclipse.jdt.internal.compiler.problem.*;
import org.eclipse.jdt.internal.compiler.util.*;
import java.io.*;
import java.util.*;
public class Compiler implements ITypeRequestor, ProblemSeverities {
public Parser parser;
public ICompilerRequestor requestor;
public CompilerOptions options;
public ProblemReporter problemReporter;
protected PrintWriter out; // output for messages that are not sent to problemReporter
public CompilerStats stats;
public CompilationProgress progress;
public int remainingIterations = 1;
// management of unit to be processed
//public CompilationUnitResult currentCompilationUnitResult;
public CompilationUnitDeclaration[] unitsToProcess;
public int totalUnits; // (totalUnits-1) gives the last unit in unitToProcess
// name lookup
public LookupEnvironment lookupEnvironment;
// ONCE STABILIZED, THESE SHOULD RETURN TO A FINAL FIELD
public static boolean DEBUG = false;
public int parseThreshold = -1;
public AbstractAnnotationProcessorManager annotationProcessorManager;
public int annotationProcessorStartIndex = 0;
public ReferenceBinding[] referenceBindings;
public boolean useSingleThread = true; // by default the compiler will not use worker threads to read/process/write
// number of initial units parsed at once (-1: none)
/*
* Static requestor reserved to listening compilation results in debug mode,
* so as for example to monitor compiler activity independantly from a particular
* builder implementation. It is reset at the end of compilation, and should not
* persist any information after having been reset.
*/
public static IDebugRequestor DebugRequestor = null;
/**
* Answer a new compiler using the given name environment and compiler options.
* The environment and options will be in effect for the lifetime of the compiler.
* When the compiler is run, compilation results are sent to the given requestor.
*
* @param environment org.eclipse.jdt.internal.compiler.api.env.INameEnvironment
* Environment used by the compiler in order to resolve type and package
* names. The name environment implements the actual connection of the compiler
* to the outside world (e.g. in batch mode the name environment is performing
* pure file accesses, reuse previous build state or connection to repositories).
* Note: the name environment is responsible for implementing the actual classpath
* rules.
*
* @param policy org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy
* Configurable part for problem handling, allowing the compiler client to
* specify the rules for handling problems (stop on first error or accumulate
* them all) and at the same time perform some actions such as opening a dialog
* in UI when compiling interactively.
* @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies
*
* @param settings java.util.Map
* The settings that control the compiler behavior.
*
* @param requestor org.eclipse.jdt.internal.compiler.api.ICompilerRequestor
* Component which will receive and persist all compilation results and is intended
* to consume them as they are produced. Typically, in a batch compiler, it is
* responsible for writing out the actual .class files to the file system.
* @see org.eclipse.jdt.internal.compiler.CompilationResult
*
* @param problemFactory org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory
* Factory used inside the compiler to create problem descriptors. It allows the
* compiler client to supply its own representation of compilation problems in
* order to avoid object conversions. Note that the factory is not supposed
* to accumulate the created problems, the compiler will gather them all and hand
* them back as part of the compilation unit result.
*
* @deprecated this constructor is kept to preserve 3.1 and 3.2M4 compatibility
*/
public Compiler(
INameEnvironment environment,
IErrorHandlingPolicy policy,
Map settings,
final ICompilerRequestor requestor,
IProblemFactory problemFactory) {
this(environment, policy, new CompilerOptions(settings), requestor, problemFactory, null /* printwriter */, null /* progress */);
}
/**
* Answer a new compiler using the given name environment and compiler options.
* The environment and options will be in effect for the lifetime of the compiler.
* When the compiler is run, compilation results are sent to the given requestor.
*
* @param environment org.eclipse.jdt.internal.compiler.api.env.INameEnvironment
* Environment used by the compiler in order to resolve type and package
* names. The name environment implements the actual connection of the compiler
* to the outside world (e.g. in batch mode the name environment is performing
* pure file accesses, reuse previous build state or connection to repositories).
* Note: the name environment is responsible for implementing the actual classpath
* rules.
*
* @param policy org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy
* Configurable part for problem handling, allowing the compiler client to
* specify the rules for handling problems (stop on first error or accumulate
* them all) and at the same time perform some actions such as opening a dialog
* in UI when compiling interactively.
* @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies
*
* @param settings java.util.Map
* The settings that control the compiler behavior.
*
* @param requestor org.eclipse.jdt.internal.compiler.api.ICompilerRequestor
* Component which will receive and persist all compilation results and is intended
* to consume them as they are produced. Typically, in a batch compiler, it is
* responsible for writing out the actual .class files to the file system.
* @see org.eclipse.jdt.internal.compiler.CompilationResult
*
* @param problemFactory org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory
* Factory used inside the compiler to create problem descriptors. It allows the
* compiler client to supply its own representation of compilation problems in
* order to avoid object conversions. Note that the factory is not supposed
* to accumulate the created problems, the compiler will gather them all and hand
* them back as part of the compilation unit result.
*
* @param parseLiteralExpressionsAsConstants <code>boolean</code>
* This parameter is used to optimize the literals or leave them as they are in the source.
* If you put true, "Hello" + " world" will be converted to "Hello world".
*
* @deprecated this constructor is kept to preserve 3.1 and 3.2M4 compatibility
*/
public Compiler(
INameEnvironment environment,
IErrorHandlingPolicy policy,
Map settings,
final ICompilerRequestor requestor,
IProblemFactory problemFactory,
boolean parseLiteralExpressionsAsConstants) {
this(environment, policy, new CompilerOptions(settings, parseLiteralExpressionsAsConstants), requestor, problemFactory, null /* printwriter */, null /* progress */);
}
/**
* Answer a new compiler using the given name environment and compiler options.
* The environment and options will be in effect for the lifetime of the compiler.
* When the compiler is run, compilation results are sent to the given requestor.
*
* @param environment org.eclipse.jdt.internal.compiler.api.env.INameEnvironment
* Environment used by the compiler in order to resolve type and package
* names. The name environment implements the actual connection of the compiler
* to the outside world (e.g. in batch mode the name environment is performing
* pure file accesses, reuse previous build state or connection to repositories).
* Note: the name environment is responsible for implementing the actual classpath
* rules.
*
* @param policy org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy
* Configurable part for problem handling, allowing the compiler client to
* specify the rules for handling problems (stop on first error or accumulate
* them all) and at the same time perform some actions such as opening a dialog
* in UI when compiling interactively.
* @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies
*
* @param options org.eclipse.jdt.internal.compiler.impl.CompilerOptions
* The options that control the compiler behavior.
*
* @param requestor org.eclipse.jdt.internal.compiler.api.ICompilerRequestor
* Component which will receive and persist all compilation results and is intended
* to consume them as they are produced. Typically, in a batch compiler, it is
* responsible for writing out the actual .class files to the file system.
* @see org.eclipse.jdt.internal.compiler.CompilationResult
*
* @param problemFactory org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory
* Factory used inside the compiler to create problem descriptors. It allows the
* compiler client to supply its own representation of compilation problems in
* order to avoid object conversions. Note that the factory is not supposed
* to accumulate the created problems, the compiler will gather them all and hand
* them back as part of the compilation unit result.
*/
public Compiler(
INameEnvironment environment,
IErrorHandlingPolicy policy,
CompilerOptions options,
final ICompilerRequestor requestor,
IProblemFactory problemFactory) {
this(environment, policy, options, requestor, problemFactory, null /* printwriter */, null /* progress */);
}
/**
* Answer a new compiler using the given name environment and compiler options.
* The environment and options will be in effect for the lifetime of the compiler.
* When the compiler is run, compilation results are sent to the given requestor.
*
* @param environment org.eclipse.jdt.internal.compiler.api.env.INameEnvironment
* Environment used by the compiler in order to resolve type and package
* names. The name environment implements the actual connection of the compiler
* to the outside world (e.g. in batch mode the name environment is performing
* pure file accesses, reuse previous build state or connection to repositories).
* Note: the name environment is responsible for implementing the actual classpath
* rules.
*
* @param policy org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy
* Configurable part for problem handling, allowing the compiler client to
* specify the rules for handling problems (stop on first error or accumulate
* them all) and at the same time perform some actions such as opening a dialog
* in UI when compiling interactively.
* @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies
*
* @param options org.eclipse.jdt.internal.compiler.impl.CompilerOptions
* The options that control the compiler behavior.
*
* @param requestor org.eclipse.jdt.internal.compiler.api.ICompilerRequestor
* Component which will receive and persist all compilation results and is intended
* to consume them as they are produced. Typically, in a batch compiler, it is
* responsible for writing out the actual .class files to the file system.
* @see org.eclipse.jdt.internal.compiler.CompilationResult
*
* @param problemFactory org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory
* Factory used inside the compiler to create problem descriptors. It allows the
* compiler client to supply its own representation of compilation problems in
* order to avoid object conversions. Note that the factory is not supposed
* to accumulate the created problems, the compiler will gather them all and hand
* them back as part of the compilation unit result.
* @deprecated
*/
public Compiler(
INameEnvironment environment,
IErrorHandlingPolicy policy,
CompilerOptions options,
final ICompilerRequestor requestor,
IProblemFactory problemFactory,
PrintWriter out) {
this(environment, policy, options, requestor, problemFactory, out, null /* progress */);
}
public Compiler(
INameEnvironment environment,
IErrorHandlingPolicy policy,
CompilerOptions options,
final ICompilerRequestor requestor,
IProblemFactory problemFactory,
PrintWriter out,
CompilationProgress progress) {
this.options = options;
this.progress = progress;
// GROOVY start - temporary
if (this.options.buildGroovyFiles==0) {
// demoted to error message, groovy disabled
System.err.println("Build groovy files option has not been set one way or the other: use 'options.put(CompilerOptions.OPTIONG_BuildGroovyFiles, CompilerOptions.ENABLED);'");//$NON-NLS-1$
this.options.buildGroovyFiles=1;
this.options.groovyFlags = 0;
// throw new RuntimeException("Build groovy files option has not been set one way or the other: use 'options.put(CompilerOptions.OPTIONG_BuildGroovyFiles, CompilerOptions.ENABLED);'"); //$NON-NLS-1$
}
// GROOVY end
// wrap requestor in DebugRequestor if one is specified
if(DebugRequestor == null) {
this.requestor = requestor;
} else {
this.requestor = new ICompilerRequestor(){
public void acceptResult(CompilationResult result){
if (DebugRequestor.isActive()){
DebugRequestor.acceptDebugResult(result);
}
requestor.acceptResult(result);
}
};
}
this.problemReporter = new ProblemReporter(policy, this.options, problemFactory);
this.lookupEnvironment = new LookupEnvironment(this, this.options, this.problemReporter, environment);
this.out = out == null ? new PrintWriter(System.out, true) : out;
this.stats = new CompilerStats();
initializeParser();
}
/**
* Add an additional binary type
*/
public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
if (this.options.verbose) {
this.out.println(
Messages.bind(Messages.compilation_loadBinary, new String(binaryType.getName())));
// new Exception("TRACE BINARY").printStackTrace(System.out);
// System.out.println();
}
this.lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);
}
/**
* Add an additional compilation unit into the loop
* -> build compilation unit declarations, their bindings and record their results.
*/
public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) {
// Switch the current policy and compilation result for this unit to the requested one.
CompilationResult unitResult =
new CompilationResult(sourceUnit, this.totalUnits, this.totalUnits, this.options.maxProblemsPerUnit);
unitResult.checkSecondaryTypes = true;
try {
if (this.options.verbose) {
String count = String.valueOf(this.totalUnits + 1);
this.out.println(
Messages.bind(Messages.compilation_request,
new String[] {
count,
count,
new String(sourceUnit.getFileName())
}));
}
// diet parsing for large collection of unit
CompilationUnitDeclaration parsedUnit;
if (this.totalUnits < this.parseThreshold) {
parsedUnit = this.parser.parse(sourceUnit, unitResult);
} else {
parsedUnit = this.parser.dietParse(sourceUnit, unitResult);
}
parsedUnit.bits |= ASTNode.IsImplicitUnit;
// initial type binding creation
this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction);
addCompilationUnit(sourceUnit, parsedUnit);
// binding resolution
this.lookupEnvironment.completeTypeBindings(parsedUnit);
} catch (AbortCompilationUnit e) {
// at this point, currentCompilationUnitResult may not be sourceUnit, but some other
// one requested further along to resolve sourceUnit.
if (unitResult.compilationUnit == sourceUnit) { // only report once
this.requestor.acceptResult(unitResult.tagAsAccepted());
} else {
throw e; // want to abort enclosing request to compile
}
}
}
/**
* Add additional source types
*/
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
this.problemReporter.abortDueToInternalError(
Messages.bind(Messages.abort_againstSourceModel, new String[] { String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0].getFileName()) }));
}
protected synchronized void addCompilationUnit(
ICompilationUnit sourceUnit,
CompilationUnitDeclaration parsedUnit) {
// append the unit to the list of ones to process later on
int size = this.unitsToProcess.length;
if (this.totalUnits == size)
// when growing reposition units starting at position 0
System.arraycopy(
this.unitsToProcess,
0,
(this.unitsToProcess = new CompilationUnitDeclaration[size * 2]),
0,
this.totalUnits);
this.unitsToProcess[this.totalUnits++] = parsedUnit;
}
/**
* Add the initial set of compilation units into the loop
* -> build compilation unit declarations, their bindings and record their results.
*/
protected void beginToCompile(ICompilationUnit[] sourceUnits) {
int maxUnits = sourceUnits.length;
this.totalUnits = 0;
this.unitsToProcess = new CompilationUnitDeclaration[maxUnits];
internalBeginToCompile(sourceUnits, maxUnits);
}
/**
* Checks whether the compilation has been canceled and reports the given progress to the compiler progress.
*/
protected void reportProgress(String taskDecription) {
if (this.progress != null) {
if (this.progress.isCanceled()) {
// Only AbortCompilation can stop the compiler cleanly.
// We check cancellation again following the call to compile.
throw new AbortCompilation(true, null);
}
this.progress.setTaskName(taskDecription);
}
}
/**
* Checks whether the compilation has been canceled and reports the given work increment to the compiler progress.
*/
protected void reportWorked(int workIncrement, int currentUnitIndex) {
if (this.progress != null) {
if (this.progress.isCanceled()) {
// Only AbortCompilation can stop the compiler cleanly.
// We check cancellation again following the call to compile.
throw new AbortCompilation(true, null);
}
this.progress.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1);
}
}
/**
* General API
* -> compile each of supplied files
* -> recompile any required types for which we have an incomplete principle structure
*/
public void compile(ICompilationUnit[] sourceUnits) {
this.stats.startTime = System.currentTimeMillis();
// GROOVY start
// sort the sourceUnits - java first! might be temporary, hmmm
if (this.options.buildGroovyFiles==2) {
int groovyFileIndex = -1;
// System.out.println("before");
// for (int u=0,max=sourceUnits.length;u<max;u++) {
// System.out.println(sourceUnits[u].getFileName());
// }
for (int u=0,max=sourceUnits.length;u<max;u++) {
char[] fn = sourceUnits[u].getFileName();
boolean isDotJava = fn[fn.length-1]=='a'; // a means .java
if (isDotJava) {
if (groovyFileIndex!=-1) {
// swap them!
ICompilationUnit swap = sourceUnits[groovyFileIndex];
sourceUnits[groovyFileIndex] = sourceUnits[u];
sourceUnits[u] = swap;
// find the next .groovy file after the groovyFileIndex (worst case it will be 'u')
int newGroovyFileIndex = -1;
for (int g=groovyFileIndex;g<=u;g++) {
char[] fn2 = sourceUnits[g].getFileName();
- boolean isDotGroovy = fn2[fn2.length-1]=='y';
+ boolean isDotGroovy = fn2[fn2.length-1]=='m'; //ZALUUM
if (isDotGroovy) {
newGroovyFileIndex = g;
break;
}
}
groovyFileIndex = newGroovyFileIndex;
}
} else {
if (groovyFileIndex==-1) {
groovyFileIndex = u;
}
}
}
// System.out.println("after");
// for (int u=0,max=sourceUnits.length;u<max;u++) {
// System.out.println(sourceUnits[u].getFileName());
// }
}
// GROOVY end
CompilationUnitDeclaration unit = null;
ProcessTaskManager processingTask = null;
try {
// build and record parsed units
reportProgress(Messages.compilation_beginningToCompile);
if (this.annotationProcessorManager == null) {
beginToCompile(sourceUnits);
} else {
ICompilationUnit[] originalUnits = (ICompilationUnit[]) sourceUnits.clone(); // remember source units in case a source type collision occurs
try {
beginToCompile(sourceUnits);
processAnnotations();
if (!this.options.generateClassFiles) {
// -proc:only was set on the command line
return;
}
} catch (SourceTypeCollisionException e) {
reset();
// a generated type was referenced before it was created
// the compiler either created a MissingType or found a BinaryType for it
// so add the processor's generated files & start over,
// but remember to only pass the generated files to the annotation processor
int originalLength = originalUnits.length;
int newProcessedLength = e.newAnnotationProcessorUnits.length;
ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];
System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);
System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);
this.annotationProcessorStartIndex = originalLength;
compile(combinedUnits);
return;
}
}
if (this.useSingleThread) {
// process all units (some more could be injected in the loop by the lookup environment)
for (int i = 0; i < this.totalUnits; i++) {
unit = this.unitsToProcess[i];
reportProgress(Messages.bind(Messages.compilation_processing, new String(unit.getFileName())));
try {
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_process,
new String[] {
String.valueOf(i + 1),
String.valueOf(this.totalUnits),
new String(this.unitsToProcess[i].getFileName())
}));
process(unit, i);
} finally {
// cleanup compilation unit result
unit.cleanUp();
}
this.unitsToProcess[i] = null; // release reference to processed unit declaration
reportWorked(1, i);
this.stats.lineCount += unit.compilationResult.lineSeparatorPositions.length;
long acceptStart = System.currentTimeMillis();
this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
this.stats.generateTime += System.currentTimeMillis() - acceptStart; // record accept time as part of generation
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_done,
new String[] {
String.valueOf(i + 1),
String.valueOf(this.totalUnits),
new String(unit.getFileName())
}));
}
} else {
processingTask = new ProcessTaskManager(this);
int acceptedCount = 0;
// process all units (some more could be injected in the loop by the lookup environment)
// the processTask can continue to process units until its fixed sized cache is full then it must wait
// for this this thread to accept the units as they appear (it only waits if no units are available)
while (true) {
try {
unit = processingTask.removeNextUnit(); // waits if no units are in the processed queue
} catch (Error e) {
unit = processingTask.unitToProcess;
throw e;
} catch (RuntimeException e) {
unit = processingTask.unitToProcess;
throw e;
}
if (unit == null) break;
reportWorked(1, acceptedCount++);
this.stats.lineCount += unit.compilationResult.lineSeparatorPositions.length;
this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_done,
new String[] {
String.valueOf(acceptedCount),
String.valueOf(this.totalUnits),
new String(unit.getFileName())
}));
}
}
} catch (AbortCompilation e) {
this.handleInternalException(e, unit);
} catch (Error e) {
this.handleInternalException(e, unit, null);
throw e; // rethrow
} catch (RuntimeException e) {
this.handleInternalException(e, unit, null);
throw e; // rethrow
} finally {
if (processingTask != null) {
processingTask.shutdown();
processingTask = null;
}
reset();
this.annotationProcessorStartIndex = 0;
this.stats.endTime = System.currentTimeMillis();
}
if (this.options.verbose) {
if (this.totalUnits > 1) {
this.out.println(
Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));
} else {
this.out.println(
Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));
}
}
}
public synchronized CompilationUnitDeclaration getUnitToProcess(int next) {
if (next < this.totalUnits) {
CompilationUnitDeclaration unit = this.unitsToProcess[next];
this.unitsToProcess[next] = null; // release reference to processed unit declaration
return unit;
}
return null;
}
public void setBinaryTypes(ReferenceBinding[] binaryTypes) {
this.referenceBindings = binaryTypes;
}
/*
* Compiler crash recovery in case of unexpected runtime exceptions
*/
protected void handleInternalException(
Throwable internalException,
CompilationUnitDeclaration unit,
CompilationResult result) {
if (result == null && unit != null) {
result = unit.compilationResult; // current unit being processed ?
}
// Lookup environment may be in middle of connecting types
if (result == null && this.lookupEnvironment.unitBeingCompleted != null) {
result = this.lookupEnvironment.unitBeingCompleted.compilationResult;
}
if (result == null) {
synchronized (this) {
if (this.unitsToProcess != null && this.totalUnits > 0)
result = this.unitsToProcess[this.totalUnits - 1].compilationResult;
}
}
// last unit in beginToCompile ?
boolean needToPrint = true;
if (result != null) {
/* create and record a compilation problem */
// only keep leading portion of the trace
String[] pbArguments = new String[] {
Messages.bind(Messages.compilation_internalError, Util.getExceptionSummary(internalException)),
};
result
.record(
this.problemReporter
.createProblem(
result.getFileName(),
IProblem.Unclassified,
pbArguments,
pbArguments,
Error, // severity
0, // source start
0, // source end
0, // line number
0),// column number
unit);
/* hand back the compilation result */
if (!result.hasBeenAccepted) {
this.requestor.acceptResult(result.tagAsAccepted());
needToPrint = false;
}
}
if (needToPrint) {
/* dump a stack trace to the console */
internalException.printStackTrace();
}
}
/*
* Compiler recovery in case of internal AbortCompilation event
*/
protected void handleInternalException(
AbortCompilation abortException,
CompilationUnitDeclaration unit) {
/* special treatment for SilentAbort: silently cancelling the compilation process */
if (abortException.isSilent) {
if (abortException.silentException == null) {
return;
}
throw abortException.silentException;
}
/* uncomment following line to see where the abort came from */
// abortException.printStackTrace();
// Exception may tell which compilation result it is related, and which problem caused it
CompilationResult result = abortException.compilationResult;
if (result == null && unit != null) {
result = unit.compilationResult; // current unit being processed ?
}
// Lookup environment may be in middle of connecting types
if (result == null && this.lookupEnvironment.unitBeingCompleted != null) {
result = this.lookupEnvironment.unitBeingCompleted.compilationResult;
}
if (result == null) {
synchronized (this) {
if (this.unitsToProcess != null && this.totalUnits > 0)
result = this.unitsToProcess[this.totalUnits - 1].compilationResult;
}
}
// last unit in beginToCompile ?
if (result != null && !result.hasBeenAccepted) {
/* distant problem which could not be reported back there? */
if (abortException.problem != null) {
recordDistantProblem: {
CategorizedProblem distantProblem = abortException.problem;
CategorizedProblem[] knownProblems = result.problems;
for (int i = 0; i < result.problemCount; i++) {
if (knownProblems[i] == distantProblem) { // already recorded
break recordDistantProblem;
}
}
if (distantProblem instanceof DefaultProblem) { // fixup filename TODO (philippe) should improve API to make this official
((DefaultProblem) distantProblem).setOriginatingFileName(result.getFileName());
}
result.record(distantProblem, unit);
}
} else {
/* distant internal exception which could not be reported back there */
if (abortException.exception != null) {
this.handleInternalException(abortException.exception, null, result);
return;
}
}
/* hand back the compilation result */
if (!result.hasBeenAccepted) {
this.requestor.acceptResult(result.tagAsAccepted());
}
} else {
abortException.printStackTrace();
}
}
public void initializeParser() {
// GROOVY start
/* old
this.parser = new Parser(this.problemReporter, this.options.parseLiteralExpressionsAsConstants);
// new */
this.parser = LanguageSupportFactory.getParser(this, this.lookupEnvironment==null?null:this.lookupEnvironment.globalOptions,this.problemReporter, this.options.parseLiteralExpressionsAsConstants, 1);
// GROOVY end
}
/**
* Add the initial set of compilation units into the loop
* -> build compilation unit declarations, their bindings and record their results.
*/
protected void internalBeginToCompile(ICompilationUnit[] sourceUnits, int maxUnits) {
if (!this.useSingleThread && maxUnits >= ReadManager.THRESHOLD)
this.parser.readManager = new ReadManager(sourceUnits, maxUnits);
// Switch the current policy and compilation result for this unit to the requested one.
for (int i = 0; i < maxUnits; i++) {
try {
if (this.options.verbose) {
this.out.println(
Messages.bind(Messages.compilation_request,
new String[] {
String.valueOf(i + 1),
String.valueOf(maxUnits),
new String(sourceUnits[i].getFileName())
}));
}
// diet parsing for large collection of units
CompilationUnitDeclaration parsedUnit;
CompilationResult unitResult =
new CompilationResult(sourceUnits[i], i, maxUnits, this.options.maxProblemsPerUnit);
long parseStart = System.currentTimeMillis();
if (this.totalUnits < this.parseThreshold) {
parsedUnit = this.parser.parse(sourceUnits[i], unitResult);
} else {
parsedUnit = this.parser.dietParse(sourceUnits[i], unitResult);
}
long resolveStart = System.currentTimeMillis();
this.stats.parseTime += resolveStart - parseStart;
// initial type binding creation
this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
this.stats.resolveTime += System.currentTimeMillis() - resolveStart;
addCompilationUnit(sourceUnits[i], parsedUnit);
ImportReference currentPackage = parsedUnit.currentPackage;
if (currentPackage != null) {
unitResult.recordPackageName(currentPackage.tokens);
}
//} catch (AbortCompilationUnit e) {
// requestor.acceptResult(unitResult.tagAsAccepted());
} finally {
sourceUnits[i] = null; // no longer hold onto the unit
}
}
if (this.parser.readManager != null) {
this.parser.readManager.shutdown();
this.parser.readManager = null;
}
// binding resolution
this.lookupEnvironment.completeTypeBindings();
}
/**
* Process a compilation unit already parsed and build.
*/
public void process(CompilationUnitDeclaration unit, int i) {
this.lookupEnvironment.unitBeingCompleted = unit;
long parseStart = System.currentTimeMillis();
this.parser.getMethodBodies(unit);
long resolveStart = System.currentTimeMillis();
this.stats.parseTime += resolveStart - parseStart;
// fault in fields & methods
if (unit.scope != null)
unit.scope.faultInTypes();
// verify inherited methods
if (unit.scope != null)
unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());
// type checking
unit.resolve();
long analyzeStart = System.currentTimeMillis();
this.stats.resolveTime += analyzeStart - resolveStart;
//No need of analysis or generation of code if statements are not required
if (!this.options.ignoreMethodBodies) unit.analyseCode(); // flow analysis
long generateStart = System.currentTimeMillis();
this.stats.analyzeTime += generateStart - analyzeStart;
if (!this.options.ignoreMethodBodies) unit.generateCode(); // code generation
// reference info
if (this.options.produceReferenceInfo && unit.scope != null)
unit.scope.storeDependencyInfo();
// finalize problems (suppressWarnings)
unit.finalizeProblems();
this.stats.generateTime += System.currentTimeMillis() - generateStart;
// refresh the total number of units known at this stage
unit.compilationResult.totalUnitsKnown = this.totalUnits;
this.lookupEnvironment.unitBeingCompleted = null;
}
protected void processAnnotations() {
int newUnitSize = 0;
int newClassFilesSize = 0;
int bottom = this.annotationProcessorStartIndex;
int top = this.totalUnits;
ReferenceBinding[] binaryTypeBindingsTemp = this.referenceBindings;
if (top == 0 && binaryTypeBindingsTemp == null) return;
this.referenceBindings = null;
do {
// extract units to process
int length = top - bottom;
CompilationUnitDeclaration[] currentUnits = new CompilationUnitDeclaration[length];
int index = 0;
for (int i = bottom; i < top; i++) {
CompilationUnitDeclaration currentUnit = this.unitsToProcess[i];
if ((currentUnit.bits & ASTNode.IsImplicitUnit) == 0) {
currentUnits[index++] = currentUnit;
}
}
if (index != length) {
System.arraycopy(currentUnits, 0, (currentUnits = new CompilationUnitDeclaration[index]), 0, index);
}
this.annotationProcessorManager.processAnnotations(currentUnits, binaryTypeBindingsTemp, false);
ICompilationUnit[] newUnits = this.annotationProcessorManager.getNewUnits();
newUnitSize = newUnits.length;
ReferenceBinding[] newClassFiles = this.annotationProcessorManager.getNewClassFiles();
binaryTypeBindingsTemp = newClassFiles;
newClassFilesSize = newClassFiles.length;
if (newUnitSize != 0) {
ICompilationUnit[] newProcessedUnits = (ICompilationUnit[]) newUnits.clone(); // remember new units in case a source type collision occurs
try {
this.lookupEnvironment.isProcessingAnnotations = true;
internalBeginToCompile(newUnits, newUnitSize);
} catch (SourceTypeCollisionException e) {
e.newAnnotationProcessorUnits = newProcessedUnits;
throw e;
} finally {
this.lookupEnvironment.isProcessingAnnotations = false;
this.annotationProcessorManager.reset();
}
bottom = top;
top = this.totalUnits; // last unit added
} else {
bottom = top;
this.annotationProcessorManager.reset();
}
} while (newUnitSize != 0 || newClassFilesSize != 0);
// one more loop to create possible resources
// this loop cannot create any java source files
this.annotationProcessorManager.processAnnotations(null, null, true);
// TODO we might want to check if this loop created new units
}
public void reset() {
this.lookupEnvironment.reset();
// GROOVY start: give the parser a chance to reset as well
parser.reset();
// GROOVY end
this.parser.scanner.source = null;
this.unitsToProcess = null;
if (DebugRequestor != null) DebugRequestor.reset();
this.problemReporter.reset();
}
/**
* Internal API used to resolve a given compilation unit. Can run a subset of the compilation process
*/
public CompilationUnitDeclaration resolve(
CompilationUnitDeclaration unit,
ICompilationUnit sourceUnit,
boolean verifyMethods,
boolean analyzeCode,
boolean generateCode) {
try {
if (unit == null) {
// build and record parsed units
this.parseThreshold = 0; // will request a full parse
beginToCompile(new ICompilationUnit[] { sourceUnit });
// process all units (some more could be injected in the loop by the lookup environment)
unit = this.unitsToProcess[0];
} else {
// initial type binding creation
this.lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);
// binding resolution
this.lookupEnvironment.completeTypeBindings();
}
this.lookupEnvironment.unitBeingCompleted = unit;
this.parser.getMethodBodies(unit);
if (unit.scope != null) {
// fault in fields & methods
unit.scope.faultInTypes();
if (unit.scope != null && verifyMethods) {
// http://dev.eclipse.org/bugs/show_bug.cgi?id=23117
// verify inherited methods
unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());
}
// type checking
unit.resolve();
// flow analysis
if (analyzeCode) unit.analyseCode();
// code generation
if (generateCode) unit.generateCode();
// finalize problems (suppressWarnings)
unit.finalizeProblems();
}
if (this.unitsToProcess != null) this.unitsToProcess[0] = null; // release reference to processed unit declaration
this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
return unit;
} catch (AbortCompilation e) {
this.handleInternalException(e, unit);
return unit == null ? this.unitsToProcess[0] : unit;
} catch (Error e) {
this.handleInternalException(e, unit, null);
throw e; // rethrow
} catch (RuntimeException e) {
this.handleInternalException(e, unit, null);
throw e; // rethrow
} finally {
// leave this.lookupEnvironment.unitBeingCompleted set to the unit, until another unit is resolved
// other calls to dom can cause classpath errors to be detected, resulting in AbortCompilation exceptions
// No reset is performed there anymore since,
// within the CodeAssist (or related tools),
// the compiler may be called *after* a call
// to this resolve(...) method. And such a call
// needs to have a compiler with a non-empty
// environment.
// this.reset();
}
}
/**
* Internal API used to resolve a given compilation unit. Can run a subset of the compilation process
*/
public CompilationUnitDeclaration resolve(
ICompilationUnit sourceUnit,
boolean verifyMethods,
boolean analyzeCode,
boolean generateCode) {
return resolve(
null,
sourceUnit,
verifyMethods,
analyzeCode,
generateCode);
}
}
| true | true | public void compile(ICompilationUnit[] sourceUnits) {
this.stats.startTime = System.currentTimeMillis();
// GROOVY start
// sort the sourceUnits - java first! might be temporary, hmmm
if (this.options.buildGroovyFiles==2) {
int groovyFileIndex = -1;
// System.out.println("before");
// for (int u=0,max=sourceUnits.length;u<max;u++) {
// System.out.println(sourceUnits[u].getFileName());
// }
for (int u=0,max=sourceUnits.length;u<max;u++) {
char[] fn = sourceUnits[u].getFileName();
boolean isDotJava = fn[fn.length-1]=='a'; // a means .java
if (isDotJava) {
if (groovyFileIndex!=-1) {
// swap them!
ICompilationUnit swap = sourceUnits[groovyFileIndex];
sourceUnits[groovyFileIndex] = sourceUnits[u];
sourceUnits[u] = swap;
// find the next .groovy file after the groovyFileIndex (worst case it will be 'u')
int newGroovyFileIndex = -1;
for (int g=groovyFileIndex;g<=u;g++) {
char[] fn2 = sourceUnits[g].getFileName();
boolean isDotGroovy = fn2[fn2.length-1]=='y';
if (isDotGroovy) {
newGroovyFileIndex = g;
break;
}
}
groovyFileIndex = newGroovyFileIndex;
}
} else {
if (groovyFileIndex==-1) {
groovyFileIndex = u;
}
}
}
// System.out.println("after");
// for (int u=0,max=sourceUnits.length;u<max;u++) {
// System.out.println(sourceUnits[u].getFileName());
// }
}
// GROOVY end
CompilationUnitDeclaration unit = null;
ProcessTaskManager processingTask = null;
try {
// build and record parsed units
reportProgress(Messages.compilation_beginningToCompile);
if (this.annotationProcessorManager == null) {
beginToCompile(sourceUnits);
} else {
ICompilationUnit[] originalUnits = (ICompilationUnit[]) sourceUnits.clone(); // remember source units in case a source type collision occurs
try {
beginToCompile(sourceUnits);
processAnnotations();
if (!this.options.generateClassFiles) {
// -proc:only was set on the command line
return;
}
} catch (SourceTypeCollisionException e) {
reset();
// a generated type was referenced before it was created
// the compiler either created a MissingType or found a BinaryType for it
// so add the processor's generated files & start over,
// but remember to only pass the generated files to the annotation processor
int originalLength = originalUnits.length;
int newProcessedLength = e.newAnnotationProcessorUnits.length;
ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];
System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);
System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);
this.annotationProcessorStartIndex = originalLength;
compile(combinedUnits);
return;
}
}
if (this.useSingleThread) {
// process all units (some more could be injected in the loop by the lookup environment)
for (int i = 0; i < this.totalUnits; i++) {
unit = this.unitsToProcess[i];
reportProgress(Messages.bind(Messages.compilation_processing, new String(unit.getFileName())));
try {
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_process,
new String[] {
String.valueOf(i + 1),
String.valueOf(this.totalUnits),
new String(this.unitsToProcess[i].getFileName())
}));
process(unit, i);
} finally {
// cleanup compilation unit result
unit.cleanUp();
}
this.unitsToProcess[i] = null; // release reference to processed unit declaration
reportWorked(1, i);
this.stats.lineCount += unit.compilationResult.lineSeparatorPositions.length;
long acceptStart = System.currentTimeMillis();
this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
this.stats.generateTime += System.currentTimeMillis() - acceptStart; // record accept time as part of generation
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_done,
new String[] {
String.valueOf(i + 1),
String.valueOf(this.totalUnits),
new String(unit.getFileName())
}));
}
} else {
processingTask = new ProcessTaskManager(this);
int acceptedCount = 0;
// process all units (some more could be injected in the loop by the lookup environment)
// the processTask can continue to process units until its fixed sized cache is full then it must wait
// for this this thread to accept the units as they appear (it only waits if no units are available)
while (true) {
try {
unit = processingTask.removeNextUnit(); // waits if no units are in the processed queue
} catch (Error e) {
unit = processingTask.unitToProcess;
throw e;
} catch (RuntimeException e) {
unit = processingTask.unitToProcess;
throw e;
}
if (unit == null) break;
reportWorked(1, acceptedCount++);
this.stats.lineCount += unit.compilationResult.lineSeparatorPositions.length;
this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_done,
new String[] {
String.valueOf(acceptedCount),
String.valueOf(this.totalUnits),
new String(unit.getFileName())
}));
}
}
} catch (AbortCompilation e) {
this.handleInternalException(e, unit);
} catch (Error e) {
this.handleInternalException(e, unit, null);
throw e; // rethrow
} catch (RuntimeException e) {
this.handleInternalException(e, unit, null);
throw e; // rethrow
} finally {
if (processingTask != null) {
processingTask.shutdown();
processingTask = null;
}
reset();
this.annotationProcessorStartIndex = 0;
this.stats.endTime = System.currentTimeMillis();
}
if (this.options.verbose) {
if (this.totalUnits > 1) {
this.out.println(
Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));
} else {
this.out.println(
Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));
}
}
}
| public void compile(ICompilationUnit[] sourceUnits) {
this.stats.startTime = System.currentTimeMillis();
// GROOVY start
// sort the sourceUnits - java first! might be temporary, hmmm
if (this.options.buildGroovyFiles==2) {
int groovyFileIndex = -1;
// System.out.println("before");
// for (int u=0,max=sourceUnits.length;u<max;u++) {
// System.out.println(sourceUnits[u].getFileName());
// }
for (int u=0,max=sourceUnits.length;u<max;u++) {
char[] fn = sourceUnits[u].getFileName();
boolean isDotJava = fn[fn.length-1]=='a'; // a means .java
if (isDotJava) {
if (groovyFileIndex!=-1) {
// swap them!
ICompilationUnit swap = sourceUnits[groovyFileIndex];
sourceUnits[groovyFileIndex] = sourceUnits[u];
sourceUnits[u] = swap;
// find the next .groovy file after the groovyFileIndex (worst case it will be 'u')
int newGroovyFileIndex = -1;
for (int g=groovyFileIndex;g<=u;g++) {
char[] fn2 = sourceUnits[g].getFileName();
boolean isDotGroovy = fn2[fn2.length-1]=='m'; //ZALUUM
if (isDotGroovy) {
newGroovyFileIndex = g;
break;
}
}
groovyFileIndex = newGroovyFileIndex;
}
} else {
if (groovyFileIndex==-1) {
groovyFileIndex = u;
}
}
}
// System.out.println("after");
// for (int u=0,max=sourceUnits.length;u<max;u++) {
// System.out.println(sourceUnits[u].getFileName());
// }
}
// GROOVY end
CompilationUnitDeclaration unit = null;
ProcessTaskManager processingTask = null;
try {
// build and record parsed units
reportProgress(Messages.compilation_beginningToCompile);
if (this.annotationProcessorManager == null) {
beginToCompile(sourceUnits);
} else {
ICompilationUnit[] originalUnits = (ICompilationUnit[]) sourceUnits.clone(); // remember source units in case a source type collision occurs
try {
beginToCompile(sourceUnits);
processAnnotations();
if (!this.options.generateClassFiles) {
// -proc:only was set on the command line
return;
}
} catch (SourceTypeCollisionException e) {
reset();
// a generated type was referenced before it was created
// the compiler either created a MissingType or found a BinaryType for it
// so add the processor's generated files & start over,
// but remember to only pass the generated files to the annotation processor
int originalLength = originalUnits.length;
int newProcessedLength = e.newAnnotationProcessorUnits.length;
ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];
System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);
System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);
this.annotationProcessorStartIndex = originalLength;
compile(combinedUnits);
return;
}
}
if (this.useSingleThread) {
// process all units (some more could be injected in the loop by the lookup environment)
for (int i = 0; i < this.totalUnits; i++) {
unit = this.unitsToProcess[i];
reportProgress(Messages.bind(Messages.compilation_processing, new String(unit.getFileName())));
try {
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_process,
new String[] {
String.valueOf(i + 1),
String.valueOf(this.totalUnits),
new String(this.unitsToProcess[i].getFileName())
}));
process(unit, i);
} finally {
// cleanup compilation unit result
unit.cleanUp();
}
this.unitsToProcess[i] = null; // release reference to processed unit declaration
reportWorked(1, i);
this.stats.lineCount += unit.compilationResult.lineSeparatorPositions.length;
long acceptStart = System.currentTimeMillis();
this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
this.stats.generateTime += System.currentTimeMillis() - acceptStart; // record accept time as part of generation
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_done,
new String[] {
String.valueOf(i + 1),
String.valueOf(this.totalUnits),
new String(unit.getFileName())
}));
}
} else {
processingTask = new ProcessTaskManager(this);
int acceptedCount = 0;
// process all units (some more could be injected in the loop by the lookup environment)
// the processTask can continue to process units until its fixed sized cache is full then it must wait
// for this this thread to accept the units as they appear (it only waits if no units are available)
while (true) {
try {
unit = processingTask.removeNextUnit(); // waits if no units are in the processed queue
} catch (Error e) {
unit = processingTask.unitToProcess;
throw e;
} catch (RuntimeException e) {
unit = processingTask.unitToProcess;
throw e;
}
if (unit == null) break;
reportWorked(1, acceptedCount++);
this.stats.lineCount += unit.compilationResult.lineSeparatorPositions.length;
this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
if (this.options.verbose)
this.out.println(
Messages.bind(Messages.compilation_done,
new String[] {
String.valueOf(acceptedCount),
String.valueOf(this.totalUnits),
new String(unit.getFileName())
}));
}
}
} catch (AbortCompilation e) {
this.handleInternalException(e, unit);
} catch (Error e) {
this.handleInternalException(e, unit, null);
throw e; // rethrow
} catch (RuntimeException e) {
this.handleInternalException(e, unit, null);
throw e; // rethrow
} finally {
if (processingTask != null) {
processingTask.shutdown();
processingTask = null;
}
reset();
this.annotationProcessorStartIndex = 0;
this.stats.endTime = System.currentTimeMillis();
}
if (this.options.verbose) {
if (this.totalUnits > 1) {
this.out.println(
Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));
} else {
this.out.println(
Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));
}
}
}
|
diff --git a/src/jvm/final_project/view/ScoreView.java b/src/jvm/final_project/view/ScoreView.java
index aeaaaad..9d9ca6c 100644
--- a/src/jvm/final_project/view/ScoreView.java
+++ b/src/jvm/final_project/view/ScoreView.java
@@ -1,96 +1,96 @@
package final_project.view;
import java.awt.*;
import javax.swing.*;
import final_project.control.*;
import final_project.model.*;
public class ScoreView extends JPanel {
TournamentController tournament;
public final String player1Name, player2Name;
/**
* Create the panel.
* @wbp.parser.constructor
*/
private ScoreView(TournamentController tournament, PlayerResult player1, PlayerResult player2) {
this.tournament = tournament;
player1Name = tournament.getNameFromId(player1.getPlayerId());
player2Name = tournament.getNameFromId(player2.getPlayerId());
int player1Score = player1.getPlayerScore();
int player2Score = player2.getPlayerScore();
setBackground(Color.BLACK);
GridBagConstraints gbc_panel_1 = new GridBagConstraints();
gbc_panel_1.anchor = GridBagConstraints.NORTHWEST;
gbc_panel_1.insets = new Insets(0, 0, 0, 5);
gbc_panel_1.fill = GridBagConstraints.HORIZONTAL;
gbc_panel_1.gridx = 1;
gbc_panel_1.gridy = 0;
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{200, 30, 30, 30, 200, 0};
gridBagLayout.rowHeights = new int[]{19, 0};
gridBagLayout.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JLabel player1NameLabel = new JLabel(player1Name);
GridBagConstraints gbc_player1NameLabel = new GridBagConstraints();
gbc_player1NameLabel.anchor = GridBagConstraints.EAST;
gbc_player1NameLabel.insets = new Insets(0, 0, 0, 5);
gbc_player1NameLabel.gridx = 0;
gbc_player1NameLabel.gridy = 0;
add(player1NameLabel, gbc_player1NameLabel);
- player1NameLabel.setFont(new Font("Score Board", Font.PLAIN, 18));
+ player1NameLabel.setFont(new Font("Score Board", Font.PLAIN, 17));
player1NameLabel.setForeground(Color.WHITE);
JLabel player1ScoreLabel = new JLabel("");
player1ScoreLabel.setForeground(Color.CYAN);
player1ScoreLabel.setFont(new Font("Score Board", Font.PLAIN, 16));
if (player1Score != -1)
player1ScoreLabel.setText("" + player1Score);
GridBagConstraints gbc_player1ScoreLabel = new GridBagConstraints();
gbc_player1ScoreLabel.insets = new Insets(0, 0, 0, 5);
gbc_player1ScoreLabel.gridx = 1;
gbc_player1ScoreLabel.gridy = 0;
add(player1ScoreLabel, gbc_player1ScoreLabel);
JLabel vs = new JLabel("vs");
GridBagConstraints gbc_vs = new GridBagConstraints();
gbc_vs.insets = new Insets(0, 0, 0, 5);
gbc_vs.gridx = 2;
gbc_vs.gridy = 0;
add(vs, gbc_vs);
vs.setFont(new Font("Score Board", Font.PLAIN, 16));
vs.setForeground(Color.RED);
JLabel player2ScoreLabel = new JLabel("");
player2ScoreLabel.setForeground(Color.ORANGE);
player2ScoreLabel.setFont(new Font("Score Board", Font.PLAIN, 16));
if (player2Score != -1)
player2ScoreLabel.setText("" + player2Score);
GridBagConstraints gbc_player2ScoreLabel1 = new GridBagConstraints();
gbc_player2ScoreLabel1.insets = new Insets(0, 0, 0, 5);
gbc_player2ScoreLabel1.gridx = 3;
gbc_player2ScoreLabel1.gridy = 0;
add(player2ScoreLabel, gbc_player2ScoreLabel1);
JLabel player2NameLabel = new JLabel(player2Name);
player2NameLabel.setForeground(Color.WHITE);
- player2NameLabel.setFont(new Font("Score Board", Font.PLAIN, 16));
+ player2NameLabel.setFont(new Font("Score Board", Font.PLAIN, 17));
GridBagConstraints gbc_player2NameLabel = new GridBagConstraints();
gbc_player2NameLabel.anchor = GridBagConstraints.WEST;
gbc_player2NameLabel.gridx = 4;
gbc_player2NameLabel.gridy = 0;
add(player2NameLabel, gbc_player2NameLabel);
}
public ScoreView(TournamentController tournament, IncompleteResult result) {
this(tournament, new PlayerResult(result.getPlayer1(), -1), new PlayerResult(result.getPlayer2(), -1));
}
public ScoreView(TournamentController tournament, CompleteResult result) {
this(tournament, new PlayerResult(result.getWinner(), result.getWinnerScore()), new PlayerResult(result.getLoser(), result.getLoserScore()));
}
}
| false | true | private ScoreView(TournamentController tournament, PlayerResult player1, PlayerResult player2) {
this.tournament = tournament;
player1Name = tournament.getNameFromId(player1.getPlayerId());
player2Name = tournament.getNameFromId(player2.getPlayerId());
int player1Score = player1.getPlayerScore();
int player2Score = player2.getPlayerScore();
setBackground(Color.BLACK);
GridBagConstraints gbc_panel_1 = new GridBagConstraints();
gbc_panel_1.anchor = GridBagConstraints.NORTHWEST;
gbc_panel_1.insets = new Insets(0, 0, 0, 5);
gbc_panel_1.fill = GridBagConstraints.HORIZONTAL;
gbc_panel_1.gridx = 1;
gbc_panel_1.gridy = 0;
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{200, 30, 30, 30, 200, 0};
gridBagLayout.rowHeights = new int[]{19, 0};
gridBagLayout.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JLabel player1NameLabel = new JLabel(player1Name);
GridBagConstraints gbc_player1NameLabel = new GridBagConstraints();
gbc_player1NameLabel.anchor = GridBagConstraints.EAST;
gbc_player1NameLabel.insets = new Insets(0, 0, 0, 5);
gbc_player1NameLabel.gridx = 0;
gbc_player1NameLabel.gridy = 0;
add(player1NameLabel, gbc_player1NameLabel);
player1NameLabel.setFont(new Font("Score Board", Font.PLAIN, 18));
player1NameLabel.setForeground(Color.WHITE);
JLabel player1ScoreLabel = new JLabel("");
player1ScoreLabel.setForeground(Color.CYAN);
player1ScoreLabel.setFont(new Font("Score Board", Font.PLAIN, 16));
if (player1Score != -1)
player1ScoreLabel.setText("" + player1Score);
GridBagConstraints gbc_player1ScoreLabel = new GridBagConstraints();
gbc_player1ScoreLabel.insets = new Insets(0, 0, 0, 5);
gbc_player1ScoreLabel.gridx = 1;
gbc_player1ScoreLabel.gridy = 0;
add(player1ScoreLabel, gbc_player1ScoreLabel);
JLabel vs = new JLabel("vs");
GridBagConstraints gbc_vs = new GridBagConstraints();
gbc_vs.insets = new Insets(0, 0, 0, 5);
gbc_vs.gridx = 2;
gbc_vs.gridy = 0;
add(vs, gbc_vs);
vs.setFont(new Font("Score Board", Font.PLAIN, 16));
vs.setForeground(Color.RED);
JLabel player2ScoreLabel = new JLabel("");
player2ScoreLabel.setForeground(Color.ORANGE);
player2ScoreLabel.setFont(new Font("Score Board", Font.PLAIN, 16));
if (player2Score != -1)
player2ScoreLabel.setText("" + player2Score);
GridBagConstraints gbc_player2ScoreLabel1 = new GridBagConstraints();
gbc_player2ScoreLabel1.insets = new Insets(0, 0, 0, 5);
gbc_player2ScoreLabel1.gridx = 3;
gbc_player2ScoreLabel1.gridy = 0;
add(player2ScoreLabel, gbc_player2ScoreLabel1);
JLabel player2NameLabel = new JLabel(player2Name);
player2NameLabel.setForeground(Color.WHITE);
player2NameLabel.setFont(new Font("Score Board", Font.PLAIN, 16));
GridBagConstraints gbc_player2NameLabel = new GridBagConstraints();
gbc_player2NameLabel.anchor = GridBagConstraints.WEST;
gbc_player2NameLabel.gridx = 4;
gbc_player2NameLabel.gridy = 0;
add(player2NameLabel, gbc_player2NameLabel);
}
| private ScoreView(TournamentController tournament, PlayerResult player1, PlayerResult player2) {
this.tournament = tournament;
player1Name = tournament.getNameFromId(player1.getPlayerId());
player2Name = tournament.getNameFromId(player2.getPlayerId());
int player1Score = player1.getPlayerScore();
int player2Score = player2.getPlayerScore();
setBackground(Color.BLACK);
GridBagConstraints gbc_panel_1 = new GridBagConstraints();
gbc_panel_1.anchor = GridBagConstraints.NORTHWEST;
gbc_panel_1.insets = new Insets(0, 0, 0, 5);
gbc_panel_1.fill = GridBagConstraints.HORIZONTAL;
gbc_panel_1.gridx = 1;
gbc_panel_1.gridy = 0;
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{200, 30, 30, 30, 200, 0};
gridBagLayout.rowHeights = new int[]{19, 0};
gridBagLayout.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JLabel player1NameLabel = new JLabel(player1Name);
GridBagConstraints gbc_player1NameLabel = new GridBagConstraints();
gbc_player1NameLabel.anchor = GridBagConstraints.EAST;
gbc_player1NameLabel.insets = new Insets(0, 0, 0, 5);
gbc_player1NameLabel.gridx = 0;
gbc_player1NameLabel.gridy = 0;
add(player1NameLabel, gbc_player1NameLabel);
player1NameLabel.setFont(new Font("Score Board", Font.PLAIN, 17));
player1NameLabel.setForeground(Color.WHITE);
JLabel player1ScoreLabel = new JLabel("");
player1ScoreLabel.setForeground(Color.CYAN);
player1ScoreLabel.setFont(new Font("Score Board", Font.PLAIN, 16));
if (player1Score != -1)
player1ScoreLabel.setText("" + player1Score);
GridBagConstraints gbc_player1ScoreLabel = new GridBagConstraints();
gbc_player1ScoreLabel.insets = new Insets(0, 0, 0, 5);
gbc_player1ScoreLabel.gridx = 1;
gbc_player1ScoreLabel.gridy = 0;
add(player1ScoreLabel, gbc_player1ScoreLabel);
JLabel vs = new JLabel("vs");
GridBagConstraints gbc_vs = new GridBagConstraints();
gbc_vs.insets = new Insets(0, 0, 0, 5);
gbc_vs.gridx = 2;
gbc_vs.gridy = 0;
add(vs, gbc_vs);
vs.setFont(new Font("Score Board", Font.PLAIN, 16));
vs.setForeground(Color.RED);
JLabel player2ScoreLabel = new JLabel("");
player2ScoreLabel.setForeground(Color.ORANGE);
player2ScoreLabel.setFont(new Font("Score Board", Font.PLAIN, 16));
if (player2Score != -1)
player2ScoreLabel.setText("" + player2Score);
GridBagConstraints gbc_player2ScoreLabel1 = new GridBagConstraints();
gbc_player2ScoreLabel1.insets = new Insets(0, 0, 0, 5);
gbc_player2ScoreLabel1.gridx = 3;
gbc_player2ScoreLabel1.gridy = 0;
add(player2ScoreLabel, gbc_player2ScoreLabel1);
JLabel player2NameLabel = new JLabel(player2Name);
player2NameLabel.setForeground(Color.WHITE);
player2NameLabel.setFont(new Font("Score Board", Font.PLAIN, 17));
GridBagConstraints gbc_player2NameLabel = new GridBagConstraints();
gbc_player2NameLabel.anchor = GridBagConstraints.WEST;
gbc_player2NameLabel.gridx = 4;
gbc_player2NameLabel.gridy = 0;
add(player2NameLabel, gbc_player2NameLabel);
}
|
diff --git a/src/com/itmill/toolkit/demo/featurebrowser/ComboBoxExample.java b/src/com/itmill/toolkit/demo/featurebrowser/ComboBoxExample.java
index d346eddac..c83db8b2a 100644
--- a/src/com/itmill/toolkit/demo/featurebrowser/ComboBoxExample.java
+++ b/src/com/itmill/toolkit/demo/featurebrowser/ComboBoxExample.java
@@ -1,62 +1,62 @@
package com.itmill.toolkit.demo.featurebrowser;
import com.itmill.toolkit.ui.ComboBox;
import com.itmill.toolkit.ui.CustomComponent;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.AbstractSelect.Filtering;
/**
*
*/
public class ComboBoxExample extends CustomComponent {
private static final String[] firstnames = new String[] { "John", "Mary",
"Joe", "Sarah", "Jeff", "Jane", "Peter", "Marc", "Robert", "Paula",
"Lenny", "Kenny", "Nathan", "Nicole", "Laura", "Jos", "Josie",
"Linus" };
private static final String[] lastnames = new String[] { "Torvalds",
"Smith", "Adams", "Black", "Wilson", "Richards", "Thompson",
"McGoff", "Halas", "Jones", "Beck", "Sheridan", "Picard", "Hill",
"Fielding", "Einstein" };
public ComboBoxExample() {
OrderedLayout main = new OrderedLayout();
main.setMargin(true);
setCompositionRoot(main);
// starts-with filter
ComboBox s1 = new ComboBox("Select with starts-with filter");
s1.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH);
s1.setColumns(20);
for (int i = 0; i < 105; i++) {
s1
.addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ " "
+ lastnames[(int) (Math.random() * (lastnames.length - 1))]);
}
s1.setImmediate(true);
main.addComponent(s1);
// contains filter
ComboBox s2 = new ComboBox("Select with contains filter");
s2.setFilteringMode(Filtering.FILTERINGMODE_CONTAINS);
s2.setColumns(20);
for (int i = 0; i < 500; i++) {
s2
.addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ " "
+ lastnames[(int) (Math.random() * (lastnames.length - 1))]);
}
s2.setImmediate(true);
main.addComponent(s2);
- // contains filter
+ // initially empty
ComboBox s3 = new ComboBox("Initially empty; enter your own");
s3.setColumns(20);
s3.setImmediate(true);
main.addComponent(s3);
}
}
| true | true | public ComboBoxExample() {
OrderedLayout main = new OrderedLayout();
main.setMargin(true);
setCompositionRoot(main);
// starts-with filter
ComboBox s1 = new ComboBox("Select with starts-with filter");
s1.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH);
s1.setColumns(20);
for (int i = 0; i < 105; i++) {
s1
.addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ " "
+ lastnames[(int) (Math.random() * (lastnames.length - 1))]);
}
s1.setImmediate(true);
main.addComponent(s1);
// contains filter
ComboBox s2 = new ComboBox("Select with contains filter");
s2.setFilteringMode(Filtering.FILTERINGMODE_CONTAINS);
s2.setColumns(20);
for (int i = 0; i < 500; i++) {
s2
.addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ " "
+ lastnames[(int) (Math.random() * (lastnames.length - 1))]);
}
s2.setImmediate(true);
main.addComponent(s2);
// contains filter
ComboBox s3 = new ComboBox("Initially empty; enter your own");
s3.setColumns(20);
s3.setImmediate(true);
main.addComponent(s3);
}
| public ComboBoxExample() {
OrderedLayout main = new OrderedLayout();
main.setMargin(true);
setCompositionRoot(main);
// starts-with filter
ComboBox s1 = new ComboBox("Select with starts-with filter");
s1.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH);
s1.setColumns(20);
for (int i = 0; i < 105; i++) {
s1
.addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ " "
+ lastnames[(int) (Math.random() * (lastnames.length - 1))]);
}
s1.setImmediate(true);
main.addComponent(s1);
// contains filter
ComboBox s2 = new ComboBox("Select with contains filter");
s2.setFilteringMode(Filtering.FILTERINGMODE_CONTAINS);
s2.setColumns(20);
for (int i = 0; i < 500; i++) {
s2
.addItem(firstnames[(int) (Math.random() * (firstnames.length - 1))]
+ " "
+ lastnames[(int) (Math.random() * (lastnames.length - 1))]);
}
s2.setImmediate(true);
main.addComponent(s2);
// initially empty
ComboBox s3 = new ComboBox("Initially empty; enter your own");
s3.setColumns(20);
s3.setImmediate(true);
main.addComponent(s3);
}
|
diff --git a/de.xwic.cube/src/de/xwic/cube/util/JDBCSerializerUtil.java b/de.xwic.cube/src/de/xwic/cube/util/JDBCSerializerUtil.java
index db4b2c0..d7134c1 100644
--- a/de.xwic.cube/src/de/xwic/cube/util/JDBCSerializerUtil.java
+++ b/de.xwic.cube/src/de/xwic/cube/util/JDBCSerializerUtil.java
@@ -1,347 +1,347 @@
/**
*
*/
package de.xwic.cube.util;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import de.xwic.cube.IDataPool;
import de.xwic.cube.IDimension;
import de.xwic.cube.IDimensionElement;
import de.xwic.cube.IMeasure;
/**
* @author Developer
*
*/
public class JDBCSerializerUtil {
private static Log log = LogFactory.getLog(JDBCSerializerUtil.class);
/**
* Update the specified table with the measures in the DataPool.
* @param connection
* @param tableName
* @param pool
* @throws SQLException
*/
public static void storeMeasures(Connection connection, IDataPool pool, String tableName) throws SQLException {
Statement stmt = connection.createStatement();
PreparedStatement psUpdate = connection.prepareStatement("UPDATE [" + tableName + "] SET [Title] = ?, [FunctionClass] = ?, [ValueFormatProvider] = ? WHERE [Key] = ?");
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO [" + tableName + "] ([Key], [Title], [FunctionClass], [ValueFormatProvider]) VALUES (?, ?, ?, ?)");
PreparedStatement psDelete = connection.prepareStatement("DELETE FROM [" + tableName + "] WHERE [Key] = ?");
ResultSet rs = stmt.executeQuery("SELECT [Key] FROM [" + tableName + "]");
Set<String> keys = new HashSet<String>();
while (rs.next()) {
keys.add(rs.getString(1));
}
rs.close();
stmt.close();
for (IMeasure measure : pool.getMeasures()) {
if (keys.contains(measure.getKey())) {
psUpdate.clearParameters();
psUpdate.setString(1, measure.getTitle());
if (measure.isFunction()) {
psUpdate.setString(2, measure.getFunction().getClass().getName());
} else {
psUpdate.setNull(2, Types.VARCHAR);
}
psUpdate.setString(3, measure.getValueFormatProvider().getClass().getName());
psUpdate.setString(4, measure.getKey());
int updates = psUpdate.executeUpdate();
if (updates != 1) {
System.out.println("Measure update failed for " + measure.getKey());
}
keys.remove(measure.getKey());
} else {
psInsert.clearParameters();
psInsert.setString(1, measure.getKey());
psInsert.setString(2, measure.getTitle());
if (measure.isFunction()) {
psInsert.setString(3, measure.getFunction().getClass().getName());
} else {
psInsert.setNull(3, Types.VARCHAR);
}
psInsert.setString(4, measure.getValueFormatProvider().getClass().getName());
psInsert.executeUpdate();
}
}
// delete old keys.
for (String key : keys) {
psDelete.clearParameters();
psDelete.setString(1, key);
psDelete.executeUpdate();
}
psUpdate.close();
psInsert.close();
psDelete.close();
}
/**
* Update the specified table with the measures in the DataPool.
* @param connection
* @param tableName
* @param pool
* @throws SQLException
*/
public static void storeDimensions(Connection connection, IDataPool pool, String dimTableName, String dimElmTableName) throws SQLException {
checkDimensionTable(connection, dimTableName, dimElmTableName);
PreparedStatement psUpdateDim = connection.prepareStatement("UPDATE [" + dimTableName + "] SET [Title] = ?, [Sealed] = ? WHERE [Key] = ?");
- PreparedStatement psInsertDim = connection.prepareStatement("INSERT INTO [" + dimTableName + "] ([Key], [Title], [Sealed]) VALUES (?, ?)");
+ PreparedStatement psInsertDim = connection.prepareStatement("INSERT INTO [" + dimTableName + "] ([Key], [Title], [Sealed]) VALUES (?, ?, ?)");
PreparedStatement psDeleteDim = connection.prepareStatement("DELETE FROM [" + dimTableName + "] WHERE [Key] = ?");
PreparedStatement psSelectDimElm = connection.prepareStatement("SELECT [ID] FROM [" + dimElmTableName + "] WHERE [DimensionKey] = ? AND [ParentID] = ?");
PreparedStatement psUpdateDimElm = connection.prepareStatement("UPDATE [" + dimElmTableName + "] SET [Title] = ?, [weight] = ?, [order_index] = ? WHERE [ID] = ?");
PreparedStatement psInsertDimElm = connection.prepareStatement("INSERT INTO [" + dimElmTableName + "] ([ID], [ParentID], [DimensionKey], [Key], [Title], [weight], [order_index]) VALUES (?, ?, ?, ?, ?, ?, ?)");
PreparedStatement psDeleteDimElm = connection.prepareStatement("DELETE FROM [" + dimElmTableName + "] WHERE [ID] = ?");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT [Key] FROM [" + dimTableName + "]");
Set<String> keys = new HashSet<String>();
while (rs.next()) {
keys.add(rs.getString(1));
}
rs.close();
stmt.close();
for (IDimension dimension : pool.getDimensions()) {
if (keys.contains(dimension.getKey())) {
psUpdateDim.clearParameters();
psUpdateDim.setString(1, dimension.getTitle());
psUpdateDim.setBoolean(2, dimension.isSealed());
psUpdateDim.setString(3, dimension.getKey());
int updates = psUpdateDim.executeUpdate();
if (updates != 1) {
System.out.println("Dimension update failed for " + dimension.getKey());
}
keys.remove(dimension.getKey());
} else {
psInsertDim.clearParameters();
psInsertDim.setString(1, dimension.getKey());
psInsertDim.setString(2, dimension.getTitle());
- psUpdateDim.setBoolean(3, dimension.isSealed());
+ psInsertDim.setBoolean(3, dimension.isSealed());
psInsertDim.executeUpdate();
}
updateDimensionElements(dimension, psSelectDimElm, psInsertDimElm, psUpdateDimElm, psDeleteDimElm);
}
// delete old keys.
for (String key : keys) {
psDeleteDim.clearParameters();
psDeleteDim.setString(1, key);
psDeleteDim.executeUpdate();
}
psUpdateDim.close();
psInsertDim.close();
psDeleteDim.close();
psSelectDimElm.close();
psUpdateDimElm.close();
psDeleteDimElm.close();
psInsertDimElm.close();
}
/**
* @param connection
* @param dimElmTableName
* @param dimTableName
* @throws SQLException
*/
private static void checkDimensionTable(Connection connection, String dimTableName, String dimElmTableName) throws SQLException {
if (!columnExists(connection, dimTableName, "Sealed")) {
// create column
log.warn("Column 'Sealed' does not exist - will be created now..");
Statement stmt = connection.createStatement();
stmt.execute("ALTER TABLE [" + dimTableName + "] ADD [Sealed] Bit NOT NULL Default 0");
SQLWarning sw = stmt.getWarnings();
if (sw != null) {
log.warn("SQL Result: " + sw);
}
}
}
/**
* Check if a column exists already.
* @param con
* @param tableName
* @param columnName
* @return
* @throws SQLException
*/
private static boolean columnExists(Connection con, String tableName, String columnName) throws SQLException {
DatabaseMetaData metaData = con.getMetaData();
ResultSet columns = metaData.getColumns(con.getCatalog(), null, tableName, columnName);
try {
if (columns.next()) {
return true;
}
return false;
} finally {
columns.close();
}
}
/**
* @param dimension
* @param psInsertDimElm
* @param psUpdateDimElm
* @param psDeleteDimElm
*/
private static void updateDimensionElements(IDimensionElement elm, PreparedStatement psSelectDimElm, PreparedStatement psInsertDimElm, PreparedStatement psUpdateDimElm, PreparedStatement psDeleteDimElm) throws SQLException {
psSelectDimElm.clearParameters();
psSelectDimElm.setString(1, elm.getDimension().getKey());
psSelectDimElm.setString(2, elm.getID());
ResultSet rs = psSelectDimElm.executeQuery();
Set<String> keys = new HashSet<String>();
while (rs.next()) {
keys.add(rs.getString(1));
}
rs.close();
int index = 0;
for (IDimensionElement dimElm : elm.getDimensionElements()) {
if (keys.contains(dimElm.getID())) {
psUpdateDimElm.clearParameters();
psUpdateDimElm.setString(1, dimElm.getTitle());
psUpdateDimElm.setDouble(2, dimElm.getWeight());
psUpdateDimElm.setInt(3, index++);
psUpdateDimElm.setString(4, dimElm.getID());
int updates = psUpdateDimElm.executeUpdate();
if (updates != 1) {
System.out.println("DimensionElement update failed for " + dimElm.getKey());
}
keys.remove(dimElm.getID());
} else {
// ([ID], [ParentID], [DimensionKey], [Key], [Title], [weight], [order_index])
psInsertDimElm.clearParameters();
psInsertDimElm.setString(1, dimElm.getID());
psInsertDimElm.setString(2, elm.getID());
psInsertDimElm.setString(3, dimElm.getDimension().getKey());
psInsertDimElm.setString(4, dimElm.getKey());
psInsertDimElm.setString(5, dimElm.getTitle());
psInsertDimElm.setDouble(6, dimElm.getWeight());
psInsertDimElm.setInt(7, index++);
psInsertDimElm.executeUpdate();
}
updateDimensionElements(dimElm, psSelectDimElm, psInsertDimElm, psUpdateDimElm, psDeleteDimElm);
}
// delete old keys.
for (String key : keys) {
psDeleteDimElm.clearParameters();
psDeleteDimElm.setString(1, key);
psDeleteDimElm.executeUpdate();
}
}
/**
* @param connection
* @param pool
* @throws SQLException
*/
public static void restoreDimensions(Connection connection, IDataPool pool, String dimTableName, String dimElmTableName) throws SQLException {
checkDimensionTable(connection, dimTableName, dimElmTableName);
// restores dimensions.
PreparedStatement psSelectDimElm = connection.prepareStatement("SELECT [Key], [Title], [weight], [order_index], [ParentID] FROM [" + dimElmTableName + "] WHERE [DimensionKey] = ? ORDER BY order_index asc");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT [Key], [Title], [Sealed] FROM [" + dimTableName + "]");
while (rs.next()) {
String key = rs.getString(1);
String title = rs.getString(2);
boolean sealed = rs.getBoolean(3);
System.out.println("Validating Dimension " + key);
IDimension dim;
if (!pool.containsDimension(key)) {
dim = pool.createDimension(key);
} else {
dim = pool.getDimension(key);
}
dim.setTitle(title);
dim.setSealed(false);
// load child elements
psSelectDimElm.clearParameters();
psSelectDimElm.setString(1, dim.getKey());
psSelectDimElm.setFetchSize(1000);
ResultSet rsE = psSelectDimElm.executeQuery();
// load them first
List<DimElmDef> elmList = new ArrayList<DimElmDef>();
while (rsE.next()) {
DimElmDef de = new DimElmDef();
de.key = rsE.getString("Key");
de.title = rsE.getString("Title");
de.weight = rsE.getDouble("weight");
de.parentId = rsE.getString("ParentID");
de.order_index = rsE.getInt("order_index");
elmList.add(de);
}
rsE.close();
restoreChilds(dim, elmList);
dim.setSealed(sealed);
}
rs.close();
stmt.close();
}
/**
* @param dim
* @param elmList
* @throws SQLException
*/
private static void restoreChilds(IDimensionElement elm, List<DimElmDef> elmList) throws SQLException {
String parentId = elm.getID();
for (DimElmDef ded : elmList) {
if (parentId.equals(ded.parentId)) {
IDimensionElement child;
if (elm.containsDimensionElement(ded.key)) {
child = elm.getDimensionElement(ded.key);
} else {
child = elm.createDimensionElement(ded.key);
}
child.setTitle(ded.title);
child.setWeight(ded.weight);
}
}
for (IDimensionElement child : elm.getDimensionElements()) {
restoreChilds(child, elmList);
}
}
}
| false | true | public static void storeDimensions(Connection connection, IDataPool pool, String dimTableName, String dimElmTableName) throws SQLException {
checkDimensionTable(connection, dimTableName, dimElmTableName);
PreparedStatement psUpdateDim = connection.prepareStatement("UPDATE [" + dimTableName + "] SET [Title] = ?, [Sealed] = ? WHERE [Key] = ?");
PreparedStatement psInsertDim = connection.prepareStatement("INSERT INTO [" + dimTableName + "] ([Key], [Title], [Sealed]) VALUES (?, ?)");
PreparedStatement psDeleteDim = connection.prepareStatement("DELETE FROM [" + dimTableName + "] WHERE [Key] = ?");
PreparedStatement psSelectDimElm = connection.prepareStatement("SELECT [ID] FROM [" + dimElmTableName + "] WHERE [DimensionKey] = ? AND [ParentID] = ?");
PreparedStatement psUpdateDimElm = connection.prepareStatement("UPDATE [" + dimElmTableName + "] SET [Title] = ?, [weight] = ?, [order_index] = ? WHERE [ID] = ?");
PreparedStatement psInsertDimElm = connection.prepareStatement("INSERT INTO [" + dimElmTableName + "] ([ID], [ParentID], [DimensionKey], [Key], [Title], [weight], [order_index]) VALUES (?, ?, ?, ?, ?, ?, ?)");
PreparedStatement psDeleteDimElm = connection.prepareStatement("DELETE FROM [" + dimElmTableName + "] WHERE [ID] = ?");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT [Key] FROM [" + dimTableName + "]");
Set<String> keys = new HashSet<String>();
while (rs.next()) {
keys.add(rs.getString(1));
}
rs.close();
stmt.close();
for (IDimension dimension : pool.getDimensions()) {
if (keys.contains(dimension.getKey())) {
psUpdateDim.clearParameters();
psUpdateDim.setString(1, dimension.getTitle());
psUpdateDim.setBoolean(2, dimension.isSealed());
psUpdateDim.setString(3, dimension.getKey());
int updates = psUpdateDim.executeUpdate();
if (updates != 1) {
System.out.println("Dimension update failed for " + dimension.getKey());
}
keys.remove(dimension.getKey());
} else {
psInsertDim.clearParameters();
psInsertDim.setString(1, dimension.getKey());
psInsertDim.setString(2, dimension.getTitle());
psUpdateDim.setBoolean(3, dimension.isSealed());
psInsertDim.executeUpdate();
}
updateDimensionElements(dimension, psSelectDimElm, psInsertDimElm, psUpdateDimElm, psDeleteDimElm);
}
// delete old keys.
for (String key : keys) {
psDeleteDim.clearParameters();
psDeleteDim.setString(1, key);
psDeleteDim.executeUpdate();
}
psUpdateDim.close();
psInsertDim.close();
psDeleteDim.close();
psSelectDimElm.close();
psUpdateDimElm.close();
psDeleteDimElm.close();
psInsertDimElm.close();
}
| public static void storeDimensions(Connection connection, IDataPool pool, String dimTableName, String dimElmTableName) throws SQLException {
checkDimensionTable(connection, dimTableName, dimElmTableName);
PreparedStatement psUpdateDim = connection.prepareStatement("UPDATE [" + dimTableName + "] SET [Title] = ?, [Sealed] = ? WHERE [Key] = ?");
PreparedStatement psInsertDim = connection.prepareStatement("INSERT INTO [" + dimTableName + "] ([Key], [Title], [Sealed]) VALUES (?, ?, ?)");
PreparedStatement psDeleteDim = connection.prepareStatement("DELETE FROM [" + dimTableName + "] WHERE [Key] = ?");
PreparedStatement psSelectDimElm = connection.prepareStatement("SELECT [ID] FROM [" + dimElmTableName + "] WHERE [DimensionKey] = ? AND [ParentID] = ?");
PreparedStatement psUpdateDimElm = connection.prepareStatement("UPDATE [" + dimElmTableName + "] SET [Title] = ?, [weight] = ?, [order_index] = ? WHERE [ID] = ?");
PreparedStatement psInsertDimElm = connection.prepareStatement("INSERT INTO [" + dimElmTableName + "] ([ID], [ParentID], [DimensionKey], [Key], [Title], [weight], [order_index]) VALUES (?, ?, ?, ?, ?, ?, ?)");
PreparedStatement psDeleteDimElm = connection.prepareStatement("DELETE FROM [" + dimElmTableName + "] WHERE [ID] = ?");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT [Key] FROM [" + dimTableName + "]");
Set<String> keys = new HashSet<String>();
while (rs.next()) {
keys.add(rs.getString(1));
}
rs.close();
stmt.close();
for (IDimension dimension : pool.getDimensions()) {
if (keys.contains(dimension.getKey())) {
psUpdateDim.clearParameters();
psUpdateDim.setString(1, dimension.getTitle());
psUpdateDim.setBoolean(2, dimension.isSealed());
psUpdateDim.setString(3, dimension.getKey());
int updates = psUpdateDim.executeUpdate();
if (updates != 1) {
System.out.println("Dimension update failed for " + dimension.getKey());
}
keys.remove(dimension.getKey());
} else {
psInsertDim.clearParameters();
psInsertDim.setString(1, dimension.getKey());
psInsertDim.setString(2, dimension.getTitle());
psInsertDim.setBoolean(3, dimension.isSealed());
psInsertDim.executeUpdate();
}
updateDimensionElements(dimension, psSelectDimElm, psInsertDimElm, psUpdateDimElm, psDeleteDimElm);
}
// delete old keys.
for (String key : keys) {
psDeleteDim.clearParameters();
psDeleteDim.setString(1, key);
psDeleteDim.executeUpdate();
}
psUpdateDim.close();
psInsertDim.close();
psDeleteDim.close();
psSelectDimElm.close();
psUpdateDimElm.close();
psDeleteDimElm.close();
psInsertDimElm.close();
}
|
diff --git a/src/main/java/uk/ac/ebi/fgpt/sampletab/AbstractInfileDriver.java b/src/main/java/uk/ac/ebi/fgpt/sampletab/AbstractInfileDriver.java
index 866dd61c..67d53d36 100644
--- a/src/main/java/uk/ac/ebi/fgpt/sampletab/AbstractInfileDriver.java
+++ b/src/main/java/uk/ac/ebi/fgpt/sampletab/AbstractInfileDriver.java
@@ -1,113 +1,118 @@
package uk.ac.ebi.fgpt.sampletab;
import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Iterables;
import uk.ac.ebi.fgpt.sampletab.utils.FileRecursiveIterable;
import uk.ac.ebi.fgpt.sampletab.utils.FileGlobIterable;
public abstract class AbstractInfileDriver<T extends Runnable> extends AbstractDriver {
@Argument(required=true, index=0, metaVar="INPUT", usage = "input filenames or globs")
protected List<String> inputFilenames;
@Option(name = "--threads", aliases = { "-t" }, usage = "number of additional threads")
protected int threads = 0;
@Option(name = "--recursive", aliases = { "-r" }, usage="recusively match filename?")
protected boolean recursive = false;
@Option(name = "--startpath", aliases = { "-s" }, usage="starting path for matching")
protected List<File> startpaths = null;
private Logger log = LoggerFactory.getLogger(getClass());
protected abstract T getNewTask(File inputFile);
protected void preProcess() {
//do nothing
//override in subclass
}
protected void postProcess() {
//do nothing
//override in subclass
}
protected void doMain(String[] args) {
super.doMain(args);
Iterable<File> inputFiles = null;
for (String inputFilename : inputFilenames) {
if (recursive){
if (startpaths == null) {
log.info("Looking recursively for input files named "+inputFilename);
if (inputFiles == null) {
inputFiles = new FileRecursiveIterable(inputFilename, null);
} else {
inputFiles = Iterables.concat(inputFiles, new FileRecursiveIterable(inputFilename, null));
}
} else {
for (File startpath : startpaths) {
log.info("Looking recursively for input files named "+inputFilename+" from "+startpath);
if (inputFiles == null) {
inputFiles = new FileRecursiveIterable(inputFilename, startpath);
} else {
inputFiles = Iterables.concat(inputFiles, new FileRecursiveIterable(inputFilename, startpath));
}
}
}
} else {
log.info("Looking for input files in glob "+inputFilename);
if (inputFiles == null) {
inputFiles = new FileGlobIterable(inputFilename);
} else {
inputFiles = Iterables.concat(inputFiles,new FileGlobIterable(inputFilename));
}
}
}
- ExecutorService pool = Executors.newFixedThreadPool(threads);
+ ExecutorService pool = null;
+ if (threads > 0) {
+ pool = Executors.newFixedThreadPool(threads);
+ }
preProcess();
for (File inputFile : inputFiles) {
Runnable t = getNewTask(inputFile);
- if (threads > 0) {
+ if (pool != null) {
pool.execute(t);
} else {
t.run();
}
}
// run the pool and then close it afterwards
// must synchronize on the pool object
- synchronized (pool) {
- pool.shutdown();
- try {
- // allow 24h to execute. Rather too much, but meh
- pool.awaitTermination(1, TimeUnit.DAYS);
- } catch (InterruptedException e) {
- log.error("Interupted awaiting thread pool termination", e);
+ if (pool != null) {
+ synchronized (pool) {
+ pool.shutdown();
+ try {
+ // allow 24h to execute. Rather too much, but meh
+ pool.awaitTermination(1, TimeUnit.DAYS);
+ } catch (InterruptedException e) {
+ log.error("Interupted awaiting thread pool termination", e);
+ }
}
}
postProcess();
log.info("Finished reading");
}
}
| false | true | protected void doMain(String[] args) {
super.doMain(args);
Iterable<File> inputFiles = null;
for (String inputFilename : inputFilenames) {
if (recursive){
if (startpaths == null) {
log.info("Looking recursively for input files named "+inputFilename);
if (inputFiles == null) {
inputFiles = new FileRecursiveIterable(inputFilename, null);
} else {
inputFiles = Iterables.concat(inputFiles, new FileRecursiveIterable(inputFilename, null));
}
} else {
for (File startpath : startpaths) {
log.info("Looking recursively for input files named "+inputFilename+" from "+startpath);
if (inputFiles == null) {
inputFiles = new FileRecursiveIterable(inputFilename, startpath);
} else {
inputFiles = Iterables.concat(inputFiles, new FileRecursiveIterable(inputFilename, startpath));
}
}
}
} else {
log.info("Looking for input files in glob "+inputFilename);
if (inputFiles == null) {
inputFiles = new FileGlobIterable(inputFilename);
} else {
inputFiles = Iterables.concat(inputFiles,new FileGlobIterable(inputFilename));
}
}
}
ExecutorService pool = Executors.newFixedThreadPool(threads);
preProcess();
for (File inputFile : inputFiles) {
Runnable t = getNewTask(inputFile);
if (threads > 0) {
pool.execute(t);
} else {
t.run();
}
}
// run the pool and then close it afterwards
// must synchronize on the pool object
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interupted awaiting thread pool termination", e);
}
}
postProcess();
log.info("Finished reading");
}
| protected void doMain(String[] args) {
super.doMain(args);
Iterable<File> inputFiles = null;
for (String inputFilename : inputFilenames) {
if (recursive){
if (startpaths == null) {
log.info("Looking recursively for input files named "+inputFilename);
if (inputFiles == null) {
inputFiles = new FileRecursiveIterable(inputFilename, null);
} else {
inputFiles = Iterables.concat(inputFiles, new FileRecursiveIterable(inputFilename, null));
}
} else {
for (File startpath : startpaths) {
log.info("Looking recursively for input files named "+inputFilename+" from "+startpath);
if (inputFiles == null) {
inputFiles = new FileRecursiveIterable(inputFilename, startpath);
} else {
inputFiles = Iterables.concat(inputFiles, new FileRecursiveIterable(inputFilename, startpath));
}
}
}
} else {
log.info("Looking for input files in glob "+inputFilename);
if (inputFiles == null) {
inputFiles = new FileGlobIterable(inputFilename);
} else {
inputFiles = Iterables.concat(inputFiles,new FileGlobIterable(inputFilename));
}
}
}
ExecutorService pool = null;
if (threads > 0) {
pool = Executors.newFixedThreadPool(threads);
}
preProcess();
for (File inputFile : inputFiles) {
Runnable t = getNewTask(inputFile);
if (pool != null) {
pool.execute(t);
} else {
t.run();
}
}
// run the pool and then close it afterwards
// must synchronize on the pool object
if (pool != null) {
synchronized (pool) {
pool.shutdown();
try {
// allow 24h to execute. Rather too much, but meh
pool.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
log.error("Interupted awaiting thread pool termination", e);
}
}
}
postProcess();
log.info("Finished reading");
}
|
diff --git a/ndx/src/main/uk/ac/starlink/ndx/BridgeNdx.java b/ndx/src/main/uk/ac/starlink/ndx/BridgeNdx.java
index 635f1dbfa..2fb518143 100644
--- a/ndx/src/main/uk/ac/starlink/ndx/BridgeNdx.java
+++ b/ndx/src/main/uk/ac/starlink/ndx/BridgeNdx.java
@@ -1,411 +1,414 @@
package uk.ac.starlink.ndx;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import uk.ac.starlink.array.NDArray;
import uk.ac.starlink.array.NDShape;
import uk.ac.starlink.array.Requirements;
import uk.ac.starlink.ast.Frame;
import uk.ac.starlink.ast.FrameSet;
import uk.ac.starlink.ast.Mapping;
import uk.ac.starlink.ast.WinMap;
import uk.ac.starlink.ast.xml.XAstReader;
import uk.ac.starlink.ast.xml.XAstWriter;
import uk.ac.starlink.util.SourceReader;
/**
* Default <tt>Ndx</tt> implementation.
* This class builds an <tt>Ndx</tt> from an {@link NdxImpl}.
*
* @author Mark Taylor (Starlink)
* @author Peter Draper (Starlink)
* @author Norman Gray (Starlink)
*/
public class BridgeNdx implements Ndx {
private static Logger logger = Logger.getLogger( "uk.ac.starlink.ndx" );
private final NdxImpl impl;
private FrameSet ast;
private String title;
private Boolean hasEtc;
private Boolean hasTitle;
private Boolean hasVariance;
private Boolean hasQuality;
private Boolean hasWCS;
private Integer badbits;
private NDArray image;
private NDArray variance;
private NDArray quality;
/**
* Constructs an {@link Ndx} implementation from an <tt>NdxImpl</tt> object.
*
* @param impl object which provides services to this BridgeNdx
*/
public BridgeNdx( NdxImpl impl ) {
this.impl = impl;
}
public NDArray getImage() {
if ( image == null ) {
image = impl.getImage();
}
return image;
}
public NDArray getVariance() {
if ( ! hasVariance() ) {
throw new UnsupportedOperationException( "No variance component" );
}
if ( variance == null ) {
variance = impl.getVariance();
}
return variance;
}
public NDArray getQuality() {
if ( ! hasQuality() ) {
throw new UnsupportedOperationException( "No quality component" );
}
if ( quality == null ) {
quality = impl.getQuality();
}
return quality;
}
public boolean hasVariance() {
if ( hasVariance == null ) {
hasVariance = Boolean.valueOf( impl.hasVariance() );
}
return hasVariance.booleanValue();
}
public boolean hasQuality() {
if ( hasQuality == null ) {
hasQuality = Boolean.valueOf( impl.hasQuality() );
}
return hasQuality.booleanValue();
}
public boolean hasTitle() {
if ( hasTitle == null ) {
hasTitle = Boolean.valueOf( impl.hasTitle() );
}
return hasTitle.booleanValue();
}
public boolean hasEtc() {
if ( hasEtc == null ) {
hasEtc = Boolean.valueOf( impl.hasEtc() );
}
return hasEtc.booleanValue();
}
public boolean hasWCS() {
if ( hasWCS == null ) {
hasWCS = Boolean.valueOf( impl.hasWCS() );
}
return hasWCS.booleanValue();
}
public String getTitle() {
if ( ! hasTitle() ) {
throw new UnsupportedOperationException( "No title component" );
}
if ( title == null ) {
title = impl.getTitle();
}
return title;
}
public Source getEtc() {
if ( ! hasEtc() ) {
throw new UnsupportedOperationException( "No Etc component" );
}
return impl.getEtc();
}
public int getBadBits() {
if ( badbits == null ) {
badbits = new Integer( impl.getBadBits() );
}
return badbits.intValue();
}
public FrameSet getAst() {
if ( ! hasWCS() ) {
throw new UnsupportedOperationException( "No WCS component" );
}
if ( ast == null ) {
try {
/* Implementation may supply the WCS in a number of formats.
* Try to cope with all, or throw an exception. */
Object fsobj = impl.getWCS();
if ( fsobj instanceof FrameSet ) {
ast = (FrameSet) fsobj;
}
else if ( fsobj instanceof Element ) {
ast = makeAst( new DOMSource( (Element) fsobj ) );
}
else if ( fsobj instanceof Source ) {
ast = makeAst( (Source) fsobj );
}
else {
logger.warning( "Unknown WCS object type " + fsobj );
}
}
catch ( IOException e ) {
logger.warning( "Error retrieving WCS: " + e );
}
if ( ast == null ) {
ast = Ndxs.getDefaultAst( this );
}
}
return ast;
}
public boolean isPersistent() {
return ( getImage().getURL() != null )
&& ( ! hasVariance() || getVariance().getURL() != null )
&& ( ! hasQuality() || getQuality().getURL() != null );
}
private static FrameSet makeAst( Source astsrc ) throws IOException {
// Note namespace prefix is null as HDX should have
// transformed it!
return (FrameSet) new XAstReader().makeAst( astsrc, null );
}
/**
* Generates an XML view of this Ndx object as a <tt>Source</tt>.
* The XML is built using only public methods of this Ndx rather than
* any private values, so that this method can safely be inherited
* by subclasses.
*
* @param base URL against which others are to be relativised
* @return an XML Source representation of this Ndx
*/
public Source toXML( URL base ) {
/* Set up the document and root element. */
DocumentBuilderFactory dfact = DocumentBuilderFactory.newInstance();
DocumentBuilder dbuild;
try {
dbuild = dfact.newDocumentBuilder();
}
catch ( ParserConfigurationException e ) {
throw new RuntimeException( "Trouble building vanilla parser", e );
}
Document doc = dbuild.newDocument();
Element ndxEl = doc.createElement( "ndx" );
doc.appendChild( ndxEl );
/* Get the base URI in a form suitable for using with URI.relativize. */
URI baseUri;
if ( base != null ) {
try {
baseUri = new URI( base.toExternalForm() );
String scheme = baseUri.getScheme();
String auth = baseUri.getAuthority();
String path = baseUri.getPath();
+ if ( path == null ) {
+ path = "";
+ }
path = path.replaceFirst( "[^/]*$", "" );
baseUri = new URI( scheme, auth, path, "", "" );
}
catch ( URISyntaxException e ) {
baseUri = null;
}
}
else {
baseUri = null;
}
/* Write a title element. */
if ( hasTitle() ) {
Element titleEl = doc.createElement( "title" );
ndxEl.appendChild( titleEl );
Node titleNode = doc.createTextNode( getTitle() );
titleEl.appendChild( titleNode );
}
/* Write an image element. */
Element imEl = doc.createElement( "image" );
ndxEl.appendChild( imEl );
if ( getImage().getURL() != null ) {
URI iuri = urlToUri( getImage().getURL() );
if ( baseUri != null ) {
iuri = baseUri.relativize( iuri );
}
Node imUrl = doc.createTextNode( iuri.toString() );
imEl.appendChild( imUrl );
}
else {
Node imComm = doc.createComment( "Image array is virtual" );
imEl.appendChild( imComm );
}
/* Write a variance element. */
if ( hasVariance() ) {
Element varEl = doc.createElement( "variance" );
ndxEl.appendChild( varEl );
if ( getVariance().getURL() != null ) {
URI vuri = urlToUri( getVariance().getURL() );
if ( baseUri != null ) {
vuri = baseUri.relativize( vuri );
}
Node varUrl = doc.createTextNode( vuri.toString() );
varEl.appendChild( varUrl );
}
else {
Node varComm = doc.createComment( "Variance array is virtual" );
varEl.appendChild( varComm );
}
}
/* Write a quality element. */
if ( hasQuality() ) {
Element qualEl = doc.createElement( "quality" );
ndxEl.appendChild( qualEl );
if ( getQuality().getURL() != null ) {
URI quri = urlToUri( getQuality().getURL() );
if ( baseUri != null ) {
quri = baseUri.relativize( quri );
}
Node qualUrl = doc.createTextNode( quri.toString() );
qualEl.appendChild( qualUrl );
}
else {
Node qualComm = doc.createComment( "Quality array is virtual" );
qualEl.appendChild( qualComm );
}
}
/* Write a badbits element. */
if ( getBadBits() != 0 ) {
String bbrep = "0x" + Integer.toHexString( getBadBits() );
Node bbContent = doc.createTextNode( bbrep );
Element bbEl = doc.createElement( "badbits" );
bbEl.appendChild( bbContent );
ndxEl.appendChild( bbEl );
}
/* Write a WCS element. */
if ( hasWCS() ) {
FrameSet wfset = getAst();
Source wcsSource = new XAstWriter().makeSource( wfset, null );
try {
Node wcsContent = new SourceReader().getDOM( wcsSource );
wcsContent = importNode( doc, wcsContent );
Element wcsEl = doc.createElement( "wcs" );
wcsEl.setAttribute( "encoding", "AST-XML" );
wcsEl.appendChild( wcsContent );
ndxEl.appendChild( wcsEl );
}
catch ( TransformerException e ) {
logger.warning( "Trouble transforming WCS: " + e.getMessage() );
ndxEl.appendChild( doc.createComment( "Broken WCS" ) );
}
}
/* Write an Etc element. */
if ( hasEtc() ) {
try {
Source etcSrc = getEtc();
Node etcEl = new SourceReader().getDOM( etcSrc );
etcEl = importNode( doc, etcEl );
/* Check that the returned object has the right form. */
if ( etcEl instanceof Element &&
((Element) etcEl).getTagName() == "etc" ) {
ndxEl.appendChild( etcEl );
}
else {
logger.warning( "Badly-formed Etc component from impl "
+ impl + " - not added" );
ndxEl.appendChild( doc.createComment( "Broken ETC" ) );
}
}
catch ( TransformerException e ) {
logger.warning(
"Error transforming Etc component - not added" );
ndxEl.appendChild( doc.createComment( "Broken ETC" ) );
}
}
/* Return the new DOM as a source. */
return ( base != null ) ? new DOMSource( ndxEl, base.toExternalForm() )
: new DOMSource( ndxEl );
}
/**
* Generalises the Document.importNode method so it works for a wider
* range of Node types.
*/
private Node importNode( Document doc, Node inode ) {
/* Importing a DocumentFragment should work (in fact I think that's
* pretty much what DocumentFragments were designed for) but when
* you try to do it using Crimson it throws:
*
* org.apache.crimson.tree.DomEx:
* HIERARCHY_REQUEST_ERR: This node isn't allowed there
*
* I'm pretty sure that's a bug. Work round it by hand here. */
if ( inode instanceof DocumentFragment ) {
Node onode = doc.createDocumentFragment();
for ( Node ichild = inode.getFirstChild(); ichild != null;
ichild = ichild.getNextSibling() ) {
Node ochild = doc.importNode( ichild, true );
onode.appendChild( ochild );
}
return onode;
}
/* It isn't permitted to import a whole document. Just get its
* root element. */
else if ( inode instanceof Document ) {
Node rootnode = ((Document) inode).getDocumentElement();
return doc.importNode( rootnode, true );
}
/* Otherwise, just let Document.importNode do the work. */
else {
return doc.importNode( inode, true );
}
}
/**
* Turns a URL into a URI catching the exceptions. I don't think that
* an exception can actuallly result here, since a URIs are surely a
* superset of URLs? So why doesn't this method (or an equivalent
* constructor) exist in the URI class??.
*/
private static URI urlToUri( URL url ) {
try {
return new URI( url.toExternalForm() );
}
catch ( URISyntaxException e ) {
throw new AssertionError( "Failed to convert URL <" + url + "> "
+ "to URI" );
}
}
}
| true | true | public Source toXML( URL base ) {
/* Set up the document and root element. */
DocumentBuilderFactory dfact = DocumentBuilderFactory.newInstance();
DocumentBuilder dbuild;
try {
dbuild = dfact.newDocumentBuilder();
}
catch ( ParserConfigurationException e ) {
throw new RuntimeException( "Trouble building vanilla parser", e );
}
Document doc = dbuild.newDocument();
Element ndxEl = doc.createElement( "ndx" );
doc.appendChild( ndxEl );
/* Get the base URI in a form suitable for using with URI.relativize. */
URI baseUri;
if ( base != null ) {
try {
baseUri = new URI( base.toExternalForm() );
String scheme = baseUri.getScheme();
String auth = baseUri.getAuthority();
String path = baseUri.getPath();
path = path.replaceFirst( "[^/]*$", "" );
baseUri = new URI( scheme, auth, path, "", "" );
}
catch ( URISyntaxException e ) {
baseUri = null;
}
}
else {
baseUri = null;
}
/* Write a title element. */
if ( hasTitle() ) {
Element titleEl = doc.createElement( "title" );
ndxEl.appendChild( titleEl );
Node titleNode = doc.createTextNode( getTitle() );
titleEl.appendChild( titleNode );
}
/* Write an image element. */
Element imEl = doc.createElement( "image" );
ndxEl.appendChild( imEl );
if ( getImage().getURL() != null ) {
URI iuri = urlToUri( getImage().getURL() );
if ( baseUri != null ) {
iuri = baseUri.relativize( iuri );
}
Node imUrl = doc.createTextNode( iuri.toString() );
imEl.appendChild( imUrl );
}
else {
Node imComm = doc.createComment( "Image array is virtual" );
imEl.appendChild( imComm );
}
/* Write a variance element. */
if ( hasVariance() ) {
Element varEl = doc.createElement( "variance" );
ndxEl.appendChild( varEl );
if ( getVariance().getURL() != null ) {
URI vuri = urlToUri( getVariance().getURL() );
if ( baseUri != null ) {
vuri = baseUri.relativize( vuri );
}
Node varUrl = doc.createTextNode( vuri.toString() );
varEl.appendChild( varUrl );
}
else {
Node varComm = doc.createComment( "Variance array is virtual" );
varEl.appendChild( varComm );
}
}
/* Write a quality element. */
if ( hasQuality() ) {
Element qualEl = doc.createElement( "quality" );
ndxEl.appendChild( qualEl );
if ( getQuality().getURL() != null ) {
URI quri = urlToUri( getQuality().getURL() );
if ( baseUri != null ) {
quri = baseUri.relativize( quri );
}
Node qualUrl = doc.createTextNode( quri.toString() );
qualEl.appendChild( qualUrl );
}
else {
Node qualComm = doc.createComment( "Quality array is virtual" );
qualEl.appendChild( qualComm );
}
}
/* Write a badbits element. */
if ( getBadBits() != 0 ) {
String bbrep = "0x" + Integer.toHexString( getBadBits() );
Node bbContent = doc.createTextNode( bbrep );
Element bbEl = doc.createElement( "badbits" );
bbEl.appendChild( bbContent );
ndxEl.appendChild( bbEl );
}
/* Write a WCS element. */
if ( hasWCS() ) {
FrameSet wfset = getAst();
Source wcsSource = new XAstWriter().makeSource( wfset, null );
try {
Node wcsContent = new SourceReader().getDOM( wcsSource );
wcsContent = importNode( doc, wcsContent );
Element wcsEl = doc.createElement( "wcs" );
wcsEl.setAttribute( "encoding", "AST-XML" );
wcsEl.appendChild( wcsContent );
ndxEl.appendChild( wcsEl );
}
catch ( TransformerException e ) {
logger.warning( "Trouble transforming WCS: " + e.getMessage() );
ndxEl.appendChild( doc.createComment( "Broken WCS" ) );
}
}
/* Write an Etc element. */
if ( hasEtc() ) {
try {
Source etcSrc = getEtc();
Node etcEl = new SourceReader().getDOM( etcSrc );
etcEl = importNode( doc, etcEl );
/* Check that the returned object has the right form. */
if ( etcEl instanceof Element &&
((Element) etcEl).getTagName() == "etc" ) {
ndxEl.appendChild( etcEl );
}
else {
logger.warning( "Badly-formed Etc component from impl "
+ impl + " - not added" );
ndxEl.appendChild( doc.createComment( "Broken ETC" ) );
}
}
catch ( TransformerException e ) {
logger.warning(
"Error transforming Etc component - not added" );
ndxEl.appendChild( doc.createComment( "Broken ETC" ) );
}
}
/* Return the new DOM as a source. */
return ( base != null ) ? new DOMSource( ndxEl, base.toExternalForm() )
: new DOMSource( ndxEl );
}
| public Source toXML( URL base ) {
/* Set up the document and root element. */
DocumentBuilderFactory dfact = DocumentBuilderFactory.newInstance();
DocumentBuilder dbuild;
try {
dbuild = dfact.newDocumentBuilder();
}
catch ( ParserConfigurationException e ) {
throw new RuntimeException( "Trouble building vanilla parser", e );
}
Document doc = dbuild.newDocument();
Element ndxEl = doc.createElement( "ndx" );
doc.appendChild( ndxEl );
/* Get the base URI in a form suitable for using with URI.relativize. */
URI baseUri;
if ( base != null ) {
try {
baseUri = new URI( base.toExternalForm() );
String scheme = baseUri.getScheme();
String auth = baseUri.getAuthority();
String path = baseUri.getPath();
if ( path == null ) {
path = "";
}
path = path.replaceFirst( "[^/]*$", "" );
baseUri = new URI( scheme, auth, path, "", "" );
}
catch ( URISyntaxException e ) {
baseUri = null;
}
}
else {
baseUri = null;
}
/* Write a title element. */
if ( hasTitle() ) {
Element titleEl = doc.createElement( "title" );
ndxEl.appendChild( titleEl );
Node titleNode = doc.createTextNode( getTitle() );
titleEl.appendChild( titleNode );
}
/* Write an image element. */
Element imEl = doc.createElement( "image" );
ndxEl.appendChild( imEl );
if ( getImage().getURL() != null ) {
URI iuri = urlToUri( getImage().getURL() );
if ( baseUri != null ) {
iuri = baseUri.relativize( iuri );
}
Node imUrl = doc.createTextNode( iuri.toString() );
imEl.appendChild( imUrl );
}
else {
Node imComm = doc.createComment( "Image array is virtual" );
imEl.appendChild( imComm );
}
/* Write a variance element. */
if ( hasVariance() ) {
Element varEl = doc.createElement( "variance" );
ndxEl.appendChild( varEl );
if ( getVariance().getURL() != null ) {
URI vuri = urlToUri( getVariance().getURL() );
if ( baseUri != null ) {
vuri = baseUri.relativize( vuri );
}
Node varUrl = doc.createTextNode( vuri.toString() );
varEl.appendChild( varUrl );
}
else {
Node varComm = doc.createComment( "Variance array is virtual" );
varEl.appendChild( varComm );
}
}
/* Write a quality element. */
if ( hasQuality() ) {
Element qualEl = doc.createElement( "quality" );
ndxEl.appendChild( qualEl );
if ( getQuality().getURL() != null ) {
URI quri = urlToUri( getQuality().getURL() );
if ( baseUri != null ) {
quri = baseUri.relativize( quri );
}
Node qualUrl = doc.createTextNode( quri.toString() );
qualEl.appendChild( qualUrl );
}
else {
Node qualComm = doc.createComment( "Quality array is virtual" );
qualEl.appendChild( qualComm );
}
}
/* Write a badbits element. */
if ( getBadBits() != 0 ) {
String bbrep = "0x" + Integer.toHexString( getBadBits() );
Node bbContent = doc.createTextNode( bbrep );
Element bbEl = doc.createElement( "badbits" );
bbEl.appendChild( bbContent );
ndxEl.appendChild( bbEl );
}
/* Write a WCS element. */
if ( hasWCS() ) {
FrameSet wfset = getAst();
Source wcsSource = new XAstWriter().makeSource( wfset, null );
try {
Node wcsContent = new SourceReader().getDOM( wcsSource );
wcsContent = importNode( doc, wcsContent );
Element wcsEl = doc.createElement( "wcs" );
wcsEl.setAttribute( "encoding", "AST-XML" );
wcsEl.appendChild( wcsContent );
ndxEl.appendChild( wcsEl );
}
catch ( TransformerException e ) {
logger.warning( "Trouble transforming WCS: " + e.getMessage() );
ndxEl.appendChild( doc.createComment( "Broken WCS" ) );
}
}
/* Write an Etc element. */
if ( hasEtc() ) {
try {
Source etcSrc = getEtc();
Node etcEl = new SourceReader().getDOM( etcSrc );
etcEl = importNode( doc, etcEl );
/* Check that the returned object has the right form. */
if ( etcEl instanceof Element &&
((Element) etcEl).getTagName() == "etc" ) {
ndxEl.appendChild( etcEl );
}
else {
logger.warning( "Badly-formed Etc component from impl "
+ impl + " - not added" );
ndxEl.appendChild( doc.createComment( "Broken ETC" ) );
}
}
catch ( TransformerException e ) {
logger.warning(
"Error transforming Etc component - not added" );
ndxEl.appendChild( doc.createComment( "Broken ETC" ) );
}
}
/* Return the new DOM as a source. */
return ( base != null ) ? new DOMSource( ndxEl, base.toExternalForm() )
: new DOMSource( ndxEl );
}
|
diff --git a/driver/GUI.java b/driver/GUI.java
index 9cb324d..8f5cdf1 100644
--- a/driver/GUI.java
+++ b/driver/GUI.java
@@ -1,2075 +1,2077 @@
/* $$$$$: Comments by Liang
*
* $$$$$$: Codes modified and/or added by Liang
*/
package driver;
import ga.GAChartOutput;
import ga.GATracker;
import ga.GeneticCode;
import ga.GeneticCodeException;
import ga.PhenotypeMaster;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.LookAndFeel;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumnModel;
import cobweb.TypeColorEnumeration;
/**
* Simulation configuration dialog
* @author time itself
*
*/
public class GUI extends JPanel implements ActionListener {
final String TickScheduler = "cobweb.TickScheduler";
JTextField Width;
JTextField Height;
JCheckBox keepOldAgents;
JCheckBox spawnNewAgents;
JCheckBox keepOldArray;
JCheckBox dropNewFood;
JCheckBox ColorCodedAgents;
JCheckBox newColorizer;
JCheckBox keepOldWaste;
JCheckBox keepOldPackets;
JCheckBox wrap;
JCheckBox flexibility;
JCheckBox PrisDilemma;
JCheckBox FoodWeb;
JTextField numColor;
JTextField colorSelectSize;
JTextField reColorTimeStep;
JTextField colorizerMode;
JTextField RandomSeed;
JTextField randomStones;
JTextField maxFoodChance;
JTextField memory_size;
// //////////////////////////////////////////////////////////////////////////////////////////////
public static final int GA_AGENT_1_ROW = 0;
public static final int GA_AGENT_2_ROW = 1;
public static final int GA_AGENT_3_ROW = 2;
public static final int GA_AGENT_4_ROW = 3;
public static final int GA_LINKED_PHENOTYPE_ROW = 4;
public static final int GA_GENE_1_COL = 1;
public static final int GA_GENE_2_COL = 2;
public static final int GA_GENE_3_COL = 3;
public static final int GA_NUM_AGENT_TYPES = 4;
public static final int GA_NUM_GENES = 3;
/** The list of mutable phenotypes shown on Genetic Algorithm tab. */
JList mutable_phenotypes;
/** The TextFields and Buttons of the Genetic Algorithm tab. */
JButton link_gene_1 = new JButton("Link to Gene 1");
JButton link_gene_2 = new JButton("Link to Gene 2");
JButton link_gene_3 = new JButton("Link to Gene 3");
public static String[] meiosis_mode_list = {"Colour Averaging",
"Random Recombination", "Gene Swapping"};
public static JComboBox meiosis_mode = new JComboBox(meiosis_mode_list);
/** Default genetic bits. All genes are 00011110. */
public static String[][] default_genetics = {
{ "Agent Type 1", "00011110", "00011110", "00011110" },
{ "Agent Type 2", "00011110", "00011110", "00011110" },
{ "Agent Type 3", "00011110", "00011110", "00011110" },
{ "Agent Type 4", "00011110", "00011110", "00011110" },
{ "Linked Phenotype", "None", "None", "None" } };
public static String[] genetic_table_col_names = { "", "Gene 1", "Gene 2",
"Gene 3" };
/** The TextFields that store the genetic bits of the agents. */
public static JTable genetic_table = new JTable(default_genetics,
genetic_table_col_names);
/** Controls whether or not the distribution of gene status of an agent type is tracked and outputted. */
public static JCheckBox track_gene_status_distribution;
/** Controls whether or not the distribution of gene value of an agent type is tracked and outputted. */
public static JCheckBox track_gene_value_distribution;
/** The number of chart updates per time step. */
public static JTextField chart_update_frequency;
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
if (e.getSource().equals(link_gene_1)) {
String linked_to_gene_1 = mutable_phenotypes.getSelectedValue()
.toString();
if (!linked_to_gene_1.equals("[No Phenotype]")) {
PhenotypeMaster.setLinkedAttributes(linked_to_gene_1,
PhenotypeMaster.RED_PHENOTYPE);
genetic_table.setValueAt(linked_to_gene_1,
GA_LINKED_PHENOTYPE_ROW, GA_GENE_1_COL);
} else if (!PhenotypeMaster.linked_phenotypes[PhenotypeMaster.RED_PHENOTYPE]
.equals("")) {
PhenotypeMaster
.removeLinkedAttributes(PhenotypeMaster.RED_PHENOTYPE);
genetic_table.setValueAt("None", GA_LINKED_PHENOTYPE_ROW,
GA_GENE_1_COL);
}
} else if (e.getSource().equals(link_gene_2)) {
String linked_to_gene_2 = mutable_phenotypes.getSelectedValue()
.toString();
if (!linked_to_gene_2.equals("[No Phenotype]")) {
PhenotypeMaster.setLinkedAttributes(linked_to_gene_2,
PhenotypeMaster.GREEN_PHENOTYPE);
genetic_table.setValueAt(linked_to_gene_2,
GA_LINKED_PHENOTYPE_ROW, GA_GENE_2_COL);
} else if (!PhenotypeMaster.linked_phenotypes[PhenotypeMaster.GREEN_PHENOTYPE]
.equals("")) {
PhenotypeMaster
.removeLinkedAttributes(PhenotypeMaster.GREEN_PHENOTYPE);
genetic_table.setValueAt("None", GA_LINKED_PHENOTYPE_ROW,
GA_GENE_2_COL);
}
} else if (e.getSource().equals(link_gene_3)) {
String linked_to_gene_3 = mutable_phenotypes.getSelectedValue()
.toString();
if (!linked_to_gene_3.equals("[No Phenotype]")) {
PhenotypeMaster.setLinkedAttributes(linked_to_gene_3,
PhenotypeMaster.BLUE_PHENOTYPE);
genetic_table.setValueAt(linked_to_gene_3,
GA_LINKED_PHENOTYPE_ROW, GA_GENE_3_COL);
} else if (!PhenotypeMaster.linked_phenotypes[PhenotypeMaster.BLUE_PHENOTYPE]
.equals("")) {
PhenotypeMaster
.removeLinkedAttributes(PhenotypeMaster.BLUE_PHENOTYPE);
genetic_table.setValueAt("None", GA_LINKED_PHENOTYPE_ROW,
GA_GENE_3_COL);
}
} else if (e.getSource().equals(meiosis_mode)) {
// Read which mode of meiosis is selected and
// add save it.
GeneticCode.meiosis_mode
= (String) ((JComboBox) e.getSource()).getSelectedItem();
} else if (e.getSource().equals(track_gene_status_distribution)) {
boolean state = GATracker.negateTrackGeneStatusDistribution();
track_gene_status_distribution.setSelected(state);
} else if (e.getSource().equals(track_gene_value_distribution)) {
boolean state = GATracker.negateTrackGeneValueDistribution();
track_gene_value_distribution.setSelected(state);
} else if (e.getSource().equals(chart_update_frequency)) {
try {
int freq = Integer.parseInt(chart_update_frequency.getText());
if (freq <= 0) {
chart_update_frequency.setText("Input must be > 0.");
} else {
GAChartOutput.update_frequency = freq;
}
} catch (NumberFormatException f) {
chart_update_frequency.setText("Input must be integer.");
}
}
} catch (GeneticCodeException f) {
// Handle Exception.
}
}
// //////////////////////////////////////////////////////////////////////////////////////////////
JTable resourceParamTable;
JTable agentParamTable;
JTable foodTable;
JTable tablePD;
JTabbedPane tabbedPane;
static JButton ok;
static JButton save;
public Object[][] inputArray;
public Object[][] foodData;
public Object[][] agentData;
public Object[][] foodwebData;
public Object[][] PDdata = { { null, null }, { null, null },
{ null, null }, { null, null } };
static JFrame frame;
Parser p;
private final CobwebApplication CA;
private static String datafile;
public static int numAgentTypes;
public static int numFoodTypes;
public GUI() {
super();
CA = null;
}
private static String[] agentParamNames = { "Initial Num. of Agents", "Mutation Rate",
"Initial Energy", "Favourite Food Energy", "Other Food Energy",
"Breed Energy", "Pregnancy Period - 1 parent",
"Step Energy Loss", "Step Rock Energy Loss",
"Turn Right Energy Loss", "Turn Left Energy Loss",
"Memory Bits", "Min. Communication Similarity",
"Step Agent Energy Loss", "Communication Bits",
"Pregnancy Period - 2 parents", "Min. Breed Similarity",
"2 parents Breed Chance", "1 parent Breed Chance",
"Aging Mode", "Aging Limit", "Aging Rate", "Waste Mode",
"Step Waste Energy Loss", "Energy gain Limit",
"Energy usage Limit", "Waste Half-life Rate",
"Initial Waste Quantity", "PD Tit for Tat",
"PD Cooperation Probability", "Broadcast Mode",
"Broadcast range energy-based", "Broadcast fixed range",
"Broadcast Minimum Energy", "Broadcast Energy Cost" };
private static String[] PDrownames = { "Temptation", "Reward", "Punishment",
"Sucker's Payoff" };
// GUI Special Constructor
public GUI(CobwebApplication ca, String filename) {
super();
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
CA = ca;
datafile = filename;
tabbedPane = new JTabbedPane();
/* Environment panel - composed of 4 panels */
JComponent envPanel = setupEnvPanel();
/*
* check filename, if file name exists and has a correct format set the
* values from the file filename
*/
controllerPanel = new AIPanel();
File f = new File(datafile);
if (f.exists()) {
try {
p = new Parser(datafile);
loadfromParser(p);
} catch (Throwable e) {
e.printStackTrace();
setDefault();
}
} else {
setDefault();
}
tabbedPane = new JTabbedPane();
tabbedPane.addTab("Environment", envPanel);
/* Resources panel */
JComponent resourcePanel = setupResourcePanel();
tabbedPane.addTab("Resources", resourcePanel);
/* Agents' panel */
JComponent agentPanel = setupAgentPanel();
tabbedPane.addTab("Agents", agentPanel);
JComponent foodPanel = setupFoodPanel();
tabbedPane.addTab("Food Web", foodPanel);
JComponent panelPD = setupPDpannel();
tabbedPane.addTab("PD Options", panelPD);
JComponent panelGA = setupGApannel();
tabbedPane.addTab("Genetic Algorithm", panelGA);
tabbedPane.addTab("AI", controllerPanel);
ok = new JButton("OK");
ok.setMaximumSize(new Dimension(80, 20));
ok.addActionListener(new OkButtonListener());
save = new JButton("Save As...");
save.setMaximumSize(new Dimension(80, 20));
save.addActionListener(new SaveAsButtonListener());
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout(FlowLayout.RIGHT));
buttons.add(save);
buttons.add(ok);
// Add the tabbed pane to this panel.
add(tabbedPane, BorderLayout.CENTER);
add(buttons, BorderLayout.SOUTH);
this.setPreferredSize(new Dimension(700, 570));
}
SettingsPanel controllerPanel;
private static final String[] AI_LIST = {
"cwcore.GeneticController",
"cwcore.LinearWeightsController"
};
private class AIPanel extends SettingsPanel {
/**
*
*/
private static final long serialVersionUID = 6045306756522429063L;
CardLayout cl = new CardLayout();
JPanel inner = new JPanel();
JComboBox aiSwitch;
public AIPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
inner.setLayout(cl);
SettingsPanel GenPanel = new SettingsPanel() {
/**
*
*/
private static final long serialVersionUID = 1139521733160862828L;
{
this.add(new JLabel("Nothing to configure"));
}
@Override
public void readFromParser(Parser p) {
}
@Override
public void writeXML(Writer out) throws IOException {
}
};
inner.add(GenPanel, AI_LIST[0]);
SettingsPanel LWpanel = new LinearAIGUI();
inner.add(LWpanel, AI_LIST[1]);
aiSwitch = new JComboBox(AI_LIST);
aiSwitch.setEditable(false);
aiSwitch.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
cl.show(inner, (String)e.getItem());
}
});
add(aiSwitch);
add(inner);
}
@Override
public void readFromParser(Parser p) {
aiSwitch.setSelectedItem(p.ControllerName);
((SettingsPanel)inner.getComponent(aiSwitch.getSelectedIndex())).readFromParser(p);
}
@Override
public void writeXML(Writer out) throws IOException {
out.write("\t<ControllerName>" + aiSwitch.getSelectedItem() + "</ControllerName>\n");
out.write("\t<ControllerConfig>");
SettingsPanel contConf = (SettingsPanel)inner.getComponent(aiSwitch.getSelectedIndex());
contConf.writeXML(out);
out.write("</ControllerConfig>\n");
}
}
private JComponent setupEnvPanel() {
JComponent envPanel = new JPanel(new GridLayout(3, 2));
/* Environment Settings */
JPanel panel11 = new JPanel();
makeGroupPanel(panel11, "Grid Settings");
JPanel fieldPane = new JPanel();
fieldPane.add(new JLabel("Width"));
fieldPane.add(Width = new JTextField(3));
fieldPane.add(new JLabel("Height"));
fieldPane.add(Height = new JTextField(3));
fieldPane.add(new JLabel("Wrap"));
fieldPane.add(wrap = new JCheckBox(""));
panel11.add(fieldPane);
makeOptionsTable(fieldPane, 3);
envPanel.add(panel11);
JPanel panel15 = new JPanel();
makeGroupPanel(panel15, "Prisoner's Dilemma Options");
PrisDilemma = new JCheckBox("");
memory_size = new JTextField(3);
flexibility = new JCheckBox("");
fieldPane = new JPanel(new GridLayout(3, 1));
fieldPane.add(new JLabel("Prisoner's Game"));
fieldPane.add(PrisDilemma);
fieldPane.add(new JLabel("Memory Size"));
fieldPane.add(memory_size);
fieldPane.add(new JLabel("Energy Based"));
fieldPane.add(flexibility);
makeOptionsTable(fieldPane, 3);
panel15.add(fieldPane);
envPanel.add(panel15, "WEST");
/* Colour Settings */
JPanel panel12 = new JPanel();
//panel12.setLayout(new BoxLayout(panel12, BoxLayout.Y_AXIS));
makeGroupPanel(panel12, "Environment Transition Settings");
fieldPane = new JPanel();
fieldPane.add(new JLabel("Keep Old Agents"));
fieldPane.add(keepOldAgents = new JCheckBox(""));
fieldPane.add(new JLabel("Spawn New Agents"));
fieldPane.add(spawnNewAgents = new JCheckBox(""));
fieldPane.add(new JLabel("Keep Old Array"));
fieldPane.add(keepOldArray = new JCheckBox(""));
fieldPane.add(new JLabel("New Colorizer"));
fieldPane.add(newColorizer = new JCheckBox("", true));
fieldPane.add(new JLabel("Keep Old Waste"));
fieldPane.add(keepOldWaste = new JCheckBox("", true));
fieldPane.add(new JLabel("Keep Old Packets"));
fieldPane.add(keepOldPackets = new JCheckBox("", true));
makeOptionsTable(fieldPane, 6);
ColorCodedAgents = new JCheckBox("");
panel12.add(fieldPane);
envPanel.add(panel12);
/* Options */
JPanel panel13 = new JPanel();
String title = "Colour Settings";
makeGroupPanel(panel13, title);
fieldPane = new JPanel(new GridLayout(5, 1));
numColor = new JTextField(3);
colorSelectSize = new JTextField(3);
reColorTimeStep = new JTextField(3);
colorizerMode = new JTextField(3);
fieldPane.add(new JLabel("No. of Colors"));
fieldPane.add(numColor);
fieldPane.add(new JLabel("Color Select Size"));
fieldPane.add(colorSelectSize);
fieldPane.add(new JLabel("Recolor Time Step"));
fieldPane.add(reColorTimeStep);
fieldPane.add(new JLabel("Colorizer Mode"));
fieldPane.add(colorizerMode);
fieldPane.add(new JLabel("Color Coded Agents"));
fieldPane.add(ColorCodedAgents);
panel13.add(fieldPane);
makeOptionsTable(fieldPane, 5);
envPanel.add(panel13);
/* Random variables */
JPanel panel14 = new JPanel();
makeGroupPanel(panel14, "Random Variables");
fieldPane = new JPanel(new GridLayout(2, 1));
RandomSeed = new JTextField(3);
randomStones = new JTextField(3);
fieldPane.add(new JLabel("Random Seed"));
fieldPane.add(RandomSeed);
fieldPane.add(new JLabel("Random Stones no."));
fieldPane.add(randomStones);
panel14.add(fieldPane, BorderLayout.EAST);
makeOptionsTable(fieldPane, 2);
envPanel.add(panel14);
JPanel panel16 = new JPanel();
makeGroupPanel(panel16, "General Food Variables");
dropNewFood = new JCheckBox("");
maxFoodChance = new JTextField(3);
fieldPane = new JPanel(new GridLayout(2, 1));
fieldPane.add(new JLabel("Drop New Food"));
fieldPane.add(dropNewFood);
//UNUSED: See ComplexEnvironment.growFood()
//fieldPane.add(new JLabel("Max Food Chance"));
//fieldPane.add(maxFoodChance);
panel16.add(fieldPane, BorderLayout.EAST);
makeOptionsTable(fieldPane, 1);
envPanel.add(panel16);
return envPanel;
}
private void makeOptionsTable(JPanel fieldPane, int items) {
fieldPane.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(fieldPane, items, 2, 0, 0, 8, 0);
}
private void makeGroupPanel(JComponent target, String title) {
target.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createLineBorder(Color.blue), title));
}
private static String[] resParamNames = { "Initial Food Amount", "Food Rate",
"Growth Rate", "Depletion Rate", "Depletion Steps",
"Draught period", "Food Mode" };
private JComponent setupResourcePanel() {
JComponent resourcePanel = new JPanel();
resourceParamTable = new JTable(new MyTableModel(resParamNames, foodData.length, foodData));
TableColumnModel colModel = resourceParamTable.getColumnModel();
// Get the column at index pColumn, and set its preferred width.
colModel.getColumn(0).setPreferredWidth(120);
System.out.println(colModel.getColumn(0).getHeaderValue());
colorHeaders(resourceParamTable, 1);
JScrollPane resourceScroll = new JScrollPane(resourceParamTable);
resourcePanel.setLayout(new BoxLayout(resourcePanel, BoxLayout.X_AXIS));
makeGroupPanel(resourcePanel, "Resource Parameters");
resourcePanel.add(resourceScroll);
return resourcePanel;
}
private JComponent setupAgentPanel() {
JComponent agentPanel = new JPanel();
agentPanel.setLayout(new BoxLayout(agentPanel, BoxLayout.X_AXIS));
makeGroupPanel(agentPanel, "Agent Parameters");
agentParamTable = new JTable(new MyTableModel(agentParamNames, agentData.length, agentData));
TableColumnModel agParamColModel = agentParamTable.getColumnModel();
// Get the column at index pColumn, and set its preferred width.
agParamColModel.getColumn(0).setPreferredWidth(200);
colorHeaders(agentParamTable, 1);
JScrollPane agentScroll = new JScrollPane(agentParamTable);
// Add the scroll pane to this panel.
agentPanel.add(agentScroll);
return agentPanel;
}
private JComponent setupFoodPanel() {
JComponent foodPanel = new JPanel();
// tabbedPane.addTab("Agents", panel3);
String[] foodNames = new String[numAgentTypes + numFoodTypes];
for (int i = 0; i < numAgentTypes; i++) {
foodNames[i] = "Agent " + i;
}
for (int i = 0; i < numFoodTypes; i++) {
foodNames[i + numAgentTypes] = "Food " + i;
}
foodTable = new JTable(new MyTableModel2(foodNames, foodwebData.length, foodwebData));
colorHeaders(foodTable, 1);
// Create the scroll pane and add the table to it.
JScrollPane foodScroll = new JScrollPane(foodTable);
foodPanel.setLayout(new BoxLayout(foodPanel, BoxLayout.X_AXIS));
makeGroupPanel(foodPanel, "Food Parameters");
foodPanel.add(foodScroll);
return foodPanel;
}
private void colorHeaders(JTable ft, int shift) {
TypeColorEnumeration tc = TypeColorEnumeration.getInstance();
for (int t = 0; t < numAgentTypes; t++) {
DefaultTableCellRenderer r = new DefaultTableCellRenderer();
r.setBackground(tc.getColor(t, 0));
ft.getColumnModel().getColumn(t + shift).setHeaderRenderer(r);
LookAndFeel.installBorder(ft.getTableHeader(), "TableHeader.cellBorder");
}
}
private JComponent setupPDpannel() {
JComponent panelPD = new JPanel();
tablePD = new JTable(new PDTable(PDrownames, PDdata));
//tablePD.setPreferredScrollableViewportSize(new Dimension(800, 300));
JScrollPane scrollPanePD = new JScrollPane(tablePD);
// Create the scroll pane and add the table to it.
//scrollPanePD.setPreferredSize(new Dimension(400, 150));
//tablePD.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//(tablePD.getColumnModel()).getColumn(0).setPreferredWidth(200);
panelPD.add(scrollPanePD, BorderLayout.CENTER);
panelPD.setLayout(new BoxLayout(panelPD, BoxLayout.X_AXIS));
makeGroupPanel(panelPD, "Prisoner's Dilemma Parameters");
return panelPD;
}
private JComponent setupGApannel() {
JComponent panelGA = new JPanel();
panelGA.setLayout(new BoxLayout(panelGA, BoxLayout.Y_AXIS));
DefaultListModel mutable_list_model = new DefaultListModel();
for (String element : PhenotypeMaster.mutable) {
mutable_list_model.addElement(element);
}
mutable_list_model.addElement("[No Phenotype]");
mutable_phenotypes = new JList(mutable_list_model);
mutable_phenotypes
.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
mutable_phenotypes.setLayoutOrientation(JList.VERTICAL_WRAP);
mutable_phenotypes.setVisibleRowCount(-1);
JScrollPane phenotypeScroller = new JScrollPane(mutable_phenotypes);
phenotypeScroller.setPreferredSize(new Dimension(150, 200));
// Set the default selected item as the previously selected item.
meiosis_mode.setSelectedIndex(GeneticCode.meiosis_mode_index);
JPanel gene_1 = new JPanel();
gene_1.add(link_gene_1);
JPanel gene_2 = new JPanel();
gene_2.add(link_gene_2);
JPanel gene_3 = new JPanel();
gene_3.add(link_gene_3);
JPanel gene_info_display = new JPanel(new BorderLayout());
gene_info_display.add(gene_1, BorderLayout.WEST);
gene_info_display.add(gene_2, BorderLayout.CENTER);
gene_info_display.add(gene_3, BorderLayout.EAST);
JPanel meiosis_mode_panel = new JPanel(new BorderLayout());
meiosis_mode_panel.add(new JLabel("Mode of Meiosis"), BorderLayout.NORTH);
meiosis_mode_panel.add(meiosis_mode, BorderLayout.CENTER);
// Checkboxes and TextAreas
track_gene_status_distribution = new JCheckBox("Track Gene Status Distribution", GATracker.getTrackGeneStatusDistribution());
track_gene_value_distribution = new JCheckBox("Track Gene Value Distribution", GATracker.getTrackGeneValueDistribution());
chart_update_frequency = new JTextField(GAChartOutput.update_frequency + "", 12);
JPanel chart_update_frequency_panel = new JPanel();
chart_update_frequency_panel.add(new JLabel("Time Steps per Chart Update"));
chart_update_frequency_panel.add(chart_update_frequency);
JPanel gene_check_boxes = new JPanel(new BorderLayout());
gene_check_boxes.add(track_gene_status_distribution, BorderLayout.NORTH);
gene_check_boxes.add(track_gene_value_distribution, BorderLayout.CENTER);
gene_check_boxes.add(chart_update_frequency_panel, BorderLayout.SOUTH);
// Combine Checkboxes and Dropdown menu
JPanel ga_combined_panel = new JPanel(new BorderLayout());
ga_combined_panel.add(meiosis_mode_panel, BorderLayout.EAST);
ga_combined_panel.add(gene_check_boxes, BorderLayout.WEST);
gene_info_display.add(ga_combined_panel, BorderLayout.SOUTH);
genetic_table.setPreferredScrollableViewportSize(new Dimension(150, 160));
genetic_table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
makeGroupPanel(phenotypeScroller, "Agent Parameter Selection");
panelGA.add(phenotypeScroller);
JScrollPane geneScroll = new JScrollPane(genetic_table);
makeGroupPanel(geneScroll, "Gene Bindings");
panelGA.add(geneScroll);
panelGA.add(gene_info_display);
/** Listeners of JButtons, JComboBoxes, and JCheckBoxes */
link_gene_1.addActionListener(this);
link_gene_2.addActionListener(this);
link_gene_3.addActionListener(this);
meiosis_mode.addActionListener(this);
track_gene_status_distribution.addActionListener(this);
track_gene_value_distribution.addActionListener(this);
chart_update_frequency.addActionListener(this);
makeGroupPanel(panelGA, "Genetic Algorithm Parameters");
return panelGA;
}
// $$$$$$ Check the validity of genetic_table input, used by "OK" and "Save" buttons. Feb 1
private boolean checkValidityOfGAInput() {
Pattern pattern = Pattern.compile("^[01]{8}$");
Matcher matcher;
boolean correct_input = true;
// $$$$$$ added on Jan 23 $$$$$ not perfect since the dialog won't popup until hit "OK"
updateTable(genetic_table);
for (int i = GA_AGENT_1_ROW; i < GA_AGENT_1_ROW + GA_NUM_AGENT_TYPES; i++) {
for (int j = GA_GENE_1_COL; j < GA_GENE_1_COL + GA_NUM_GENES; j++) {
matcher = pattern.matcher((String) genetic_table.getValueAt(i,j));
if (!matcher.find()) {
correct_input = false;
JOptionPane.showMessageDialog(GUI.this,
"GA: All genes must be binary and 8-bit long");
break;
}
}
if (!correct_input) {
break;
}
}
return correct_input;
}
/**************** Rendered defunct by Andy, because the pop up is annoying. */
// $$$$$$ To check whether RandomSeed == 0. If RandomSeed != 0, popup a message. Apr 18 [Feb 18] Refer class ComplexEnvironment line 365-6 for the reason
private int checkRandomSeedStatus() {
/*
if ( Integer.parseInt(RandomSeed.getText()) != 0) { // $$$$$$ change from "==". Apr 18
//JOptionPane.showMessageDialog(GUI.frame,
// "CAUTION: \"Random Seed\" is setting to zero.\n" +
// "\nFor retrievable experiments, please set \"Random Seed\" to non-zero.");
// $$$$$$ Change the above block as follows and return an integer. Feb 25
Object[] options = {"Yes, please",
"No, thanks"};
int n = JOptionPane.showOptionDialog(frame,
"Note: You can set \"Random Seed\" to zero for non-repeatable experiments.\n" +
"\nDo you want to be reminded next time?",
"Random Seed Setting",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
return n;
} else {
return 0;
}*/
return 0;
}
// $$$$$$ check if Width >= Height, for if Height > Width, an exception will occur and cobweb2 will malfunction. Feb 20
private boolean checkHeightLessThanWidth(){
if ( Integer.parseInt(Width.getText()) < Integer.parseInt(Height.getText()) ) {
JOptionPane.showMessageDialog(GUI.this,
"Please set Width >= Height for Grid Settings, or Cobweb2 would malfunction.",
"Warning", JOptionPane.WARNING_MESSAGE);
return false;
} else {
return true;
}
}
public void updateTable(JTable table) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
if (table.isEditing()) {
table.getCellEditor(row, col).stopCellEditing();
}
}
// $$$$$$ This openFileDialog method is invoked by pressing the "Save" button
public void openFileDialog() {
FileDialog theDialog = new FileDialog(frame,
"Choose a file to save state to", java.awt.FileDialog.SAVE);
theDialog.setVisible(true);
if (theDialog.getFile() != null) {
// $$$$$$ Check if the saving filename is one of the names reserved by CobwebApplication. Feb 8
// $$$$$$$$$$$$$$$$$$$$$$$$$$ Block silenced by Andy due to the annoyingness of this feature. May 7, 2008
//String savingFileName;
//savingFileName = theDialog.getFile();
// Block silenced, see above.
/*if ( (savingFileName.contains(CobwebApplication.INITIAL_OR_NEW_INPUT_FILE_NAME) != false)
|| (savingFileName.contains(CobwebApplication.CURRENT_DATA_FILE_NAME) != false) //$$$$$ added for "Modify Current Data"
|| (savingFileName.contains(CobwebApplication.DEFAULT_DATA_FILE_NAME) != false)) {
JOptionPane.showMessageDialog(GUI.this,
"Save State: The filename\"" + savingFileName + "\" is reserved by Cobweb Application.\n" +
" Please choose another file to save.",
"Warning", JOptionPane.WARNING_MESSAGE); // $$$$$$ modified on Feb 22
openFileDialog();
} else { */ // $$$$$ If filename not reserved. Feb 8
try {
// $$$$$$ The following block added to handle a readonly file. Feb 22
String savingFile = theDialog.getDirectory() + theDialog.getFile();
File sf = new File(savingFile);
if ( (sf.isHidden() != false) || ((sf.exists() != false) && (sf.canWrite() == false)) ) {
JOptionPane.showMessageDialog(GUI.frame, // $$$$$$ change from "this" to "GUI.frame". Feb 22
"Caution: File \"" + savingFile + "\" is NOT allowed to be written to.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else {
// $$$$$ The following block used to be the original code. Feb 22
write(theDialog.getDirectory() + theDialog.getFile());
p = new Parser(theDialog.getDirectory() + theDialog.getFile());
CA.openFile(p);
if (!datafile.equals(CA.getCurrentFile())) {CA.setCurrentFile(datafile);} // $$$$$$ added on Mar 14
frame.setVisible(false);
frame.dispose(); // $$$$$$ Feb 28
// $$$$$$ Added on Mar 14
if (CA.getUI() != null) {
if(CA.isInvokedByModify() == false) {
CA.getUI().reset(); // reset tick
//CA.refresh(CA.getUI());
//if (CA.tickField != null && !CA.tickField.getText().equals("")) {CA.tickField.setText("");} // $$$$$$ Mar 17
}
CA.getUI().refresh(1);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {
// $$$$$$ Reset the output window, specially for Linux. Mar 29
if (CA.textArea.getText().endsWith(CobwebApplication.GREETINGS) == false) {
CA.textArea.setText(CobwebApplication.GREETINGS);
}
}
}
}
} catch (java.io.IOException evt) {
JOptionPane.showMessageDialog(CA, // $$$$$$ added on Apr 22
"Save failed: " + evt.getMessage(),
"Warning", JOptionPane.WARNING_MESSAGE);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {CA.textArea.append("Save failed:" + evt.getMessage());} // $$$$$$ Added to be consistent with
// CobwebApplication's saveFile method. Feb 8
}
// }
}
}
public Parser getParser() {
return p;
}
private final class SaveAsButtonListener implements
java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent e) {
// $$$$$$ check validity of genetic table input. Feb 1
// Save the chart update frequency
try {
int freq = Integer.parseInt(chart_update_frequency.getText());
if (freq <= 0) { // Non-positive integers
GAChartOutput.update_frequency = 1;
} else { // Valid input
GAChartOutput.update_frequency = freq;
}
} catch (NumberFormatException f) { // Invalid input
GAChartOutput.update_frequency = 1;
}
boolean correct_GA_input;
correct_GA_input = checkValidityOfGAInput();
// $$$$$$ Implement "Save" only if GA input is correct
if ( (checkHeightLessThanWidth() != false) && (correct_GA_input != false) ) { // modified on Feb 21
//checkRandomSeedValidity(); // $$$$$$ added on Feb 22
// $$$$$$ Change the above code as follows on Feb 25
if (CA.randomSeedReminder == 0) {
CA.randomSeedReminder = checkRandomSeedStatus();
}
updateTable(resourceParamTable);
updateTable(agentParamTable);
updateTable(foodTable);
updateTable(tablePD); // $$$$$$ Jan 25
//updateTable(genetic_table); // $$$$$$ Jan 25 $$$$$$ genetic_table already updated by checkValidityOfGAInput(). Feb 22
openFileDialog();
}
}
}
private final class OkButtonListener implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// $$$$$$ check validity of genetic table input. Feb 1
boolean correct_GA_input;
correct_GA_input = checkValidityOfGAInput();
// Save the chart update frequency
try {
int freq = Integer.parseInt(chart_update_frequency.getText());
if (freq <= 0) { // Non-positive integers
GAChartOutput.update_frequency = 1;
} else { // Valid input
GAChartOutput.update_frequency = freq;
}
} catch (NumberFormatException e) { // Invalid input
GAChartOutput.update_frequency = 1;
}
if ( (checkHeightLessThanWidth() != false) && (correct_GA_input != false) ) {
//checkRandomSeedValidity(); // $$$$$$ added on Feb 18
// $$$$$$ Change the above code as follows on Feb 25
if (CA.randomSeedReminder == 0) {
CA.randomSeedReminder = checkRandomSeedStatus();
}
/*
* this fragment of code is necessary to update the last cell of
* the table before saving it
*/
updateTable(resourceParamTable);
updateTable(agentParamTable);
updateTable(foodTable);
updateTable(tablePD); // $$$$$$ Jan 25
/* write UI info to xml file */
try {
write(datafile); // $$$$$ write attributes showed in the "Test Data" window into the file "datafile". Jan 24
} catch (java.io.IOException e) {
throw new RuntimeException(e);
}
/* create a new parser for the xml file */
try {
p = new Parser(datafile);
} catch (FileNotFoundException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
CA.openFile(p);
if (!datafile.equals(CA.getCurrentFile())) {CA.setCurrentFile(datafile);} // $$$$$$ added on Mar 14
frame.setVisible(false);
frame.dispose(); // $$$$$$ added on Feb 28
// $$$$$$ Added on Mar 14
if (CA.getUI() != null) {
if(CA.isInvokedByModify() == false) {
CA.getUI().reset(); // reset tick
//CA.refresh(CA.getUI());
//if (CA.tickField != null && !CA.tickField.getText().equals("")) {CA.tickField.setText("");} // $$$$$$ Mar 17
}
CA.getUI().refresh(1);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {
// $$$$$$ Reset the output window, specially for Linux. Mar 29
if (CA.textArea.getText().endsWith(CobwebApplication.GREETINGS) == false) {
CA.textArea.setText(CobwebApplication.GREETINGS);
}
}
}
}
}
}
class PDTable extends AbstractTableModel {
private final Object[][] values;
private final String[] rownames;
public PDTable(String rownames[], Object data[][]) {
this.rownames = rownames;
values = data;
}
public int getRowCount() {
return values.length;
}
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int column) {
if (column == 0) {
return "";
}
return "value";
}
public String getRowName(int row) {
return rownames[row];
}
public Object getValueAt(int row, int column) {
if (column == 0) {
return rownames[row];
}
return values[row][0];
}
@Override
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col == 0) {
return false;
} else {
return true;
}
}
@Override
public void setValueAt(Object value, int row, int col) {
if ((isCellEditable(row, col))) {
try {
values[row][0] = new Integer((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane.showMessageDialog(GUI.this, "The \""
+ getRowName(row)
+ "\" row only accepts integer values.");
} else {
System.err
.println("User attempted to enter non-integer"
+ " value (" + value
+ ") into an integer-only column.");
}
}
}
}
// public Class getColumnClass(int c) { return values[0].getClass();}
public static final long serialVersionUID = 0x38FAF24EC6162F2CL;
}
/* table class */
class MyTableModel extends AbstractTableModel {
private final Object[][] data;
private final String[] rowNames;
private int numTypes = 0;
MyTableModel(String rownames[], int numcol, Object data[][]) {
this.data = data;
rowNames = rownames;
numTypes = numcol;
}
/* return the number of columns */
public int getColumnCount() {
return numTypes + 1;
}
/* return the number of rows */
public int getRowCount() {
return rowNames.length;
}
/* return column name given the number of the column */
@Override
public String getColumnName(int col) {
if (col == 0) {
return "";
} else {
return "Type" + (col);
}
}
/* return row name given the number of the row */
public String getRowName(int row) {
return rowNames[row];
}
public Object getValueAt(int row, int col) {
if (col == 0) {
return rowNames[row];
}
return data[col - 1][row];
}
/* add a column to this table */
public void addColumn() {
numTypes++;
for (int i = 0; i < getRowCount(); i++) {
data[numTypes][i] = "0";
}
}
/*
* Don't need to implement this method unless your table's editable.
*/
@Override
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col == 0) {
return false;
} else {
return true;
}
}
/*
* set the value at (row,col)
*/
@Override
public void setValueAt(Object value, int row, int col) {
if ((isCellEditable(row, col))) {
// check if this cell is supposed to contain and integer
if (data[col - 1][row] instanceof Integer) {
// If we don't do something like this, the column
// switches to contain Strings.
try {
data[col - 1][row] = new Integer((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane.showMessageDialog(GUI.this, "The \""
+ getRowName(row)
+ "\" row only accepts integer values.");
} else {
System.err
.println("User attempted to enter non-integer"
+ " value ("
+ value
+ ") into an integer-only column.");
}
}
// check if this cell is supposed to contain float or double
} else if ((data[col - 1][row] instanceof Double)
|| (data[col - 1][row] instanceof Float)) {
try {
data[col - 1][row] = new Float((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane
.showMessageDialog(
GUI.this,
"The \""
+ getRowName(row)
+ "\" row only accepts float or double values.");
} else {
System.err
.println("User attempted to enter non-float"
+ " value ("
+ value
+ ") into an float-only column.");
}
}
} else {
data[col - 1][row] = value;
}
printDebugData();
}
}
// print the data from the table each time it gets updated (used for
// testing)
private void printDebugData() {
/*
* int numRows = getRowCount(); int numCols = getColumnCount();
*
* for (int i=0; i < numRows; i++) { System.out.print(" row " + i +
* ":"); for (int j=0; j < numCols-1; j++) { System.out.print(" " +
* data[j][i]); } System.out.println(); }
* System.out.println("--------------------------");
*/
}
public static final long serialVersionUID = 0x38DC79AEAD8B2091L;
}
/* extends MyTableModel, implements the checkboxes in the food web class */
class MyTableModel2 extends MyTableModel {
@SuppressWarnings("unused")
private Object[][] data;
@SuppressWarnings("unused")
private String[] rowNames;
MyTableModel2(String rownames[], int numcol, Object data[][]) {
super(rownames, numcol, data);
}
@Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public static final long serialVersionUID = 0x6E1D565A6F6714AFL;
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
public static void createAndShowGUI(CobwebApplication ca, String filename) {
// Make sure we have nice window decorations.
//JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
frame = new JFrame("Test Data");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new GUI(ca, filename);
frame.add(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
frame.getRootPane().setDefaultButton(ok);
//frame.validate();
}
public void setDefault() {
+ numAgentTypes = 4;
+ numFoodTypes = 4;
Width.setText("20");
wrap.setSelected(false);
Height.setText(Width.getText()); // $$$$$$ change to make Width == Height. Feb 20
memory_size.setText("10");
flexibility.setSelected(false);
PrisDilemma.setSelected(false);
keepOldAgents.setSelected(false);
spawnNewAgents.setSelected(true);
keepOldArray.setSelected(false);
dropNewFood.setSelected(true);
ColorCodedAgents.setSelected(true);
newColorizer.setSelected(true);
keepOldWaste.setSelected(false); // $$$$$$ change from true to false for retrievable experiments. Feb 20
keepOldPackets.setSelected(true);
numColor.setText("3");
colorSelectSize.setText("3");
reColorTimeStep.setText("300");
colorizerMode.setText("0");
RandomSeed.setText("0");
randomStones.setText("10");
maxFoodChance.setText("0.8");
/* Resources */
Object[][] temp1 = {
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) } };
foodData = temp1;
/* AGENTS INFO */
Object[][] temp2 = { { new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) } /* Broadcast Energy Cost */
};
agentData = temp2;
/* FOOD WEB */
Object[][] temp3 = {
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) } };
foodwebData = temp3;
Object[][] tempPD = { { new Integer(8), null },
{ new Integer(6), null }, { new Integer(3), null },
{ new Integer(2), null } };
PDdata = tempPD;
}
private void loadfromParser(Parser p) {
numAgentTypes = ((Integer) (Array.get(p.getfromHashTable("AgentCount"),
0))).intValue();
numFoodTypes = ((Integer) (Array.get(p.getfromHashTable("FoodCount"),
0))).intValue();
foodData = new Object[numFoodTypes][resParamNames.length];
agentData = new Object[numAgentTypes][agentParamNames.length];
foodwebData = new Object[numFoodTypes][numAgentTypes + numFoodTypes];
// PDdata = new Object[4][2];
setTextField(Width, Array.get(p.getfromHashTable("width"), 0));
setTextField(Height, Array.get(p.getfromHashTable("height"), 0));
setCheckBoxState(wrap, Array.get(p.getfromHashTable("wrap"), 0));
setCheckBoxState(PrisDilemma, Array.get(p
.getfromHashTable("PrisDilemma"), 0));
setTextField(memory_size, Array
.get(p.getfromHashTable("memorysize"), 0));
setCheckBoxState(flexibility, Array.get(p.getfromHashTable("foodBias"),
0));
setCheckBoxState(keepOldAgents, Array.get(p
.getfromHashTable("keepoldagents"), 0));
setCheckBoxState(keepOldArray, Array.get(p
.getfromHashTable("keepoldarray"), 0));
setCheckBoxState(spawnNewAgents, Array.get(p
.getfromHashTable("spawnnewagents"), 0));
setCheckBoxState(dropNewFood, Array.get(p
.getfromHashTable("dropnewfood"), 0));
setCheckBoxState(ColorCodedAgents, Array.get(p
.getfromHashTable("colorcodedagents"), 0));
setCheckBoxState(keepOldWaste, Array.get(p
.getfromHashTable("keepoldwaste"), 0));
setCheckBoxState(keepOldPackets, Array.get(p
.getfromHashTable("keepoldpackets"), 0));
setCheckBoxState(newColorizer, Array.get(p
.getfromHashTable("newcolorizer"), 0));
setTextField(numColor, Array.get(p.getfromHashTable("numcolor"), 0));
setTextField(colorSelectSize, Array.get(p
.getfromHashTable("colorselectsize"), 0));
setTextField(reColorTimeStep, Array.get(p
.getfromHashTable("recolortimestep"), 0));
setTextField(colorizerMode, Array.get(p
.getfromHashTable("colorizermode"), 0));
setTextField(RandomSeed, Array.get(p.getfromHashTable("randomseed"), 0));
setTextField(randomStones, Array.get(
p.getfromHashTable("randomstones"), 0));
setTextField(maxFoodChance, Array.get(p
.getfromHashTable("maxfoodchance"), 0));
setTableData(foodData, Array.get(p.getfromHashTable("food"), 0), 1);
setTableData(foodData, Array.get(p.getfromHashTable("foodrate"), 0), 2);
setTableData(foodData, Array.get(p.getfromHashTable("foodgrow"), 0), 3);
setTableData(foodData, Array.get(p.getfromHashTable("fooddeplete"), 0), 4);
setTableData(foodData, Array
.get(p.getfromHashTable("depletetimesteps"), 0), 5);
setTableData(foodData, Array.get(p.getfromHashTable("DraughtPeriod"), 0),
6);
setTableData(foodData, Array.get(p.getfromHashTable("foodmode"), 0), 7);
setTableData(agentData, Array.get(p.getfromHashTable("agents"), 0), 1);
setTableData(agentData, Array.get(p.getfromHashTable("mutationrate"), 0), 2);
setTableData(agentData, Array.get(p.getfromHashTable("initenergy"), 0), 3);
setTableData(agentData, Array.get(p.getfromHashTable("foodenergy"), 0), 4);
setTableData(agentData,
Array.get(p.getfromHashTable("otherfoodenergy"), 0), 5);
setTableData(agentData, Array.get(p.getfromHashTable("breedenergy"), 0), 6);
setTableData(agentData,
Array.get(p.getfromHashTable("pregnancyperiod"), 0), 7);
setTableData(agentData, Array.get(p.getfromHashTable("stepenergy"), 0), 8);
setTableData(agentData, Array.get(p.getfromHashTable("steprockenergy"), 0),
9);
setTableData(agentData,
Array.get(p.getfromHashTable("turnrightenergy"), 0), 10);
setTableData(agentData, Array.get(p.getfromHashTable("turnleftenergy"), 0),
11);
setTableData(agentData, Array.get(p.getfromHashTable("memorybits"), 0), 12);
setTableData(agentData, Array.get(p.getfromHashTable("commsimmin"), 0), 13);
setTableData(agentData,
Array.get(p.getfromHashTable("stepagentenergy"), 0), 14);
setTableData(agentData, Array.get(p.getfromHashTable("communicationbits"),
0), 15);
setTableData(agentData, Array.get(p
.getfromHashTable("sexualpregnancyperiod"), 0), 16);
setTableData(agentData, Array.get(p.getfromHashTable("breedsimmin"), 0), 17);
setTableData(agentData, Array.get(p.getfromHashTable("sexualbreedchance"),
0), 18);
setTableData(agentData, Array.get(p.getfromHashTable("asexualbreedchance"),
0), 19);
setTableData(agentData, Array.get(p.getfromHashTable("agingMode"), 0), 20);
setTableData(agentData, Array.get(p.getfromHashTable("agingLimit"), 0), 21);
setTableData(agentData, Array.get(p.getfromHashTable("agingRate"), 0), 22);
setTableData(agentData, Array.get(p.getfromHashTable("wasteMode"), 0), 23);
setTableData(agentData, Array.get(p.getfromHashTable("wastePen"), 0), 24);
setTableData(agentData, Array.get(p.getfromHashTable("wasteGain"), 0), 25);
setTableData(agentData, Array.get(p.getfromHashTable("wasteLoss"), 0), 26);
setTableData(agentData, Array.get(p.getfromHashTable("wasteRate"), 0), 27);
setTableData(agentData, Array.get(p.getfromHashTable("wasteInit"), 0), 28);
setTableData(agentData, Array.get(p.getfromHashTable("pdTitForTat"), 0), 29);
setTableData(agentData, Array.get(p.getfromHashTable("pdCoopProb"), 0), 30);
setTableData(agentData, Array.get(p.getfromHashTable("broadcastMode"), 0),
31);
setTableData(agentData, Array.get(p
.getfromHashTable("broadcastEnergyBased"), 0), 32);
setTableData(agentData, Array.get(
p.getfromHashTable("broadcastFixedRange"), 0), 33);
setTableData(agentData, Array.get(p.getfromHashTable("broadcastEnergyMin"),
0), 34);
setTableData(agentData, Array.get(
p.getfromHashTable("broadcastEnergyCost"), 0), 35);
setTableHelper(foodwebData);
for (int i = 0; i < foodwebData.length; i++) {
int j;
for (j = 0; j < foodwebData.length; j++) {
setTableData_agents2eat(foodwebData, Array.get(p
.getfromHashTable("agents2eat"), i), j, i);
}
for (int k = 0; k < foodwebData.length; k++) {
// setTableData2(data3,
// Array.get(p.getfromHashTable("plants2eat"), i),k+j, i);
setTableData_plants2eat(foodwebData, Array.get(p
.getfromHashTable("plants2eat"), i), k, i);
}
}
// TODO take off second dimension from array if not used
PDdata[0][0] = Array.get(p.getfromHashTable("temptation"), 0);
PDdata[1][0] = Array.get(p.getfromHashTable("reward"), 0);
PDdata[2][0] = Array.get(p.getfromHashTable("punishment"), 0);
PDdata[3][0] = Array.get(p.getfromHashTable("sucker"), 0);
controllerPanel.readFromParser(p);
}
private void setTextField(JTextField fieldName, Object value) {
fieldName.setText(value.toString());
}
private void setCheckBoxState(JCheckBox boxName, Object state) {
boxName.setSelected(((Boolean) state).booleanValue());
}
private void setTableData(Object data[][], Object rowdata, int row) {
for (int i = 0; i < data.length; i++) {
data[i][row - 1] = Array.get(rowdata, i);
}
}
/*
* Helper method: load a list of "agents to eat" from the hashtable into
* current data array
*/
private void setTableData_agents2eat(Object data[][], Object coldata,
int j, int i) {
int k = ((Integer) Array.get(coldata, j)).intValue();
if (k > -1) {
data[i][k] = new Boolean(true);
}
}
/*
* Helper method: load a list of "plants to eat" from the hashtable into
* current data array
*/
private void setTableData_plants2eat(Object data[][], Object coldata,
int j, int i) {
int k = ((Integer) Array.get(coldata, j)).intValue();
if (k > -1) {
data[i][k + foodwebData.length] = new Boolean(true);
}
}
private void setTableHelper(Object data[][]) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
data[i][j] = new Boolean(false);
}
}
}
/**
* Writes the information stored in this tree to an XML file, conforming to
* the rules of our spec.
*
* @param fileName
* the name of the file to which to save the file
* @return true if the file was saved successfully, false otherwise
*/
public boolean write(String fileName) throws IOException {
try {
// open the file
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
if (out != null) {
// write the initial project info
out.write("<?xml version='1.0' encoding='utf-8'?>");
out.write("\n\n");
out.write("<inputData>" + "\n");
out.write("\t" + "<scheduler>" + TickScheduler + "</scheduler>"
+ "\n");
controllerPanel.writeXML(out);
// out.write("\t" + "<ComplexEnvironment>" + new
// Integer(ComplexEnvironment.getText()) +
// "</ComplexEnvironment>" + "\n");
out.write("\t" + "<Width>" + Width.getText() + "</Width>"
+ "\n");
out.write("\t" + "<Height>" + Height.getText() + "</Height>"
+ "\n");
out.write("\t" + "<wrap>" + new Boolean(wrap.isSelected())
+ "</wrap>" + "\n");
out.write("\t" + "<PrisDilemma>"
+ new Boolean(PrisDilemma.isSelected())
+ "</PrisDilemma>" + "\n");
out.write("\t" + "<randomStones>"
+ new Integer(randomStones.getText())
+ "</randomStones>" + "\n");
out.write("\t" + "<maxFoodChance>"
+ new Float(maxFoodChance.getText())
+ "</maxFoodChance>" + "\n");
out.write("\t" + "<keepOldAgents>"
+ new Boolean(keepOldAgents.isSelected())
+ "</keepOldAgents>" + "\n");
out.write("\t" + "<spawnNewAgents>"
+ new Boolean(spawnNewAgents.isSelected())
+ "</spawnNewAgents>" + "\n");
out.write("\t" + "<keepOldArray>"
+ new Boolean(keepOldArray.isSelected())
+ "</keepOldArray>" + "\n");
out.write("\t" + "<dropNewFood>"
+ new Boolean(dropNewFood.isSelected())
+ "</dropNewFood>" + "\n");
out.write("\t" + "<randomSeed>"
+ new Integer(RandomSeed.getText()) + "</randomSeed>"
+ "\n");
out.write("\t" + "<newColorizer>"
+ new Boolean(newColorizer.isSelected())
+ "</newColorizer>" + "\n");
out.write("\t" + "<keepOldWaste>"
+ new Boolean(keepOldWaste.isSelected())
+ "</keepOldWaste>" + "\n");
out.write("\t" + "<keepOldPackets>"
+ new Boolean(keepOldPackets.isSelected())
+ "</keepOldPackets>" + "\n");
out.write("\t" + "<numColor>" + new Integer(numColor.getText())
+ "</numColor>" + "\n");
out.write("\t" + "<colorSelectSize>"
+ new Integer(colorSelectSize.getText())
+ "</colorSelectSize>" + "\n");
out.write("\t" + "<reColorTimeStep>"
+ new Integer(reColorTimeStep.getText())
+ "</reColorTimeStep>" + "\n");
out.write("\t" + "<colorizerMode>"
+ new Integer(colorizerMode.getText())
+ "</colorizerMode>" + "\n");
out.write("\t" + "<ColorCodedAgents>"
+ new Boolean(ColorCodedAgents.isSelected())
+ "</ColorCodedAgents>" + "\n");
out.write("\t" + "<memorySize>"
+ new Integer(memory_size.getText()) + "</memorySize>"
+ "\n");
out.write("\t" + "<food_bias>"
+ new Boolean(flexibility.isSelected()) + "</food_bias>"
+ "\n");
writeHelperFood(out, resourceParamTable.getColumnCount());
writeHelperAgents(out, agentParamTable.getColumnCount());
writeHelperPDOptions(out);
writeHelperGA(out);
out.write("</inputData>");
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
/**
* internal recursive helper
*/
private boolean writeHelperFood(BufferedWriter out, int foodtypes)
throws IOException {
for (int type = 1; type < foodtypes; type++) {
try {
// write the node info for the current node
out.write("<food>" + "\n");
out.write("\t" + "<Index>" + (type - 1) + "</Index>" + "\n");
out.write("\t" + "<Food>" + resourceParamTable.getValueAt(0, type)
+ "</Food>" + "\n");
out.write("\t" + "<FoodRate>" + resourceParamTable.getValueAt(1, type)
+ "</FoodRate>" + "\n");
out.write("\t" + "<FoodGrow>" + resourceParamTable.getValueAt(2, type)
+ "</FoodGrow>" + "\n");
out.write("\t" + "<FoodDeplete>" + resourceParamTable.getValueAt(3, type)
+ "</FoodDeplete>" + "\n");
out.write("\t" + "<DepleteTimeSteps>"
+ resourceParamTable.getValueAt(4, type) + "</DepleteTimeSteps>"
+ "\n");
out.write("\t" + "<DraughtPeriod>" + resourceParamTable.getValueAt(5, type)
+ "</DraughtPeriod>" + "\n");
out.write("\t" + "<FoodMode>" + resourceParamTable.getValueAt(6, type)
+ "</FoodMode>" + "\n");
out.write("</food>" + "\n");
} catch (IOException e) {
return false;
}
}
return true;
}
/* helper method for agents' parameters */
private boolean writeHelperAgents(BufferedWriter out, int agentypes) {
for (int type = 1; type < agentypes; type++) {
try {
// write the node info for the current node
out.write("<agent>" + "\n");
out.write("\t" + "<Index>" + (type - 1) + "</Index>" + "\n");
out.write("\t" + "<Agents>" + agentParamTable.getValueAt(0, type)
+ "</Agents>" + "\n");
out.write("\t" + "<MutationRate>" + agentParamTable.getValueAt(1, type)
+ "</MutationRate>" + "\n");
out.write("\t" + "<InitEnergy>" + agentParamTable.getValueAt(2, type)
+ "</InitEnergy>" + "\n");
out.write("\t" + "<FoodEnergy>" + agentParamTable.getValueAt(3, type)
+ "</FoodEnergy>" + "\n");
out.write("\t" + "<OtherFoodEnergy>"
+ agentParamTable.getValueAt(4, type) + "</OtherFoodEnergy>"
+ "\n");
out.write("\t" + "<BreedEnergy>" + agentParamTable.getValueAt(5, type)
+ "</BreedEnergy>" + "\n");
out.write("\t" + "<pregnancyPeriod>"
+ agentParamTable.getValueAt(6, type) + "</pregnancyPeriod>"
+ "\n");
out.write("\t" + "<StepEnergy>" + agentParamTable.getValueAt(7, type)
+ "</StepEnergy>" + "\n");
out.write("\t" + "<StepRockEnergy>"
+ agentParamTable.getValueAt(8, type) + "</StepRockEnergy>"
+ "\n");
out.write("\t" + "<TurnRightEnergy>"
+ agentParamTable.getValueAt(9, type) + "</TurnRightEnergy>"
+ "\n");
out.write("\t" + "<TurnLeftEnergy>"
+ agentParamTable.getValueAt(10, type) + "</TurnLeftEnergy>"
+ "\n");
out.write("\t" + "<MemoryBits>" + agentParamTable.getValueAt(11, type)
+ "</MemoryBits>" + "\n");
out.write("\t" + "<commSimMin>" + agentParamTable.getValueAt(12, type)
+ "</commSimMin>" + "\n");
out.write("\t" + "<StepAgentEnergy>"
+ agentParamTable.getValueAt(13, type) + "</StepAgentEnergy>"
+ "\n");
out.write("\t" + "<communicationBits>"
+ agentParamTable.getValueAt(14, type) + "</communicationBits>"
+ "\n");
out.write("\t" + "<sexualPregnancyPeriod>"
+ agentParamTable.getValueAt(15, type)
+ "</sexualPregnancyPeriod>" + "\n");
out.write("\t" + "<breedSimMin>" + agentParamTable.getValueAt(16, type)
+ "</breedSimMin>" + "\n");
out.write("\t" + "<sexualBreedChance>"
+ agentParamTable.getValueAt(17, type) + "</sexualBreedChance>"
+ "\n");
out.write("\t" + "<asexualBreedChance>"
+ agentParamTable.getValueAt(18, type) + "</asexualBreedChance>"
+ "\n");
out.write("\t" + "<agingMode>" + agentParamTable.getValueAt(19, type)
+ "</agingMode>" + "\n");
out.write("\t" + "<agingLimit>" + agentParamTable.getValueAt(20, type)
+ "</agingLimit>" + "\n");
out.write("\t" + "<agingRate>" + agentParamTable.getValueAt(21, type)
+ "</agingRate>" + "\n");
out.write("\t" + "<wasteMode>" + agentParamTable.getValueAt(22, type)
+ "</wasteMode>" + "\n");
out.write("\t" + "<wastePen>" + agentParamTable.getValueAt(23, type)
+ "</wastePen>" + "\n");
out.write("\t" + "<wasteGain>" + agentParamTable.getValueAt(24, type)
+ "</wasteGain>" + "\n");
out.write("\t" + "<wasteLoss>" + agentParamTable.getValueAt(25, type)
+ "</wasteLoss>" + "\n");
out.write("\t" + "<wasteRate>" + agentParamTable.getValueAt(26, type)
+ "</wasteRate>" + "\n");
out.write("\t" + "<wasteInit>" + agentParamTable.getValueAt(27, type)
+ "</wasteInit>" + "\n");
out.write("\t" + "<pdTitForTat>" + agentParamTable.getValueAt(28, type)
+ "</pdTitForTat>" + "\n");
out.write("\t" + "<pdCoopProb>" + agentParamTable.getValueAt(29, type)
+ "</pdCoopProb>" + "\n");
out.write("\t" + "<broadcastMode>"
+ agentParamTable.getValueAt(30, type) + "</broadcastMode>"
+ "\n");
out.write("\t" + "<broadcastEnergyBased>"
+ agentParamTable.getValueAt(31, type)
+ "</broadcastEnergyBased>" + "\n");
out.write("\t" + "<broadcastFixedRange>"
+ agentParamTable.getValueAt(32, type)
+ "</broadcastFixedRange>" + "\n");
out.write("\t" + "<broadcastEnergyMin>"
+ agentParamTable.getValueAt(33, type) + "</broadcastEnergyMin>"
+ "\n");
out.write("\t" + "<broadcastEnergyCost>"
+ agentParamTable.getValueAt(34, type)
+ "</broadcastEnergyCost>" + "\n");
writeHelperFoodWeb(out, type, resourceParamTable.getColumnCount(), agentParamTable
.getColumnCount());
out.write("</agent>" + "\n");
} catch (IOException e) {
return false;
}
}
return true;
}
private boolean writeHelperFoodWeb(BufferedWriter out, int type,
int num_foodtypes, int num_agentypes) throws IOException {
try {
// write the node info for the current node
out.write("<foodweb>" + "\n");
for (int i = 1; i < num_agentypes; i++) {
out.write("\t" + "<agent" + i + ">"
+ foodTable.getValueAt(i - 1, type) + "</agent" + i + ">"
+ "\n");
}
for (int i = 1; i < num_foodtypes; i++) {
out.write("\t" + "<food" + i + ">"
+ foodTable.getValueAt((num_agentypes + i) - 2, type)
+ "</food" + i + ">" + "\n");
}
out.write("</foodweb>" + "\n");
} catch (IOException e) {
return false;
}
return true;
}
private boolean writeHelperPDOptions(BufferedWriter out) throws IOException {
try {
out.write("<pd>");
out.write("<temptation>");
out.write("" + tablePD.getValueAt(0, 1));
out.write("</temptation>\n");
out.write("<reward>");
out.write("" + tablePD.getValueAt(1, 1));
out.write("</reward>\n");
out.write("<punishment>");
out.write("" + tablePD.getValueAt(2, 1));
out.write("</punishment>");
out.write("<sucker>");
out.write("" + tablePD.getValueAt(3, 1));
out.write("</sucker>\n");
out.write("</pd>\n");
} catch (IOException e) {
return false;
}
return true;
}
/** The GA portion of the write() method that writes parameters to xml file. */
private boolean writeHelperGA(BufferedWriter out) throws IOException {
try {
out.write("<ga>");
out.write("<agent1gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_1_COL));
out.write("</agent1gene1>\n");
out.write("<agent1gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_2_COL));
out.write("</agent1gene2>\n");
out.write("<agent1gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_3_COL));
out.write("</agent1gene3>\n");
out.write("<agent2gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_1_COL));
out.write("</agent2gene1>\n");
out.write("<agent2gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_2_COL));
out.write("</agent2gene2>\n");
out.write("<agent2gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_3_COL));
out.write("</agent2gene3>\n");
out.write("<agent3gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_1_COL));
out.write("</agent3gene1>\n");
out.write("<agent3gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_2_COL));
out.write("</agent3gene2>\n");
out.write("<agent3gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_3_COL));
out.write("</agent3gene3>\n");
out.write("<agent4gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_1_COL));
out.write("</agent4gene1>\n");
out.write("<agent4gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_2_COL));
out.write("</agent4gene2>\n");
out.write("<agent4gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_3_COL));
out.write("</agent4gene3>\n");
out.write("<linkedphenotype1>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_1_COL));
out.write("</linkedphenotype1>\n");
out.write("<linkedphenotype2>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_2_COL));
out.write("</linkedphenotype2>\n");
out.write("<linkedphenotype3>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_3_COL));
out.write("</linkedphenotype3>\n");
out.write("<meiosismode>");
out.write(""+ GeneticCode.meiosis_mode);
out.write("</meiosismode>\n");
out.write("<trackgenestatusdistribution>");
out.write("" + GATracker.getTrackGeneStatusDistribution());
out.write("</trackgenestatusdistribution>\n");
out.write("<trackgenevaluedistribution>");
out.write("" + GATracker.getTrackGeneValueDistribution());
out.write("</trackgenevaluedistribution>\n");
out.write("<chartupdatefrequency>");
out.write("" + GAChartOutput.update_frequency);
out.write("</chartupdatefrequency>");
out.write("</ga>\n");
} catch (IOException e) {
return false;
}
return true;
}
public static final long serialVersionUID = 0xB9967684A8375BC0L;
}
| true | true | public void openFileDialog() {
FileDialog theDialog = new FileDialog(frame,
"Choose a file to save state to", java.awt.FileDialog.SAVE);
theDialog.setVisible(true);
if (theDialog.getFile() != null) {
// $$$$$$ Check if the saving filename is one of the names reserved by CobwebApplication. Feb 8
// $$$$$$$$$$$$$$$$$$$$$$$$$$ Block silenced by Andy due to the annoyingness of this feature. May 7, 2008
//String savingFileName;
//savingFileName = theDialog.getFile();
// Block silenced, see above.
/*if ( (savingFileName.contains(CobwebApplication.INITIAL_OR_NEW_INPUT_FILE_NAME) != false)
|| (savingFileName.contains(CobwebApplication.CURRENT_DATA_FILE_NAME) != false) //$$$$$ added for "Modify Current Data"
|| (savingFileName.contains(CobwebApplication.DEFAULT_DATA_FILE_NAME) != false)) {
JOptionPane.showMessageDialog(GUI.this,
"Save State: The filename\"" + savingFileName + "\" is reserved by Cobweb Application.\n" +
" Please choose another file to save.",
"Warning", JOptionPane.WARNING_MESSAGE); // $$$$$$ modified on Feb 22
openFileDialog();
} else { */ // $$$$$ If filename not reserved. Feb 8
try {
// $$$$$$ The following block added to handle a readonly file. Feb 22
String savingFile = theDialog.getDirectory() + theDialog.getFile();
File sf = new File(savingFile);
if ( (sf.isHidden() != false) || ((sf.exists() != false) && (sf.canWrite() == false)) ) {
JOptionPane.showMessageDialog(GUI.frame, // $$$$$$ change from "this" to "GUI.frame". Feb 22
"Caution: File \"" + savingFile + "\" is NOT allowed to be written to.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else {
// $$$$$ The following block used to be the original code. Feb 22
write(theDialog.getDirectory() + theDialog.getFile());
p = new Parser(theDialog.getDirectory() + theDialog.getFile());
CA.openFile(p);
if (!datafile.equals(CA.getCurrentFile())) {CA.setCurrentFile(datafile);} // $$$$$$ added on Mar 14
frame.setVisible(false);
frame.dispose(); // $$$$$$ Feb 28
// $$$$$$ Added on Mar 14
if (CA.getUI() != null) {
if(CA.isInvokedByModify() == false) {
CA.getUI().reset(); // reset tick
//CA.refresh(CA.getUI());
//if (CA.tickField != null && !CA.tickField.getText().equals("")) {CA.tickField.setText("");} // $$$$$$ Mar 17
}
CA.getUI().refresh(1);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {
// $$$$$$ Reset the output window, specially for Linux. Mar 29
if (CA.textArea.getText().endsWith(CobwebApplication.GREETINGS) == false) {
CA.textArea.setText(CobwebApplication.GREETINGS);
}
}
}
}
} catch (java.io.IOException evt) {
JOptionPane.showMessageDialog(CA, // $$$$$$ added on Apr 22
"Save failed: " + evt.getMessage(),
"Warning", JOptionPane.WARNING_MESSAGE);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {CA.textArea.append("Save failed:" + evt.getMessage());} // $$$$$$ Added to be consistent with
// CobwebApplication's saveFile method. Feb 8
}
// }
}
}
public Parser getParser() {
return p;
}
private final class SaveAsButtonListener implements
java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent e) {
// $$$$$$ check validity of genetic table input. Feb 1
// Save the chart update frequency
try {
int freq = Integer.parseInt(chart_update_frequency.getText());
if (freq <= 0) { // Non-positive integers
GAChartOutput.update_frequency = 1;
} else { // Valid input
GAChartOutput.update_frequency = freq;
}
} catch (NumberFormatException f) { // Invalid input
GAChartOutput.update_frequency = 1;
}
boolean correct_GA_input;
correct_GA_input = checkValidityOfGAInput();
// $$$$$$ Implement "Save" only if GA input is correct
if ( (checkHeightLessThanWidth() != false) && (correct_GA_input != false) ) { // modified on Feb 21
//checkRandomSeedValidity(); // $$$$$$ added on Feb 22
// $$$$$$ Change the above code as follows on Feb 25
if (CA.randomSeedReminder == 0) {
CA.randomSeedReminder = checkRandomSeedStatus();
}
updateTable(resourceParamTable);
updateTable(agentParamTable);
updateTable(foodTable);
updateTable(tablePD); // $$$$$$ Jan 25
//updateTable(genetic_table); // $$$$$$ Jan 25 $$$$$$ genetic_table already updated by checkValidityOfGAInput(). Feb 22
openFileDialog();
}
}
}
private final class OkButtonListener implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// $$$$$$ check validity of genetic table input. Feb 1
boolean correct_GA_input;
correct_GA_input = checkValidityOfGAInput();
// Save the chart update frequency
try {
int freq = Integer.parseInt(chart_update_frequency.getText());
if (freq <= 0) { // Non-positive integers
GAChartOutput.update_frequency = 1;
} else { // Valid input
GAChartOutput.update_frequency = freq;
}
} catch (NumberFormatException e) { // Invalid input
GAChartOutput.update_frequency = 1;
}
if ( (checkHeightLessThanWidth() != false) && (correct_GA_input != false) ) {
//checkRandomSeedValidity(); // $$$$$$ added on Feb 18
// $$$$$$ Change the above code as follows on Feb 25
if (CA.randomSeedReminder == 0) {
CA.randomSeedReminder = checkRandomSeedStatus();
}
/*
* this fragment of code is necessary to update the last cell of
* the table before saving it
*/
updateTable(resourceParamTable);
updateTable(agentParamTable);
updateTable(foodTable);
updateTable(tablePD); // $$$$$$ Jan 25
/* write UI info to xml file */
try {
write(datafile); // $$$$$ write attributes showed in the "Test Data" window into the file "datafile". Jan 24
} catch (java.io.IOException e) {
throw new RuntimeException(e);
}
/* create a new parser for the xml file */
try {
p = new Parser(datafile);
} catch (FileNotFoundException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
CA.openFile(p);
if (!datafile.equals(CA.getCurrentFile())) {CA.setCurrentFile(datafile);} // $$$$$$ added on Mar 14
frame.setVisible(false);
frame.dispose(); // $$$$$$ added on Feb 28
// $$$$$$ Added on Mar 14
if (CA.getUI() != null) {
if(CA.isInvokedByModify() == false) {
CA.getUI().reset(); // reset tick
//CA.refresh(CA.getUI());
//if (CA.tickField != null && !CA.tickField.getText().equals("")) {CA.tickField.setText("");} // $$$$$$ Mar 17
}
CA.getUI().refresh(1);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {
// $$$$$$ Reset the output window, specially for Linux. Mar 29
if (CA.textArea.getText().endsWith(CobwebApplication.GREETINGS) == false) {
CA.textArea.setText(CobwebApplication.GREETINGS);
}
}
}
}
}
}
class PDTable extends AbstractTableModel {
private final Object[][] values;
private final String[] rownames;
public PDTable(String rownames[], Object data[][]) {
this.rownames = rownames;
values = data;
}
public int getRowCount() {
return values.length;
}
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int column) {
if (column == 0) {
return "";
}
return "value";
}
public String getRowName(int row) {
return rownames[row];
}
public Object getValueAt(int row, int column) {
if (column == 0) {
return rownames[row];
}
return values[row][0];
}
@Override
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col == 0) {
return false;
} else {
return true;
}
}
@Override
public void setValueAt(Object value, int row, int col) {
if ((isCellEditable(row, col))) {
try {
values[row][0] = new Integer((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane.showMessageDialog(GUI.this, "The \""
+ getRowName(row)
+ "\" row only accepts integer values.");
} else {
System.err
.println("User attempted to enter non-integer"
+ " value (" + value
+ ") into an integer-only column.");
}
}
}
}
// public Class getColumnClass(int c) { return values[0].getClass();}
public static final long serialVersionUID = 0x38FAF24EC6162F2CL;
}
/* table class */
class MyTableModel extends AbstractTableModel {
private final Object[][] data;
private final String[] rowNames;
private int numTypes = 0;
MyTableModel(String rownames[], int numcol, Object data[][]) {
this.data = data;
rowNames = rownames;
numTypes = numcol;
}
/* return the number of columns */
public int getColumnCount() {
return numTypes + 1;
}
/* return the number of rows */
public int getRowCount() {
return rowNames.length;
}
/* return column name given the number of the column */
@Override
public String getColumnName(int col) {
if (col == 0) {
return "";
} else {
return "Type" + (col);
}
}
/* return row name given the number of the row */
public String getRowName(int row) {
return rowNames[row];
}
public Object getValueAt(int row, int col) {
if (col == 0) {
return rowNames[row];
}
return data[col - 1][row];
}
/* add a column to this table */
public void addColumn() {
numTypes++;
for (int i = 0; i < getRowCount(); i++) {
data[numTypes][i] = "0";
}
}
/*
* Don't need to implement this method unless your table's editable.
*/
@Override
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col == 0) {
return false;
} else {
return true;
}
}
/*
* set the value at (row,col)
*/
@Override
public void setValueAt(Object value, int row, int col) {
if ((isCellEditable(row, col))) {
// check if this cell is supposed to contain and integer
if (data[col - 1][row] instanceof Integer) {
// If we don't do something like this, the column
// switches to contain Strings.
try {
data[col - 1][row] = new Integer((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane.showMessageDialog(GUI.this, "The \""
+ getRowName(row)
+ "\" row only accepts integer values.");
} else {
System.err
.println("User attempted to enter non-integer"
+ " value ("
+ value
+ ") into an integer-only column.");
}
}
// check if this cell is supposed to contain float or double
} else if ((data[col - 1][row] instanceof Double)
|| (data[col - 1][row] instanceof Float)) {
try {
data[col - 1][row] = new Float((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane
.showMessageDialog(
GUI.this,
"The \""
+ getRowName(row)
+ "\" row only accepts float or double values.");
} else {
System.err
.println("User attempted to enter non-float"
+ " value ("
+ value
+ ") into an float-only column.");
}
}
} else {
data[col - 1][row] = value;
}
printDebugData();
}
}
// print the data from the table each time it gets updated (used for
// testing)
private void printDebugData() {
/*
* int numRows = getRowCount(); int numCols = getColumnCount();
*
* for (int i=0; i < numRows; i++) { System.out.print(" row " + i +
* ":"); for (int j=0; j < numCols-1; j++) { System.out.print(" " +
* data[j][i]); } System.out.println(); }
* System.out.println("--------------------------");
*/
}
public static final long serialVersionUID = 0x38DC79AEAD8B2091L;
}
/* extends MyTableModel, implements the checkboxes in the food web class */
class MyTableModel2 extends MyTableModel {
@SuppressWarnings("unused")
private Object[][] data;
@SuppressWarnings("unused")
private String[] rowNames;
MyTableModel2(String rownames[], int numcol, Object data[][]) {
super(rownames, numcol, data);
}
@Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public static final long serialVersionUID = 0x6E1D565A6F6714AFL;
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
public static void createAndShowGUI(CobwebApplication ca, String filename) {
// Make sure we have nice window decorations.
//JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
frame = new JFrame("Test Data");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new GUI(ca, filename);
frame.add(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
frame.getRootPane().setDefaultButton(ok);
//frame.validate();
}
public void setDefault() {
Width.setText("20");
wrap.setSelected(false);
Height.setText(Width.getText()); // $$$$$$ change to make Width == Height. Feb 20
memory_size.setText("10");
flexibility.setSelected(false);
PrisDilemma.setSelected(false);
keepOldAgents.setSelected(false);
spawnNewAgents.setSelected(true);
keepOldArray.setSelected(false);
dropNewFood.setSelected(true);
ColorCodedAgents.setSelected(true);
newColorizer.setSelected(true);
keepOldWaste.setSelected(false); // $$$$$$ change from true to false for retrievable experiments. Feb 20
keepOldPackets.setSelected(true);
numColor.setText("3");
colorSelectSize.setText("3");
reColorTimeStep.setText("300");
colorizerMode.setText("0");
RandomSeed.setText("0");
randomStones.setText("10");
maxFoodChance.setText("0.8");
/* Resources */
Object[][] temp1 = {
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) } };
foodData = temp1;
/* AGENTS INFO */
Object[][] temp2 = { { new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) } /* Broadcast Energy Cost */
};
agentData = temp2;
/* FOOD WEB */
Object[][] temp3 = {
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) } };
foodwebData = temp3;
Object[][] tempPD = { { new Integer(8), null },
{ new Integer(6), null }, { new Integer(3), null },
{ new Integer(2), null } };
PDdata = tempPD;
}
private void loadfromParser(Parser p) {
numAgentTypes = ((Integer) (Array.get(p.getfromHashTable("AgentCount"),
0))).intValue();
numFoodTypes = ((Integer) (Array.get(p.getfromHashTable("FoodCount"),
0))).intValue();
foodData = new Object[numFoodTypes][resParamNames.length];
agentData = new Object[numAgentTypes][agentParamNames.length];
foodwebData = new Object[numFoodTypes][numAgentTypes + numFoodTypes];
// PDdata = new Object[4][2];
setTextField(Width, Array.get(p.getfromHashTable("width"), 0));
setTextField(Height, Array.get(p.getfromHashTable("height"), 0));
setCheckBoxState(wrap, Array.get(p.getfromHashTable("wrap"), 0));
setCheckBoxState(PrisDilemma, Array.get(p
.getfromHashTable("PrisDilemma"), 0));
setTextField(memory_size, Array
.get(p.getfromHashTable("memorysize"), 0));
setCheckBoxState(flexibility, Array.get(p.getfromHashTable("foodBias"),
0));
setCheckBoxState(keepOldAgents, Array.get(p
.getfromHashTable("keepoldagents"), 0));
setCheckBoxState(keepOldArray, Array.get(p
.getfromHashTable("keepoldarray"), 0));
setCheckBoxState(spawnNewAgents, Array.get(p
.getfromHashTable("spawnnewagents"), 0));
setCheckBoxState(dropNewFood, Array.get(p
.getfromHashTable("dropnewfood"), 0));
setCheckBoxState(ColorCodedAgents, Array.get(p
.getfromHashTable("colorcodedagents"), 0));
setCheckBoxState(keepOldWaste, Array.get(p
.getfromHashTable("keepoldwaste"), 0));
setCheckBoxState(keepOldPackets, Array.get(p
.getfromHashTable("keepoldpackets"), 0));
setCheckBoxState(newColorizer, Array.get(p
.getfromHashTable("newcolorizer"), 0));
setTextField(numColor, Array.get(p.getfromHashTable("numcolor"), 0));
setTextField(colorSelectSize, Array.get(p
.getfromHashTable("colorselectsize"), 0));
setTextField(reColorTimeStep, Array.get(p
.getfromHashTable("recolortimestep"), 0));
setTextField(colorizerMode, Array.get(p
.getfromHashTable("colorizermode"), 0));
setTextField(RandomSeed, Array.get(p.getfromHashTable("randomseed"), 0));
setTextField(randomStones, Array.get(
p.getfromHashTable("randomstones"), 0));
setTextField(maxFoodChance, Array.get(p
.getfromHashTable("maxfoodchance"), 0));
setTableData(foodData, Array.get(p.getfromHashTable("food"), 0), 1);
setTableData(foodData, Array.get(p.getfromHashTable("foodrate"), 0), 2);
setTableData(foodData, Array.get(p.getfromHashTable("foodgrow"), 0), 3);
setTableData(foodData, Array.get(p.getfromHashTable("fooddeplete"), 0), 4);
setTableData(foodData, Array
.get(p.getfromHashTable("depletetimesteps"), 0), 5);
setTableData(foodData, Array.get(p.getfromHashTable("DraughtPeriod"), 0),
6);
setTableData(foodData, Array.get(p.getfromHashTable("foodmode"), 0), 7);
setTableData(agentData, Array.get(p.getfromHashTable("agents"), 0), 1);
setTableData(agentData, Array.get(p.getfromHashTable("mutationrate"), 0), 2);
setTableData(agentData, Array.get(p.getfromHashTable("initenergy"), 0), 3);
setTableData(agentData, Array.get(p.getfromHashTable("foodenergy"), 0), 4);
setTableData(agentData,
Array.get(p.getfromHashTable("otherfoodenergy"), 0), 5);
setTableData(agentData, Array.get(p.getfromHashTable("breedenergy"), 0), 6);
setTableData(agentData,
Array.get(p.getfromHashTable("pregnancyperiod"), 0), 7);
setTableData(agentData, Array.get(p.getfromHashTable("stepenergy"), 0), 8);
setTableData(agentData, Array.get(p.getfromHashTable("steprockenergy"), 0),
9);
setTableData(agentData,
Array.get(p.getfromHashTable("turnrightenergy"), 0), 10);
setTableData(agentData, Array.get(p.getfromHashTable("turnleftenergy"), 0),
11);
setTableData(agentData, Array.get(p.getfromHashTable("memorybits"), 0), 12);
setTableData(agentData, Array.get(p.getfromHashTable("commsimmin"), 0), 13);
setTableData(agentData,
Array.get(p.getfromHashTable("stepagentenergy"), 0), 14);
setTableData(agentData, Array.get(p.getfromHashTable("communicationbits"),
0), 15);
setTableData(agentData, Array.get(p
.getfromHashTable("sexualpregnancyperiod"), 0), 16);
setTableData(agentData, Array.get(p.getfromHashTable("breedsimmin"), 0), 17);
setTableData(agentData, Array.get(p.getfromHashTable("sexualbreedchance"),
0), 18);
setTableData(agentData, Array.get(p.getfromHashTable("asexualbreedchance"),
0), 19);
setTableData(agentData, Array.get(p.getfromHashTable("agingMode"), 0), 20);
setTableData(agentData, Array.get(p.getfromHashTable("agingLimit"), 0), 21);
setTableData(agentData, Array.get(p.getfromHashTable("agingRate"), 0), 22);
setTableData(agentData, Array.get(p.getfromHashTable("wasteMode"), 0), 23);
setTableData(agentData, Array.get(p.getfromHashTable("wastePen"), 0), 24);
setTableData(agentData, Array.get(p.getfromHashTable("wasteGain"), 0), 25);
setTableData(agentData, Array.get(p.getfromHashTable("wasteLoss"), 0), 26);
setTableData(agentData, Array.get(p.getfromHashTable("wasteRate"), 0), 27);
setTableData(agentData, Array.get(p.getfromHashTable("wasteInit"), 0), 28);
setTableData(agentData, Array.get(p.getfromHashTable("pdTitForTat"), 0), 29);
setTableData(agentData, Array.get(p.getfromHashTable("pdCoopProb"), 0), 30);
setTableData(agentData, Array.get(p.getfromHashTable("broadcastMode"), 0),
31);
setTableData(agentData, Array.get(p
.getfromHashTable("broadcastEnergyBased"), 0), 32);
setTableData(agentData, Array.get(
p.getfromHashTable("broadcastFixedRange"), 0), 33);
setTableData(agentData, Array.get(p.getfromHashTable("broadcastEnergyMin"),
0), 34);
setTableData(agentData, Array.get(
p.getfromHashTable("broadcastEnergyCost"), 0), 35);
setTableHelper(foodwebData);
for (int i = 0; i < foodwebData.length; i++) {
int j;
for (j = 0; j < foodwebData.length; j++) {
setTableData_agents2eat(foodwebData, Array.get(p
.getfromHashTable("agents2eat"), i), j, i);
}
for (int k = 0; k < foodwebData.length; k++) {
// setTableData2(data3,
// Array.get(p.getfromHashTable("plants2eat"), i),k+j, i);
setTableData_plants2eat(foodwebData, Array.get(p
.getfromHashTable("plants2eat"), i), k, i);
}
}
// TODO take off second dimension from array if not used
PDdata[0][0] = Array.get(p.getfromHashTable("temptation"), 0);
PDdata[1][0] = Array.get(p.getfromHashTable("reward"), 0);
PDdata[2][0] = Array.get(p.getfromHashTable("punishment"), 0);
PDdata[3][0] = Array.get(p.getfromHashTable("sucker"), 0);
controllerPanel.readFromParser(p);
}
private void setTextField(JTextField fieldName, Object value) {
fieldName.setText(value.toString());
}
private void setCheckBoxState(JCheckBox boxName, Object state) {
boxName.setSelected(((Boolean) state).booleanValue());
}
private void setTableData(Object data[][], Object rowdata, int row) {
for (int i = 0; i < data.length; i++) {
data[i][row - 1] = Array.get(rowdata, i);
}
}
/*
* Helper method: load a list of "agents to eat" from the hashtable into
* current data array
*/
private void setTableData_agents2eat(Object data[][], Object coldata,
int j, int i) {
int k = ((Integer) Array.get(coldata, j)).intValue();
if (k > -1) {
data[i][k] = new Boolean(true);
}
}
/*
* Helper method: load a list of "plants to eat" from the hashtable into
* current data array
*/
private void setTableData_plants2eat(Object data[][], Object coldata,
int j, int i) {
int k = ((Integer) Array.get(coldata, j)).intValue();
if (k > -1) {
data[i][k + foodwebData.length] = new Boolean(true);
}
}
private void setTableHelper(Object data[][]) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
data[i][j] = new Boolean(false);
}
}
}
/**
* Writes the information stored in this tree to an XML file, conforming to
* the rules of our spec.
*
* @param fileName
* the name of the file to which to save the file
* @return true if the file was saved successfully, false otherwise
*/
public boolean write(String fileName) throws IOException {
try {
// open the file
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
if (out != null) {
// write the initial project info
out.write("<?xml version='1.0' encoding='utf-8'?>");
out.write("\n\n");
out.write("<inputData>" + "\n");
out.write("\t" + "<scheduler>" + TickScheduler + "</scheduler>"
+ "\n");
controllerPanel.writeXML(out);
// out.write("\t" + "<ComplexEnvironment>" + new
// Integer(ComplexEnvironment.getText()) +
// "</ComplexEnvironment>" + "\n");
out.write("\t" + "<Width>" + Width.getText() + "</Width>"
+ "\n");
out.write("\t" + "<Height>" + Height.getText() + "</Height>"
+ "\n");
out.write("\t" + "<wrap>" + new Boolean(wrap.isSelected())
+ "</wrap>" + "\n");
out.write("\t" + "<PrisDilemma>"
+ new Boolean(PrisDilemma.isSelected())
+ "</PrisDilemma>" + "\n");
out.write("\t" + "<randomStones>"
+ new Integer(randomStones.getText())
+ "</randomStones>" + "\n");
out.write("\t" + "<maxFoodChance>"
+ new Float(maxFoodChance.getText())
+ "</maxFoodChance>" + "\n");
out.write("\t" + "<keepOldAgents>"
+ new Boolean(keepOldAgents.isSelected())
+ "</keepOldAgents>" + "\n");
out.write("\t" + "<spawnNewAgents>"
+ new Boolean(spawnNewAgents.isSelected())
+ "</spawnNewAgents>" + "\n");
out.write("\t" + "<keepOldArray>"
+ new Boolean(keepOldArray.isSelected())
+ "</keepOldArray>" + "\n");
out.write("\t" + "<dropNewFood>"
+ new Boolean(dropNewFood.isSelected())
+ "</dropNewFood>" + "\n");
out.write("\t" + "<randomSeed>"
+ new Integer(RandomSeed.getText()) + "</randomSeed>"
+ "\n");
out.write("\t" + "<newColorizer>"
+ new Boolean(newColorizer.isSelected())
+ "</newColorizer>" + "\n");
out.write("\t" + "<keepOldWaste>"
+ new Boolean(keepOldWaste.isSelected())
+ "</keepOldWaste>" + "\n");
out.write("\t" + "<keepOldPackets>"
+ new Boolean(keepOldPackets.isSelected())
+ "</keepOldPackets>" + "\n");
out.write("\t" + "<numColor>" + new Integer(numColor.getText())
+ "</numColor>" + "\n");
out.write("\t" + "<colorSelectSize>"
+ new Integer(colorSelectSize.getText())
+ "</colorSelectSize>" + "\n");
out.write("\t" + "<reColorTimeStep>"
+ new Integer(reColorTimeStep.getText())
+ "</reColorTimeStep>" + "\n");
out.write("\t" + "<colorizerMode>"
+ new Integer(colorizerMode.getText())
+ "</colorizerMode>" + "\n");
out.write("\t" + "<ColorCodedAgents>"
+ new Boolean(ColorCodedAgents.isSelected())
+ "</ColorCodedAgents>" + "\n");
out.write("\t" + "<memorySize>"
+ new Integer(memory_size.getText()) + "</memorySize>"
+ "\n");
out.write("\t" + "<food_bias>"
+ new Boolean(flexibility.isSelected()) + "</food_bias>"
+ "\n");
writeHelperFood(out, resourceParamTable.getColumnCount());
writeHelperAgents(out, agentParamTable.getColumnCount());
writeHelperPDOptions(out);
writeHelperGA(out);
out.write("</inputData>");
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
/**
* internal recursive helper
*/
private boolean writeHelperFood(BufferedWriter out, int foodtypes)
throws IOException {
for (int type = 1; type < foodtypes; type++) {
try {
// write the node info for the current node
out.write("<food>" + "\n");
out.write("\t" + "<Index>" + (type - 1) + "</Index>" + "\n");
out.write("\t" + "<Food>" + resourceParamTable.getValueAt(0, type)
+ "</Food>" + "\n");
out.write("\t" + "<FoodRate>" + resourceParamTable.getValueAt(1, type)
+ "</FoodRate>" + "\n");
out.write("\t" + "<FoodGrow>" + resourceParamTable.getValueAt(2, type)
+ "</FoodGrow>" + "\n");
out.write("\t" + "<FoodDeplete>" + resourceParamTable.getValueAt(3, type)
+ "</FoodDeplete>" + "\n");
out.write("\t" + "<DepleteTimeSteps>"
+ resourceParamTable.getValueAt(4, type) + "</DepleteTimeSteps>"
+ "\n");
out.write("\t" + "<DraughtPeriod>" + resourceParamTable.getValueAt(5, type)
+ "</DraughtPeriod>" + "\n");
out.write("\t" + "<FoodMode>" + resourceParamTable.getValueAt(6, type)
+ "</FoodMode>" + "\n");
out.write("</food>" + "\n");
} catch (IOException e) {
return false;
}
}
return true;
}
/* helper method for agents' parameters */
private boolean writeHelperAgents(BufferedWriter out, int agentypes) {
for (int type = 1; type < agentypes; type++) {
try {
// write the node info for the current node
out.write("<agent>" + "\n");
out.write("\t" + "<Index>" + (type - 1) + "</Index>" + "\n");
out.write("\t" + "<Agents>" + agentParamTable.getValueAt(0, type)
+ "</Agents>" + "\n");
out.write("\t" + "<MutationRate>" + agentParamTable.getValueAt(1, type)
+ "</MutationRate>" + "\n");
out.write("\t" + "<InitEnergy>" + agentParamTable.getValueAt(2, type)
+ "</InitEnergy>" + "\n");
out.write("\t" + "<FoodEnergy>" + agentParamTable.getValueAt(3, type)
+ "</FoodEnergy>" + "\n");
out.write("\t" + "<OtherFoodEnergy>"
+ agentParamTable.getValueAt(4, type) + "</OtherFoodEnergy>"
+ "\n");
out.write("\t" + "<BreedEnergy>" + agentParamTable.getValueAt(5, type)
+ "</BreedEnergy>" + "\n");
out.write("\t" + "<pregnancyPeriod>"
+ agentParamTable.getValueAt(6, type) + "</pregnancyPeriod>"
+ "\n");
out.write("\t" + "<StepEnergy>" + agentParamTable.getValueAt(7, type)
+ "</StepEnergy>" + "\n");
out.write("\t" + "<StepRockEnergy>"
+ agentParamTable.getValueAt(8, type) + "</StepRockEnergy>"
+ "\n");
out.write("\t" + "<TurnRightEnergy>"
+ agentParamTable.getValueAt(9, type) + "</TurnRightEnergy>"
+ "\n");
out.write("\t" + "<TurnLeftEnergy>"
+ agentParamTable.getValueAt(10, type) + "</TurnLeftEnergy>"
+ "\n");
out.write("\t" + "<MemoryBits>" + agentParamTable.getValueAt(11, type)
+ "</MemoryBits>" + "\n");
out.write("\t" + "<commSimMin>" + agentParamTable.getValueAt(12, type)
+ "</commSimMin>" + "\n");
out.write("\t" + "<StepAgentEnergy>"
+ agentParamTable.getValueAt(13, type) + "</StepAgentEnergy>"
+ "\n");
out.write("\t" + "<communicationBits>"
+ agentParamTable.getValueAt(14, type) + "</communicationBits>"
+ "\n");
out.write("\t" + "<sexualPregnancyPeriod>"
+ agentParamTable.getValueAt(15, type)
+ "</sexualPregnancyPeriod>" + "\n");
out.write("\t" + "<breedSimMin>" + agentParamTable.getValueAt(16, type)
+ "</breedSimMin>" + "\n");
out.write("\t" + "<sexualBreedChance>"
+ agentParamTable.getValueAt(17, type) + "</sexualBreedChance>"
+ "\n");
out.write("\t" + "<asexualBreedChance>"
+ agentParamTable.getValueAt(18, type) + "</asexualBreedChance>"
+ "\n");
out.write("\t" + "<agingMode>" + agentParamTable.getValueAt(19, type)
+ "</agingMode>" + "\n");
out.write("\t" + "<agingLimit>" + agentParamTable.getValueAt(20, type)
+ "</agingLimit>" + "\n");
out.write("\t" + "<agingRate>" + agentParamTable.getValueAt(21, type)
+ "</agingRate>" + "\n");
out.write("\t" + "<wasteMode>" + agentParamTable.getValueAt(22, type)
+ "</wasteMode>" + "\n");
out.write("\t" + "<wastePen>" + agentParamTable.getValueAt(23, type)
+ "</wastePen>" + "\n");
out.write("\t" + "<wasteGain>" + agentParamTable.getValueAt(24, type)
+ "</wasteGain>" + "\n");
out.write("\t" + "<wasteLoss>" + agentParamTable.getValueAt(25, type)
+ "</wasteLoss>" + "\n");
out.write("\t" + "<wasteRate>" + agentParamTable.getValueAt(26, type)
+ "</wasteRate>" + "\n");
out.write("\t" + "<wasteInit>" + agentParamTable.getValueAt(27, type)
+ "</wasteInit>" + "\n");
out.write("\t" + "<pdTitForTat>" + agentParamTable.getValueAt(28, type)
+ "</pdTitForTat>" + "\n");
out.write("\t" + "<pdCoopProb>" + agentParamTable.getValueAt(29, type)
+ "</pdCoopProb>" + "\n");
out.write("\t" + "<broadcastMode>"
+ agentParamTable.getValueAt(30, type) + "</broadcastMode>"
+ "\n");
out.write("\t" + "<broadcastEnergyBased>"
+ agentParamTable.getValueAt(31, type)
+ "</broadcastEnergyBased>" + "\n");
out.write("\t" + "<broadcastFixedRange>"
+ agentParamTable.getValueAt(32, type)
+ "</broadcastFixedRange>" + "\n");
out.write("\t" + "<broadcastEnergyMin>"
+ agentParamTable.getValueAt(33, type) + "</broadcastEnergyMin>"
+ "\n");
out.write("\t" + "<broadcastEnergyCost>"
+ agentParamTable.getValueAt(34, type)
+ "</broadcastEnergyCost>" + "\n");
writeHelperFoodWeb(out, type, resourceParamTable.getColumnCount(), agentParamTable
.getColumnCount());
out.write("</agent>" + "\n");
} catch (IOException e) {
return false;
}
}
return true;
}
private boolean writeHelperFoodWeb(BufferedWriter out, int type,
int num_foodtypes, int num_agentypes) throws IOException {
try {
// write the node info for the current node
out.write("<foodweb>" + "\n");
for (int i = 1; i < num_agentypes; i++) {
out.write("\t" + "<agent" + i + ">"
+ foodTable.getValueAt(i - 1, type) + "</agent" + i + ">"
+ "\n");
}
for (int i = 1; i < num_foodtypes; i++) {
out.write("\t" + "<food" + i + ">"
+ foodTable.getValueAt((num_agentypes + i) - 2, type)
+ "</food" + i + ">" + "\n");
}
out.write("</foodweb>" + "\n");
} catch (IOException e) {
return false;
}
return true;
}
private boolean writeHelperPDOptions(BufferedWriter out) throws IOException {
try {
out.write("<pd>");
out.write("<temptation>");
out.write("" + tablePD.getValueAt(0, 1));
out.write("</temptation>\n");
out.write("<reward>");
out.write("" + tablePD.getValueAt(1, 1));
out.write("</reward>\n");
out.write("<punishment>");
out.write("" + tablePD.getValueAt(2, 1));
out.write("</punishment>");
out.write("<sucker>");
out.write("" + tablePD.getValueAt(3, 1));
out.write("</sucker>\n");
out.write("</pd>\n");
} catch (IOException e) {
return false;
}
return true;
}
/** The GA portion of the write() method that writes parameters to xml file. */
private boolean writeHelperGA(BufferedWriter out) throws IOException {
try {
out.write("<ga>");
out.write("<agent1gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_1_COL));
out.write("</agent1gene1>\n");
out.write("<agent1gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_2_COL));
out.write("</agent1gene2>\n");
out.write("<agent1gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_3_COL));
out.write("</agent1gene3>\n");
out.write("<agent2gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_1_COL));
out.write("</agent2gene1>\n");
out.write("<agent2gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_2_COL));
out.write("</agent2gene2>\n");
out.write("<agent2gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_3_COL));
out.write("</agent2gene3>\n");
out.write("<agent3gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_1_COL));
out.write("</agent3gene1>\n");
out.write("<agent3gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_2_COL));
out.write("</agent3gene2>\n");
out.write("<agent3gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_3_COL));
out.write("</agent3gene3>\n");
out.write("<agent4gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_1_COL));
out.write("</agent4gene1>\n");
out.write("<agent4gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_2_COL));
out.write("</agent4gene2>\n");
out.write("<agent4gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_3_COL));
out.write("</agent4gene3>\n");
out.write("<linkedphenotype1>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_1_COL));
out.write("</linkedphenotype1>\n");
out.write("<linkedphenotype2>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_2_COL));
out.write("</linkedphenotype2>\n");
out.write("<linkedphenotype3>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_3_COL));
out.write("</linkedphenotype3>\n");
out.write("<meiosismode>");
out.write(""+ GeneticCode.meiosis_mode);
out.write("</meiosismode>\n");
out.write("<trackgenestatusdistribution>");
out.write("" + GATracker.getTrackGeneStatusDistribution());
out.write("</trackgenestatusdistribution>\n");
out.write("<trackgenevaluedistribution>");
out.write("" + GATracker.getTrackGeneValueDistribution());
out.write("</trackgenevaluedistribution>\n");
out.write("<chartupdatefrequency>");
out.write("" + GAChartOutput.update_frequency);
out.write("</chartupdatefrequency>");
out.write("</ga>\n");
} catch (IOException e) {
return false;
}
return true;
}
public static final long serialVersionUID = 0xB9967684A8375BC0L;
}
| public void openFileDialog() {
FileDialog theDialog = new FileDialog(frame,
"Choose a file to save state to", java.awt.FileDialog.SAVE);
theDialog.setVisible(true);
if (theDialog.getFile() != null) {
// $$$$$$ Check if the saving filename is one of the names reserved by CobwebApplication. Feb 8
// $$$$$$$$$$$$$$$$$$$$$$$$$$ Block silenced by Andy due to the annoyingness of this feature. May 7, 2008
//String savingFileName;
//savingFileName = theDialog.getFile();
// Block silenced, see above.
/*if ( (savingFileName.contains(CobwebApplication.INITIAL_OR_NEW_INPUT_FILE_NAME) != false)
|| (savingFileName.contains(CobwebApplication.CURRENT_DATA_FILE_NAME) != false) //$$$$$ added for "Modify Current Data"
|| (savingFileName.contains(CobwebApplication.DEFAULT_DATA_FILE_NAME) != false)) {
JOptionPane.showMessageDialog(GUI.this,
"Save State: The filename\"" + savingFileName + "\" is reserved by Cobweb Application.\n" +
" Please choose another file to save.",
"Warning", JOptionPane.WARNING_MESSAGE); // $$$$$$ modified on Feb 22
openFileDialog();
} else { */ // $$$$$ If filename not reserved. Feb 8
try {
// $$$$$$ The following block added to handle a readonly file. Feb 22
String savingFile = theDialog.getDirectory() + theDialog.getFile();
File sf = new File(savingFile);
if ( (sf.isHidden() != false) || ((sf.exists() != false) && (sf.canWrite() == false)) ) {
JOptionPane.showMessageDialog(GUI.frame, // $$$$$$ change from "this" to "GUI.frame". Feb 22
"Caution: File \"" + savingFile + "\" is NOT allowed to be written to.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else {
// $$$$$ The following block used to be the original code. Feb 22
write(theDialog.getDirectory() + theDialog.getFile());
p = new Parser(theDialog.getDirectory() + theDialog.getFile());
CA.openFile(p);
if (!datafile.equals(CA.getCurrentFile())) {CA.setCurrentFile(datafile);} // $$$$$$ added on Mar 14
frame.setVisible(false);
frame.dispose(); // $$$$$$ Feb 28
// $$$$$$ Added on Mar 14
if (CA.getUI() != null) {
if(CA.isInvokedByModify() == false) {
CA.getUI().reset(); // reset tick
//CA.refresh(CA.getUI());
//if (CA.tickField != null && !CA.tickField.getText().equals("")) {CA.tickField.setText("");} // $$$$$$ Mar 17
}
CA.getUI().refresh(1);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {
// $$$$$$ Reset the output window, specially for Linux. Mar 29
if (CA.textArea.getText().endsWith(CobwebApplication.GREETINGS) == false) {
CA.textArea.setText(CobwebApplication.GREETINGS);
}
}
}
}
} catch (java.io.IOException evt) {
JOptionPane.showMessageDialog(CA, // $$$$$$ added on Apr 22
"Save failed: " + evt.getMessage(),
"Warning", JOptionPane.WARNING_MESSAGE);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {CA.textArea.append("Save failed:" + evt.getMessage());} // $$$$$$ Added to be consistent with
// CobwebApplication's saveFile method. Feb 8
}
// }
}
}
public Parser getParser() {
return p;
}
private final class SaveAsButtonListener implements
java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent e) {
// $$$$$$ check validity of genetic table input. Feb 1
// Save the chart update frequency
try {
int freq = Integer.parseInt(chart_update_frequency.getText());
if (freq <= 0) { // Non-positive integers
GAChartOutput.update_frequency = 1;
} else { // Valid input
GAChartOutput.update_frequency = freq;
}
} catch (NumberFormatException f) { // Invalid input
GAChartOutput.update_frequency = 1;
}
boolean correct_GA_input;
correct_GA_input = checkValidityOfGAInput();
// $$$$$$ Implement "Save" only if GA input is correct
if ( (checkHeightLessThanWidth() != false) && (correct_GA_input != false) ) { // modified on Feb 21
//checkRandomSeedValidity(); // $$$$$$ added on Feb 22
// $$$$$$ Change the above code as follows on Feb 25
if (CA.randomSeedReminder == 0) {
CA.randomSeedReminder = checkRandomSeedStatus();
}
updateTable(resourceParamTable);
updateTable(agentParamTable);
updateTable(foodTable);
updateTable(tablePD); // $$$$$$ Jan 25
//updateTable(genetic_table); // $$$$$$ Jan 25 $$$$$$ genetic_table already updated by checkValidityOfGAInput(). Feb 22
openFileDialog();
}
}
}
private final class OkButtonListener implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent evt) {
// $$$$$$ check validity of genetic table input. Feb 1
boolean correct_GA_input;
correct_GA_input = checkValidityOfGAInput();
// Save the chart update frequency
try {
int freq = Integer.parseInt(chart_update_frequency.getText());
if (freq <= 0) { // Non-positive integers
GAChartOutput.update_frequency = 1;
} else { // Valid input
GAChartOutput.update_frequency = freq;
}
} catch (NumberFormatException e) { // Invalid input
GAChartOutput.update_frequency = 1;
}
if ( (checkHeightLessThanWidth() != false) && (correct_GA_input != false) ) {
//checkRandomSeedValidity(); // $$$$$$ added on Feb 18
// $$$$$$ Change the above code as follows on Feb 25
if (CA.randomSeedReminder == 0) {
CA.randomSeedReminder = checkRandomSeedStatus();
}
/*
* this fragment of code is necessary to update the last cell of
* the table before saving it
*/
updateTable(resourceParamTable);
updateTable(agentParamTable);
updateTable(foodTable);
updateTable(tablePD); // $$$$$$ Jan 25
/* write UI info to xml file */
try {
write(datafile); // $$$$$ write attributes showed in the "Test Data" window into the file "datafile". Jan 24
} catch (java.io.IOException e) {
throw new RuntimeException(e);
}
/* create a new parser for the xml file */
try {
p = new Parser(datafile);
} catch (FileNotFoundException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
CA.openFile(p);
if (!datafile.equals(CA.getCurrentFile())) {CA.setCurrentFile(datafile);} // $$$$$$ added on Mar 14
frame.setVisible(false);
frame.dispose(); // $$$$$$ added on Feb 28
// $$$$$$ Added on Mar 14
if (CA.getUI() != null) {
if(CA.isInvokedByModify() == false) {
CA.getUI().reset(); // reset tick
//CA.refresh(CA.getUI());
//if (CA.tickField != null && !CA.tickField.getText().equals("")) {CA.tickField.setText("");} // $$$$$$ Mar 17
}
CA.getUI().refresh(1);
/*** $$$$$$ Cancel textWindow Apr 22*/
if (cobweb.globals.usingTextWindow == true) {
// $$$$$$ Reset the output window, specially for Linux. Mar 29
if (CA.textArea.getText().endsWith(CobwebApplication.GREETINGS) == false) {
CA.textArea.setText(CobwebApplication.GREETINGS);
}
}
}
}
}
}
class PDTable extends AbstractTableModel {
private final Object[][] values;
private final String[] rownames;
public PDTable(String rownames[], Object data[][]) {
this.rownames = rownames;
values = data;
}
public int getRowCount() {
return values.length;
}
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int column) {
if (column == 0) {
return "";
}
return "value";
}
public String getRowName(int row) {
return rownames[row];
}
public Object getValueAt(int row, int column) {
if (column == 0) {
return rownames[row];
}
return values[row][0];
}
@Override
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col == 0) {
return false;
} else {
return true;
}
}
@Override
public void setValueAt(Object value, int row, int col) {
if ((isCellEditable(row, col))) {
try {
values[row][0] = new Integer((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane.showMessageDialog(GUI.this, "The \""
+ getRowName(row)
+ "\" row only accepts integer values.");
} else {
System.err
.println("User attempted to enter non-integer"
+ " value (" + value
+ ") into an integer-only column.");
}
}
}
}
// public Class getColumnClass(int c) { return values[0].getClass();}
public static final long serialVersionUID = 0x38FAF24EC6162F2CL;
}
/* table class */
class MyTableModel extends AbstractTableModel {
private final Object[][] data;
private final String[] rowNames;
private int numTypes = 0;
MyTableModel(String rownames[], int numcol, Object data[][]) {
this.data = data;
rowNames = rownames;
numTypes = numcol;
}
/* return the number of columns */
public int getColumnCount() {
return numTypes + 1;
}
/* return the number of rows */
public int getRowCount() {
return rowNames.length;
}
/* return column name given the number of the column */
@Override
public String getColumnName(int col) {
if (col == 0) {
return "";
} else {
return "Type" + (col);
}
}
/* return row name given the number of the row */
public String getRowName(int row) {
return rowNames[row];
}
public Object getValueAt(int row, int col) {
if (col == 0) {
return rowNames[row];
}
return data[col - 1][row];
}
/* add a column to this table */
public void addColumn() {
numTypes++;
for (int i = 0; i < getRowCount(); i++) {
data[numTypes][i] = "0";
}
}
/*
* Don't need to implement this method unless your table's editable.
*/
@Override
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col == 0) {
return false;
} else {
return true;
}
}
/*
* set the value at (row,col)
*/
@Override
public void setValueAt(Object value, int row, int col) {
if ((isCellEditable(row, col))) {
// check if this cell is supposed to contain and integer
if (data[col - 1][row] instanceof Integer) {
// If we don't do something like this, the column
// switches to contain Strings.
try {
data[col - 1][row] = new Integer((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane.showMessageDialog(GUI.this, "The \""
+ getRowName(row)
+ "\" row only accepts integer values.");
} else {
System.err
.println("User attempted to enter non-integer"
+ " value ("
+ value
+ ") into an integer-only column.");
}
}
// check if this cell is supposed to contain float or double
} else if ((data[col - 1][row] instanceof Double)
|| (data[col - 1][row] instanceof Float)) {
try {
data[col - 1][row] = new Float((String) value);
} catch (NumberFormatException e) {
if (SwingUtilities.isEventDispatchThread()) {
JOptionPane
.showMessageDialog(
GUI.this,
"The \""
+ getRowName(row)
+ "\" row only accepts float or double values.");
} else {
System.err
.println("User attempted to enter non-float"
+ " value ("
+ value
+ ") into an float-only column.");
}
}
} else {
data[col - 1][row] = value;
}
printDebugData();
}
}
// print the data from the table each time it gets updated (used for
// testing)
private void printDebugData() {
/*
* int numRows = getRowCount(); int numCols = getColumnCount();
*
* for (int i=0; i < numRows; i++) { System.out.print(" row " + i +
* ":"); for (int j=0; j < numCols-1; j++) { System.out.print(" " +
* data[j][i]); } System.out.println(); }
* System.out.println("--------------------------");
*/
}
public static final long serialVersionUID = 0x38DC79AEAD8B2091L;
}
/* extends MyTableModel, implements the checkboxes in the food web class */
class MyTableModel2 extends MyTableModel {
@SuppressWarnings("unused")
private Object[][] data;
@SuppressWarnings("unused")
private String[] rowNames;
MyTableModel2(String rownames[], int numcol, Object data[][]) {
super(rownames, numcol, data);
}
@Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public static final long serialVersionUID = 0x6E1D565A6F6714AFL;
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
public static void createAndShowGUI(CobwebApplication ca, String filename) {
// Make sure we have nice window decorations.
//JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
frame = new JFrame("Test Data");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new GUI(ca, filename);
frame.add(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
frame.getRootPane().setDefaultButton(ok);
//frame.validate();
}
public void setDefault() {
numAgentTypes = 4;
numFoodTypes = 4;
Width.setText("20");
wrap.setSelected(false);
Height.setText(Width.getText()); // $$$$$$ change to make Width == Height. Feb 20
memory_size.setText("10");
flexibility.setSelected(false);
PrisDilemma.setSelected(false);
keepOldAgents.setSelected(false);
spawnNewAgents.setSelected(true);
keepOldArray.setSelected(false);
dropNewFood.setSelected(true);
ColorCodedAgents.setSelected(true);
newColorizer.setSelected(true);
keepOldWaste.setSelected(false); // $$$$$$ change from true to false for retrievable experiments. Feb 20
keepOldPackets.setSelected(true);
numColor.setText("3");
colorSelectSize.setText("3");
reColorTimeStep.setText("300");
colorizerMode.setText("0");
RandomSeed.setText("0");
randomStones.setText("10");
maxFoodChance.setText("0.8");
/* Resources */
Object[][] temp1 = {
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) },
{ new Integer(20), new Double(0.5), new Integer(5),
new Double(0.9), new Integer(40), new Integer(0),
new Integer(0) } };
foodData = temp1;
/* AGENTS INFO */
Object[][] temp2 = { { new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) }, /* Broadcast Energy Cost */
{ new Integer(20), /* Initial num of agents */
new Float(0.05), /* Mutation Rate */
new Integer(30), /* Initial Energy */
new Integer(30), /* Favourite Food Energy */
new Integer(20), /* Other Food Energy */
new Integer(100), /* Breed Energy */
new Integer(0), /* Pregnancy Period - 1 parent */
new Integer(1), /* Step ENergy Loss */
new Integer(20), /* Step Rock Energy Loss */
new Integer(1), /* TUrn Right Energy Loss */
new Integer(1), /* Turn Left Energy Loss */
new Integer(2), /* Memory Bits */
new Integer(0), /* Min. Communication Similarity */
new Integer(4), /* Step Agent Energy Loss */
new Integer(2), /* Communication Bits */
new Integer(1), /* Pregnancy Period - 2 parents */
new Float(0.0), /* Min. Breed Similarity */
new Float(1.0), /* 2-parents Breed Chance */
new Float(0.0), /* 1 parent Breed Chance */
new Boolean(false), /* Agent Aging */
new Integer(100), /* Age LImit */
new Float(1.0), /* Age Rate */
new Boolean(true), /* Waste Production */
new Integer(20), /* Step Waste Energy Loss */
new Integer(110), /* Energy gain to trigger waste production */
new Integer(110), /* Energy spend to trigger Waste production */
new Float(0.20), /* Half-life rate for the waste */
new Integer(110), /* Initial waste amount */
new Boolean(true), /* PD Tit for Tat on/off */
new Integer(50), /* PD cooperation bias */
new Boolean(true), /* Broadcast Mode */
new Boolean(true), /* Broadcast range energy-based */
new Integer(20), /* Broadcast fixed range */
new Integer(100), /* Broadcast Minimum Energy */
new Integer(40) } /* Broadcast Energy Cost */
};
agentData = temp2;
/* FOOD WEB */
Object[][] temp3 = {
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) },
{ new Boolean(false), new Boolean(false), new Boolean(false),
new Boolean(false), new Boolean(true),
new Boolean(true), new Boolean(true), new Boolean(true) } };
foodwebData = temp3;
Object[][] tempPD = { { new Integer(8), null },
{ new Integer(6), null }, { new Integer(3), null },
{ new Integer(2), null } };
PDdata = tempPD;
}
private void loadfromParser(Parser p) {
numAgentTypes = ((Integer) (Array.get(p.getfromHashTable("AgentCount"),
0))).intValue();
numFoodTypes = ((Integer) (Array.get(p.getfromHashTable("FoodCount"),
0))).intValue();
foodData = new Object[numFoodTypes][resParamNames.length];
agentData = new Object[numAgentTypes][agentParamNames.length];
foodwebData = new Object[numFoodTypes][numAgentTypes + numFoodTypes];
// PDdata = new Object[4][2];
setTextField(Width, Array.get(p.getfromHashTable("width"), 0));
setTextField(Height, Array.get(p.getfromHashTable("height"), 0));
setCheckBoxState(wrap, Array.get(p.getfromHashTable("wrap"), 0));
setCheckBoxState(PrisDilemma, Array.get(p
.getfromHashTable("PrisDilemma"), 0));
setTextField(memory_size, Array
.get(p.getfromHashTable("memorysize"), 0));
setCheckBoxState(flexibility, Array.get(p.getfromHashTable("foodBias"),
0));
setCheckBoxState(keepOldAgents, Array.get(p
.getfromHashTable("keepoldagents"), 0));
setCheckBoxState(keepOldArray, Array.get(p
.getfromHashTable("keepoldarray"), 0));
setCheckBoxState(spawnNewAgents, Array.get(p
.getfromHashTable("spawnnewagents"), 0));
setCheckBoxState(dropNewFood, Array.get(p
.getfromHashTable("dropnewfood"), 0));
setCheckBoxState(ColorCodedAgents, Array.get(p
.getfromHashTable("colorcodedagents"), 0));
setCheckBoxState(keepOldWaste, Array.get(p
.getfromHashTable("keepoldwaste"), 0));
setCheckBoxState(keepOldPackets, Array.get(p
.getfromHashTable("keepoldpackets"), 0));
setCheckBoxState(newColorizer, Array.get(p
.getfromHashTable("newcolorizer"), 0));
setTextField(numColor, Array.get(p.getfromHashTable("numcolor"), 0));
setTextField(colorSelectSize, Array.get(p
.getfromHashTable("colorselectsize"), 0));
setTextField(reColorTimeStep, Array.get(p
.getfromHashTable("recolortimestep"), 0));
setTextField(colorizerMode, Array.get(p
.getfromHashTable("colorizermode"), 0));
setTextField(RandomSeed, Array.get(p.getfromHashTable("randomseed"), 0));
setTextField(randomStones, Array.get(
p.getfromHashTable("randomstones"), 0));
setTextField(maxFoodChance, Array.get(p
.getfromHashTable("maxfoodchance"), 0));
setTableData(foodData, Array.get(p.getfromHashTable("food"), 0), 1);
setTableData(foodData, Array.get(p.getfromHashTable("foodrate"), 0), 2);
setTableData(foodData, Array.get(p.getfromHashTable("foodgrow"), 0), 3);
setTableData(foodData, Array.get(p.getfromHashTable("fooddeplete"), 0), 4);
setTableData(foodData, Array
.get(p.getfromHashTable("depletetimesteps"), 0), 5);
setTableData(foodData, Array.get(p.getfromHashTable("DraughtPeriod"), 0),
6);
setTableData(foodData, Array.get(p.getfromHashTable("foodmode"), 0), 7);
setTableData(agentData, Array.get(p.getfromHashTable("agents"), 0), 1);
setTableData(agentData, Array.get(p.getfromHashTable("mutationrate"), 0), 2);
setTableData(agentData, Array.get(p.getfromHashTable("initenergy"), 0), 3);
setTableData(agentData, Array.get(p.getfromHashTable("foodenergy"), 0), 4);
setTableData(agentData,
Array.get(p.getfromHashTable("otherfoodenergy"), 0), 5);
setTableData(agentData, Array.get(p.getfromHashTable("breedenergy"), 0), 6);
setTableData(agentData,
Array.get(p.getfromHashTable("pregnancyperiod"), 0), 7);
setTableData(agentData, Array.get(p.getfromHashTable("stepenergy"), 0), 8);
setTableData(agentData, Array.get(p.getfromHashTable("steprockenergy"), 0),
9);
setTableData(agentData,
Array.get(p.getfromHashTable("turnrightenergy"), 0), 10);
setTableData(agentData, Array.get(p.getfromHashTable("turnleftenergy"), 0),
11);
setTableData(agentData, Array.get(p.getfromHashTable("memorybits"), 0), 12);
setTableData(agentData, Array.get(p.getfromHashTable("commsimmin"), 0), 13);
setTableData(agentData,
Array.get(p.getfromHashTable("stepagentenergy"), 0), 14);
setTableData(agentData, Array.get(p.getfromHashTable("communicationbits"),
0), 15);
setTableData(agentData, Array.get(p
.getfromHashTable("sexualpregnancyperiod"), 0), 16);
setTableData(agentData, Array.get(p.getfromHashTable("breedsimmin"), 0), 17);
setTableData(agentData, Array.get(p.getfromHashTable("sexualbreedchance"),
0), 18);
setTableData(agentData, Array.get(p.getfromHashTable("asexualbreedchance"),
0), 19);
setTableData(agentData, Array.get(p.getfromHashTable("agingMode"), 0), 20);
setTableData(agentData, Array.get(p.getfromHashTable("agingLimit"), 0), 21);
setTableData(agentData, Array.get(p.getfromHashTable("agingRate"), 0), 22);
setTableData(agentData, Array.get(p.getfromHashTable("wasteMode"), 0), 23);
setTableData(agentData, Array.get(p.getfromHashTable("wastePen"), 0), 24);
setTableData(agentData, Array.get(p.getfromHashTable("wasteGain"), 0), 25);
setTableData(agentData, Array.get(p.getfromHashTable("wasteLoss"), 0), 26);
setTableData(agentData, Array.get(p.getfromHashTable("wasteRate"), 0), 27);
setTableData(agentData, Array.get(p.getfromHashTable("wasteInit"), 0), 28);
setTableData(agentData, Array.get(p.getfromHashTable("pdTitForTat"), 0), 29);
setTableData(agentData, Array.get(p.getfromHashTable("pdCoopProb"), 0), 30);
setTableData(agentData, Array.get(p.getfromHashTable("broadcastMode"), 0),
31);
setTableData(agentData, Array.get(p
.getfromHashTable("broadcastEnergyBased"), 0), 32);
setTableData(agentData, Array.get(
p.getfromHashTable("broadcastFixedRange"), 0), 33);
setTableData(agentData, Array.get(p.getfromHashTable("broadcastEnergyMin"),
0), 34);
setTableData(agentData, Array.get(
p.getfromHashTable("broadcastEnergyCost"), 0), 35);
setTableHelper(foodwebData);
for (int i = 0; i < foodwebData.length; i++) {
int j;
for (j = 0; j < foodwebData.length; j++) {
setTableData_agents2eat(foodwebData, Array.get(p
.getfromHashTable("agents2eat"), i), j, i);
}
for (int k = 0; k < foodwebData.length; k++) {
// setTableData2(data3,
// Array.get(p.getfromHashTable("plants2eat"), i),k+j, i);
setTableData_plants2eat(foodwebData, Array.get(p
.getfromHashTable("plants2eat"), i), k, i);
}
}
// TODO take off second dimension from array if not used
PDdata[0][0] = Array.get(p.getfromHashTable("temptation"), 0);
PDdata[1][0] = Array.get(p.getfromHashTable("reward"), 0);
PDdata[2][0] = Array.get(p.getfromHashTable("punishment"), 0);
PDdata[3][0] = Array.get(p.getfromHashTable("sucker"), 0);
controllerPanel.readFromParser(p);
}
private void setTextField(JTextField fieldName, Object value) {
fieldName.setText(value.toString());
}
private void setCheckBoxState(JCheckBox boxName, Object state) {
boxName.setSelected(((Boolean) state).booleanValue());
}
private void setTableData(Object data[][], Object rowdata, int row) {
for (int i = 0; i < data.length; i++) {
data[i][row - 1] = Array.get(rowdata, i);
}
}
/*
* Helper method: load a list of "agents to eat" from the hashtable into
* current data array
*/
private void setTableData_agents2eat(Object data[][], Object coldata,
int j, int i) {
int k = ((Integer) Array.get(coldata, j)).intValue();
if (k > -1) {
data[i][k] = new Boolean(true);
}
}
/*
* Helper method: load a list of "plants to eat" from the hashtable into
* current data array
*/
private void setTableData_plants2eat(Object data[][], Object coldata,
int j, int i) {
int k = ((Integer) Array.get(coldata, j)).intValue();
if (k > -1) {
data[i][k + foodwebData.length] = new Boolean(true);
}
}
private void setTableHelper(Object data[][]) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
data[i][j] = new Boolean(false);
}
}
}
/**
* Writes the information stored in this tree to an XML file, conforming to
* the rules of our spec.
*
* @param fileName
* the name of the file to which to save the file
* @return true if the file was saved successfully, false otherwise
*/
public boolean write(String fileName) throws IOException {
try {
// open the file
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
if (out != null) {
// write the initial project info
out.write("<?xml version='1.0' encoding='utf-8'?>");
out.write("\n\n");
out.write("<inputData>" + "\n");
out.write("\t" + "<scheduler>" + TickScheduler + "</scheduler>"
+ "\n");
controllerPanel.writeXML(out);
// out.write("\t" + "<ComplexEnvironment>" + new
// Integer(ComplexEnvironment.getText()) +
// "</ComplexEnvironment>" + "\n");
out.write("\t" + "<Width>" + Width.getText() + "</Width>"
+ "\n");
out.write("\t" + "<Height>" + Height.getText() + "</Height>"
+ "\n");
out.write("\t" + "<wrap>" + new Boolean(wrap.isSelected())
+ "</wrap>" + "\n");
out.write("\t" + "<PrisDilemma>"
+ new Boolean(PrisDilemma.isSelected())
+ "</PrisDilemma>" + "\n");
out.write("\t" + "<randomStones>"
+ new Integer(randomStones.getText())
+ "</randomStones>" + "\n");
out.write("\t" + "<maxFoodChance>"
+ new Float(maxFoodChance.getText())
+ "</maxFoodChance>" + "\n");
out.write("\t" + "<keepOldAgents>"
+ new Boolean(keepOldAgents.isSelected())
+ "</keepOldAgents>" + "\n");
out.write("\t" + "<spawnNewAgents>"
+ new Boolean(spawnNewAgents.isSelected())
+ "</spawnNewAgents>" + "\n");
out.write("\t" + "<keepOldArray>"
+ new Boolean(keepOldArray.isSelected())
+ "</keepOldArray>" + "\n");
out.write("\t" + "<dropNewFood>"
+ new Boolean(dropNewFood.isSelected())
+ "</dropNewFood>" + "\n");
out.write("\t" + "<randomSeed>"
+ new Integer(RandomSeed.getText()) + "</randomSeed>"
+ "\n");
out.write("\t" + "<newColorizer>"
+ new Boolean(newColorizer.isSelected())
+ "</newColorizer>" + "\n");
out.write("\t" + "<keepOldWaste>"
+ new Boolean(keepOldWaste.isSelected())
+ "</keepOldWaste>" + "\n");
out.write("\t" + "<keepOldPackets>"
+ new Boolean(keepOldPackets.isSelected())
+ "</keepOldPackets>" + "\n");
out.write("\t" + "<numColor>" + new Integer(numColor.getText())
+ "</numColor>" + "\n");
out.write("\t" + "<colorSelectSize>"
+ new Integer(colorSelectSize.getText())
+ "</colorSelectSize>" + "\n");
out.write("\t" + "<reColorTimeStep>"
+ new Integer(reColorTimeStep.getText())
+ "</reColorTimeStep>" + "\n");
out.write("\t" + "<colorizerMode>"
+ new Integer(colorizerMode.getText())
+ "</colorizerMode>" + "\n");
out.write("\t" + "<ColorCodedAgents>"
+ new Boolean(ColorCodedAgents.isSelected())
+ "</ColorCodedAgents>" + "\n");
out.write("\t" + "<memorySize>"
+ new Integer(memory_size.getText()) + "</memorySize>"
+ "\n");
out.write("\t" + "<food_bias>"
+ new Boolean(flexibility.isSelected()) + "</food_bias>"
+ "\n");
writeHelperFood(out, resourceParamTable.getColumnCount());
writeHelperAgents(out, agentParamTable.getColumnCount());
writeHelperPDOptions(out);
writeHelperGA(out);
out.write("</inputData>");
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
/**
* internal recursive helper
*/
private boolean writeHelperFood(BufferedWriter out, int foodtypes)
throws IOException {
for (int type = 1; type < foodtypes; type++) {
try {
// write the node info for the current node
out.write("<food>" + "\n");
out.write("\t" + "<Index>" + (type - 1) + "</Index>" + "\n");
out.write("\t" + "<Food>" + resourceParamTable.getValueAt(0, type)
+ "</Food>" + "\n");
out.write("\t" + "<FoodRate>" + resourceParamTable.getValueAt(1, type)
+ "</FoodRate>" + "\n");
out.write("\t" + "<FoodGrow>" + resourceParamTable.getValueAt(2, type)
+ "</FoodGrow>" + "\n");
out.write("\t" + "<FoodDeplete>" + resourceParamTable.getValueAt(3, type)
+ "</FoodDeplete>" + "\n");
out.write("\t" + "<DepleteTimeSteps>"
+ resourceParamTable.getValueAt(4, type) + "</DepleteTimeSteps>"
+ "\n");
out.write("\t" + "<DraughtPeriod>" + resourceParamTable.getValueAt(5, type)
+ "</DraughtPeriod>" + "\n");
out.write("\t" + "<FoodMode>" + resourceParamTable.getValueAt(6, type)
+ "</FoodMode>" + "\n");
out.write("</food>" + "\n");
} catch (IOException e) {
return false;
}
}
return true;
}
/* helper method for agents' parameters */
private boolean writeHelperAgents(BufferedWriter out, int agentypes) {
for (int type = 1; type < agentypes; type++) {
try {
// write the node info for the current node
out.write("<agent>" + "\n");
out.write("\t" + "<Index>" + (type - 1) + "</Index>" + "\n");
out.write("\t" + "<Agents>" + agentParamTable.getValueAt(0, type)
+ "</Agents>" + "\n");
out.write("\t" + "<MutationRate>" + agentParamTable.getValueAt(1, type)
+ "</MutationRate>" + "\n");
out.write("\t" + "<InitEnergy>" + agentParamTable.getValueAt(2, type)
+ "</InitEnergy>" + "\n");
out.write("\t" + "<FoodEnergy>" + agentParamTable.getValueAt(3, type)
+ "</FoodEnergy>" + "\n");
out.write("\t" + "<OtherFoodEnergy>"
+ agentParamTable.getValueAt(4, type) + "</OtherFoodEnergy>"
+ "\n");
out.write("\t" + "<BreedEnergy>" + agentParamTable.getValueAt(5, type)
+ "</BreedEnergy>" + "\n");
out.write("\t" + "<pregnancyPeriod>"
+ agentParamTable.getValueAt(6, type) + "</pregnancyPeriod>"
+ "\n");
out.write("\t" + "<StepEnergy>" + agentParamTable.getValueAt(7, type)
+ "</StepEnergy>" + "\n");
out.write("\t" + "<StepRockEnergy>"
+ agentParamTable.getValueAt(8, type) + "</StepRockEnergy>"
+ "\n");
out.write("\t" + "<TurnRightEnergy>"
+ agentParamTable.getValueAt(9, type) + "</TurnRightEnergy>"
+ "\n");
out.write("\t" + "<TurnLeftEnergy>"
+ agentParamTable.getValueAt(10, type) + "</TurnLeftEnergy>"
+ "\n");
out.write("\t" + "<MemoryBits>" + agentParamTable.getValueAt(11, type)
+ "</MemoryBits>" + "\n");
out.write("\t" + "<commSimMin>" + agentParamTable.getValueAt(12, type)
+ "</commSimMin>" + "\n");
out.write("\t" + "<StepAgentEnergy>"
+ agentParamTable.getValueAt(13, type) + "</StepAgentEnergy>"
+ "\n");
out.write("\t" + "<communicationBits>"
+ agentParamTable.getValueAt(14, type) + "</communicationBits>"
+ "\n");
out.write("\t" + "<sexualPregnancyPeriod>"
+ agentParamTable.getValueAt(15, type)
+ "</sexualPregnancyPeriod>" + "\n");
out.write("\t" + "<breedSimMin>" + agentParamTable.getValueAt(16, type)
+ "</breedSimMin>" + "\n");
out.write("\t" + "<sexualBreedChance>"
+ agentParamTable.getValueAt(17, type) + "</sexualBreedChance>"
+ "\n");
out.write("\t" + "<asexualBreedChance>"
+ agentParamTable.getValueAt(18, type) + "</asexualBreedChance>"
+ "\n");
out.write("\t" + "<agingMode>" + agentParamTable.getValueAt(19, type)
+ "</agingMode>" + "\n");
out.write("\t" + "<agingLimit>" + agentParamTable.getValueAt(20, type)
+ "</agingLimit>" + "\n");
out.write("\t" + "<agingRate>" + agentParamTable.getValueAt(21, type)
+ "</agingRate>" + "\n");
out.write("\t" + "<wasteMode>" + agentParamTable.getValueAt(22, type)
+ "</wasteMode>" + "\n");
out.write("\t" + "<wastePen>" + agentParamTable.getValueAt(23, type)
+ "</wastePen>" + "\n");
out.write("\t" + "<wasteGain>" + agentParamTable.getValueAt(24, type)
+ "</wasteGain>" + "\n");
out.write("\t" + "<wasteLoss>" + agentParamTable.getValueAt(25, type)
+ "</wasteLoss>" + "\n");
out.write("\t" + "<wasteRate>" + agentParamTable.getValueAt(26, type)
+ "</wasteRate>" + "\n");
out.write("\t" + "<wasteInit>" + agentParamTable.getValueAt(27, type)
+ "</wasteInit>" + "\n");
out.write("\t" + "<pdTitForTat>" + agentParamTable.getValueAt(28, type)
+ "</pdTitForTat>" + "\n");
out.write("\t" + "<pdCoopProb>" + agentParamTable.getValueAt(29, type)
+ "</pdCoopProb>" + "\n");
out.write("\t" + "<broadcastMode>"
+ agentParamTable.getValueAt(30, type) + "</broadcastMode>"
+ "\n");
out.write("\t" + "<broadcastEnergyBased>"
+ agentParamTable.getValueAt(31, type)
+ "</broadcastEnergyBased>" + "\n");
out.write("\t" + "<broadcastFixedRange>"
+ agentParamTable.getValueAt(32, type)
+ "</broadcastFixedRange>" + "\n");
out.write("\t" + "<broadcastEnergyMin>"
+ agentParamTable.getValueAt(33, type) + "</broadcastEnergyMin>"
+ "\n");
out.write("\t" + "<broadcastEnergyCost>"
+ agentParamTable.getValueAt(34, type)
+ "</broadcastEnergyCost>" + "\n");
writeHelperFoodWeb(out, type, resourceParamTable.getColumnCount(), agentParamTable
.getColumnCount());
out.write("</agent>" + "\n");
} catch (IOException e) {
return false;
}
}
return true;
}
private boolean writeHelperFoodWeb(BufferedWriter out, int type,
int num_foodtypes, int num_agentypes) throws IOException {
try {
// write the node info for the current node
out.write("<foodweb>" + "\n");
for (int i = 1; i < num_agentypes; i++) {
out.write("\t" + "<agent" + i + ">"
+ foodTable.getValueAt(i - 1, type) + "</agent" + i + ">"
+ "\n");
}
for (int i = 1; i < num_foodtypes; i++) {
out.write("\t" + "<food" + i + ">"
+ foodTable.getValueAt((num_agentypes + i) - 2, type)
+ "</food" + i + ">" + "\n");
}
out.write("</foodweb>" + "\n");
} catch (IOException e) {
return false;
}
return true;
}
private boolean writeHelperPDOptions(BufferedWriter out) throws IOException {
try {
out.write("<pd>");
out.write("<temptation>");
out.write("" + tablePD.getValueAt(0, 1));
out.write("</temptation>\n");
out.write("<reward>");
out.write("" + tablePD.getValueAt(1, 1));
out.write("</reward>\n");
out.write("<punishment>");
out.write("" + tablePD.getValueAt(2, 1));
out.write("</punishment>");
out.write("<sucker>");
out.write("" + tablePD.getValueAt(3, 1));
out.write("</sucker>\n");
out.write("</pd>\n");
} catch (IOException e) {
return false;
}
return true;
}
/** The GA portion of the write() method that writes parameters to xml file. */
private boolean writeHelperGA(BufferedWriter out) throws IOException {
try {
out.write("<ga>");
out.write("<agent1gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_1_COL));
out.write("</agent1gene1>\n");
out.write("<agent1gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_2_COL));
out.write("</agent1gene2>\n");
out.write("<agent1gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_1_ROW, GA_GENE_3_COL));
out.write("</agent1gene3>\n");
out.write("<agent2gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_1_COL));
out.write("</agent2gene1>\n");
out.write("<agent2gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_2_COL));
out.write("</agent2gene2>\n");
out.write("<agent2gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_2_ROW, GA_GENE_3_COL));
out.write("</agent2gene3>\n");
out.write("<agent3gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_1_COL));
out.write("</agent3gene1>\n");
out.write("<agent3gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_2_COL));
out.write("</agent3gene2>\n");
out.write("<agent3gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_3_ROW, GA_GENE_3_COL));
out.write("</agent3gene3>\n");
out.write("<agent4gene1>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_1_COL));
out.write("</agent4gene1>\n");
out.write("<agent4gene2>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_2_COL));
out.write("</agent4gene2>\n");
out.write("<agent4gene3>");
out.write(""
+ genetic_table.getValueAt(GA_AGENT_4_ROW, GA_GENE_3_COL));
out.write("</agent4gene3>\n");
out.write("<linkedphenotype1>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_1_COL));
out.write("</linkedphenotype1>\n");
out.write("<linkedphenotype2>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_2_COL));
out.write("</linkedphenotype2>\n");
out.write("<linkedphenotype3>");
out.write(""
+ genetic_table.getValueAt(GA_LINKED_PHENOTYPE_ROW,
GA_GENE_3_COL));
out.write("</linkedphenotype3>\n");
out.write("<meiosismode>");
out.write(""+ GeneticCode.meiosis_mode);
out.write("</meiosismode>\n");
out.write("<trackgenestatusdistribution>");
out.write("" + GATracker.getTrackGeneStatusDistribution());
out.write("</trackgenestatusdistribution>\n");
out.write("<trackgenevaluedistribution>");
out.write("" + GATracker.getTrackGeneValueDistribution());
out.write("</trackgenevaluedistribution>\n");
out.write("<chartupdatefrequency>");
out.write("" + GAChartOutput.update_frequency);
out.write("</chartupdatefrequency>");
out.write("</ga>\n");
} catch (IOException e) {
return false;
}
return true;
}
public static final long serialVersionUID = 0xB9967684A8375BC0L;
}
|
diff --git a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/PlugInLoadTest.java b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/PlugInLoadTest.java
index ba9a78abc..a197bb2d0 100644
--- a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/PlugInLoadTest.java
+++ b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/PlugInLoadTest.java
@@ -1,202 +1,200 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.tests;
import junit.framework.TestCase;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
public class PlugInLoadTest extends TestCase {
public static final String rhdsNS = "org.jboss.tools.";
private static String jbideNS = "org.jboss.ide.eclipse.";
private static String hibNS = "org.hibernate.eclipse.";
private static String jbpmNS = "org.jbpm.gd.jpdl";
private static String jbwsNS = "com.eviware.soapui.";
private boolean isPluginResolved (String pluginId)
{
Bundle bundle = Platform.getBundle(pluginId);
assertNotNull(pluginId + " failed to load.",bundle);
try {
// In 3.3 when test case is running plug-in.getState always returns STARTING state
// to move plug-in in ACTIVE state even one class should be loaded from plug-in
bundle.loadClass("fake class");
} catch (Exception e) {
// It happen always because loaded class is not exists
}
return ((bundle.getState() & Bundle.RESOLVED) > 0) ||
((bundle.getState() & Bundle.ACTIVE) > 0);
}
private void assertPluginsResolved (String[] pluginIds)
{
for (int i = 0; i < pluginIds.length; i++) {
assertTrue ("plugin '" + pluginIds[i] + "' is not resolved",isPluginResolved(pluginIds[i]));
}
}
public void testCommonPluginsResolved ()
{
assertPluginsResolved(new String[] {
rhdsNS+"common",
rhdsNS+"common.gef",
rhdsNS+"common.kb",
rhdsNS+"common.model",
rhdsNS+"common.model.ui",
rhdsNS+"common.projecttemplates",
rhdsNS+"common.text.ext",
rhdsNS+"common.text.xml",
rhdsNS+"common.verification",
rhdsNS+"common.verification.ui",
});
}
public void testJsfPluginsResolved()
{
assertPluginsResolved(new String[] {
rhdsNS+"jsf",
rhdsNS+"jsf.text.ext",
rhdsNS+"jsf.text.ext.facelets",
rhdsNS+"jsf.ui",
rhdsNS+"jsf.verification",
rhdsNS+"jsf.vpe.ajax4jsf",
rhdsNS+"jsf.vpe.facelets",
rhdsNS+"jsf.vpe.richfaces",
rhdsNS+"jsf.vpe.seam",
rhdsNS+"jsf.vpe.tomahawk"
});
}
public void testJstPluginsResolved ()
{
assertPluginsResolved(new String[] {
rhdsNS+"jst.jsp",
rhdsNS+"jst.server.jetty",
rhdsNS+"jst.server.jrun",
rhdsNS+"jst.server.resin",
rhdsNS+"jst.web",
rhdsNS+"jst.web.debug",
rhdsNS+"jst.web.debug.ui",
rhdsNS+"jst.web.tiles",
rhdsNS+"jst.web.tiles.ui",
rhdsNS+"jst.web.ui",
rhdsNS+"jst.web.verification"
});
}
public void testVpePluginsResolved ()
{
assertPluginsResolved(new String[] {
rhdsNS+"vpe.mozilla",
rhdsNS+"vpe.ui",
rhdsNS+"vpe",
rhdsNS+"vpe.ui.palette"
});
}
public void testStrutsPluginsResolved ()
{
assertPluginsResolved(new String[] {
rhdsNS+"struts",
rhdsNS+"struts.debug",
rhdsNS+"struts.text.ext",
rhdsNS+"struts.ui",
rhdsNS+"struts.validator.ui",
rhdsNS+"struts.verification"
});
}
public void testShalePluginsResolved ()
{
assertPluginsResolved(new String[] {
rhdsNS+"shale.ui",
rhdsNS+"shale",
rhdsNS+"shale.text.ext"
});
}
public void testCorePluginsResolved ()
{
assertPluginsResolved(new String[] {
jbideNS+"core",
jbideNS+"jdt.core",
jbideNS+"jdt.j2ee.core",
jbideNS+"jdt.j2ee.ui",
jbideNS+"jdt.j2ee.xml.ui",
jbideNS+"jdt.ui",
- jbideNS+"jdt.ws.core",
- jbideNS+"jdt.ws.ui",
jbideNS+"archives.core",
jbideNS+"archives.ui",
jbideNS+"ui",
jbideNS+"xdoclet.assist",
jbideNS+"xdoclet.core",
jbideNS+"xdoclet.run",
jbideNS+"xdoclet.ui"
});
}
public void testASPluginsResolved ()
{
assertPluginsResolved(new String[] {
jbideNS+"as.core",
jbideNS+"as.ui",
jbideNS+"as.ui.mbeans"
});
}
public void testHibernatePluginsResolved ()
{
assertPluginsResolved(new String[] {
"org.hibernate.eclipse",
hibNS+"console",
hibNS+"help",
hibNS+"mapper",
hibNS+"jdt.ui",
hibNS+"jdt.apt.ui"
});
}
public void testJbpmPluginsResolved ()
{
assertPluginsResolved(new String[] {
jbpmNS
});
}
public void testFreemarkerPluginsResolved ()
{
assertPluginsResolved(new String[] {
jbideNS+"freemarker"
});
}
public void testDroolsPluginsResolved ()
{
// Skipped until drools migartion to 3.3 is finished
// assertPluginsResolved(new String[] {
// "org.drools.ide"
// });
}
public void testJBossWSPluginsResolved ()
{
// assertPluginsResolved(new String[] {
// jbwsNS+"core",
// jbwsNS+"eclipse.core",
// jbwsNS+"jbosside.wstools",
// jbwsNS+"libs"
// });
}
}
| true | true | public void testCorePluginsResolved ()
{
assertPluginsResolved(new String[] {
jbideNS+"core",
jbideNS+"jdt.core",
jbideNS+"jdt.j2ee.core",
jbideNS+"jdt.j2ee.ui",
jbideNS+"jdt.j2ee.xml.ui",
jbideNS+"jdt.ui",
jbideNS+"jdt.ws.core",
jbideNS+"jdt.ws.ui",
jbideNS+"archives.core",
jbideNS+"archives.ui",
jbideNS+"ui",
jbideNS+"xdoclet.assist",
jbideNS+"xdoclet.core",
jbideNS+"xdoclet.run",
jbideNS+"xdoclet.ui"
});
}
| public void testCorePluginsResolved ()
{
assertPluginsResolved(new String[] {
jbideNS+"core",
jbideNS+"jdt.core",
jbideNS+"jdt.j2ee.core",
jbideNS+"jdt.j2ee.ui",
jbideNS+"jdt.j2ee.xml.ui",
jbideNS+"jdt.ui",
jbideNS+"archives.core",
jbideNS+"archives.ui",
jbideNS+"ui",
jbideNS+"xdoclet.assist",
jbideNS+"xdoclet.core",
jbideNS+"xdoclet.run",
jbideNS+"xdoclet.ui"
});
}
|
diff --git a/src/com/untamedears/citadel/listener/PlayerListener.java b/src/com/untamedears/citadel/listener/PlayerListener.java
index 8c26db0..664981d 100644
--- a/src/com/untamedears/citadel/listener/PlayerListener.java
+++ b/src/com/untamedears/citadel/listener/PlayerListener.java
@@ -1,218 +1,215 @@
package com.untamedears.citadel.listener;
import static com.untamedears.citadel.Utility.createPlayerReinforcement;
import static com.untamedears.citadel.Utility.maybeReinforcementDamaged;
import static com.untamedears.citadel.Utility.reinforcementBroken;
import static com.untamedears.citadel.Utility.sendMessage;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.material.Openable;
import com.untamedears.citadel.Citadel;
import com.untamedears.citadel.GroupManager;
import com.untamedears.citadel.MemberManager;
import com.untamedears.citadel.PersonalGroupManager;
import com.untamedears.citadel.PlacementMode;
import com.untamedears.citadel.SecurityLevel;
import com.untamedears.citadel.access.AccessDelegate;
import com.untamedears.citadel.entity.Faction;
import com.untamedears.citadel.entity.Member;
import com.untamedears.citadel.entity.PlayerState;
import com.untamedears.citadel.entity.IReinforcement;
import com.untamedears.citadel.entity.PlayerReinforcement;
/**
* Created by IntelliJ IDEA.
* User: chrisrico
* Date: 3/21/12
* Time: 9:57 PM
*
* Last edited by JonnyD
* 7/18/12
*/
public class PlayerListener implements Listener {
@EventHandler
public void login(PlayerLoginEvent ple) {
MemberManager memberManager = Citadel.getMemberManager();
memberManager.addOnlinePlayer(ple.getPlayer());
String playerName = ple.getPlayer().getDisplayName();
Member member = memberManager.getMember(playerName);
if(member == null){
member = new Member(playerName);
memberManager.addMember(member);
}
PersonalGroupManager personalGroupManager = Citadel.getPersonalGroupManager();
boolean hasPersonalGroup = personalGroupManager.hasPersonalGroup(playerName);
GroupManager groupManager = Citadel.getGroupManager();
if(!hasPersonalGroup){
String groupName = playerName;
int i = 1;
while(groupManager.isGroup(groupName)){
groupName = playerName + i;
i++;
}
Faction group = new Faction(groupName, playerName);
groupManager.addGroup(group);
personalGroupManager.addPersonalGroup(groupName, playerName);
} else if(hasPersonalGroup){
String personalGroupName = personalGroupManager.getPersonalGroup(playerName).getGroupName();
if(!groupManager.isGroup(personalGroupName)){
Faction group = new Faction(personalGroupName, playerName);
groupManager.addGroup(group);
}
}
}
@EventHandler
public void quit(PlayerQuitEvent pqe) {
Player player = pqe.getPlayer();
MemberManager memberManager = Citadel.getMemberManager();
memberManager.removeOnlinePlayer(player);
PlayerState.remove(player);
}
@EventHandler(priority = EventPriority.LOWEST)
public void bookshelf(PlayerInteractEvent pie) {
if (pie.hasBlock() && pie.getMaterial() == Material.BOOKSHELF)
interact(pie);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void bucketEmpty(PlayerBucketEmptyEvent pbee) {
Material bucket = pbee.getBucket();
if (Material.LAVA_BUCKET == bucket) {
Block block = pbee.getBlockClicked();
BlockFace face = pbee.getBlockFace();
Block relativeBlock = block.getRelative(face);
// Protection for reinforced rails types from direct lava bucket drop.
if (Material.RAILS == relativeBlock.getType() || Material.POWERED_RAIL == relativeBlock.getType() || Material.DETECTOR_RAIL == relativeBlock.getType()) {
boolean isReinforced = maybeReinforcementDamaged(relativeBlock);
pbee.setCancelled(isReinforced);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void interact(PlayerInteractEvent pie) {
try {
if (!pie.hasBlock()) return;
Player player = pie.getPlayer();
Block block = pie.getClickedBlock();
AccessDelegate accessDelegate = AccessDelegate.getDelegate(block);
block = accessDelegate.getBlock();
IReinforcement generic_reinforcement = accessDelegate.getReinforcement();
PlayerReinforcement reinforcement = null;
if (generic_reinforcement instanceof PlayerReinforcement) {
reinforcement = (PlayerReinforcement)generic_reinforcement;
}
if (reinforcement != null
&& reinforcement.isSecurable()
&& !reinforcement.isAccessible(player)) {
Action action = pie.getAction();
- if(action == Action.LEFT_CLICK_BLOCK
- && reinforcement.getBlock().getState().getData() instanceof Openable){
- pie.setUseInteractedBlock(Event.Result.DENY);
- } else if(action == Action.RIGHT_CLICK_BLOCK){
+ if(action == Action.RIGHT_CLICK_BLOCK){
Citadel.info("%s failed to access locked reinforcement %s, "
+ player.getDisplayName() + " at "
+ block.getLocation().toString());
sendMessage(pie.getPlayer(), ChatColor.RED, "%s is locked", block.getType().name());
pie.setCancelled(true);
}
}
if (pie.isCancelled()) return;
PlayerState state = PlayerState.get(player);
PlacementMode placementMode = state.getMode();
switch (placementMode) {
case NORMAL:
return;
case FORTIFICATION:
return;
case INFO:
// did player click on a reinforced block?
if (reinforcement != null) {
String reinforcementStatus = reinforcement.getStatus();
SecurityLevel securityLevel = reinforcement.getSecurityLevel();
if(reinforcement.isAccessible(player)){
Faction group = reinforcement.getOwner();
String groupName = group.getName();
String message = "";
if(group.isPersonalGroup()){
message = String.format("%s, security: %s, group: %s (Default Group)", reinforcementStatus, securityLevel, groupName);
} else {
message = String.format("%s, security: %s, group: %s", reinforcementStatus, securityLevel, groupName);
}
sendMessage(player, ChatColor.GREEN, message);
} else {
sendMessage(player, ChatColor.RED, "%s, security: %s", reinforcementStatus, securityLevel);
}
}
break;
default:
// player is in reinforcement mode
if (reinforcement == null) {
// Break any natural reinforcement before placing the player reinforcement
if (generic_reinforcement != null) {
reinforcementBroken(generic_reinforcement);
}
createPlayerReinforcement(player, block);
} else if (reinforcement.isBypassable(player)) {
boolean update = false;
String message = "";
if (reinforcement.getSecurityLevel() != state.getSecurityLevel()){
reinforcement.setSecurityLevel(state.getSecurityLevel());
update = true;
message = String.format("Changed security level %s", reinforcement.getSecurityLevel().name());
}
if(!reinforcement.getOwner().equals(state.getFaction())) {
reinforcement.setOwner(state.getFaction());
update = true;
if(!message.equals("")){
message = message + ". ";
}
if(reinforcement.getSecurityLevel() != SecurityLevel.PRIVATE){
message = message + String.format("Changed group to %s", state.getFaction().getName());
}
}
if(update){
Citadel.getReinforcementManager().addReinforcement(reinforcement);
sendMessage(player, ChatColor.GREEN, message);
}
} else {
sendMessage(player, ChatColor.RED, "You are not permitted to modify this reinforcement");
}
pie.setCancelled(true);
if (state.getMode() == PlacementMode.REINFORCEMENT_SINGLE_BLOCK) {
state.reset();
} else {
state.checkResetMode();
}
}
}
catch(Exception e)
{
Citadel.printStackTrace(e);
}
}
}
| true | true | public void interact(PlayerInteractEvent pie) {
try {
if (!pie.hasBlock()) return;
Player player = pie.getPlayer();
Block block = pie.getClickedBlock();
AccessDelegate accessDelegate = AccessDelegate.getDelegate(block);
block = accessDelegate.getBlock();
IReinforcement generic_reinforcement = accessDelegate.getReinforcement();
PlayerReinforcement reinforcement = null;
if (generic_reinforcement instanceof PlayerReinforcement) {
reinforcement = (PlayerReinforcement)generic_reinforcement;
}
if (reinforcement != null
&& reinforcement.isSecurable()
&& !reinforcement.isAccessible(player)) {
Action action = pie.getAction();
if(action == Action.LEFT_CLICK_BLOCK
&& reinforcement.getBlock().getState().getData() instanceof Openable){
pie.setUseInteractedBlock(Event.Result.DENY);
} else if(action == Action.RIGHT_CLICK_BLOCK){
Citadel.info("%s failed to access locked reinforcement %s, "
+ player.getDisplayName() + " at "
+ block.getLocation().toString());
sendMessage(pie.getPlayer(), ChatColor.RED, "%s is locked", block.getType().name());
pie.setCancelled(true);
}
}
if (pie.isCancelled()) return;
PlayerState state = PlayerState.get(player);
PlacementMode placementMode = state.getMode();
switch (placementMode) {
case NORMAL:
return;
case FORTIFICATION:
return;
case INFO:
// did player click on a reinforced block?
if (reinforcement != null) {
String reinforcementStatus = reinforcement.getStatus();
SecurityLevel securityLevel = reinforcement.getSecurityLevel();
if(reinforcement.isAccessible(player)){
Faction group = reinforcement.getOwner();
String groupName = group.getName();
String message = "";
if(group.isPersonalGroup()){
message = String.format("%s, security: %s, group: %s (Default Group)", reinforcementStatus, securityLevel, groupName);
} else {
message = String.format("%s, security: %s, group: %s", reinforcementStatus, securityLevel, groupName);
}
sendMessage(player, ChatColor.GREEN, message);
} else {
sendMessage(player, ChatColor.RED, "%s, security: %s", reinforcementStatus, securityLevel);
}
}
break;
default:
// player is in reinforcement mode
if (reinforcement == null) {
// Break any natural reinforcement before placing the player reinforcement
if (generic_reinforcement != null) {
reinforcementBroken(generic_reinforcement);
}
createPlayerReinforcement(player, block);
} else if (reinforcement.isBypassable(player)) {
boolean update = false;
String message = "";
if (reinforcement.getSecurityLevel() != state.getSecurityLevel()){
reinforcement.setSecurityLevel(state.getSecurityLevel());
update = true;
message = String.format("Changed security level %s", reinforcement.getSecurityLevel().name());
}
if(!reinforcement.getOwner().equals(state.getFaction())) {
reinforcement.setOwner(state.getFaction());
update = true;
if(!message.equals("")){
message = message + ". ";
}
if(reinforcement.getSecurityLevel() != SecurityLevel.PRIVATE){
message = message + String.format("Changed group to %s", state.getFaction().getName());
}
}
if(update){
Citadel.getReinforcementManager().addReinforcement(reinforcement);
sendMessage(player, ChatColor.GREEN, message);
}
} else {
sendMessage(player, ChatColor.RED, "You are not permitted to modify this reinforcement");
}
pie.setCancelled(true);
if (state.getMode() == PlacementMode.REINFORCEMENT_SINGLE_BLOCK) {
state.reset();
} else {
state.checkResetMode();
}
}
}
catch(Exception e)
{
Citadel.printStackTrace(e);
}
}
| public void interact(PlayerInteractEvent pie) {
try {
if (!pie.hasBlock()) return;
Player player = pie.getPlayer();
Block block = pie.getClickedBlock();
AccessDelegate accessDelegate = AccessDelegate.getDelegate(block);
block = accessDelegate.getBlock();
IReinforcement generic_reinforcement = accessDelegate.getReinforcement();
PlayerReinforcement reinforcement = null;
if (generic_reinforcement instanceof PlayerReinforcement) {
reinforcement = (PlayerReinforcement)generic_reinforcement;
}
if (reinforcement != null
&& reinforcement.isSecurable()
&& !reinforcement.isAccessible(player)) {
Action action = pie.getAction();
if(action == Action.RIGHT_CLICK_BLOCK){
Citadel.info("%s failed to access locked reinforcement %s, "
+ player.getDisplayName() + " at "
+ block.getLocation().toString());
sendMessage(pie.getPlayer(), ChatColor.RED, "%s is locked", block.getType().name());
pie.setCancelled(true);
}
}
if (pie.isCancelled()) return;
PlayerState state = PlayerState.get(player);
PlacementMode placementMode = state.getMode();
switch (placementMode) {
case NORMAL:
return;
case FORTIFICATION:
return;
case INFO:
// did player click on a reinforced block?
if (reinforcement != null) {
String reinforcementStatus = reinforcement.getStatus();
SecurityLevel securityLevel = reinforcement.getSecurityLevel();
if(reinforcement.isAccessible(player)){
Faction group = reinforcement.getOwner();
String groupName = group.getName();
String message = "";
if(group.isPersonalGroup()){
message = String.format("%s, security: %s, group: %s (Default Group)", reinforcementStatus, securityLevel, groupName);
} else {
message = String.format("%s, security: %s, group: %s", reinforcementStatus, securityLevel, groupName);
}
sendMessage(player, ChatColor.GREEN, message);
} else {
sendMessage(player, ChatColor.RED, "%s, security: %s", reinforcementStatus, securityLevel);
}
}
break;
default:
// player is in reinforcement mode
if (reinforcement == null) {
// Break any natural reinforcement before placing the player reinforcement
if (generic_reinforcement != null) {
reinforcementBroken(generic_reinforcement);
}
createPlayerReinforcement(player, block);
} else if (reinforcement.isBypassable(player)) {
boolean update = false;
String message = "";
if (reinforcement.getSecurityLevel() != state.getSecurityLevel()){
reinforcement.setSecurityLevel(state.getSecurityLevel());
update = true;
message = String.format("Changed security level %s", reinforcement.getSecurityLevel().name());
}
if(!reinforcement.getOwner().equals(state.getFaction())) {
reinforcement.setOwner(state.getFaction());
update = true;
if(!message.equals("")){
message = message + ". ";
}
if(reinforcement.getSecurityLevel() != SecurityLevel.PRIVATE){
message = message + String.format("Changed group to %s", state.getFaction().getName());
}
}
if(update){
Citadel.getReinforcementManager().addReinforcement(reinforcement);
sendMessage(player, ChatColor.GREEN, message);
}
} else {
sendMessage(player, ChatColor.RED, "You are not permitted to modify this reinforcement");
}
pie.setCancelled(true);
if (state.getMode() == PlacementMode.REINFORCEMENT_SINGLE_BLOCK) {
state.reset();
} else {
state.checkResetMode();
}
}
}
catch(Exception e)
{
Citadel.printStackTrace(e);
}
}
|
diff --git a/src/uk/me/parabola/imgfmt/sys/ImgHeader.java b/src/uk/me/parabola/imgfmt/sys/ImgHeader.java
index 8adf2686..d532827e 100644
--- a/src/uk/me/parabola/imgfmt/sys/ImgHeader.java
+++ b/src/uk/me/parabola/imgfmt/sys/ImgHeader.java
@@ -1,320 +1,326 @@
/*
* Copyright (C) 2006 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* Author: Steve Ratcliffe
* Create date: 26-Nov-2006
*/
package uk.me.parabola.imgfmt.sys;
import uk.me.parabola.imgfmt.FileSystemParam;
import uk.me.parabola.imgfmt.Utils;
import uk.me.parabola.imgfmt.fs.ImgChannel;
import uk.me.parabola.log.Logger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Calendar;
import java.util.Date;
/**
* The header at the very begining of the .img filesystem. It has the
* same signature as a DOS partition table, although I don't know
* exactly how much the partition concepts are used.
*
* @author Steve Ratcliffe
*/
class ImgHeader {
private static final Logger log = Logger.getLogger(ImgHeader.class);
// Offsets into the header.
private static final int OFF_XOR = 0x0;
private static final int OFF_UPDATE_MONTH = 0xa;
private static final int OFF_UPDATE_YEAR = 0xb; // +1900 for val >= 0x63, +2000 for less
private static final int OFF_CHECKSUM = 0xf;
private static final int OFF_SIGNATURE = 0x10;
private static final int OFF_UNK_1 = 0x17;
// If this was a real boot sector these would be the meanings
private static final int OFF_SECTORS = 0x18;
private static final int OFF_HEADS = 0x1a;
private static final int OFF_CYLINDERS = 0x1c;
private static final int OFF_CREATION_YEAR = 0x39;
// private static final int OFF_CREATION_MONTH = 0x3b;
// private static final int OFF_CREATION_DAY = 0x3c;
// private static final int OFF_CREATION_HOUR = 0x3d;
// private static final int OFF_CREATION_MINUTE = 0x3e;
// private static final int OFF_CREATION_SECOND = 0x3f;
// The block number where the directory starts.
private static final int OFF_DIRECTORY_START_BLOCK = 0x40;
private static final int OFF_MAP_FILE_INTENTIFIER = 0x41;
private static final int OFF_MAP_DESCRIPTION = 0x49; // 0x20 padded
private static final int OFF_HEADS2 = 0x5d;
private static final int OFF_SECTORS2 = 0x5f;
private static final int OFF_BLOCK_SIZE_EXPONENT1 = 0x61;
private static final int OFF_BLOCK_SIZE_EXPONENT2 = 0x62;
private static final int OFF_BLOCK_SIZE = 0x63;
// private static final int OFF_UKN_3 = 0x63;
private static final int OFF_MAP_NAME_CONT = 0x65;
// 'Partition table' offsets.
private static final int OFF_START_HEAD = 0x1bf;
private static final int OFF_START_SECTOR = 0x1c0;
private static final int OFF_START_CYLINDER = 0x1c1;
private static final int OFF_SYSTEM_TYPE = 0x1c2;
private static final int OFF_END_HEAD = 0x1c3;
private static final int OFF_END_SECTOR = 0x1c4;
private static final int OFF_END_CYLINDER = 0x1c5;
private static final int OFF_REL_SECTORS = 0x1c6;
private static final int OFF_NUMBER_OF_SECTORS = 0x1ca;
private static final int OFF_PARTITION_SIG = 0x1fe;
private FileSystemParam fsParams;
private final ByteBuffer header = ByteBuffer.allocate(512);
private ImgChannel file;
private Date creationTime;
// Signatures.
private static final byte[] FILE_ID = new byte[]{
'G', 'A', 'R', 'M', 'I', 'N', '\0'};
private static final byte[] SIGNATURE = new byte[]{
'D', 'S', 'K', 'I', 'M', 'G', '\0'};
ImgHeader(ImgChannel chan) {
this.file = chan;
header.order(ByteOrder.LITTLE_ENDIAN);
}
/**
* Create a header from scratch.
* @param params File system parameters.
*/
void createHeader(FileSystemParam params) {
this.fsParams = params;
header.put(OFF_XOR, (byte) 0);
// Set the block size. 2^(E1+E2) where E1 is always 9.
int exp = 9;
int bs = params.getBlockSize();
for (int i = 0; i < 32; i++) {
bs >>>= 1;
if (bs == 0) {
exp = i;
break;
}
}
if (exp < 9)
throw new IllegalArgumentException("block size too small");
header.put(OFF_BLOCK_SIZE_EXPONENT1, (byte) 0x9);
header.put(OFF_BLOCK_SIZE_EXPONENT2, (byte) (exp - 9));
header.position(OFF_SIGNATURE);
header.put(SIGNATURE);
header.position(OFF_MAP_FILE_INTENTIFIER);
header.put(FILE_ID);
header.put(OFF_UNK_1, (byte) 0x2);
// Acutally this may not be the directory start block, I am guessing -
// always assume it is 2 anyway.
header.put(OFF_DIRECTORY_START_BLOCK, (byte) fsParams.getDirectoryStartBlock());
- // This secotors, heads, cylinders stuff is probably just 'unknown'
- int sectors = 4;
- int heads = 0x10;
- int cylinders = 0x20;
+ // This sectors, head, cylinders stuff appears to be used by mapsource
+ // and they have to be larger than the actual size of the map. It
+ // doesn't appear to have any effect on a garmin device or other software.
+ int sectors = 0x20; // 0x20 appears to be a max
+ int heads = 0x20; // 0x20 appears to be max
+ int cylinders = 0x100; // gives 128M will try more later
header.putShort(OFF_SECTORS, (short) sectors);
header.putShort(OFF_HEADS, (short) heads);
header.putShort(OFF_CYLINDERS, (short) cylinders);
header.putShort(OFF_HEADS2, (short) heads);
header.putShort(OFF_SECTORS2, (short) sectors);
header.position(OFF_CREATION_YEAR);
Utils.setCreationTime(header, creationTime);
- char blocks = (char) (heads * sectors * cylinders / (1 << exp - 9));
- header.putChar(OFF_BLOCK_SIZE, blocks);
+ // Since there are only 2 bytes here but it can easily overflow, if it
+ // does we replace it with 0xffff, it doesn't work to set it to say zero
+ int blocks = heads * sectors * cylinders / (1 << exp - 9);
+ char shortBlocks = blocks > 0xffff ? 0xffff : (char) blocks;
+ header.putChar(OFF_BLOCK_SIZE, shortBlocks);
header.put(OFF_PARTITION_SIG, (byte) 0x55);
header.put(OFF_PARTITION_SIG+1, (byte) 0xaa);
header.put(OFF_START_HEAD, (byte) 0);
header.put(OFF_START_SECTOR, (byte) 1);
header.put(OFF_START_CYLINDER, (byte) 0);
header.put(OFF_SYSTEM_TYPE, (byte) 0);
header.put(OFF_END_HEAD, (byte) (heads - 1));
header.put(OFF_END_SECTOR, (byte) sectors);
header.put(OFF_END_CYLINDER, (byte) (cylinders - 1));
header.putInt(OFF_REL_SECTORS, 0);
header.putInt(OFF_NUMBER_OF_SECTORS, (blocks * (1 << (exp - 9))));
+ log.info("number of blocks " + blocks);
setDirectoryStartBlock(params.getDirectoryStartBlock());
// Set the times.
Date date = new Date();
setCreationTime(date);
setUpdateTime(date);
setDescription(params.getMapDescription());
// Checksum is not checked.
int check = 0;
header.put(OFF_CHECKSUM, (byte) check);
}
void setHeader(ByteBuffer buf) {
buf.flip();
header.put(buf);
byte exp1 = header.get(OFF_BLOCK_SIZE_EXPONENT1);
byte exp2 = header.get(OFF_BLOCK_SIZE_EXPONENT2);
log.debug("header exponent", exp1, exp2);
fsParams = new FileSystemParam();
fsParams.setBlockSize(1 << (exp1 + exp2));
fsParams.setDirectoryStartBlock(header.get(OFF_DIRECTORY_START_BLOCK));
// ... more to do
}
void setFile(ImgChannel file) {
this.file = file;
}
FileSystemParam getParams() {
return fsParams;
}
/**
* Sync the header to disk.
* @throws IOException If an error occurs during writing.
*/
public void sync() throws IOException {
setUpdateTime(new Date());
header.rewind();
file.position(0);
file.write(header);
file.position(fsParams.getDirectoryStartBlock() * (long) 512);
}
/**
* Set the update time.
* @param date The date to use.
*/
protected void setUpdateTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
header.put(OFF_UPDATE_YEAR, toYearCode(cal.get(Calendar.YEAR)));
header.put(OFF_UPDATE_MONTH, (byte) (cal.get(Calendar.MONTH)+1));
}
/**
* Set the description. It is spread across two areas in the header.
* @param desc The description.
*/
protected void setDescription(String desc) {
header.position(OFF_MAP_DESCRIPTION);
int len = desc.length();
if (len > 50)
throw new IllegalArgumentException("Description is too long (max 50)");
String part1, part2;
if (len > 20) {
part1 = desc.substring(0, 20);
part2 = desc.substring(20, len);
} else {
part1 = desc.substring(0, len);
part2 = "";
}
header.put(toByte(part1));
for (int i = len; i < 20; i++) {
header.put((byte) ' ');
}
header.position(OFF_MAP_NAME_CONT);
header.put(toByte(part2));
int start = len - 20;
if (start < 0)
start = 0;
for (int i = start; i < 30; i++)
header.put((byte) ' ');
header.put((byte) 0);
}
/**
* Convert a string to a byte array.
* @param s The string
* @return A byte array.
*/
private byte[] toByte(String s) {
// NB: what character set should be used?
return s.getBytes();
}
/**
* Convert to the one byte code that is used for the year.
* If the year is in the 1900, then subtract 1900 and add the result to 0x63,
* else subtract 2000.
* Actually looks simpler, just subtract 1900..
* @param y The year in real-world format eg 2006.
* @return A one byte code representing the year.
*/
private byte toYearCode(int y) {
return (byte) (y - 1900);
}
public int getBlockSize() {
return fsParams.getBlockSize();
}
/**
* Set the block size. This may only work if creating the file
* from scratch.
* @param blockSize The new block size to use.
*/
public void setBlockSize(int blockSize) {
header.put(OFF_BLOCK_SIZE, (byte) blockSize);
fsParams.setBlockSize(blockSize);
}
public int getDirectoryStartBlock() {
return fsParams.getDirectoryStartBlock();
}
protected void setDirectoryStartBlock(int directoryStartBlock) {
header.put(OFF_DIRECTORY_START_BLOCK, (byte) directoryStartBlock);
fsParams.setDirectoryStartBlock(directoryStartBlock);
}
protected void setCreationTime(Date date) {
this.creationTime = date;
}
}
| false | true | void createHeader(FileSystemParam params) {
this.fsParams = params;
header.put(OFF_XOR, (byte) 0);
// Set the block size. 2^(E1+E2) where E1 is always 9.
int exp = 9;
int bs = params.getBlockSize();
for (int i = 0; i < 32; i++) {
bs >>>= 1;
if (bs == 0) {
exp = i;
break;
}
}
if (exp < 9)
throw new IllegalArgumentException("block size too small");
header.put(OFF_BLOCK_SIZE_EXPONENT1, (byte) 0x9);
header.put(OFF_BLOCK_SIZE_EXPONENT2, (byte) (exp - 9));
header.position(OFF_SIGNATURE);
header.put(SIGNATURE);
header.position(OFF_MAP_FILE_INTENTIFIER);
header.put(FILE_ID);
header.put(OFF_UNK_1, (byte) 0x2);
// Acutally this may not be the directory start block, I am guessing -
// always assume it is 2 anyway.
header.put(OFF_DIRECTORY_START_BLOCK, (byte) fsParams.getDirectoryStartBlock());
// This secotors, heads, cylinders stuff is probably just 'unknown'
int sectors = 4;
int heads = 0x10;
int cylinders = 0x20;
header.putShort(OFF_SECTORS, (short) sectors);
header.putShort(OFF_HEADS, (short) heads);
header.putShort(OFF_CYLINDERS, (short) cylinders);
header.putShort(OFF_HEADS2, (short) heads);
header.putShort(OFF_SECTORS2, (short) sectors);
header.position(OFF_CREATION_YEAR);
Utils.setCreationTime(header, creationTime);
char blocks = (char) (heads * sectors * cylinders / (1 << exp - 9));
header.putChar(OFF_BLOCK_SIZE, blocks);
header.put(OFF_PARTITION_SIG, (byte) 0x55);
header.put(OFF_PARTITION_SIG+1, (byte) 0xaa);
header.put(OFF_START_HEAD, (byte) 0);
header.put(OFF_START_SECTOR, (byte) 1);
header.put(OFF_START_CYLINDER, (byte) 0);
header.put(OFF_SYSTEM_TYPE, (byte) 0);
header.put(OFF_END_HEAD, (byte) (heads - 1));
header.put(OFF_END_SECTOR, (byte) sectors);
header.put(OFF_END_CYLINDER, (byte) (cylinders - 1));
header.putInt(OFF_REL_SECTORS, 0);
header.putInt(OFF_NUMBER_OF_SECTORS, (blocks * (1 << (exp - 9))));
setDirectoryStartBlock(params.getDirectoryStartBlock());
// Set the times.
Date date = new Date();
setCreationTime(date);
setUpdateTime(date);
setDescription(params.getMapDescription());
// Checksum is not checked.
int check = 0;
header.put(OFF_CHECKSUM, (byte) check);
}
| void createHeader(FileSystemParam params) {
this.fsParams = params;
header.put(OFF_XOR, (byte) 0);
// Set the block size. 2^(E1+E2) where E1 is always 9.
int exp = 9;
int bs = params.getBlockSize();
for (int i = 0; i < 32; i++) {
bs >>>= 1;
if (bs == 0) {
exp = i;
break;
}
}
if (exp < 9)
throw new IllegalArgumentException("block size too small");
header.put(OFF_BLOCK_SIZE_EXPONENT1, (byte) 0x9);
header.put(OFF_BLOCK_SIZE_EXPONENT2, (byte) (exp - 9));
header.position(OFF_SIGNATURE);
header.put(SIGNATURE);
header.position(OFF_MAP_FILE_INTENTIFIER);
header.put(FILE_ID);
header.put(OFF_UNK_1, (byte) 0x2);
// Acutally this may not be the directory start block, I am guessing -
// always assume it is 2 anyway.
header.put(OFF_DIRECTORY_START_BLOCK, (byte) fsParams.getDirectoryStartBlock());
// This sectors, head, cylinders stuff appears to be used by mapsource
// and they have to be larger than the actual size of the map. It
// doesn't appear to have any effect on a garmin device or other software.
int sectors = 0x20; // 0x20 appears to be a max
int heads = 0x20; // 0x20 appears to be max
int cylinders = 0x100; // gives 128M will try more later
header.putShort(OFF_SECTORS, (short) sectors);
header.putShort(OFF_HEADS, (short) heads);
header.putShort(OFF_CYLINDERS, (short) cylinders);
header.putShort(OFF_HEADS2, (short) heads);
header.putShort(OFF_SECTORS2, (short) sectors);
header.position(OFF_CREATION_YEAR);
Utils.setCreationTime(header, creationTime);
// Since there are only 2 bytes here but it can easily overflow, if it
// does we replace it with 0xffff, it doesn't work to set it to say zero
int blocks = heads * sectors * cylinders / (1 << exp - 9);
char shortBlocks = blocks > 0xffff ? 0xffff : (char) blocks;
header.putChar(OFF_BLOCK_SIZE, shortBlocks);
header.put(OFF_PARTITION_SIG, (byte) 0x55);
header.put(OFF_PARTITION_SIG+1, (byte) 0xaa);
header.put(OFF_START_HEAD, (byte) 0);
header.put(OFF_START_SECTOR, (byte) 1);
header.put(OFF_START_CYLINDER, (byte) 0);
header.put(OFF_SYSTEM_TYPE, (byte) 0);
header.put(OFF_END_HEAD, (byte) (heads - 1));
header.put(OFF_END_SECTOR, (byte) sectors);
header.put(OFF_END_CYLINDER, (byte) (cylinders - 1));
header.putInt(OFF_REL_SECTORS, 0);
header.putInt(OFF_NUMBER_OF_SECTORS, (blocks * (1 << (exp - 9))));
log.info("number of blocks " + blocks);
setDirectoryStartBlock(params.getDirectoryStartBlock());
// Set the times.
Date date = new Date();
setCreationTime(date);
setUpdateTime(date);
setDescription(params.getMapDescription());
// Checksum is not checked.
int check = 0;
header.put(OFF_CHECKSUM, (byte) check);
}
|
diff --git a/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/lexer/FXDLexer.java b/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/lexer/FXDLexer.java
index b33c0e75..8f5305fa 100644
--- a/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/lexer/FXDLexer.java
+++ b/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/lexer/FXDLexer.java
@@ -1,443 +1,443 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.javafx.fxd.composer.lexer;
import com.sun.javafx.tools.fxd.FXDObjectElement;
import com.sun.javafx.tools.fxd.FXDReference;
import com.sun.javafx.tools.fxd.container.scene.fxd.FXDException;
import com.sun.javafx.tools.fxd.container.scene.fxd.FXDParser;
import com.sun.javafx.tools.fxd.container.scene.fxd.FXDSyntaxErrorException;
import com.sun.javafx.tools.fxd.container.scene.fxd.lexer.ContentLexer;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import org.netbeans.api.lexer.Token;
import org.netbeans.spi.lexer.Lexer;
import org.netbeans.spi.lexer.LexerInput;
import org.netbeans.spi.lexer.LexerRestartInfo;
import org.netbeans.spi.lexer.TokenPropertyProvider;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
/**
*
* @author Andrew Korostelev
*/
public class FXDLexer implements Lexer<FXDTokenId> {
private static final String MSG_NOT_SUPPORTED = "MSG_NOT_SUPPORTED"; //NOI18N
private LexerRestartInfo<FXDTokenId> m_info;
private int m_tokenIdx;
private List<TokenData<FXDTokenId>> m_tokensList;
FXDLexer(LexerRestartInfo<FXDTokenId> info) {
this.m_info = info;
//buildTokensList();
}
// TODO change error handling
private void buildTokensList() {
final LexerInput input = m_info.input();
Reader reader = new LexerInputReader(input);
ContentLexerImpl contLexer = new ContentLexerImpl(m_info, m_tokensList);
FXDParser parser = null;
try {
parser = new FXDParser(reader, contLexer);
parser.parseObject();
FXDTokenId lastId = contLexer.getLastTokenId();
if (FXDTokenId.EOF != lastId) {
contLexer.parsingFinished();
}
} catch (FXDSyntaxErrorException syntaxEx) {
try {
// workaround for #183149.
// TODO: FXDSyntaxErrorException thrown by FXDReference.parse should have offset.
if (syntaxEx.getOffset() == -1 && parser != null) {
syntaxEx = new FXDSyntaxErrorException(
syntaxEx.getLocalizedMessage(), parser.getPosition());
}
contLexer.markError(syntaxEx);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
} catch (Exception ex) {
- ex.printStackTrace();
+ //ex.printStackTrace();
try {
String msg = NbBundle.getMessage(FXDLexer.class, MSG_NOT_SUPPORTED,
ex.getLocalizedMessage());
FXDSyntaxErrorException syntaxEx = new FXDSyntaxErrorException(
msg, parser.getPosition());
contLexer.markError(syntaxEx);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
}
public Token<FXDTokenId> nextToken() {
if (m_tokensList == null) {
m_tokensList = new ArrayList<TokenData<FXDTokenId>>();
buildTokensList();
}
TokenData<FXDTokenId> tData = getNextTokenData();
if (tData.id() == FXDTokenId.EOF){
m_tokenIdx = 0;
tData = null;
return null;
}
return createToken(tData);
}
private Token<FXDTokenId> createToken(TokenData<FXDTokenId> tData){
if(tData.hasProperties()){
return m_info.tokenFactory().createPropertyToken(tData.id(),
tData.length(), tData.getPropertyProvider());
}
return m_info.tokenFactory().createToken(tData.id(), tData.length());
}
private TokenData<FXDTokenId> getNextTokenData(){
return m_tokensList.get(m_tokenIdx++);
}
public void release() {
m_tokensList = null;
}
public Object state() {
return null;
}
private static class LexerInputReader extends Reader {
private final LexerInput m_input;
public LexerInputReader(LexerInput input) {
m_input = input;
}
@Override
public int read() throws IOException {
int c = m_input.read();
if (m_input.readLength() == 0){
return -1;
}
return c;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int c = m_input.read();
int read = 0;
while (c != LexerInput.EOF && m_input.readLength() < len) {
cbuf[off++] = (char) c;
read++;
c = m_input.read();
}
if (read > 0) {
return read;
} else {
return -1;
}
}
@Override
public void close() throws IOException {
}
}
private static class ContentLexerImpl implements ContentLexer {
private TreeMap<Integer, Integer> m_comments = new TreeMap<Integer, Integer>();
private TreeMap<Integer, FXDTokenId> m_commentTypes = new TreeMap<Integer, FXDTokenId>();
private FXDParser m_parser;
private int m_tokenizedLength = 0;
private LexerRestartInfo<FXDTokenId> m_info;
private List<TokenData<FXDTokenId>> m_tokensList;
public ContentLexerImpl(LexerRestartInfo<FXDTokenId> info,
List<TokenData<FXDTokenId>> tokensList) {
this.m_info = info;
this.m_tokensList = tokensList;
}
protected FXDTokenId getLastTokenId() {
TokenData<FXDTokenId> td = m_tokensList.get(m_tokensList.size() - 1);
return (td != null) ? td.id() : null;
}
public void parsingStarted(FXDParser parser) {
m_parser = parser;
}
public void parsingFinished() throws IOException, FXDException {
if (m_parser.peekClean() != 0){
String msg = "Unexpected content"; //NOI18N
markError(new FXDSyntaxErrorException(msg, m_parser.getPosition()));
} else {
markTailParsed();
}
}
private void markTailParsed() throws IOException {
char c = m_parser.peek();
while (c != 0) {
c = m_parser.fetch();
}
if (m_tokenizedLength < m_parser.getPosition()) {
addTokenData(FXDTokenId.WS, m_tokenizedLength,
m_parser.getPosition() - m_tokenizedLength);
}
addTokenData(FXDTokenId.EOF, m_parser.getPosition(), 1);
}
public void identifier(String str, int startOff) throws FXDException {
addTokenData(FXDTokenId.IDENTIFIER, startOff, str.length());
}
public void separator(char c, int offset) throws FXDException {
switch (c) {
case '{':
addTokenData(FXDTokenId.LBRACE, offset, 1);
break;
case '}':
addTokenData(FXDTokenId.RBRACE, offset, 1);
break;
case '[':
addTokenData(FXDTokenId.LBRACKET, offset, 1);
break;
case ']':
addTokenData(FXDTokenId.RBRACKET, offset, 1);
break;
case '(':
addTokenData(FXDTokenId.LPAREN, offset, 1);
break;
case ')':
addTokenData(FXDTokenId.RPAREN, offset, 1);
break;
case ',':
addTokenData(FXDTokenId.COMMA, offset, 1);
break;
case '.':
addTokenData(FXDTokenId.DOT, offset, 1);
break;
case ';':
addTokenData(FXDTokenId.SEMI, offset, 1);
break;
case ' ':
addTokenData(FXDTokenId.COMMA, offset, 1);
break;
}
}
public void attributeName(String name, int startOff, boolean isMeta) throws FXDException {
addTokenData(FXDTokenId.IDENTIFIER_ATTR, startOff, name.length());
}
public void attributeValue(String value, int droppedChars, int startOff) throws FXDException {
Object obj = m_parser.parseValue(value);
FXDTokenId id = objectToToken(obj, value);
int len = value.length();
if (id == FXDTokenId.STRING_LITERAL){
len += droppedChars;
startOff -= droppedChars;
}
addTokenData(id, startOff, len);
}
private FXDTokenId objectToToken(Object obj, String value) {
if (obj.equals(Boolean.TRUE)) {
return FXDTokenId.TRUE;
} else if (obj.equals(Boolean.FALSE)) {
return FXDTokenId.FALSE;
} else if (obj.equals(FXDObjectElement.NULL_VALUE)) {
return FXDTokenId.NULL;
} else if (obj instanceof String) {
char c = value.charAt(0);
if (c == '"') {
return FXDTokenId.STRING_LITERAL;
}
} else if (obj instanceof FXDReference) {
// TODO should nark reference in any special way?
return FXDTokenId.STRING_LITERAL;
} else if (obj instanceof Integer) {
return FXDTokenId.NUMERIC_LITERAL;
} else if (obj instanceof Long) {
return FXDTokenId.NUMERIC_LITERAL;
} else if (obj instanceof Float) {
return FXDTokenId.FLOATING_POINT_LITERAL;
}
return FXDTokenId.IDENTIFIER;
}
public void operator(char c, int offset) throws FXDException {
switch (c) {
case ':':
addTokenData(FXDTokenId.COLON, offset, 1);
break;
case '=':
addTokenData(FXDTokenId.EQ, offset, 1);
break;
}
}
public void comment(int startOff, int endOff) {
createComment(FXDTokenId.COMMENT, startOff, endOff);
}
public void lineComment(int startOff, int endOff) {
createComment(FXDTokenId.LINE_COMMENT, startOff, endOff);
}
public void error(int startOff, int endOff, FXDSyntaxErrorException syntaxEx) {
if (startOff < endOff) {
SyntaxErrorPropertyProvider provider = syntaxEx == null ? null
: new SyntaxErrorPropertyProvider(syntaxEx);
addTokenData(FXDTokenId.UNKNOWN, startOff, endOff - startOff, provider);
}
}
protected void markError(FXDSyntaxErrorException syntaxEx) throws IOException {
char c = m_parser.peek();
while (c != 0){
c = m_parser.fetch();
}
error(m_tokenizedLength, m_parser.getPosition(), syntaxEx);
addTokenData(FXDTokenId.EOF, m_tokenizedLength, 1);
}
protected TokenData<FXDTokenId> addTokenData(FXDTokenId id, int startOff, int len) {
return addTokenData(id, startOff, len, null);
}
protected TokenData<FXDTokenId> addTokenData(FXDTokenId id, int startOff, int len,
TokenPropertyProvider<FXDTokenId> propProvider) {
if (m_tokenizedLength < startOff) {
for (Iterator<Integer> i = m_comments.keySet().iterator(); i.hasNext();) {
int k = i.next();
if (k >= m_tokenizedLength && k < startOff) {
int v = m_comments.get(k);
i.remove();
addTokenData(m_commentTypes.remove(k), k, v);
} else {
break;
}
}
if (m_tokenizedLength < startOff) {
addTokenData(FXDTokenId.WS, m_tokenizedLength, startOff - m_tokenizedLength);
}
}
m_tokenizedLength += len;
TokenData<FXDTokenId> tData = new TokenData<FXDTokenId>(id, len, propProvider);
m_tokensList.add(tData);
return tData;
}
private void createComment(FXDTokenId id, int startOff, int endOff){
if (startOff == m_tokenizedLength) {
addTokenData(id, startOff, endOff - startOff);
} else {
m_comments.put(startOff, endOff - startOff);
m_commentTypes.put(startOff, id);
}
}
public boolean stopOnError() {
return false;
}
}
private static class TokenData<E> {
private E m_id;
private int m_lenght;
private TokenPropertyProvider<FXDTokenId> m_propProvider;
public TokenData(E id, int lenght) {
this(id, lenght, null);
}
public TokenData(E id, int lenght, TokenPropertyProvider<FXDTokenId> propProvider) {
assert id != null;
assert lenght > 0;
m_id = id;
m_lenght = lenght;
m_propProvider = propProvider;
}
public E id(){
return m_id;
}
public int length(){
return m_lenght;
}
public boolean hasProperties(){
return m_propProvider != null;
}
public TokenPropertyProvider<FXDTokenId> getPropertyProvider(){
return m_propProvider;
}
@Override
public String toString() {
return "TokenData<"+m_id.getClass().getSimpleName()+">[id="+m_id+",length="+m_lenght+"]";
}
}
}
| true | true | private void buildTokensList() {
final LexerInput input = m_info.input();
Reader reader = new LexerInputReader(input);
ContentLexerImpl contLexer = new ContentLexerImpl(m_info, m_tokensList);
FXDParser parser = null;
try {
parser = new FXDParser(reader, contLexer);
parser.parseObject();
FXDTokenId lastId = contLexer.getLastTokenId();
if (FXDTokenId.EOF != lastId) {
contLexer.parsingFinished();
}
} catch (FXDSyntaxErrorException syntaxEx) {
try {
// workaround for #183149.
// TODO: FXDSyntaxErrorException thrown by FXDReference.parse should have offset.
if (syntaxEx.getOffset() == -1 && parser != null) {
syntaxEx = new FXDSyntaxErrorException(
syntaxEx.getLocalizedMessage(), parser.getPosition());
}
contLexer.markError(syntaxEx);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
} catch (Exception ex) {
ex.printStackTrace();
try {
String msg = NbBundle.getMessage(FXDLexer.class, MSG_NOT_SUPPORTED,
ex.getLocalizedMessage());
FXDSyntaxErrorException syntaxEx = new FXDSyntaxErrorException(
msg, parser.getPosition());
contLexer.markError(syntaxEx);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
}
| private void buildTokensList() {
final LexerInput input = m_info.input();
Reader reader = new LexerInputReader(input);
ContentLexerImpl contLexer = new ContentLexerImpl(m_info, m_tokensList);
FXDParser parser = null;
try {
parser = new FXDParser(reader, contLexer);
parser.parseObject();
FXDTokenId lastId = contLexer.getLastTokenId();
if (FXDTokenId.EOF != lastId) {
contLexer.parsingFinished();
}
} catch (FXDSyntaxErrorException syntaxEx) {
try {
// workaround for #183149.
// TODO: FXDSyntaxErrorException thrown by FXDReference.parse should have offset.
if (syntaxEx.getOffset() == -1 && parser != null) {
syntaxEx = new FXDSyntaxErrorException(
syntaxEx.getLocalizedMessage(), parser.getPosition());
}
contLexer.markError(syntaxEx);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
} catch (Exception ex) {
//ex.printStackTrace();
try {
String msg = NbBundle.getMessage(FXDLexer.class, MSG_NOT_SUPPORTED,
ex.getLocalizedMessage());
FXDSyntaxErrorException syntaxEx = new FXDSyntaxErrorException(
msg, parser.getPosition());
contLexer.markError(syntaxEx);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
}
|
diff --git a/geotools2/geotools-src/wmsserver/src/org/geotools/wms/WMSServlet.java b/geotools2/geotools-src/wmsserver/src/org/geotools/wms/WMSServlet.java
index 6a457c082..566eaf830 100644
--- a/geotools2/geotools-src/wmsserver/src/org/geotools/wms/WMSServlet.java
+++ b/geotools2/geotools-src/wmsserver/src/org/geotools/wms/WMSServlet.java
@@ -1,1342 +1,1343 @@
/*
* Geotools2 - OpenSource mapping toolkit
* http://geotools.org
* (C) 2002, Geotools Project Managment Committee (PMC)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package org.geotools.wms;
import org.apache.commons.collections.LRUMap;
import org.geotools.feature.Feature;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.*;
import javax.servlet.http.*;
import org.geotools.feature.FeatureCollection;
import org.geotools.renderer.LegendImageGenerator;
/**
* A servlet implementation of the WMS spec. This servlet delegates the
* required call to an implementor of WMSServer. Much of the front-end logic,
* such as Exception throwing, and Feature Formatting, is handled here,
* leaving the implementation of WMSServer abstracted away from the WMS
* details as much as possible. The exception to this rule is the
* getCapabilites call, which returns the capabilities XML directly from the
* WMSServer. This may be changed later.
*/
public class WMSServlet extends HttpServlet {
// Basic service elements parameters
public static final String PARAM_VERSION = "VERSION";
public static final String PARAM_SERVICE = "SERVICE";
public static final String PARAM_REQUEST = "REQUEST";
// GetCapabilites parameters
public static final String PARAM_UPDATESEQUENCE = "UPDATESEQUENCE";
// GetMap parameters
public static final String PARAM_LAYERS = "LAYERS";
public static final String PARAM_STYLES = "STYLES";
public static final String PARAM_SRS = "SRS";
public static final String PARAM_BBOX = "BBOX";
public static final String PARAM_WIDTH = "WIDTH";
public static final String PARAM_HEIGHT = "HEIGHT";
public static final String PARAM_FORMAT = "FORMAT";
public static final String PARAM_TRANSPARENT = "TRANSPARENT";
public static final String PARAM_BGCOLOR = "BGCOLOR";
public static final String PARAM_EXCEPTIONS = "EXCEPTIONS";
public static final String PARAM_TIME = "TIME";
public static final String PARAM_ELEVATION = "ELEVATION";
// additional getLegend parameters
public static final String PARAM_SCALE = "SCALE";
public static final String PARAM_RULE = "RULE";
// cache controls
public static final String PARAM_USECACHE = "USECACHE";
public static final String PARAM_CACHESIZE = "CACHESIZE";
// GetFeatureInfo parameters
public static final String PARAM_QUERY_LAYERS = "QUERY_LAYERS";
public static final String PARAM_INFO_FORMAT = "INFO_FORMAT";
public static final String PARAM_FEATURE_COUNT = "FEATURE_COUNT";
public static final String PARAM_X = "X";
public static final String PARAM_Y = "Y";
// Default values
public static final String DEFAULT_FORMAT = "image/jpeg";
public static final String DEFAULT_FEATURE_FORMAT = "text/xml";
public static final String DEFAULT_COLOR = "#FFFFFF";
public static final String DEFAULT_EXCEPTION = "text/xml";
// Capabilities XML tags
public static final String XML_MAPFORMATS = "<?GEO MAPFORMATS ?>";
public static final String XML_GETFEATUREINFO = "<?GEO GETFEATUREINFO ?>";
public static final String XML_EXCEPTIONFORMATS = "<?GEO EXCEPTIONFORMATS ?>";
public static final String XML_VENDORSPECIFIC = "<?GEO VENDORSPECIFICCAPABILITIES ?>";
public static final String XML_LAYERS = "<?GEO LAYERS ?>";
public static final String XML_GETURL = "<?GEO GETURL ?>";
private static final int CACHE_SIZE = 20;
private static Map allMaps;
private static Map nationalMaps;// = new HashMap();
private static final Logger LOGGER = Logger.getLogger(
"org.geotools.wmsserver");
ServletContext context = null;
private WMSServer server;
private Vector featureFormatters;
private String getUrl;
private int cacheSize = CACHE_SIZE;
private String[] outputTypes;
private static String[] exceptionTypes={"application/vnd.ogc.se_xml","application/vnd.ogc.se_inimage","application/vnd.ogc.se_blank","text/xml","text/plain"};
/**
* Override init() to set up data used by invocations of this servlet.
*
* @param config DOCUMENT ME!
*
* @throws ServletException DOCUMENT ME!
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
// save servlet context
context = config.getServletContext();
// The installed featureFormatters - none is this version
featureFormatters = new Vector();
// Get the WMSServer class to be used by this servlet
try {
server = (WMSServer) Class.forName(config.getInitParameter(
"WMSServerClass")).newInstance();
// Build properties to send to the server implementation
Properties prop = new Properties();
Enumeration en = config.getInitParameterNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
prop.setProperty(key, config.getInitParameter(key));
}
//pass in the context as well
String real = getServletContext().getRealPath("");
LOGGER.fine("setting base.url to " + real);
prop.setProperty("base.url", real);
server.init(prop);
} catch (Exception exp) {
throw new ServletException("Cannot instantiate WMSServer class specified in WEB.XML",
exp);
}
// Try to load any feature formaters
try {
String formatList = config.getInitParameter("WMSFeatureFormatters");
if (formatList != null) {
StringTokenizer items = new StringTokenizer(formatList, ",");
while (items.hasMoreTokens()) {
String item = items.nextToken();
WMSFeatureFormatter format = (WMSFeatureFormatter) Class.forName(item)
.newInstance();
featureFormatters.add(format);
}
}
} catch (Exception exp) {
throw new ServletException("Cannot instantiate WMSFeatureFormater class specified in WEB.XML",
exp);
}
// set up the cache
String cachep = config.getInitParameter("cachesize");
if (cachep != null) {
try {
cacheSize = Integer.parseInt(cachep);
} catch (NumberFormatException e) {
LOGGER.warning("Bad cache size in setup: " + e);
}
}
LOGGER.info("Setting cache to " + cacheSize);
LRUMap allMapsBase = new LRUMap(cacheSize);
allMaps = Collections.synchronizedMap(allMapsBase);
LRUMap nationalMapsBase = new LRUMap(cacheSize);
nationalMaps = Collections.synchronizedMap(nationalMapsBase);
outputTypes = ImageIO.getWriterMIMETypes();
}
/**
* Basic servlet method, answers requests fromt the browser.
*
* @param request HTTPServletRequest
* @param response HTTPServletResponse
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LOGGER.fine("DoGet called from " + request.getRemoteAddr());
// Nullify caching
//What's my address?
getUrl = HttpUtils.getRequestURL(request).append("?").toString();
// Check request type
String sRequest = getParameter(request, PARAM_REQUEST);
if ((sRequest == null) || (sRequest.trim().length() == 0)) {
doException("InvalidRequest",
"Invalid REQUEST parameter sent to servlet", request, response);
return;
} else if (sRequest.trim().equalsIgnoreCase("GetCapabilities") ||
sRequest.trim().equalsIgnoreCase("capabilities")) {
doGetCapabilities(request, response);
} else if (sRequest.trim().equalsIgnoreCase("GetMap") ||
sRequest.trim().equalsIgnoreCase("Map")) {
doGetMap(request, response);
} else if (sRequest.trim().equalsIgnoreCase("GetFeatureInfo")) {
doGetFeatureInfo(request, response);
} else if (sRequest.trim().equalsIgnoreCase("GetLegendGraphic")) {
doGetLegendGraphic(request,response);
}else if (sRequest.trim().equalsIgnoreCase("ClearCache")) {
// note unpublished request to prevent users clearing the cache for fun.
clearCache();
} else if (sRequest.trim().equalsIgnoreCase("SetCache")) {
resetCache(request, response);
}
}
/**
* Gets the given parameter value, in a non case-sensitive way
*
* @param request The HttpServletRequest object to search for the parameter
* value
* @param param The parameter to get the value for
*
* @return DOCUMENT ME!
*/
private String getParameter(HttpServletRequest request, String param) {
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
if (key.trim().equalsIgnoreCase(param.trim())) {
return request.getParameter(key);
}
}
return null;
}
/**
* Returns WMS 1.1.1 compatible response for a getCapabilities request
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
public void doGetCapabilities(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
LOGGER.fine("Sending capabilities");
LOGGER.fine("My path is " + request.getServletPath() + "?");
try {
// Get Capabilities object from server implementation
Capabilities capabilities = server.getCapabilities();
// Convert the object to XML
String xml = capabilitiesToXML(capabilities);
// Send to client
response.setContentType("application/vnd.ogc.wms_xml");
PrintWriter pr = response.getWriter();
pr.print(xml);
pr.close();
} catch (WMSException wmsexp) {
doException(wmsexp.getCode(), wmsexp.getMessage(), request, response);
return;
} catch (Exception exp) {
LOGGER.severe("Unexpected exception " + exp);
exp.printStackTrace();
doException(null,
"Unknown exception : " + exp + " " + exp.getStackTrace()[0] +
" " + exp.getMessage(), request, response);
return;
}
}
/**
* Returns WMS 1.1.1 compatible response for a getMap request
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
public void doGetMap(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
LOGGER.fine("Sending Map");
BufferedImage image = null;
String exceptions = getParameter(request, PARAM_EXCEPTIONS);
String format = getParameter(request, PARAM_FORMAT);
// note this is not a published param to prevent users avoiding the cache for fun!
String nocache = getParameter(request, PARAM_USECACHE);
boolean useCache = true;
if ((nocache != null) && nocache.trim().equalsIgnoreCase("false")) {
useCache = false;
}
// if (format == null) {
// format = DEFAULT_FORMAT;
// }
// Get the requested exception mime-type (if any)
try {
// Get all the parameters for the call
String[] layers = commaSeparated(getParameter(request, PARAM_LAYERS));
String[] styles = commaSeparated(getParameter(request, PARAM_STYLES),
layers.length);
String srs = getParameter(request, PARAM_SRS);
String bbox = getParameter(request, PARAM_BBOX);
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
LOGGER.fine("Checking params");
// Check values
if ((layers == null) || (layers.length == 0)) {
doException(null, "No Layers defined", request, response,
exceptions);
return;
}
if ((styles != null) && (styles.length != layers.length)) {
doException(null,
"Invalid number of style defined for passed layers",
request, response, exceptions);
return;
}
if (srs == null) {
doException(WMSException.WMSCODE_INVALIDSRS, "SRS not defined",
request, response, exceptions);
return;
}
if (bbox == null) {
doException(null, "BBOX not defined", request, response,
exceptions);
return;
}
if ((height == -1) || (width == -1)) {
doException(null, "HEIGHT or WIDTH not defined", request,
response, exceptions);
return;
}
if (format == null) {
// we should throw an exception here I think but we'll let it go!
// instead of a default format we should try to give them the best image we can
// so check accept to see what they'll take
format=negotiateFormat(request);
}
// Check the bbox
String[] sBbox = commaSeparated(bbox, 4);
if (sBbox == null) {
doException(null, "Invalid bbox : " + bbox, request, response,
exceptions);
}
double[] dBbox = new double[4];
for (int i = 0; i < 4; i++)
dBbox[i] = doubleParam(sBbox[i]);
LOGGER.fine("Params check out - getting image");
CacheKey key = null;
if(useCache==true){
key = new CacheKey(request);
LOGGER.fine("About to request map with key = " + key +
" usecache " + useCache);
}
if ((useCache == false)||(((image = (BufferedImage) nationalMaps.get(key)) == null) &&
((image = (BufferedImage) allMaps.get(key)) == null))) {
// Get the image
image = server.getMap(layers, styles, srs, dBbox, width,
height, trans, bgcolor);
if(useCache == true){
//if requested bbox = layer bbox then cache in nationalMaps
Capabilities capabilities = server.getCapabilities();
Rectangle2D rect = null;
for (int i = 0; i < layers.length; i++) {
Capabilities.Layer l = capabilities.getLayer(layers[i]);
double[] box = l.getBbox();
if (rect == null) {
rect = new Rectangle2D.Double(box[0], box[1],
box[2] - box[0], box[3] - box[1]);
} else {
rect.add(box[0], box[1]);
rect.add(box[2], box[3]);
}
}
Rectangle2D rbbox = new Rectangle2D.Double(dBbox[0], dBbox[1],
dBbox[2] - dBbox[0], dBbox[3] - dBbox[1]);
LOGGER.fine("layers " + rect + " request " + rbbox);
if ((rbbox.getCenterX() == rect.getCenterX()) &&
(rbbox.getCenterY() == rect.getCenterY())&&useCache==true) {
LOGGER.fine("Caching a national map with key " + key);
nationalMaps.put(key, image);
} else if(useCache==true){
LOGGER.fine("all maps cache with key " + key);
allMaps.put(key, image);
}
}
LOGGER.fine("Got image - sending response as " + format + " (" +
image.getWidth(null) + "," + image.getHeight(null) + ")");
}
} catch (WMSException wmsexp) {
doException(wmsexp.getCode(), wmsexp.getMessage(), request,
response, exceptions);
return;
} catch (Exception exp) {
doException(null,
"Unknown exception : " + exp + " : " + exp.getStackTrace()[0] +
exp.getMessage(), request, response, exceptions);
return;
}
// Write the response
response.setContentType(format);
OutputStream out = response.getOutputStream();
// avoid caching in browser
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
formatImageOutputStream(format, image, out);
} catch (Exception exp) {
exp.printStackTrace();
LOGGER.severe(
"Unable to complete image generation after response started : " +
exp + exp.getMessage());
if (exp instanceof SecurityException) {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] +
" JAI may not have 'write' and 'delete' permissions in temp folder");
} else {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] + "Check JAI configuration");
}
}finally{
out.close();
image = null;
}
}
/**
* Gets an outputstream of the given image, formatted to the given mime
* format
*
* @param format The mime-type of the format for the image (image/jpeg)
* @param image The image to be formatted
* @param outStream OutputStream of the formatted image
*
* @throws WMSException DOCUMENT ME!
*/
public void formatImageOutputStream(String format, BufferedImage image,
OutputStream outStream) throws Exception {
if (format.equalsIgnoreCase("jpeg")) {
format = "image/jpeg";
}
Iterator it = ImageIO.getImageWritersByMIMEType(format);
if (!it.hasNext()) {
throw new WMSException(WMSException.WMSCODE_INVALIDFORMAT,
"Format not supported: " + format);
}
ImageWriter writer = (ImageWriter) it.next();
ImageOutputStream ioutstream = null;
ioutstream = ImageIO.createImageOutputStream(outStream);
writer.setOutput(ioutstream);
writer.write(image);
writer.dispose();
ioutstream.close();
}
/**
* Returns WMS 1.1.1 compatible response for a getFeatureInfo request
* Currently, this returns an exception, as this servlet does not support
* getFeatureInfo
*
* @param request DOCUMENT ME!
* @param response DOCUMENT ME!
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
public void doGetFeatureInfo(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Get the requested exception mime-type (if any)
String exceptions = getParameter(request, PARAM_EXCEPTIONS);
try {
// Get parameters
String[] layers = commaSeparated(getParameter(request,
PARAM_QUERY_LAYERS));
String srs = getParameter(request, PARAM_SRS);
String bbox = getParameter(request, PARAM_BBOX);
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
String format = getParameter(request, PARAM_INFO_FORMAT);
int featureCount = posIntParam(getParameter(request,
PARAM_FEATURE_COUNT));
int x = posIntParam(getParameter(request, PARAM_X));
int y = posIntParam(getParameter(request, PARAM_Y));
// Check values
if ((layers == null) || (layers.length == 0)) {
doException(null, "No Layers defined", request, response,
exceptions);
return;
}
if (srs == null) {
doException(WMSException.WMSCODE_INVALIDSRS, "SRS not defined",
request, response, exceptions);
return;
}
if (bbox == null) {
doException(null, "BBOX not defined", request, response,
exceptions);
return;
}
if ((height == -1) || (width == -1)) {
doException(null, "HEIGHT or WIDTH not defined", request,
response, exceptions);
return;
}
// Check the bbox
String[] sBbox = commaSeparated(bbox, 4);
if (sBbox == null) {
doException(null, "Invalid bbox : " + bbox, request, response,
exceptions);
}
double[] dBbox = new double[4];
for (int i = 0; i < 4; i++)
dBbox[i] = doubleParam(sBbox[i]);
// Check the feature count
if (featureCount < 1) {
featureCount = 1;
}
if ((x < 0) || (y < 0)) {
doException(null, "Invalid X or Y parameter", request,
response, exceptions);
return;
}
// Check the feature format
if ((format == null) || (format.trim().length() == 0)) {
format = DEFAULT_FEATURE_FORMAT;
}
// Get features
FeatureCollection features = server.getFeatureInfo(layers, srs, dBbox,
width, height, featureCount, x, y);
// Get featureFormatter with the requested mime-type
WMSFeatureFormatter formatter = getFeatureFormatter(format);
// return Features
response.setContentType(formatter.getMimeType());
OutputStream out = response.getOutputStream();
formatter.formatFeatures(features, out);
try {
out.close();
} catch (IOException ioexp) {
}
} catch (WMSException wmsexp) {
doException(wmsexp.getCode(), wmsexp.getMessage(), request,
response, exceptions);
} catch (Exception exp) {
doException(null, "Unknown exception : " + exp.getMessage(),
request, response, exceptions);
}
}
public void doGetLegendGraphic(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
BufferedImage image = null;
String exceptions = getParameter(request, PARAM_EXCEPTIONS);
String format = getParameter(request, PARAM_FORMAT);
String[] layers = commaSeparated(getParameter(request, PARAM_LAYERS));
String[] styles = commaSeparated(getParameter(request, PARAM_STYLES),
layers.length);
double scale = doubleParam(getParameter(request,PARAM_SCALE));
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
if(format==null || format.equals("")){
format=negotiateFormat(request);
}
if(scale == Double.NaN){
scale=1;
}
try{
image=server.getLegend(layers,styles,width,height,trans,bgcolor,scale);
} catch (WMSException wmsexp) {
doException(wmsexp.getCode(), wmsexp.getMessage(), request,
response, exceptions);
return;
} catch (Exception exp) {
doException(null,
"Unknown exception : " + exp + " : " + exp.getStackTrace()[0] +
exp.getMessage(), request, response, exceptions);
return;
}
// Write the response
response.setContentType(format);
OutputStream out = response.getOutputStream();
// avoid caching in browser
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
formatImageOutputStream(format, image, out);
} catch (Exception exp) {
exp.printStackTrace();
LOGGER.severe(
"Unable to complete image generation after response started : " +
exp + exp.getMessage());
if (exp instanceof SecurityException) {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] +
" JAI may not have 'write' and 'delete' permissions in temp folder");
} else {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] + "Check JAI configuration");
}
}//finally{
// out.close();
// image = null;
// }
}
private WMSFeatureFormatter getFeatureFormatter(String mime)
throws WMSException {
for (int i = 0; i < featureFormatters.size(); i++)
if (((WMSFeatureFormatter) featureFormatters.elementAt(i)).getMimeType()
.equalsIgnoreCase(mime)) {
return (WMSFeatureFormatter) featureFormatters.elementAt(i);
}
throw new WMSException(WMSException.WMSCODE_INVALIDFORMAT,
"Invalid Feature Format " + mime);
}
/**
* Returns WMS 1.1.1 compatible Exception
*
* @param sCode The WMS 1.1.1 exception code
* @param sException The detailed exception message
* @param request The ServletRequest object for the current request
* @param response The ServletResponse object for the current request
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*
* @see WMSException
*/
public void doException(String sCode, String sException,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doException(sCode, sException, request, response, DEFAULT_EXCEPTION);
}
/**
* Returns WMS 1.1.1 compatible Exception
*
* @param sCode The WMS 1.1.1 exception code
* @param sException The detailed exception message
* @param request The ServletRequest object for the current request
* @param response The ServletResponse object for the current request
* @param exp_type The mime-type for the exception to be returned as
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*
* @see WMSException
*/
public void doException(String sCode, String sException,
HttpServletRequest request, HttpServletResponse response,
String exp_type) throws ServletException, IOException {
// Send to client
if ((exp_type == null) || (exp_type.trim().length() == 0)) {
exp_type = DEFAULT_EXCEPTION;
}
LOGGER.severe("Its all gone wrong! " + sException);
// *********************************************************************************************
// * NOTE if you add a new exception type then you *must* add it to exceptionTypes for it to be
// * advertised in the capabilities document.
// *********************************************************************************************
// Check the optional response code (mime-type of exception)
if (exp_type.equalsIgnoreCase("application/vnd.ogc.se_xml") || exp_type.equalsIgnoreCase("text/xml")) {
response.setContentType("text/xml"); // otherwise the browser probably won't know what we'return talking about
PrintWriter pw = response.getWriter();
outputXMLException(sCode, sException, pw);
} else if (exp_type.equalsIgnoreCase("text/plain")) {
response.setContentType(exp_type);
PrintWriter pw = response.getWriter();
pw.println("Exception : Code="+sCode);
pw.println(sException);
} else if(exp_type.equalsIgnoreCase("application/vnd.ogc.se_inimage")||
exp_type.equalsIgnoreCase("application/vnd.ogc.se_blank")){
String format = getParameter(request, PARAM_FORMAT);
if(format==null) {
format=negotiateFormat(request);
}
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
LOGGER.fine("Creating image "+width+"x"+height);
LOGGER.fine("BGCOlor = "+bgcolor+" transparency "+trans);
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setBackground(bgcolor);
Color fgcolor = Color.black;
if(Color.black.equals(bgcolor)){
fgcolor = Color.white;
}else{
fgcolor = Color.black;
}
if (!trans) {
g.setPaint(bgcolor);
g.fillRect(0, 0, width, height);
}
g.setPaint(fgcolor);
if(exp_type.equalsIgnoreCase("application/vnd.ogc.se_inimage")){
LOGGER.fine("Writing to image");
LOGGER.fine("Background color "+g.getBackground()+" forground "+g.getPaint());
g.drawString("Exception : Code="+sCode,10,20);
g.drawString(sException,10,40);
}
response.setContentType(format);
OutputStream out = response.getOutputStream();
// avoid caching in browser
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
formatImageOutputStream(format, image, out);
} catch (Exception exp) {
exp.printStackTrace();
LOGGER.severe(
"Unable to complete image generation after response started : " +
exp + exp.getMessage());
if (exp instanceof SecurityException) {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] +
" JAI may not have 'write' and 'delete' permissions in temp folder");
} else {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] + "Check JAI configuration");
}
}finally{
out.close();
image = null;
}
} else {
LOGGER.severe("Unknow exception format "+exp_type);
}
}
/**
* returns an xml encoded error message to the client
*
* @param sCode the service exception code (can be null)
* @param sException the exception message
* @param pw the printwriter to send to
*/
protected void outputXMLException(final String sCode, final String sException,
final PrintWriter pw) {
// Write header
pw.println(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>");
pw.println(
"<!DOCTYPE ServiceExceptionReport SYSTEM \"http://www.digitalearth.gov/wmt/xml/exception_1_1_0.dtd\"> ");
pw.println("<ServiceExceptionReport version=\"1.1.0\">");
// Write exception code
pw.println(" <ServiceException" +
((sCode != null) ? (" code=\"" + sCode + "\"") : "") + ">" +
sException + "</ServiceException>");
// Write footer
pw.println(" </ServiceExceptionReport>");
pw.close();
}
/**
* Converts this object into a WMS 1.1.1 compliant Capabilities XML string.
*
* @param cap DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String capabilitiesToXML(Capabilities cap) {
String home = getServletContext().getRealPath("");
URL base;
URL url;
try {
base = new File(home).toURL();
LOGGER.fine("base set to " + base);
url = new URL(base, "capabilities.xml");
InputStream is = url.openStream();
LOGGER.fine("input stream " + is + " from url " + url);
StringBuffer xml = new StringBuffer();
int length = 0;
byte[] b = new byte[100];
while ((length = is.read(b)) != -1)
xml.append(new String(b, 0, length));
// address of this service
String resource =
"<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" " +
"xlink:href=\"" + getUrl + "\"/>";
xml.replace(xml.toString().indexOf(XML_GETURL),
xml.toString().indexOf(XML_GETURL) + XML_GETURL.length(),
resource);
// Map formats
String mapFormats = "";
for (int i = 0; i < outputTypes.length; i++) {
mapFormats += ("\t<Format>" + outputTypes[i] + "</Format>\n");
}
xml.replace(xml.toString().indexOf(XML_MAPFORMATS),
xml.toString().indexOf(XML_MAPFORMATS) +
XML_MAPFORMATS.length(), mapFormats);
// GetFeatureInfo
String getFeatureInfo = "";
LOGGER.fine("supports FI? " + cap.getSupportsGetFeatureInfo());
if (cap.getSupportsGetFeatureInfo()) {
getFeatureInfo += "<GetFeatureInfo>\n";
for (int i = 0; i < featureFormatters.size(); i++) {
getFeatureInfo += ("<Format>" +
((WMSFeatureFormatter) featureFormatters.elementAt(i)).getMimeType() +
"</Format>\n");
}
getFeatureInfo += "<DCPType><HTTP><Get>\n";
getFeatureInfo += ("<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" " +
"xlink:href=\"" + getUrl + "\"/>\n");
getFeatureInfo += "</Get></HTTP></DCPType>\n";
getFeatureInfo += "</GetFeatureInfo>\n";
LOGGER.fine("feature info support = " + getFeatureInfo);
}
xml.replace(xml.toString().indexOf(XML_GETFEATUREINFO),
xml.toString().indexOf(XML_GETFEATUREINFO) +
XML_GETFEATUREINFO.length(), getFeatureInfo);
// Exception formats
String exceptionFormats = "";
for (int i = 0; i < exceptionTypes.length; i++) {
exceptionFormats += ("\t<Format>" + exceptionTypes[i] + "</Format>\n");
}
// -No more exception formats at this time
xml.replace(xml.toString().indexOf(XML_EXCEPTIONFORMATS),
xml.toString().indexOf(XML_EXCEPTIONFORMATS) +
XML_EXCEPTIONFORMATS.length(), exceptionFormats);
// Vendor specific capabilities
String vendorSpecific = "";
if (cap.getVendorSpecificCapabilitiesXML() != null) {
vendorSpecific = cap.getVendorSpecificCapabilitiesXML();
}
xml.replace(xml.toString().indexOf(XML_VENDORSPECIFIC),
xml.toString().indexOf(XML_VENDORSPECIFIC) +
XML_VENDORSPECIFIC.length(), vendorSpecific);
// Layers
String layerStr = "<Layer>\n<Name>Experimental Web Map Server</Name>\n";
layerStr += "<Title>GeoTools2 web map server</Title>";
layerStr += "<SRS>EPSG:27700</SRS><SRS>EPSG:4326</SRS>\n";
layerStr += "<LatLonBoundingBox minx=\"-1\" miny=\"-1\" maxx=\"-1\" maxy=\"-1\" />\n";
layerStr += "<BoundingBox SRS=\"EPSG:4326\" minx=\"-1\" miny=\"-1\" maxx=\"-1\" maxy=\"-1\" />\n";
Enumeration en = cap.layers.elements();
while (en.hasMoreElements()) {
Capabilities.Layer l = (Capabilities.Layer) en.nextElement();
// Layer properties
layerStr += layersToXml(l, 1);
}
layerStr += "</Layer>";
xml.replace(xml.toString().indexOf(XML_LAYERS),
xml.toString().indexOf(XML_LAYERS) + XML_LAYERS.length(),
layerStr);
return xml.toString();
} catch (IOException ioexp) {
return null;
}
}
/**
* add layer to the capabilites xml
*
* @param root DOCUMENT ME!
* @param tabIndex DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @task TODO: Support LegendUrl which requires additional format and size
* information.
* @task HACK: queryable is fixed to true for the moment, needs to be set
* as required
*/
private String layersToXml(Capabilities.Layer root, int tabIndex) {
String tab = "\t";
for (int t = 0; t < tabIndex; t++)
tab += "\t";
StringBuffer xml = new StringBuffer(tab + "<Layer queryable=\"1\">\n");
// Tab in a little
if (root.name != null) {
xml.append(tab + "<Name>" + root.name + "</Name>\n");
}
xml.append(tab + "<Title>" + root.title + "</Title>\n");
xml.append(tab + "<Abstract></Abstract>\n");
xml.append(tab + "<LatLonBoundingBox minx=\"" + root.bbox[0] +
"\" miny=\"" + root.bbox[1] + "\" maxx=\"" + root.bbox[2] +
"\" maxy=\"" + root.bbox[3] + "\" />\n");
if (root.srs != null) {
xml.append(tab + "<SRS>" + root.srs + "</SRS>\n");
}
// Styles
if (root.styles != null) {
Enumeration styles = root.styles.elements();
while (styles.hasMoreElements()) {
Capabilities.Style s = (Capabilities.Style) styles.nextElement();
xml.append(tab + "<Style>\n");
xml.append(tab + "<Name>" + s.name + "</Name>\n");
xml.append(tab + "<Title>" + s.title + "</Title>\n");
//xml += tab+"<LegendUrl>"+s.legendUrl+"</LegenUrl>\n";
xml.append(tab + "</Style>\n");
}
}
// Recurse child nodes
for (int i = 0; i < root.layers.size(); i++) {
Capabilities.Layer l = (Capabilities.Layer) root.layers.elementAt(i);
xml.append(layersToXml(l, tabIndex + 1));
}
xml.append(tab + "</Layer>\n");
return xml.toString();
}
/**
* Parse a given comma-separated parameter string and return the values it
* contains
*
* @param paramStr DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String[] commaSeparated(String paramStr) {
if (paramStr == null) {
return new String[0];
}
StringTokenizer st = new StringTokenizer(paramStr, ",");
String[] params = new String[st.countTokens()];
int index = 0;
while (st.hasMoreTokens()) {
params[index] = st.nextToken();
index++;
}
return params;
}
/**
* Parse a given comma-separated parameter string and return the values it
* contains - must contain the number of values in numParams
*
* @param paramStr DOCUMENT ME!
* @param numParams DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String[] commaSeparated(String paramStr, int numParams) {
String[] params = commaSeparated(paramStr);
if ((params == null) || (params.length != numParams)) {
return null;
}
return params;
}
/**
* Parses a positive integer parameter into an integer
*
* @param param DOCUMENT ME!
*
* @return The positive integer value of param. -1 if the parameter was
* invalid, or less then 0.
*/
private int posIntParam(String param) {
try {
int val = Integer.parseInt(param);
if (val < 0) {
return -1;
}
return val;
} catch (NumberFormatException nfexp) {
return -1;
}
}
/**
* Parses a parameter into a double
*
* @param param DOCUMENT ME!
*
* @return a valid double value, NaN if param is invalid
*/
private double doubleParam(String param) {
+ if(param==null||param.trim()=="") return Double.NaN;
try {
double val = Double.parseDouble(param);
return val;
} catch (NumberFormatException nfexp) {
return Double.NaN;
}
}
/**
* Parses a parameter into a boolean value
*
* @param param DOCUMENT ME!
*
* @return true if param equals "true", "t", "1", "yes" - not
* case-sensitive.
*/
private boolean boolParam(String param) {
if (param == null) {
return false;
}
if (param.equalsIgnoreCase("true") || param.equalsIgnoreCase("t") ||
param.equalsIgnoreCase("1") || param.equalsIgnoreCase("yes")) {
return true;
}
return false;
}
/**
* Parses a color value of the form "#FFFFFF", defaults to white;
*
* @param color DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private Color colorParam(String color) {
if (color == null) {
return colorParam(DEFAULT_COLOR);
}
// Parse the string
color = color.replace('#', ' ');
color = color.replaceAll("0x", ""); // incase they passed in 0XFFFFFF instead like cubewerx do
try {
LOGGER.finest("decoding " + color);
return new Color(Integer.parseInt(color.trim(), 16));
} catch (NumberFormatException nfexp) {
LOGGER.severe("Cannot decode " + color + ", using default bgcolor");
return colorParam(DEFAULT_COLOR);
}
}
private void clearCache() {
LRUMap allMapsBase = new LRUMap(cacheSize);
allMaps = Collections.synchronizedMap(allMapsBase);
LRUMap nationalMapsBase = new LRUMap(cacheSize);
nationalMaps = Collections.synchronizedMap(nationalMapsBase);
}
private void resetCache(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int size = posIntParam(getParameter(request, PARAM_CACHESIZE));
cacheSize = size;
LOGGER.info("Setting cacheSize to " + size);
clearCache();
}
/**
* a Key for wms requests which ignores case and ordering of layers, styles
* parameters etc.
*/
class CacheKey {
int key;
/**
* construct a probably unique key for this wms request
*
* @param request the WMS request
*/
CacheKey(HttpServletRequest request) {
String tmp = getParameter(request, PARAM_LAYERS);
LOGGER.finest("layer string " + tmp);
String[] layers = commaSeparated(tmp);
String srs = getParameter(request, PARAM_SRS);
String bbox = getParameter(request, PARAM_BBOX);
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
String[] styles = commaSeparated(getParameter(request, PARAM_STYLES),
layers.length);
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
// Check values
if ((layers == null) || (layers.length == 0)) {
LOGGER.severe("No Layers defined");
return;
}
if ((styles != null) && (styles.length != layers.length)) {
LOGGER.severe(
"Invalid number of styles defined for passed layers");
return;
}
key = 0;
for (int i = 0; i < layers.length; i++) {
key += layers[i].toLowerCase().hashCode();
LOGGER.finest("layer " + layers[i] + " key = " + key);
if ((styles != null) && (i < styles.length)) {
key += styles[i].toLowerCase().hashCode();
LOGGER.finest("style " + styles[i] + " key = " + key);
}
}
key *= 37;
LOGGER.finest("key = " + key);
key += (bgcolor.hashCode() * 37);
LOGGER.finest("color " + bgcolor + " key = " + key);
key += (srs.hashCode() * 37);
LOGGER.finest("srs " + srs + " key = " + key);
key += (bbox.hashCode() * 37);
LOGGER.finest("bbox " + bbox + " key = " + key);
key += (((width * 37) + height) * 37);
LOGGER.fine("Key = " + key);
}
/**
* return the hashcode of this key
*
* @return the key value
*/
public int hashCode() {
return key;
}
/**
* checks if this key is equal to the object passed in
*
* @param k - Object to test for equality
*
* @return true if k equals this object, false if not
*/
public boolean equals(Object k) {
if (k == null) {
return false;
}
if (this.getClass() != k.getClass()) {
return false;
}
if (((CacheKey) k).key != key) {
return false;
}
return true;
}
/**
* converts the key to a string
*
* @return the string representation of the key
*/
public String toString() {
return "" + key;
}
}
private String negotiateFormat(HttpServletRequest request){
String format=DEFAULT_FORMAT;
String accept = request.getHeader("Accept");
if(LOGGER.getLevel()==Level.FINE){
LOGGER.fine("browser accepts: " + accept);
LOGGER.fine("JAI supports: ");
for(int i=0;i<outputTypes.length;i++){
LOGGER.fine("\t"+outputTypes[i]);
}
}
// now we need to find the best overlap between these two lists;
if(accept !=null){
for(int i=0;i<outputTypes.length;i++){
if (accept.indexOf(outputTypes[i]) != -1) {
format = outputTypes[i];
break;
}
}
}
return format;
}
}
| true | true | public void doGetLegendGraphic(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
BufferedImage image = null;
String exceptions = getParameter(request, PARAM_EXCEPTIONS);
String format = getParameter(request, PARAM_FORMAT);
String[] layers = commaSeparated(getParameter(request, PARAM_LAYERS));
String[] styles = commaSeparated(getParameter(request, PARAM_STYLES),
layers.length);
double scale = doubleParam(getParameter(request,PARAM_SCALE));
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
if(format==null || format.equals("")){
format=negotiateFormat(request);
}
if(scale == Double.NaN){
scale=1;
}
try{
image=server.getLegend(layers,styles,width,height,trans,bgcolor,scale);
} catch (WMSException wmsexp) {
doException(wmsexp.getCode(), wmsexp.getMessage(), request,
response, exceptions);
return;
} catch (Exception exp) {
doException(null,
"Unknown exception : " + exp + " : " + exp.getStackTrace()[0] +
exp.getMessage(), request, response, exceptions);
return;
}
// Write the response
response.setContentType(format);
OutputStream out = response.getOutputStream();
// avoid caching in browser
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
formatImageOutputStream(format, image, out);
} catch (Exception exp) {
exp.printStackTrace();
LOGGER.severe(
"Unable to complete image generation after response started : " +
exp + exp.getMessage());
if (exp instanceof SecurityException) {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] +
" JAI may not have 'write' and 'delete' permissions in temp folder");
} else {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] + "Check JAI configuration");
}
}//finally{
// out.close();
// image = null;
// }
}
private WMSFeatureFormatter getFeatureFormatter(String mime)
throws WMSException {
for (int i = 0; i < featureFormatters.size(); i++)
if (((WMSFeatureFormatter) featureFormatters.elementAt(i)).getMimeType()
.equalsIgnoreCase(mime)) {
return (WMSFeatureFormatter) featureFormatters.elementAt(i);
}
throw new WMSException(WMSException.WMSCODE_INVALIDFORMAT,
"Invalid Feature Format " + mime);
}
/**
* Returns WMS 1.1.1 compatible Exception
*
* @param sCode The WMS 1.1.1 exception code
* @param sException The detailed exception message
* @param request The ServletRequest object for the current request
* @param response The ServletResponse object for the current request
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*
* @see WMSException
*/
public void doException(String sCode, String sException,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doException(sCode, sException, request, response, DEFAULT_EXCEPTION);
}
/**
* Returns WMS 1.1.1 compatible Exception
*
* @param sCode The WMS 1.1.1 exception code
* @param sException The detailed exception message
* @param request The ServletRequest object for the current request
* @param response The ServletResponse object for the current request
* @param exp_type The mime-type for the exception to be returned as
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*
* @see WMSException
*/
public void doException(String sCode, String sException,
HttpServletRequest request, HttpServletResponse response,
String exp_type) throws ServletException, IOException {
// Send to client
if ((exp_type == null) || (exp_type.trim().length() == 0)) {
exp_type = DEFAULT_EXCEPTION;
}
LOGGER.severe("Its all gone wrong! " + sException);
// *********************************************************************************************
// * NOTE if you add a new exception type then you *must* add it to exceptionTypes for it to be
// * advertised in the capabilities document.
// *********************************************************************************************
// Check the optional response code (mime-type of exception)
if (exp_type.equalsIgnoreCase("application/vnd.ogc.se_xml") || exp_type.equalsIgnoreCase("text/xml")) {
response.setContentType("text/xml"); // otherwise the browser probably won't know what we'return talking about
PrintWriter pw = response.getWriter();
outputXMLException(sCode, sException, pw);
} else if (exp_type.equalsIgnoreCase("text/plain")) {
response.setContentType(exp_type);
PrintWriter pw = response.getWriter();
pw.println("Exception : Code="+sCode);
pw.println(sException);
} else if(exp_type.equalsIgnoreCase("application/vnd.ogc.se_inimage")||
exp_type.equalsIgnoreCase("application/vnd.ogc.se_blank")){
String format = getParameter(request, PARAM_FORMAT);
if(format==null) {
format=negotiateFormat(request);
}
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
LOGGER.fine("Creating image "+width+"x"+height);
LOGGER.fine("BGCOlor = "+bgcolor+" transparency "+trans);
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setBackground(bgcolor);
Color fgcolor = Color.black;
if(Color.black.equals(bgcolor)){
fgcolor = Color.white;
}else{
fgcolor = Color.black;
}
if (!trans) {
g.setPaint(bgcolor);
g.fillRect(0, 0, width, height);
}
g.setPaint(fgcolor);
if(exp_type.equalsIgnoreCase("application/vnd.ogc.se_inimage")){
LOGGER.fine("Writing to image");
LOGGER.fine("Background color "+g.getBackground()+" forground "+g.getPaint());
g.drawString("Exception : Code="+sCode,10,20);
g.drawString(sException,10,40);
}
response.setContentType(format);
OutputStream out = response.getOutputStream();
// avoid caching in browser
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
formatImageOutputStream(format, image, out);
} catch (Exception exp) {
exp.printStackTrace();
LOGGER.severe(
"Unable to complete image generation after response started : " +
exp + exp.getMessage());
if (exp instanceof SecurityException) {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] +
" JAI may not have 'write' and 'delete' permissions in temp folder");
} else {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] + "Check JAI configuration");
}
}finally{
out.close();
image = null;
}
} else {
LOGGER.severe("Unknow exception format "+exp_type);
}
}
/**
* returns an xml encoded error message to the client
*
* @param sCode the service exception code (can be null)
* @param sException the exception message
* @param pw the printwriter to send to
*/
protected void outputXMLException(final String sCode, final String sException,
final PrintWriter pw) {
// Write header
pw.println(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>");
pw.println(
"<!DOCTYPE ServiceExceptionReport SYSTEM \"http://www.digitalearth.gov/wmt/xml/exception_1_1_0.dtd\"> ");
pw.println("<ServiceExceptionReport version=\"1.1.0\">");
// Write exception code
pw.println(" <ServiceException" +
((sCode != null) ? (" code=\"" + sCode + "\"") : "") + ">" +
sException + "</ServiceException>");
// Write footer
pw.println(" </ServiceExceptionReport>");
pw.close();
}
/**
* Converts this object into a WMS 1.1.1 compliant Capabilities XML string.
*
* @param cap DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String capabilitiesToXML(Capabilities cap) {
String home = getServletContext().getRealPath("");
URL base;
URL url;
try {
base = new File(home).toURL();
LOGGER.fine("base set to " + base);
url = new URL(base, "capabilities.xml");
InputStream is = url.openStream();
LOGGER.fine("input stream " + is + " from url " + url);
StringBuffer xml = new StringBuffer();
int length = 0;
byte[] b = new byte[100];
while ((length = is.read(b)) != -1)
xml.append(new String(b, 0, length));
// address of this service
String resource =
"<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" " +
"xlink:href=\"" + getUrl + "\"/>";
xml.replace(xml.toString().indexOf(XML_GETURL),
xml.toString().indexOf(XML_GETURL) + XML_GETURL.length(),
resource);
// Map formats
String mapFormats = "";
for (int i = 0; i < outputTypes.length; i++) {
mapFormats += ("\t<Format>" + outputTypes[i] + "</Format>\n");
}
xml.replace(xml.toString().indexOf(XML_MAPFORMATS),
xml.toString().indexOf(XML_MAPFORMATS) +
XML_MAPFORMATS.length(), mapFormats);
// GetFeatureInfo
String getFeatureInfo = "";
LOGGER.fine("supports FI? " + cap.getSupportsGetFeatureInfo());
if (cap.getSupportsGetFeatureInfo()) {
getFeatureInfo += "<GetFeatureInfo>\n";
for (int i = 0; i < featureFormatters.size(); i++) {
getFeatureInfo += ("<Format>" +
((WMSFeatureFormatter) featureFormatters.elementAt(i)).getMimeType() +
"</Format>\n");
}
getFeatureInfo += "<DCPType><HTTP><Get>\n";
getFeatureInfo += ("<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" " +
"xlink:href=\"" + getUrl + "\"/>\n");
getFeatureInfo += "</Get></HTTP></DCPType>\n";
getFeatureInfo += "</GetFeatureInfo>\n";
LOGGER.fine("feature info support = " + getFeatureInfo);
}
xml.replace(xml.toString().indexOf(XML_GETFEATUREINFO),
xml.toString().indexOf(XML_GETFEATUREINFO) +
XML_GETFEATUREINFO.length(), getFeatureInfo);
// Exception formats
String exceptionFormats = "";
for (int i = 0; i < exceptionTypes.length; i++) {
exceptionFormats += ("\t<Format>" + exceptionTypes[i] + "</Format>\n");
}
// -No more exception formats at this time
xml.replace(xml.toString().indexOf(XML_EXCEPTIONFORMATS),
xml.toString().indexOf(XML_EXCEPTIONFORMATS) +
XML_EXCEPTIONFORMATS.length(), exceptionFormats);
// Vendor specific capabilities
String vendorSpecific = "";
if (cap.getVendorSpecificCapabilitiesXML() != null) {
vendorSpecific = cap.getVendorSpecificCapabilitiesXML();
}
xml.replace(xml.toString().indexOf(XML_VENDORSPECIFIC),
xml.toString().indexOf(XML_VENDORSPECIFIC) +
XML_VENDORSPECIFIC.length(), vendorSpecific);
// Layers
String layerStr = "<Layer>\n<Name>Experimental Web Map Server</Name>\n";
layerStr += "<Title>GeoTools2 web map server</Title>";
layerStr += "<SRS>EPSG:27700</SRS><SRS>EPSG:4326</SRS>\n";
layerStr += "<LatLonBoundingBox minx=\"-1\" miny=\"-1\" maxx=\"-1\" maxy=\"-1\" />\n";
layerStr += "<BoundingBox SRS=\"EPSG:4326\" minx=\"-1\" miny=\"-1\" maxx=\"-1\" maxy=\"-1\" />\n";
Enumeration en = cap.layers.elements();
while (en.hasMoreElements()) {
Capabilities.Layer l = (Capabilities.Layer) en.nextElement();
// Layer properties
layerStr += layersToXml(l, 1);
}
layerStr += "</Layer>";
xml.replace(xml.toString().indexOf(XML_LAYERS),
xml.toString().indexOf(XML_LAYERS) + XML_LAYERS.length(),
layerStr);
return xml.toString();
} catch (IOException ioexp) {
return null;
}
}
/**
* add layer to the capabilites xml
*
* @param root DOCUMENT ME!
* @param tabIndex DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @task TODO: Support LegendUrl which requires additional format and size
* information.
* @task HACK: queryable is fixed to true for the moment, needs to be set
* as required
*/
private String layersToXml(Capabilities.Layer root, int tabIndex) {
String tab = "\t";
for (int t = 0; t < tabIndex; t++)
tab += "\t";
StringBuffer xml = new StringBuffer(tab + "<Layer queryable=\"1\">\n");
// Tab in a little
if (root.name != null) {
xml.append(tab + "<Name>" + root.name + "</Name>\n");
}
xml.append(tab + "<Title>" + root.title + "</Title>\n");
xml.append(tab + "<Abstract></Abstract>\n");
xml.append(tab + "<LatLonBoundingBox minx=\"" + root.bbox[0] +
"\" miny=\"" + root.bbox[1] + "\" maxx=\"" + root.bbox[2] +
"\" maxy=\"" + root.bbox[3] + "\" />\n");
if (root.srs != null) {
xml.append(tab + "<SRS>" + root.srs + "</SRS>\n");
}
// Styles
if (root.styles != null) {
Enumeration styles = root.styles.elements();
while (styles.hasMoreElements()) {
Capabilities.Style s = (Capabilities.Style) styles.nextElement();
xml.append(tab + "<Style>\n");
xml.append(tab + "<Name>" + s.name + "</Name>\n");
xml.append(tab + "<Title>" + s.title + "</Title>\n");
//xml += tab+"<LegendUrl>"+s.legendUrl+"</LegenUrl>\n";
xml.append(tab + "</Style>\n");
}
}
// Recurse child nodes
for (int i = 0; i < root.layers.size(); i++) {
Capabilities.Layer l = (Capabilities.Layer) root.layers.elementAt(i);
xml.append(layersToXml(l, tabIndex + 1));
}
xml.append(tab + "</Layer>\n");
return xml.toString();
}
/**
* Parse a given comma-separated parameter string and return the values it
* contains
*
* @param paramStr DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String[] commaSeparated(String paramStr) {
if (paramStr == null) {
return new String[0];
}
StringTokenizer st = new StringTokenizer(paramStr, ",");
String[] params = new String[st.countTokens()];
int index = 0;
while (st.hasMoreTokens()) {
params[index] = st.nextToken();
index++;
}
return params;
}
/**
* Parse a given comma-separated parameter string and return the values it
* contains - must contain the number of values in numParams
*
* @param paramStr DOCUMENT ME!
* @param numParams DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String[] commaSeparated(String paramStr, int numParams) {
String[] params = commaSeparated(paramStr);
if ((params == null) || (params.length != numParams)) {
return null;
}
return params;
}
/**
* Parses a positive integer parameter into an integer
*
* @param param DOCUMENT ME!
*
* @return The positive integer value of param. -1 if the parameter was
* invalid, or less then 0.
*/
private int posIntParam(String param) {
try {
int val = Integer.parseInt(param);
if (val < 0) {
return -1;
}
return val;
} catch (NumberFormatException nfexp) {
return -1;
}
}
/**
* Parses a parameter into a double
*
* @param param DOCUMENT ME!
*
* @return a valid double value, NaN if param is invalid
*/
private double doubleParam(String param) {
try {
double val = Double.parseDouble(param);
return val;
} catch (NumberFormatException nfexp) {
return Double.NaN;
}
}
/**
* Parses a parameter into a boolean value
*
* @param param DOCUMENT ME!
*
* @return true if param equals "true", "t", "1", "yes" - not
* case-sensitive.
*/
private boolean boolParam(String param) {
if (param == null) {
return false;
}
if (param.equalsIgnoreCase("true") || param.equalsIgnoreCase("t") ||
param.equalsIgnoreCase("1") || param.equalsIgnoreCase("yes")) {
return true;
}
return false;
}
/**
* Parses a color value of the form "#FFFFFF", defaults to white;
*
* @param color DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private Color colorParam(String color) {
if (color == null) {
return colorParam(DEFAULT_COLOR);
}
// Parse the string
color = color.replace('#', ' ');
color = color.replaceAll("0x", ""); // incase they passed in 0XFFFFFF instead like cubewerx do
try {
LOGGER.finest("decoding " + color);
return new Color(Integer.parseInt(color.trim(), 16));
} catch (NumberFormatException nfexp) {
LOGGER.severe("Cannot decode " + color + ", using default bgcolor");
return colorParam(DEFAULT_COLOR);
}
}
private void clearCache() {
LRUMap allMapsBase = new LRUMap(cacheSize);
allMaps = Collections.synchronizedMap(allMapsBase);
LRUMap nationalMapsBase = new LRUMap(cacheSize);
nationalMaps = Collections.synchronizedMap(nationalMapsBase);
}
private void resetCache(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int size = posIntParam(getParameter(request, PARAM_CACHESIZE));
cacheSize = size;
LOGGER.info("Setting cacheSize to " + size);
clearCache();
}
/**
* a Key for wms requests which ignores case and ordering of layers, styles
* parameters etc.
*/
class CacheKey {
int key;
/**
* construct a probably unique key for this wms request
*
* @param request the WMS request
*/
CacheKey(HttpServletRequest request) {
String tmp = getParameter(request, PARAM_LAYERS);
LOGGER.finest("layer string " + tmp);
String[] layers = commaSeparated(tmp);
String srs = getParameter(request, PARAM_SRS);
String bbox = getParameter(request, PARAM_BBOX);
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
String[] styles = commaSeparated(getParameter(request, PARAM_STYLES),
layers.length);
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
// Check values
if ((layers == null) || (layers.length == 0)) {
LOGGER.severe("No Layers defined");
return;
}
if ((styles != null) && (styles.length != layers.length)) {
LOGGER.severe(
"Invalid number of styles defined for passed layers");
return;
}
key = 0;
for (int i = 0; i < layers.length; i++) {
key += layers[i].toLowerCase().hashCode();
LOGGER.finest("layer " + layers[i] + " key = " + key);
if ((styles != null) && (i < styles.length)) {
key += styles[i].toLowerCase().hashCode();
LOGGER.finest("style " + styles[i] + " key = " + key);
}
}
key *= 37;
LOGGER.finest("key = " + key);
key += (bgcolor.hashCode() * 37);
LOGGER.finest("color " + bgcolor + " key = " + key);
key += (srs.hashCode() * 37);
LOGGER.finest("srs " + srs + " key = " + key);
key += (bbox.hashCode() * 37);
LOGGER.finest("bbox " + bbox + " key = " + key);
key += (((width * 37) + height) * 37);
LOGGER.fine("Key = " + key);
}
/**
* return the hashcode of this key
*
* @return the key value
*/
public int hashCode() {
return key;
}
/**
* checks if this key is equal to the object passed in
*
* @param k - Object to test for equality
*
* @return true if k equals this object, false if not
*/
public boolean equals(Object k) {
if (k == null) {
return false;
}
if (this.getClass() != k.getClass()) {
return false;
}
if (((CacheKey) k).key != key) {
return false;
}
return true;
}
/**
* converts the key to a string
*
* @return the string representation of the key
*/
public String toString() {
return "" + key;
}
}
private String negotiateFormat(HttpServletRequest request){
String format=DEFAULT_FORMAT;
String accept = request.getHeader("Accept");
if(LOGGER.getLevel()==Level.FINE){
LOGGER.fine("browser accepts: " + accept);
LOGGER.fine("JAI supports: ");
for(int i=0;i<outputTypes.length;i++){
LOGGER.fine("\t"+outputTypes[i]);
}
}
// now we need to find the best overlap between these two lists;
if(accept !=null){
for(int i=0;i<outputTypes.length;i++){
if (accept.indexOf(outputTypes[i]) != -1) {
format = outputTypes[i];
break;
}
}
}
return format;
}
}
| public void doGetLegendGraphic(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
BufferedImage image = null;
String exceptions = getParameter(request, PARAM_EXCEPTIONS);
String format = getParameter(request, PARAM_FORMAT);
String[] layers = commaSeparated(getParameter(request, PARAM_LAYERS));
String[] styles = commaSeparated(getParameter(request, PARAM_STYLES),
layers.length);
double scale = doubleParam(getParameter(request,PARAM_SCALE));
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
if(format==null || format.equals("")){
format=negotiateFormat(request);
}
if(scale == Double.NaN){
scale=1;
}
try{
image=server.getLegend(layers,styles,width,height,trans,bgcolor,scale);
} catch (WMSException wmsexp) {
doException(wmsexp.getCode(), wmsexp.getMessage(), request,
response, exceptions);
return;
} catch (Exception exp) {
doException(null,
"Unknown exception : " + exp + " : " + exp.getStackTrace()[0] +
exp.getMessage(), request, response, exceptions);
return;
}
// Write the response
response.setContentType(format);
OutputStream out = response.getOutputStream();
// avoid caching in browser
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
formatImageOutputStream(format, image, out);
} catch (Exception exp) {
exp.printStackTrace();
LOGGER.severe(
"Unable to complete image generation after response started : " +
exp + exp.getMessage());
if (exp instanceof SecurityException) {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] +
" JAI may not have 'write' and 'delete' permissions in temp folder");
} else {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] + "Check JAI configuration");
}
}//finally{
// out.close();
// image = null;
// }
}
private WMSFeatureFormatter getFeatureFormatter(String mime)
throws WMSException {
for (int i = 0; i < featureFormatters.size(); i++)
if (((WMSFeatureFormatter) featureFormatters.elementAt(i)).getMimeType()
.equalsIgnoreCase(mime)) {
return (WMSFeatureFormatter) featureFormatters.elementAt(i);
}
throw new WMSException(WMSException.WMSCODE_INVALIDFORMAT,
"Invalid Feature Format " + mime);
}
/**
* Returns WMS 1.1.1 compatible Exception
*
* @param sCode The WMS 1.1.1 exception code
* @param sException The detailed exception message
* @param request The ServletRequest object for the current request
* @param response The ServletResponse object for the current request
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*
* @see WMSException
*/
public void doException(String sCode, String sException,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doException(sCode, sException, request, response, DEFAULT_EXCEPTION);
}
/**
* Returns WMS 1.1.1 compatible Exception
*
* @param sCode The WMS 1.1.1 exception code
* @param sException The detailed exception message
* @param request The ServletRequest object for the current request
* @param response The ServletResponse object for the current request
* @param exp_type The mime-type for the exception to be returned as
*
* @throws ServletException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*
* @see WMSException
*/
public void doException(String sCode, String sException,
HttpServletRequest request, HttpServletResponse response,
String exp_type) throws ServletException, IOException {
// Send to client
if ((exp_type == null) || (exp_type.trim().length() == 0)) {
exp_type = DEFAULT_EXCEPTION;
}
LOGGER.severe("Its all gone wrong! " + sException);
// *********************************************************************************************
// * NOTE if you add a new exception type then you *must* add it to exceptionTypes for it to be
// * advertised in the capabilities document.
// *********************************************************************************************
// Check the optional response code (mime-type of exception)
if (exp_type.equalsIgnoreCase("application/vnd.ogc.se_xml") || exp_type.equalsIgnoreCase("text/xml")) {
response.setContentType("text/xml"); // otherwise the browser probably won't know what we'return talking about
PrintWriter pw = response.getWriter();
outputXMLException(sCode, sException, pw);
} else if (exp_type.equalsIgnoreCase("text/plain")) {
response.setContentType(exp_type);
PrintWriter pw = response.getWriter();
pw.println("Exception : Code="+sCode);
pw.println(sException);
} else if(exp_type.equalsIgnoreCase("application/vnd.ogc.se_inimage")||
exp_type.equalsIgnoreCase("application/vnd.ogc.se_blank")){
String format = getParameter(request, PARAM_FORMAT);
if(format==null) {
format=negotiateFormat(request);
}
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
LOGGER.fine("Creating image "+width+"x"+height);
LOGGER.fine("BGCOlor = "+bgcolor+" transparency "+trans);
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setBackground(bgcolor);
Color fgcolor = Color.black;
if(Color.black.equals(bgcolor)){
fgcolor = Color.white;
}else{
fgcolor = Color.black;
}
if (!trans) {
g.setPaint(bgcolor);
g.fillRect(0, 0, width, height);
}
g.setPaint(fgcolor);
if(exp_type.equalsIgnoreCase("application/vnd.ogc.se_inimage")){
LOGGER.fine("Writing to image");
LOGGER.fine("Background color "+g.getBackground()+" forground "+g.getPaint());
g.drawString("Exception : Code="+sCode,10,20);
g.drawString(sException,10,40);
}
response.setContentType(format);
OutputStream out = response.getOutputStream();
// avoid caching in browser
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
formatImageOutputStream(format, image, out);
} catch (Exception exp) {
exp.printStackTrace();
LOGGER.severe(
"Unable to complete image generation after response started : " +
exp + exp.getMessage());
if (exp instanceof SecurityException) {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] +
" JAI may not have 'write' and 'delete' permissions in temp folder");
} else {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] + "Check JAI configuration");
}
}finally{
out.close();
image = null;
}
} else {
LOGGER.severe("Unknow exception format "+exp_type);
}
}
/**
* returns an xml encoded error message to the client
*
* @param sCode the service exception code (can be null)
* @param sException the exception message
* @param pw the printwriter to send to
*/
protected void outputXMLException(final String sCode, final String sException,
final PrintWriter pw) {
// Write header
pw.println(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>");
pw.println(
"<!DOCTYPE ServiceExceptionReport SYSTEM \"http://www.digitalearth.gov/wmt/xml/exception_1_1_0.dtd\"> ");
pw.println("<ServiceExceptionReport version=\"1.1.0\">");
// Write exception code
pw.println(" <ServiceException" +
((sCode != null) ? (" code=\"" + sCode + "\"") : "") + ">" +
sException + "</ServiceException>");
// Write footer
pw.println(" </ServiceExceptionReport>");
pw.close();
}
/**
* Converts this object into a WMS 1.1.1 compliant Capabilities XML string.
*
* @param cap DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String capabilitiesToXML(Capabilities cap) {
String home = getServletContext().getRealPath("");
URL base;
URL url;
try {
base = new File(home).toURL();
LOGGER.fine("base set to " + base);
url = new URL(base, "capabilities.xml");
InputStream is = url.openStream();
LOGGER.fine("input stream " + is + " from url " + url);
StringBuffer xml = new StringBuffer();
int length = 0;
byte[] b = new byte[100];
while ((length = is.read(b)) != -1)
xml.append(new String(b, 0, length));
// address of this service
String resource =
"<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" " +
"xlink:href=\"" + getUrl + "\"/>";
xml.replace(xml.toString().indexOf(XML_GETURL),
xml.toString().indexOf(XML_GETURL) + XML_GETURL.length(),
resource);
// Map formats
String mapFormats = "";
for (int i = 0; i < outputTypes.length; i++) {
mapFormats += ("\t<Format>" + outputTypes[i] + "</Format>\n");
}
xml.replace(xml.toString().indexOf(XML_MAPFORMATS),
xml.toString().indexOf(XML_MAPFORMATS) +
XML_MAPFORMATS.length(), mapFormats);
// GetFeatureInfo
String getFeatureInfo = "";
LOGGER.fine("supports FI? " + cap.getSupportsGetFeatureInfo());
if (cap.getSupportsGetFeatureInfo()) {
getFeatureInfo += "<GetFeatureInfo>\n";
for (int i = 0; i < featureFormatters.size(); i++) {
getFeatureInfo += ("<Format>" +
((WMSFeatureFormatter) featureFormatters.elementAt(i)).getMimeType() +
"</Format>\n");
}
getFeatureInfo += "<DCPType><HTTP><Get>\n";
getFeatureInfo += ("<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" " +
"xlink:href=\"" + getUrl + "\"/>\n");
getFeatureInfo += "</Get></HTTP></DCPType>\n";
getFeatureInfo += "</GetFeatureInfo>\n";
LOGGER.fine("feature info support = " + getFeatureInfo);
}
xml.replace(xml.toString().indexOf(XML_GETFEATUREINFO),
xml.toString().indexOf(XML_GETFEATUREINFO) +
XML_GETFEATUREINFO.length(), getFeatureInfo);
// Exception formats
String exceptionFormats = "";
for (int i = 0; i < exceptionTypes.length; i++) {
exceptionFormats += ("\t<Format>" + exceptionTypes[i] + "</Format>\n");
}
// -No more exception formats at this time
xml.replace(xml.toString().indexOf(XML_EXCEPTIONFORMATS),
xml.toString().indexOf(XML_EXCEPTIONFORMATS) +
XML_EXCEPTIONFORMATS.length(), exceptionFormats);
// Vendor specific capabilities
String vendorSpecific = "";
if (cap.getVendorSpecificCapabilitiesXML() != null) {
vendorSpecific = cap.getVendorSpecificCapabilitiesXML();
}
xml.replace(xml.toString().indexOf(XML_VENDORSPECIFIC),
xml.toString().indexOf(XML_VENDORSPECIFIC) +
XML_VENDORSPECIFIC.length(), vendorSpecific);
// Layers
String layerStr = "<Layer>\n<Name>Experimental Web Map Server</Name>\n";
layerStr += "<Title>GeoTools2 web map server</Title>";
layerStr += "<SRS>EPSG:27700</SRS><SRS>EPSG:4326</SRS>\n";
layerStr += "<LatLonBoundingBox minx=\"-1\" miny=\"-1\" maxx=\"-1\" maxy=\"-1\" />\n";
layerStr += "<BoundingBox SRS=\"EPSG:4326\" minx=\"-1\" miny=\"-1\" maxx=\"-1\" maxy=\"-1\" />\n";
Enumeration en = cap.layers.elements();
while (en.hasMoreElements()) {
Capabilities.Layer l = (Capabilities.Layer) en.nextElement();
// Layer properties
layerStr += layersToXml(l, 1);
}
layerStr += "</Layer>";
xml.replace(xml.toString().indexOf(XML_LAYERS),
xml.toString().indexOf(XML_LAYERS) + XML_LAYERS.length(),
layerStr);
return xml.toString();
} catch (IOException ioexp) {
return null;
}
}
/**
* add layer to the capabilites xml
*
* @param root DOCUMENT ME!
* @param tabIndex DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @task TODO: Support LegendUrl which requires additional format and size
* information.
* @task HACK: queryable is fixed to true for the moment, needs to be set
* as required
*/
private String layersToXml(Capabilities.Layer root, int tabIndex) {
String tab = "\t";
for (int t = 0; t < tabIndex; t++)
tab += "\t";
StringBuffer xml = new StringBuffer(tab + "<Layer queryable=\"1\">\n");
// Tab in a little
if (root.name != null) {
xml.append(tab + "<Name>" + root.name + "</Name>\n");
}
xml.append(tab + "<Title>" + root.title + "</Title>\n");
xml.append(tab + "<Abstract></Abstract>\n");
xml.append(tab + "<LatLonBoundingBox minx=\"" + root.bbox[0] +
"\" miny=\"" + root.bbox[1] + "\" maxx=\"" + root.bbox[2] +
"\" maxy=\"" + root.bbox[3] + "\" />\n");
if (root.srs != null) {
xml.append(tab + "<SRS>" + root.srs + "</SRS>\n");
}
// Styles
if (root.styles != null) {
Enumeration styles = root.styles.elements();
while (styles.hasMoreElements()) {
Capabilities.Style s = (Capabilities.Style) styles.nextElement();
xml.append(tab + "<Style>\n");
xml.append(tab + "<Name>" + s.name + "</Name>\n");
xml.append(tab + "<Title>" + s.title + "</Title>\n");
//xml += tab+"<LegendUrl>"+s.legendUrl+"</LegenUrl>\n";
xml.append(tab + "</Style>\n");
}
}
// Recurse child nodes
for (int i = 0; i < root.layers.size(); i++) {
Capabilities.Layer l = (Capabilities.Layer) root.layers.elementAt(i);
xml.append(layersToXml(l, tabIndex + 1));
}
xml.append(tab + "</Layer>\n");
return xml.toString();
}
/**
* Parse a given comma-separated parameter string and return the values it
* contains
*
* @param paramStr DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String[] commaSeparated(String paramStr) {
if (paramStr == null) {
return new String[0];
}
StringTokenizer st = new StringTokenizer(paramStr, ",");
String[] params = new String[st.countTokens()];
int index = 0;
while (st.hasMoreTokens()) {
params[index] = st.nextToken();
index++;
}
return params;
}
/**
* Parse a given comma-separated parameter string and return the values it
* contains - must contain the number of values in numParams
*
* @param paramStr DOCUMENT ME!
* @param numParams DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private String[] commaSeparated(String paramStr, int numParams) {
String[] params = commaSeparated(paramStr);
if ((params == null) || (params.length != numParams)) {
return null;
}
return params;
}
/**
* Parses a positive integer parameter into an integer
*
* @param param DOCUMENT ME!
*
* @return The positive integer value of param. -1 if the parameter was
* invalid, or less then 0.
*/
private int posIntParam(String param) {
try {
int val = Integer.parseInt(param);
if (val < 0) {
return -1;
}
return val;
} catch (NumberFormatException nfexp) {
return -1;
}
}
/**
* Parses a parameter into a double
*
* @param param DOCUMENT ME!
*
* @return a valid double value, NaN if param is invalid
*/
private double doubleParam(String param) {
if(param==null||param.trim()=="") return Double.NaN;
try {
double val = Double.parseDouble(param);
return val;
} catch (NumberFormatException nfexp) {
return Double.NaN;
}
}
/**
* Parses a parameter into a boolean value
*
* @param param DOCUMENT ME!
*
* @return true if param equals "true", "t", "1", "yes" - not
* case-sensitive.
*/
private boolean boolParam(String param) {
if (param == null) {
return false;
}
if (param.equalsIgnoreCase("true") || param.equalsIgnoreCase("t") ||
param.equalsIgnoreCase("1") || param.equalsIgnoreCase("yes")) {
return true;
}
return false;
}
/**
* Parses a color value of the form "#FFFFFF", defaults to white;
*
* @param color DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private Color colorParam(String color) {
if (color == null) {
return colorParam(DEFAULT_COLOR);
}
// Parse the string
color = color.replace('#', ' ');
color = color.replaceAll("0x", ""); // incase they passed in 0XFFFFFF instead like cubewerx do
try {
LOGGER.finest("decoding " + color);
return new Color(Integer.parseInt(color.trim(), 16));
} catch (NumberFormatException nfexp) {
LOGGER.severe("Cannot decode " + color + ", using default bgcolor");
return colorParam(DEFAULT_COLOR);
}
}
private void clearCache() {
LRUMap allMapsBase = new LRUMap(cacheSize);
allMaps = Collections.synchronizedMap(allMapsBase);
LRUMap nationalMapsBase = new LRUMap(cacheSize);
nationalMaps = Collections.synchronizedMap(nationalMapsBase);
}
private void resetCache(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int size = posIntParam(getParameter(request, PARAM_CACHESIZE));
cacheSize = size;
LOGGER.info("Setting cacheSize to " + size);
clearCache();
}
/**
* a Key for wms requests which ignores case and ordering of layers, styles
* parameters etc.
*/
class CacheKey {
int key;
/**
* construct a probably unique key for this wms request
*
* @param request the WMS request
*/
CacheKey(HttpServletRequest request) {
String tmp = getParameter(request, PARAM_LAYERS);
LOGGER.finest("layer string " + tmp);
String[] layers = commaSeparated(tmp);
String srs = getParameter(request, PARAM_SRS);
String bbox = getParameter(request, PARAM_BBOX);
int width = posIntParam(getParameter(request, PARAM_WIDTH));
int height = posIntParam(getParameter(request, PARAM_HEIGHT));
String[] styles = commaSeparated(getParameter(request, PARAM_STYLES),
layers.length);
boolean trans = boolParam(getParameter(request, PARAM_TRANSPARENT));
Color bgcolor = colorParam(getParameter(request, PARAM_BGCOLOR));
// Check values
if ((layers == null) || (layers.length == 0)) {
LOGGER.severe("No Layers defined");
return;
}
if ((styles != null) && (styles.length != layers.length)) {
LOGGER.severe(
"Invalid number of styles defined for passed layers");
return;
}
key = 0;
for (int i = 0; i < layers.length; i++) {
key += layers[i].toLowerCase().hashCode();
LOGGER.finest("layer " + layers[i] + " key = " + key);
if ((styles != null) && (i < styles.length)) {
key += styles[i].toLowerCase().hashCode();
LOGGER.finest("style " + styles[i] + " key = " + key);
}
}
key *= 37;
LOGGER.finest("key = " + key);
key += (bgcolor.hashCode() * 37);
LOGGER.finest("color " + bgcolor + " key = " + key);
key += (srs.hashCode() * 37);
LOGGER.finest("srs " + srs + " key = " + key);
key += (bbox.hashCode() * 37);
LOGGER.finest("bbox " + bbox + " key = " + key);
key += (((width * 37) + height) * 37);
LOGGER.fine("Key = " + key);
}
/**
* return the hashcode of this key
*
* @return the key value
*/
public int hashCode() {
return key;
}
/**
* checks if this key is equal to the object passed in
*
* @param k - Object to test for equality
*
* @return true if k equals this object, false if not
*/
public boolean equals(Object k) {
if (k == null) {
return false;
}
if (this.getClass() != k.getClass()) {
return false;
}
if (((CacheKey) k).key != key) {
return false;
}
return true;
}
/**
* converts the key to a string
*
* @return the string representation of the key
*/
public String toString() {
return "" + key;
}
}
private String negotiateFormat(HttpServletRequest request){
String format=DEFAULT_FORMAT;
String accept = request.getHeader("Accept");
if(LOGGER.getLevel()==Level.FINE){
LOGGER.fine("browser accepts: " + accept);
LOGGER.fine("JAI supports: ");
for(int i=0;i<outputTypes.length;i++){
LOGGER.fine("\t"+outputTypes[i]);
}
}
// now we need to find the best overlap between these two lists;
if(accept !=null){
for(int i=0;i<outputTypes.length;i++){
if (accept.indexOf(outputTypes[i]) != -1) {
format = outputTypes[i];
break;
}
}
}
return format;
}
}
|
diff --git a/src/com/android/launcher3/WallpaperPickerActivity.java b/src/com/android/launcher3/WallpaperPickerActivity.java
index 39921705c..d3e1c7b76 100644
--- a/src/com/android/launcher3/WallpaperPickerActivity.java
+++ b/src/com/android/launcher3/WallpaperPickerActivity.java
@@ -1,829 +1,829 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3;
import android.animation.LayoutTransition;
import android.app.ActionBar;
import android.app.Activity;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Pair;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import com.android.photos.BitmapRegionTileSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class WallpaperPickerActivity extends WallpaperCropActivity {
static final String TAG = "Launcher.WallpaperPickerActivity";
public static final int IMAGE_PICK = 5;
public static final int PICK_WALLPAPER_THIRD_PARTY_ACTIVITY = 6;
public static final int PICK_LIVE_WALLPAPER = 7;
private static final String TEMP_WALLPAPER_TILES = "TEMP_WALLPAPER_TILES";
private View mSelectedThumb;
private boolean mIgnoreNextTap;
private OnClickListener mThumbnailOnClickListener;
private LinearLayout mWallpapersView;
private View mWallpaperStrip;
private ActionMode.Callback mActionModeCallback;
private ActionMode mActionMode;
private View.OnLongClickListener mLongClickListener;
ArrayList<Uri> mTempWallpaperTiles = new ArrayList<Uri>();
private SavedWallpaperImages mSavedImages;
private WallpaperInfo mLiveWallpaperInfoOnPickerLaunch;
public static abstract class WallpaperTileInfo {
protected View mView;
public void setView(View v) {
mView = v;
}
public void onClick(WallpaperPickerActivity a) {}
public void onSave(WallpaperPickerActivity a) {}
public void onDelete(WallpaperPickerActivity a) {}
public boolean isSelectable() { return false; }
public boolean isNamelessWallpaper() { return false; }
public void onIndexUpdated(CharSequence label) {
if (isNamelessWallpaper()) {
mView.setContentDescription(label);
}
}
}
public static class PickImageInfo extends WallpaperTileInfo {
@Override
public void onClick(WallpaperPickerActivity a) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Utilities.startActivityForResultSafely(a, intent, IMAGE_PICK);
}
}
public static class UriWallpaperInfo extends WallpaperTileInfo {
private Uri mUri;
public UriWallpaperInfo(Uri uri) {
mUri = uri;
}
@Override
public void onClick(WallpaperPickerActivity a) {
CropView v = a.getCropView();
v.setTileSource(new BitmapRegionTileSource(
a, mUri, 1024, 0), null);
v.setTouchEnabled(true);
}
@Override
public void onSave(final WallpaperPickerActivity a) {
boolean finishActivityWhenDone = true;
OnBitmapCroppedHandler h = new OnBitmapCroppedHandler() {
public void onBitmapCropped(byte[] imageBytes) {
Point thumbSize = getDefaultThumbnailSize(a.getResources());
Bitmap thumb =
createThumbnail(thumbSize, null, null, imageBytes, null, 0, true);
a.getSavedImages().writeImage(thumb, imageBytes);
}
};
a.cropImageAndSetWallpaper(mUri, h, finishActivityWhenDone);
}
@Override
public boolean isSelectable() {
return true;
}
@Override
public boolean isNamelessWallpaper() {
return true;
}
}
public static class ResourceWallpaperInfo extends WallpaperTileInfo {
private Resources mResources;
private int mResId;
private Drawable mThumb;
public ResourceWallpaperInfo(Resources res, int resId, Drawable thumb) {
mResources = res;
mResId = resId;
mThumb = thumb;
}
@Override
public void onClick(WallpaperPickerActivity a) {
BitmapRegionTileSource source = new BitmapRegionTileSource(
mResources, a, mResId, 1024, 0);
CropView v = a.getCropView();
v.setTileSource(source, null);
Point wallpaperSize = WallpaperCropActivity.getDefaultWallpaperSize(
a.getResources(), a.getWindowManager());
RectF crop = WallpaperCropActivity.getMaxCropRect(
source.getImageWidth(), source.getImageHeight(),
wallpaperSize.x, wallpaperSize.y, false);
v.setScale(wallpaperSize.x / crop.width());
v.setTouchEnabled(false);
}
@Override
public void onSave(WallpaperPickerActivity a) {
boolean finishActivityWhenDone = true;
a.cropImageAndSetWallpaper(mResources, mResId, finishActivityWhenDone);
}
@Override
public boolean isSelectable() {
return true;
}
@Override
public boolean isNamelessWallpaper() {
return true;
}
}
public void setWallpaperStripYOffset(float offset) {
mWallpaperStrip.setPadding(0, 0, 0, (int) offset);
}
// called by onCreate; this is subclassed to overwrite WallpaperCropActivity
protected void init() {
setContentView(R.layout.wallpaper_picker);
final WallpaperRootView root = (WallpaperRootView) findViewById(R.id.wallpaper_root);
mCropView = (CropView) findViewById(R.id.cropView);
mWallpaperStrip = findViewById(R.id.wallpaper_strip);
mCropView.setTouchCallback(new CropView.TouchCallback() {
LauncherViewPropertyAnimator mAnim;
@Override
public void onTouchDown() {
if (mAnim != null) {
mAnim.cancel();
}
if (mWallpaperStrip.getTranslationY() == 0) {
mIgnoreNextTap = true;
}
mAnim = new LauncherViewPropertyAnimator(mWallpaperStrip);
mAnim.translationY(mWallpaperStrip.getHeight()).alpha(0f)
.setInterpolator(new DecelerateInterpolator(0.75f));
mAnim.start();
}
@Override
public void onTouchUp() {
mIgnoreNextTap = false;
}
@Override
public void onTap() {
boolean ignoreTap = mIgnoreNextTap;
mIgnoreNextTap = false;
if (!ignoreTap) {
if (mAnim != null) {
mAnim.cancel();
}
mAnim = new LauncherViewPropertyAnimator(mWallpaperStrip);
mAnim.translationY(0f).alpha(1f)
.setInterpolator(new DecelerateInterpolator(0.75f));
mAnim.start();
}
}
});
mThumbnailOnClickListener = new OnClickListener() {
public void onClick(View v) {
if (mActionMode != null) {
// When CAB is up, clicking toggles the item instead
if (v.isLongClickable()) {
mLongClickListener.onLongClick(v);
}
return;
}
WallpaperTileInfo info = (WallpaperTileInfo) v.getTag();
if (info.isSelectable()) {
if (mSelectedThumb != null) {
mSelectedThumb.setSelected(false);
mSelectedThumb = null;
}
mSelectedThumb = v;
v.setSelected(true);
// TODO: Remove this once the accessibility framework and
// services have better support for selection state.
v.announceForAccessibility(
getString(R.string.announce_selection, v.getContentDescription()));
}
info.onClick(WallpaperPickerActivity.this);
}
};
mLongClickListener = new View.OnLongClickListener() {
// Called when the user long-clicks on someView
public boolean onLongClick(View view) {
CheckableFrameLayout c = (CheckableFrameLayout) view;
c.toggle();
if (mActionMode != null) {
mActionMode.invalidate();
} else {
// Start the CAB using the ActionMode.Callback defined below
mActionMode = startActionMode(mActionModeCallback);
int childCount = mWallpapersView.getChildCount();
for (int i = 0; i < childCount; i++) {
mWallpapersView.getChildAt(i).setSelected(false);
}
}
return true;
}
};
// Populate the built-in wallpapers
ArrayList<ResourceWallpaperInfo> wallpapers = findBundledWallpapers();
mWallpapersView = (LinearLayout) findViewById(R.id.wallpaper_list);
BuiltInWallpapersAdapter ia = new BuiltInWallpapersAdapter(this, wallpapers);
populateWallpapersFromAdapter(mWallpapersView, ia, false, true);
// Populate the saved wallpapers
mSavedImages = new SavedWallpaperImages(this);
mSavedImages.loadThumbnailsAndImageIdList();
populateWallpapersFromAdapter(mWallpapersView, mSavedImages, true, true);
// Populate the live wallpapers
final LinearLayout liveWallpapersView =
(LinearLayout) findViewById(R.id.live_wallpaper_list);
final LiveWallpaperListAdapter a = new LiveWallpaperListAdapter(this);
a.registerDataSetObserver(new DataSetObserver() {
public void onChanged() {
liveWallpapersView.removeAllViews();
populateWallpapersFromAdapter(liveWallpapersView, a, false, false);
initializeScrollForRtl();
updateTileIndices();
}
});
// Populate the third-party wallpaper pickers
final LinearLayout thirdPartyWallpapersView =
(LinearLayout) findViewById(R.id.third_party_wallpaper_list);
final ThirdPartyWallpaperPickerListAdapter ta =
new ThirdPartyWallpaperPickerListAdapter(this);
populateWallpapersFromAdapter(thirdPartyWallpapersView, ta, false, false);
// Add a tile for the Gallery
LinearLayout masterWallpaperList = (LinearLayout) findViewById(R.id.master_wallpaper_list);
FrameLayout pickImageTile = (FrameLayout) getLayoutInflater().
inflate(R.layout.wallpaper_picker_image_picker_item, masterWallpaperList, false);
setWallpaperItemPaddingToZero(pickImageTile);
masterWallpaperList.addView(pickImageTile, 0);
// Make its background the last photo taken on external storage
Bitmap lastPhoto = getThumbnailOfLastPhoto();
if (lastPhoto != null) {
ImageView galleryThumbnailBg =
(ImageView) pickImageTile.findViewById(R.id.wallpaper_image);
galleryThumbnailBg.setImageBitmap(getThumbnailOfLastPhoto());
int colorOverlay = getResources().getColor(R.color.wallpaper_picker_translucent_gray);
galleryThumbnailBg.setColorFilter(colorOverlay, PorterDuff.Mode.SRC_ATOP);
}
PickImageInfo pickImageInfo = new PickImageInfo();
pickImageTile.setTag(pickImageInfo);
pickImageInfo.setView(pickImageTile);
pickImageTile.setOnClickListener(mThumbnailOnClickListener);
pickImageInfo.setView(pickImageTile);
updateTileIndices();
// Update the scroll for RTL
initializeScrollForRtl();
// Create smooth layout transitions for when items are deleted
final LayoutTransition transitioner = new LayoutTransition();
transitioner.setDuration(200);
transitioner.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 0);
transitioner.setAnimator(LayoutTransition.DISAPPEARING, null);
mWallpapersView.setLayoutTransition(transitioner);
// Action bar
// Show the custom action bar view
final ActionBar actionBar = getActionBar();
actionBar.setCustomView(R.layout.actionbar_set_wallpaper);
actionBar.getCustomView().setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mSelectedThumb != null) {
WallpaperTileInfo info = (WallpaperTileInfo) mSelectedThumb.getTag();
info.onSave(WallpaperPickerActivity.this);
}
}
});
// CAB for deleting items
mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.cab_delete_wallpapers, menu);
return true;
}
private int numCheckedItems() {
int childCount = mWallpapersView.getChildCount();
int numCheckedItems = 0;
for (int i = 0; i < childCount; i++) {
CheckableFrameLayout c = (CheckableFrameLayout) mWallpapersView.getChildAt(i);
if (c.isChecked()) {
numCheckedItems++;
}
}
return numCheckedItems;
}
// Called each time the action mode is shown. Always called after onCreateActionMode,
// but may be called multiple times if the mode is invalidated.
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
int numCheckedItems = numCheckedItems();
if (numCheckedItems == 0) {
mode.finish();
return true;
} else {
mode.setTitle(getResources().getQuantityString(
R.plurals.number_of_items_selected, numCheckedItems, numCheckedItems));
return true;
}
}
// Called when the user selects a contextual menu item
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menu_delete) {
int childCount = mWallpapersView.getChildCount();
ArrayList<View> viewsToRemove = new ArrayList<View>();
for (int i = 0; i < childCount; i++) {
CheckableFrameLayout c =
(CheckableFrameLayout) mWallpapersView.getChildAt(i);
if (c.isChecked()) {
WallpaperTileInfo info = (WallpaperTileInfo) c.getTag();
info.onDelete(WallpaperPickerActivity.this);
viewsToRemove.add(c);
}
}
for (View v : viewsToRemove) {
mWallpapersView.removeView(v);
}
updateTileIndices();
mode.finish(); // Action picked, so close the CAB
return true;
} else {
return false;
}
}
// Called when the user exits the action mode
@Override
public void onDestroyActionMode(ActionMode mode) {
int childCount = mWallpapersView.getChildCount();
for (int i = 0; i < childCount; i++) {
CheckableFrameLayout c = (CheckableFrameLayout) mWallpapersView.getChildAt(i);
c.setChecked(false);
}
mSelectedThumb.setSelected(true);
mActionMode = null;
}
};
}
private void initializeScrollForRtl() {
final HorizontalScrollView scroll =
(HorizontalScrollView) findViewById(R.id.wallpaper_scroll_container);
if (scroll.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
final ViewTreeObserver observer = scroll.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
LinearLayout masterWallpaperList =
(LinearLayout) findViewById(R.id.master_wallpaper_list);
scroll.scrollTo(masterWallpaperList.getWidth(), 0);
scroll.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
}
public boolean enableRotation() {
return super.enableRotation() || Launcher.sForceEnableRotation;
}
protected Bitmap getThumbnailOfLastPhoto() {
Cursor cursor = MediaStore.Images.Media.query(getContentResolver(),
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATE_TAKEN},
null, null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC LIMIT 1");
Bitmap thumb = null;
if (cursor.moveToNext()) {
int id = cursor.getInt(0);
thumb = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(),
id, MediaStore.Images.Thumbnails.MINI_KIND, null);
}
cursor.close();
return thumb;
}
protected void onStop() {
super.onStop();
mWallpaperStrip = findViewById(R.id.wallpaper_strip);
if (mWallpaperStrip.getTranslationY() > 0f) {
mWallpaperStrip.setTranslationY(0f);
mWallpaperStrip.setAlpha(1f);
}
}
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList(TEMP_WALLPAPER_TILES, mTempWallpaperTiles);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
ArrayList<Uri> uris = savedInstanceState.getParcelableArrayList(TEMP_WALLPAPER_TILES);
for (Uri uri : uris) {
addTemporaryWallpaperTile(uri);
}
}
private void populateWallpapersFromAdapter(ViewGroup parent, BaseAdapter adapter,
boolean addLongPressHandler, boolean selectFirstTile) {
for (int i = 0; i < adapter.getCount(); i++) {
FrameLayout thumbnail = (FrameLayout) adapter.getView(i, null, parent);
parent.addView(thumbnail, i);
WallpaperTileInfo info = (WallpaperTileInfo) adapter.getItem(i);
thumbnail.setTag(info);
info.setView(thumbnail);
if (addLongPressHandler) {
addLongPressHandler(thumbnail);
}
thumbnail.setOnClickListener(mThumbnailOnClickListener);
if (i == 0 && selectFirstTile) {
mThumbnailOnClickListener.onClick(thumbnail);
}
}
}
private void updateTileIndices() {
LinearLayout masterWallpaperList = (LinearLayout) findViewById(R.id.master_wallpaper_list);
final int childCount = masterWallpaperList.getChildCount();
ArrayList<WallpaperTileInfo> tiles = new ArrayList<WallpaperTileInfo>();
final Resources res = getResources();
// Do two passes; the first pass gets the total number of tiles
int numTiles = 0;
for (int passNum = 0; passNum < 2; passNum++) {
int tileIndex = 0;
for (int i = 0; i < childCount; i++) {
View child = masterWallpaperList.getChildAt(i);
LinearLayout subList;
int subListStart;
int subListEnd;
if (child.getTag() instanceof WallpaperTileInfo) {
subList = masterWallpaperList;
subListStart = i;
subListEnd = i + 1;
} else { // if (child instanceof LinearLayout) {
subList = (LinearLayout) child;
subListStart = 0;
subListEnd = subList.getChildCount();
}
for (int j = subListStart; j < subListEnd; j++) {
WallpaperTileInfo info = (WallpaperTileInfo) subList.getChildAt(j).getTag();
if (info.isNamelessWallpaper()) {
if (passNum == 0) {
numTiles++;
} else {
CharSequence label = res.getString(
R.string.wallpaper_accessibility_name, ++tileIndex, numTiles);
info.onIndexUpdated(label);
}
}
}
}
}
}
private static Point getDefaultThumbnailSize(Resources res) {
return new Point(res.getDimensionPixelSize(R.dimen.wallpaperThumbnailWidth),
res.getDimensionPixelSize(R.dimen.wallpaperThumbnailHeight));
}
private static Bitmap createThumbnail(Point size, Context context, Uri uri, byte[] imageBytes,
Resources res, int resId, boolean leftAligned) {
int width = size.x;
int height = size.y;
BitmapCropTask cropTask;
if (uri != null) {
cropTask = new BitmapCropTask(context, uri, null, width, height, false, true, null);
} else if (imageBytes != null) {
cropTask = new BitmapCropTask(imageBytes, null, width, height, false, true, null);
} else {
cropTask =
new BitmapCropTask(context, res, resId, null, width, height, false, true, null);
}
Point bounds = cropTask.getImageBounds();
if (bounds == null || bounds.x == 0 || bounds.y == 0) {
return null;
}
RectF cropRect = WallpaperCropActivity.getMaxCropRect(
bounds.x, bounds.y, width, height, leftAligned);
cropTask.setCropBounds(cropRect);
if (cropTask.cropBitmap()) {
return cropTask.getCroppedBitmap();
} else {
return null;
}
}
private void addTemporaryWallpaperTile(Uri uri) {
mTempWallpaperTiles.add(uri);
// Add a tile for the image picked from Gallery
FrameLayout pickedImageThumbnail = (FrameLayout) getLayoutInflater().
inflate(R.layout.wallpaper_picker_item, mWallpapersView, false);
setWallpaperItemPaddingToZero(pickedImageThumbnail);
// Load the thumbnail
ImageView image = (ImageView) pickedImageThumbnail.findViewById(R.id.wallpaper_image);
Point defaultSize = getDefaultThumbnailSize(this.getResources());
Bitmap thumb = createThumbnail(defaultSize, this, uri, null, null, 0, false);
if (thumb != null) {
image.setImageBitmap(thumb);
Drawable thumbDrawable = image.getDrawable();
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error loading thumbnail for uri=" + uri);
}
mWallpapersView.addView(pickedImageThumbnail, 0);
- updateTileIndices();
UriWallpaperInfo info = new UriWallpaperInfo(uri);
pickedImageThumbnail.setTag(info);
info.setView(pickedImageThumbnail);
+ updateTileIndices();
pickedImageThumbnail.setOnClickListener(mThumbnailOnClickListener);
mThumbnailOnClickListener.onClick(pickedImageThumbnail);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICK && resultCode == RESULT_OK) {
if (data != null && data.getData() != null) {
Uri uri = data.getData();
addTemporaryWallpaperTile(uri);
}
} else if (requestCode == PICK_WALLPAPER_THIRD_PARTY_ACTIVITY) {
setResult(RESULT_OK);
finish();
} else if (requestCode == PICK_LIVE_WALLPAPER) {
WallpaperManager wm = WallpaperManager.getInstance(this);
final WallpaperInfo oldLiveWallpaper = mLiveWallpaperInfoOnPickerLaunch;
WallpaperInfo newLiveWallpaper = wm.getWallpaperInfo();
// Try to figure out if a live wallpaper was set;
if (newLiveWallpaper != null &&
(oldLiveWallpaper == null ||
!oldLiveWallpaper.getComponent().equals(newLiveWallpaper.getComponent()))) {
// Return if a live wallpaper was set
setResult(RESULT_OK);
finish();
}
}
}
static void setWallpaperItemPaddingToZero(FrameLayout frameLayout) {
frameLayout.setPadding(0, 0, 0, 0);
frameLayout.setForeground(new ZeroPaddingDrawable(frameLayout.getForeground()));
}
private void addLongPressHandler(View v) {
v.setOnLongClickListener(mLongClickListener);
}
private ArrayList<ResourceWallpaperInfo> findBundledWallpapers() {
ArrayList<ResourceWallpaperInfo> bundledWallpapers =
new ArrayList<ResourceWallpaperInfo>(24);
Pair<ApplicationInfo, Integer> r = getWallpaperArrayResourceId();
if (r != null) {
try {
Resources wallpaperRes = getPackageManager().getResourcesForApplication(r.first);
bundledWallpapers = addWallpapers(wallpaperRes, r.first.packageName, r.second);
} catch (PackageManager.NameNotFoundException e) {
}
}
// Add an entry for the default wallpaper (stored in system resources)
ResourceWallpaperInfo defaultWallpaperInfo = getDefaultWallpaperInfo();
if (defaultWallpaperInfo != null) {
bundledWallpapers.add(0, defaultWallpaperInfo);
}
return bundledWallpapers;
}
private ResourceWallpaperInfo getDefaultWallpaperInfo() {
Resources sysRes = Resources.getSystem();
int resId = sysRes.getIdentifier("default_wallpaper", "drawable", "android");
File defaultThumbFile = new File(getFilesDir(), "default_thumb.jpg");
Bitmap thumb = null;
boolean defaultWallpaperExists = false;
if (defaultThumbFile.exists()) {
thumb = BitmapFactory.decodeFile(defaultThumbFile.getAbsolutePath());
defaultWallpaperExists = true;
} else {
Point defaultThumbSize = getDefaultThumbnailSize(getResources());
thumb = createThumbnail(defaultThumbSize, this, null, null, sysRes, resId, false);
if (thumb != null) {
try {
defaultThumbFile.createNewFile();
FileOutputStream thumbFileStream =
openFileOutput(defaultThumbFile.getName(), Context.MODE_PRIVATE);
thumb.compress(Bitmap.CompressFormat.JPEG, 95, thumbFileStream);
thumbFileStream.close();
defaultWallpaperExists = true;
} catch (IOException e) {
Log.e(TAG, "Error while writing default wallpaper thumbnail to file " + e);
defaultThumbFile.delete();
}
}
}
if (defaultWallpaperExists) {
return new ResourceWallpaperInfo(sysRes, resId, new BitmapDrawable(thumb));
}
return null;
}
public Pair<ApplicationInfo, Integer> getWallpaperArrayResourceId() {
// Context.getPackageName() may return the "original" package name,
// com.android.launcher3; Resources needs the real package name,
// com.android.launcher3. So we ask Resources for what it thinks the
// package name should be.
final String packageName = getResources().getResourcePackageName(R.array.wallpapers);
try {
ApplicationInfo info = getPackageManager().getApplicationInfo(packageName, 0);
return new Pair<ApplicationInfo, Integer>(info, R.array.wallpapers);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
private ArrayList<ResourceWallpaperInfo> addWallpapers(
Resources res, String packageName, int listResId) {
ArrayList<ResourceWallpaperInfo> bundledWallpapers =
new ArrayList<ResourceWallpaperInfo>(24);
final String[] extras = res.getStringArray(listResId);
for (String extra : extras) {
int resId = res.getIdentifier(extra, "drawable", packageName);
if (resId != 0) {
final int thumbRes = res.getIdentifier(extra + "_small", "drawable", packageName);
if (thumbRes != 0) {
ResourceWallpaperInfo wallpaperInfo =
new ResourceWallpaperInfo(res, resId, res.getDrawable(thumbRes));
bundledWallpapers.add(wallpaperInfo);
// Log.d(TAG, "add: [" + packageName + "]: " + extra + " (" + res + ")");
}
} else {
Log.e(TAG, "Couldn't find wallpaper " + extra);
}
}
return bundledWallpapers;
}
public CropView getCropView() {
return mCropView;
}
public SavedWallpaperImages getSavedImages() {
return mSavedImages;
}
public void onLiveWallpaperPickerLaunch() {
mLiveWallpaperInfoOnPickerLaunch = WallpaperManager.getInstance(this).getWallpaperInfo();
}
static class ZeroPaddingDrawable extends LevelListDrawable {
public ZeroPaddingDrawable(Drawable d) {
super();
addLevel(0, 0, d);
setLevel(0);
}
@Override
public boolean getPadding(Rect padding) {
padding.set(0, 0, 0, 0);
return true;
}
}
private static class BuiltInWallpapersAdapter extends BaseAdapter implements ListAdapter {
private LayoutInflater mLayoutInflater;
private ArrayList<ResourceWallpaperInfo> mWallpapers;
BuiltInWallpapersAdapter(Activity activity, ArrayList<ResourceWallpaperInfo> wallpapers) {
mLayoutInflater = activity.getLayoutInflater();
mWallpapers = wallpapers;
}
public int getCount() {
return mWallpapers.size();
}
public ResourceWallpaperInfo getItem(int position) {
return mWallpapers.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Drawable thumb = mWallpapers.get(position).mThumb;
if (thumb == null) {
Log.e(TAG, "Error decoding thumbnail for wallpaper #" + position);
}
return createImageTileView(mLayoutInflater, position, convertView, parent, thumb);
}
}
public static View createImageTileView(LayoutInflater layoutInflater, int position,
View convertView, ViewGroup parent, Drawable thumb) {
View view;
if (convertView == null) {
view = layoutInflater.inflate(R.layout.wallpaper_picker_item, parent, false);
} else {
view = convertView;
}
setWallpaperItemPaddingToZero((FrameLayout) view);
ImageView image = (ImageView) view.findViewById(R.id.wallpaper_image);
if (thumb != null) {
image.setImageDrawable(thumb);
thumb.setDither(true);
}
return view;
}
}
| false | true | private void updateTileIndices() {
LinearLayout masterWallpaperList = (LinearLayout) findViewById(R.id.master_wallpaper_list);
final int childCount = masterWallpaperList.getChildCount();
ArrayList<WallpaperTileInfo> tiles = new ArrayList<WallpaperTileInfo>();
final Resources res = getResources();
// Do two passes; the first pass gets the total number of tiles
int numTiles = 0;
for (int passNum = 0; passNum < 2; passNum++) {
int tileIndex = 0;
for (int i = 0; i < childCount; i++) {
View child = masterWallpaperList.getChildAt(i);
LinearLayout subList;
int subListStart;
int subListEnd;
if (child.getTag() instanceof WallpaperTileInfo) {
subList = masterWallpaperList;
subListStart = i;
subListEnd = i + 1;
} else { // if (child instanceof LinearLayout) {
subList = (LinearLayout) child;
subListStart = 0;
subListEnd = subList.getChildCount();
}
for (int j = subListStart; j < subListEnd; j++) {
WallpaperTileInfo info = (WallpaperTileInfo) subList.getChildAt(j).getTag();
if (info.isNamelessWallpaper()) {
if (passNum == 0) {
numTiles++;
} else {
CharSequence label = res.getString(
R.string.wallpaper_accessibility_name, ++tileIndex, numTiles);
info.onIndexUpdated(label);
}
}
}
}
}
}
private static Point getDefaultThumbnailSize(Resources res) {
return new Point(res.getDimensionPixelSize(R.dimen.wallpaperThumbnailWidth),
res.getDimensionPixelSize(R.dimen.wallpaperThumbnailHeight));
}
private static Bitmap createThumbnail(Point size, Context context, Uri uri, byte[] imageBytes,
Resources res, int resId, boolean leftAligned) {
int width = size.x;
int height = size.y;
BitmapCropTask cropTask;
if (uri != null) {
cropTask = new BitmapCropTask(context, uri, null, width, height, false, true, null);
} else if (imageBytes != null) {
cropTask = new BitmapCropTask(imageBytes, null, width, height, false, true, null);
} else {
cropTask =
new BitmapCropTask(context, res, resId, null, width, height, false, true, null);
}
Point bounds = cropTask.getImageBounds();
if (bounds == null || bounds.x == 0 || bounds.y == 0) {
return null;
}
RectF cropRect = WallpaperCropActivity.getMaxCropRect(
bounds.x, bounds.y, width, height, leftAligned);
cropTask.setCropBounds(cropRect);
if (cropTask.cropBitmap()) {
return cropTask.getCroppedBitmap();
} else {
return null;
}
}
private void addTemporaryWallpaperTile(Uri uri) {
mTempWallpaperTiles.add(uri);
// Add a tile for the image picked from Gallery
FrameLayout pickedImageThumbnail = (FrameLayout) getLayoutInflater().
inflate(R.layout.wallpaper_picker_item, mWallpapersView, false);
setWallpaperItemPaddingToZero(pickedImageThumbnail);
// Load the thumbnail
ImageView image = (ImageView) pickedImageThumbnail.findViewById(R.id.wallpaper_image);
Point defaultSize = getDefaultThumbnailSize(this.getResources());
Bitmap thumb = createThumbnail(defaultSize, this, uri, null, null, 0, false);
if (thumb != null) {
image.setImageBitmap(thumb);
Drawable thumbDrawable = image.getDrawable();
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error loading thumbnail for uri=" + uri);
}
mWallpapersView.addView(pickedImageThumbnail, 0);
updateTileIndices();
UriWallpaperInfo info = new UriWallpaperInfo(uri);
pickedImageThumbnail.setTag(info);
info.setView(pickedImageThumbnail);
pickedImageThumbnail.setOnClickListener(mThumbnailOnClickListener);
mThumbnailOnClickListener.onClick(pickedImageThumbnail);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICK && resultCode == RESULT_OK) {
if (data != null && data.getData() != null) {
Uri uri = data.getData();
addTemporaryWallpaperTile(uri);
}
} else if (requestCode == PICK_WALLPAPER_THIRD_PARTY_ACTIVITY) {
setResult(RESULT_OK);
finish();
} else if (requestCode == PICK_LIVE_WALLPAPER) {
WallpaperManager wm = WallpaperManager.getInstance(this);
final WallpaperInfo oldLiveWallpaper = mLiveWallpaperInfoOnPickerLaunch;
WallpaperInfo newLiveWallpaper = wm.getWallpaperInfo();
// Try to figure out if a live wallpaper was set;
if (newLiveWallpaper != null &&
(oldLiveWallpaper == null ||
!oldLiveWallpaper.getComponent().equals(newLiveWallpaper.getComponent()))) {
// Return if a live wallpaper was set
setResult(RESULT_OK);
finish();
}
}
}
static void setWallpaperItemPaddingToZero(FrameLayout frameLayout) {
frameLayout.setPadding(0, 0, 0, 0);
frameLayout.setForeground(new ZeroPaddingDrawable(frameLayout.getForeground()));
}
private void addLongPressHandler(View v) {
v.setOnLongClickListener(mLongClickListener);
}
private ArrayList<ResourceWallpaperInfo> findBundledWallpapers() {
ArrayList<ResourceWallpaperInfo> bundledWallpapers =
new ArrayList<ResourceWallpaperInfo>(24);
Pair<ApplicationInfo, Integer> r = getWallpaperArrayResourceId();
if (r != null) {
try {
Resources wallpaperRes = getPackageManager().getResourcesForApplication(r.first);
bundledWallpapers = addWallpapers(wallpaperRes, r.first.packageName, r.second);
} catch (PackageManager.NameNotFoundException e) {
}
}
// Add an entry for the default wallpaper (stored in system resources)
ResourceWallpaperInfo defaultWallpaperInfo = getDefaultWallpaperInfo();
if (defaultWallpaperInfo != null) {
bundledWallpapers.add(0, defaultWallpaperInfo);
}
return bundledWallpapers;
}
private ResourceWallpaperInfo getDefaultWallpaperInfo() {
Resources sysRes = Resources.getSystem();
int resId = sysRes.getIdentifier("default_wallpaper", "drawable", "android");
File defaultThumbFile = new File(getFilesDir(), "default_thumb.jpg");
Bitmap thumb = null;
boolean defaultWallpaperExists = false;
if (defaultThumbFile.exists()) {
thumb = BitmapFactory.decodeFile(defaultThumbFile.getAbsolutePath());
defaultWallpaperExists = true;
} else {
Point defaultThumbSize = getDefaultThumbnailSize(getResources());
thumb = createThumbnail(defaultThumbSize, this, null, null, sysRes, resId, false);
if (thumb != null) {
try {
defaultThumbFile.createNewFile();
FileOutputStream thumbFileStream =
openFileOutput(defaultThumbFile.getName(), Context.MODE_PRIVATE);
thumb.compress(Bitmap.CompressFormat.JPEG, 95, thumbFileStream);
thumbFileStream.close();
defaultWallpaperExists = true;
} catch (IOException e) {
Log.e(TAG, "Error while writing default wallpaper thumbnail to file " + e);
defaultThumbFile.delete();
}
}
}
if (defaultWallpaperExists) {
return new ResourceWallpaperInfo(sysRes, resId, new BitmapDrawable(thumb));
}
return null;
}
public Pair<ApplicationInfo, Integer> getWallpaperArrayResourceId() {
// Context.getPackageName() may return the "original" package name,
// com.android.launcher3; Resources needs the real package name,
// com.android.launcher3. So we ask Resources for what it thinks the
// package name should be.
final String packageName = getResources().getResourcePackageName(R.array.wallpapers);
try {
ApplicationInfo info = getPackageManager().getApplicationInfo(packageName, 0);
return new Pair<ApplicationInfo, Integer>(info, R.array.wallpapers);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
private ArrayList<ResourceWallpaperInfo> addWallpapers(
Resources res, String packageName, int listResId) {
ArrayList<ResourceWallpaperInfo> bundledWallpapers =
new ArrayList<ResourceWallpaperInfo>(24);
final String[] extras = res.getStringArray(listResId);
for (String extra : extras) {
int resId = res.getIdentifier(extra, "drawable", packageName);
if (resId != 0) {
final int thumbRes = res.getIdentifier(extra + "_small", "drawable", packageName);
if (thumbRes != 0) {
ResourceWallpaperInfo wallpaperInfo =
new ResourceWallpaperInfo(res, resId, res.getDrawable(thumbRes));
bundledWallpapers.add(wallpaperInfo);
// Log.d(TAG, "add: [" + packageName + "]: " + extra + " (" + res + ")");
}
} else {
Log.e(TAG, "Couldn't find wallpaper " + extra);
}
}
return bundledWallpapers;
}
public CropView getCropView() {
return mCropView;
}
public SavedWallpaperImages getSavedImages() {
return mSavedImages;
}
public void onLiveWallpaperPickerLaunch() {
mLiveWallpaperInfoOnPickerLaunch = WallpaperManager.getInstance(this).getWallpaperInfo();
}
static class ZeroPaddingDrawable extends LevelListDrawable {
public ZeroPaddingDrawable(Drawable d) {
super();
addLevel(0, 0, d);
setLevel(0);
}
@Override
public boolean getPadding(Rect padding) {
padding.set(0, 0, 0, 0);
return true;
}
}
private static class BuiltInWallpapersAdapter extends BaseAdapter implements ListAdapter {
private LayoutInflater mLayoutInflater;
private ArrayList<ResourceWallpaperInfo> mWallpapers;
BuiltInWallpapersAdapter(Activity activity, ArrayList<ResourceWallpaperInfo> wallpapers) {
mLayoutInflater = activity.getLayoutInflater();
mWallpapers = wallpapers;
}
public int getCount() {
return mWallpapers.size();
}
public ResourceWallpaperInfo getItem(int position) {
return mWallpapers.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Drawable thumb = mWallpapers.get(position).mThumb;
if (thumb == null) {
Log.e(TAG, "Error decoding thumbnail for wallpaper #" + position);
}
return createImageTileView(mLayoutInflater, position, convertView, parent, thumb);
}
}
public static View createImageTileView(LayoutInflater layoutInflater, int position,
View convertView, ViewGroup parent, Drawable thumb) {
View view;
if (convertView == null) {
view = layoutInflater.inflate(R.layout.wallpaper_picker_item, parent, false);
} else {
view = convertView;
}
setWallpaperItemPaddingToZero((FrameLayout) view);
ImageView image = (ImageView) view.findViewById(R.id.wallpaper_image);
if (thumb != null) {
image.setImageDrawable(thumb);
thumb.setDither(true);
}
return view;
}
}
| private void updateTileIndices() {
LinearLayout masterWallpaperList = (LinearLayout) findViewById(R.id.master_wallpaper_list);
final int childCount = masterWallpaperList.getChildCount();
ArrayList<WallpaperTileInfo> tiles = new ArrayList<WallpaperTileInfo>();
final Resources res = getResources();
// Do two passes; the first pass gets the total number of tiles
int numTiles = 0;
for (int passNum = 0; passNum < 2; passNum++) {
int tileIndex = 0;
for (int i = 0; i < childCount; i++) {
View child = masterWallpaperList.getChildAt(i);
LinearLayout subList;
int subListStart;
int subListEnd;
if (child.getTag() instanceof WallpaperTileInfo) {
subList = masterWallpaperList;
subListStart = i;
subListEnd = i + 1;
} else { // if (child instanceof LinearLayout) {
subList = (LinearLayout) child;
subListStart = 0;
subListEnd = subList.getChildCount();
}
for (int j = subListStart; j < subListEnd; j++) {
WallpaperTileInfo info = (WallpaperTileInfo) subList.getChildAt(j).getTag();
if (info.isNamelessWallpaper()) {
if (passNum == 0) {
numTiles++;
} else {
CharSequence label = res.getString(
R.string.wallpaper_accessibility_name, ++tileIndex, numTiles);
info.onIndexUpdated(label);
}
}
}
}
}
}
private static Point getDefaultThumbnailSize(Resources res) {
return new Point(res.getDimensionPixelSize(R.dimen.wallpaperThumbnailWidth),
res.getDimensionPixelSize(R.dimen.wallpaperThumbnailHeight));
}
private static Bitmap createThumbnail(Point size, Context context, Uri uri, byte[] imageBytes,
Resources res, int resId, boolean leftAligned) {
int width = size.x;
int height = size.y;
BitmapCropTask cropTask;
if (uri != null) {
cropTask = new BitmapCropTask(context, uri, null, width, height, false, true, null);
} else if (imageBytes != null) {
cropTask = new BitmapCropTask(imageBytes, null, width, height, false, true, null);
} else {
cropTask =
new BitmapCropTask(context, res, resId, null, width, height, false, true, null);
}
Point bounds = cropTask.getImageBounds();
if (bounds == null || bounds.x == 0 || bounds.y == 0) {
return null;
}
RectF cropRect = WallpaperCropActivity.getMaxCropRect(
bounds.x, bounds.y, width, height, leftAligned);
cropTask.setCropBounds(cropRect);
if (cropTask.cropBitmap()) {
return cropTask.getCroppedBitmap();
} else {
return null;
}
}
private void addTemporaryWallpaperTile(Uri uri) {
mTempWallpaperTiles.add(uri);
// Add a tile for the image picked from Gallery
FrameLayout pickedImageThumbnail = (FrameLayout) getLayoutInflater().
inflate(R.layout.wallpaper_picker_item, mWallpapersView, false);
setWallpaperItemPaddingToZero(pickedImageThumbnail);
// Load the thumbnail
ImageView image = (ImageView) pickedImageThumbnail.findViewById(R.id.wallpaper_image);
Point defaultSize = getDefaultThumbnailSize(this.getResources());
Bitmap thumb = createThumbnail(defaultSize, this, uri, null, null, 0, false);
if (thumb != null) {
image.setImageBitmap(thumb);
Drawable thumbDrawable = image.getDrawable();
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error loading thumbnail for uri=" + uri);
}
mWallpapersView.addView(pickedImageThumbnail, 0);
UriWallpaperInfo info = new UriWallpaperInfo(uri);
pickedImageThumbnail.setTag(info);
info.setView(pickedImageThumbnail);
updateTileIndices();
pickedImageThumbnail.setOnClickListener(mThumbnailOnClickListener);
mThumbnailOnClickListener.onClick(pickedImageThumbnail);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICK && resultCode == RESULT_OK) {
if (data != null && data.getData() != null) {
Uri uri = data.getData();
addTemporaryWallpaperTile(uri);
}
} else if (requestCode == PICK_WALLPAPER_THIRD_PARTY_ACTIVITY) {
setResult(RESULT_OK);
finish();
} else if (requestCode == PICK_LIVE_WALLPAPER) {
WallpaperManager wm = WallpaperManager.getInstance(this);
final WallpaperInfo oldLiveWallpaper = mLiveWallpaperInfoOnPickerLaunch;
WallpaperInfo newLiveWallpaper = wm.getWallpaperInfo();
// Try to figure out if a live wallpaper was set;
if (newLiveWallpaper != null &&
(oldLiveWallpaper == null ||
!oldLiveWallpaper.getComponent().equals(newLiveWallpaper.getComponent()))) {
// Return if a live wallpaper was set
setResult(RESULT_OK);
finish();
}
}
}
static void setWallpaperItemPaddingToZero(FrameLayout frameLayout) {
frameLayout.setPadding(0, 0, 0, 0);
frameLayout.setForeground(new ZeroPaddingDrawable(frameLayout.getForeground()));
}
private void addLongPressHandler(View v) {
v.setOnLongClickListener(mLongClickListener);
}
private ArrayList<ResourceWallpaperInfo> findBundledWallpapers() {
ArrayList<ResourceWallpaperInfo> bundledWallpapers =
new ArrayList<ResourceWallpaperInfo>(24);
Pair<ApplicationInfo, Integer> r = getWallpaperArrayResourceId();
if (r != null) {
try {
Resources wallpaperRes = getPackageManager().getResourcesForApplication(r.first);
bundledWallpapers = addWallpapers(wallpaperRes, r.first.packageName, r.second);
} catch (PackageManager.NameNotFoundException e) {
}
}
// Add an entry for the default wallpaper (stored in system resources)
ResourceWallpaperInfo defaultWallpaperInfo = getDefaultWallpaperInfo();
if (defaultWallpaperInfo != null) {
bundledWallpapers.add(0, defaultWallpaperInfo);
}
return bundledWallpapers;
}
private ResourceWallpaperInfo getDefaultWallpaperInfo() {
Resources sysRes = Resources.getSystem();
int resId = sysRes.getIdentifier("default_wallpaper", "drawable", "android");
File defaultThumbFile = new File(getFilesDir(), "default_thumb.jpg");
Bitmap thumb = null;
boolean defaultWallpaperExists = false;
if (defaultThumbFile.exists()) {
thumb = BitmapFactory.decodeFile(defaultThumbFile.getAbsolutePath());
defaultWallpaperExists = true;
} else {
Point defaultThumbSize = getDefaultThumbnailSize(getResources());
thumb = createThumbnail(defaultThumbSize, this, null, null, sysRes, resId, false);
if (thumb != null) {
try {
defaultThumbFile.createNewFile();
FileOutputStream thumbFileStream =
openFileOutput(defaultThumbFile.getName(), Context.MODE_PRIVATE);
thumb.compress(Bitmap.CompressFormat.JPEG, 95, thumbFileStream);
thumbFileStream.close();
defaultWallpaperExists = true;
} catch (IOException e) {
Log.e(TAG, "Error while writing default wallpaper thumbnail to file " + e);
defaultThumbFile.delete();
}
}
}
if (defaultWallpaperExists) {
return new ResourceWallpaperInfo(sysRes, resId, new BitmapDrawable(thumb));
}
return null;
}
public Pair<ApplicationInfo, Integer> getWallpaperArrayResourceId() {
// Context.getPackageName() may return the "original" package name,
// com.android.launcher3; Resources needs the real package name,
// com.android.launcher3. So we ask Resources for what it thinks the
// package name should be.
final String packageName = getResources().getResourcePackageName(R.array.wallpapers);
try {
ApplicationInfo info = getPackageManager().getApplicationInfo(packageName, 0);
return new Pair<ApplicationInfo, Integer>(info, R.array.wallpapers);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
private ArrayList<ResourceWallpaperInfo> addWallpapers(
Resources res, String packageName, int listResId) {
ArrayList<ResourceWallpaperInfo> bundledWallpapers =
new ArrayList<ResourceWallpaperInfo>(24);
final String[] extras = res.getStringArray(listResId);
for (String extra : extras) {
int resId = res.getIdentifier(extra, "drawable", packageName);
if (resId != 0) {
final int thumbRes = res.getIdentifier(extra + "_small", "drawable", packageName);
if (thumbRes != 0) {
ResourceWallpaperInfo wallpaperInfo =
new ResourceWallpaperInfo(res, resId, res.getDrawable(thumbRes));
bundledWallpapers.add(wallpaperInfo);
// Log.d(TAG, "add: [" + packageName + "]: " + extra + " (" + res + ")");
}
} else {
Log.e(TAG, "Couldn't find wallpaper " + extra);
}
}
return bundledWallpapers;
}
public CropView getCropView() {
return mCropView;
}
public SavedWallpaperImages getSavedImages() {
return mSavedImages;
}
public void onLiveWallpaperPickerLaunch() {
mLiveWallpaperInfoOnPickerLaunch = WallpaperManager.getInstance(this).getWallpaperInfo();
}
static class ZeroPaddingDrawable extends LevelListDrawable {
public ZeroPaddingDrawable(Drawable d) {
super();
addLevel(0, 0, d);
setLevel(0);
}
@Override
public boolean getPadding(Rect padding) {
padding.set(0, 0, 0, 0);
return true;
}
}
private static class BuiltInWallpapersAdapter extends BaseAdapter implements ListAdapter {
private LayoutInflater mLayoutInflater;
private ArrayList<ResourceWallpaperInfo> mWallpapers;
BuiltInWallpapersAdapter(Activity activity, ArrayList<ResourceWallpaperInfo> wallpapers) {
mLayoutInflater = activity.getLayoutInflater();
mWallpapers = wallpapers;
}
public int getCount() {
return mWallpapers.size();
}
public ResourceWallpaperInfo getItem(int position) {
return mWallpapers.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Drawable thumb = mWallpapers.get(position).mThumb;
if (thumb == null) {
Log.e(TAG, "Error decoding thumbnail for wallpaper #" + position);
}
return createImageTileView(mLayoutInflater, position, convertView, parent, thumb);
}
}
public static View createImageTileView(LayoutInflater layoutInflater, int position,
View convertView, ViewGroup parent, Drawable thumb) {
View view;
if (convertView == null) {
view = layoutInflater.inflate(R.layout.wallpaper_picker_item, parent, false);
} else {
view = convertView;
}
setWallpaperItemPaddingToZero((FrameLayout) view);
ImageView image = (ImageView) view.findViewById(R.id.wallpaper_image);
if (thumb != null) {
image.setImageDrawable(thumb);
thumb.setDither(true);
}
return view;
}
}
|
diff --git a/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java b/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java
index f990bae16..bb3c5e85e 100644
--- a/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java
+++ b/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java
@@ -1,208 +1,206 @@
package fr.cg95.cvq.service.users.impl;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import com.google.gson.JsonObject;
import fr.cg95.cvq.business.authority.LocalAuthorityResource;
import fr.cg95.cvq.business.users.HomeFolder;
import fr.cg95.cvq.business.users.Individual;
import fr.cg95.cvq.business.users.UserAction;
import fr.cg95.cvq.business.users.UserState;
import fr.cg95.cvq.business.users.UserWorkflow;
import fr.cg95.cvq.business.users.UserEvent;
import fr.cg95.cvq.dao.users.IHomeFolderDAO;
import fr.cg95.cvq.exception.CvqInvalidTransitionException;
import fr.cg95.cvq.exception.CvqModelException;
import fr.cg95.cvq.security.SecurityContext;
import fr.cg95.cvq.security.annotation.Context;
import fr.cg95.cvq.security.annotation.ContextPrivilege;
import fr.cg95.cvq.security.annotation.ContextType;
import fr.cg95.cvq.service.authority.ILocalAuthorityRegistry;
import fr.cg95.cvq.service.users.IHomeFolderService;
import fr.cg95.cvq.service.users.IUserWorkflowService;
import fr.cg95.cvq.util.translation.ITranslationService;
public class UserWorkflowService implements IUserWorkflowService, ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
private ILocalAuthorityRegistry localAuthorityRegistry;
private ITranslationService translationService;
private IHomeFolderService homeFolderService;
private IHomeFolderDAO homeFolderDAO;
private Map<String, UserWorkflow> workflows = new HashMap<String, UserWorkflow>();
@Override
public UserState[] getPossibleTransitions(UserState state) {
return getWorkflow().getPossibleTransitions(state);
}
@Override
@Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.READ)
public UserState[] getPossibleTransitions(Individual user) {
UserState[] allStates = getPossibleTransitions(user.getState());
List<UserState> result = new ArrayList<UserState>(allStates.length);
for (UserState state : allStates) result.add(state);
if (homeFolderService.getHomeFolderResponsible(user.getHomeFolder().getId()).getId()
.equals(user.getId())) {
for (Individual i : user.getHomeFolder().getIndividuals()) {
if (!i.getId().equals(user.getId()) && !UserState.ARCHIVED.equals(i.getState())) {
result.remove(UserState.ARCHIVED);
break;
}
}
}
return result.toArray(new UserState[result.size()]);
}
@Override
@Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.READ)
public UserState[] getPossibleTransitions(HomeFolder user) {
return getPossibleTransitions(user.getState());
}
@Override
public boolean isValidTransition(UserState from, UserState to) {
return getWorkflow().isValidTransition(from, to);
}
@Override
public UserState[] getStatesBefore(UserState state) {
return getWorkflow().getStatesBefore(state);
}
@Override
public UserState[] getStatesWithProperty(String propertyName) {
return getWorkflow().getStatesWithProperty(propertyName);
}
private UserWorkflow getWorkflow() {
String name = SecurityContext.getCurrentSite().getName();
UserWorkflow workflow = workflows.get(name);
if (workflow == null) {
File file = localAuthorityRegistry.getLocalAuthorityResourceFileForLocalAuthority(name,
LocalAuthorityResource.Type.XML, "userWorkflow", false);
if (file.exists()) {
workflow = UserWorkflow.load(file);
workflows.put(name, workflow);
} else {
workflow = workflows.get("default");
if (workflow == null) {
file = localAuthorityRegistry.getReferentialResource(
LocalAuthorityResource.Type.XML, "userWorkflow");
workflow = UserWorkflow.load(file);
workflows.put("default", workflow);
}
}
}
return workflow;
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE)
public void changeState(HomeFolder homeFolder, UserState state)
throws CvqModelException, CvqInvalidTransitionException {
if (!isValidTransition(homeFolder.getState(), state))
throw new CvqInvalidTransitionException(
translationService.translate(
"user.state." + homeFolder.getState().toString().toLowerCase()),
translationService.translate(
"user.state." + state.toString().toLowerCase()));
if (UserState.VALID.equals(state)) {
for (Individual individual : homeFolder.getIndividuals()) {
if (!UserState.VALID.equals(individual.getState())
&& !UserState.ARCHIVED.equals(individual.getState()))
throw new CvqModelException("");
}
}
homeFolder.setState(state);
JsonObject payload = new JsonObject();
payload.addProperty("state", state.toString());
UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, homeFolder.getId(), payload);
homeFolder.getActions().add(action);
homeFolderDAO.update(homeFolder);
applicationEventPublisher.publishEvent(new UserEvent(this, action));
}
@Override
@Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE)
public void changeState(Individual individual, UserState state)
throws CvqModelException, CvqInvalidTransitionException {
if (!isValidTransition(individual.getState(), state))
throw new CvqInvalidTransitionException(
translationService.translate(
"user.state." + individual.getState().toString().toLowerCase()),
translationService.translate(
"user.state." + state.toString().toLowerCase()));
individual.setState(state);
individual.setLastModificationDate(new Date());
if (SecurityContext.isBackOfficeContext()) {
individual.setQoS(null);
}
HomeFolder homeFolder = individual.getHomeFolder();
if (UserState.ARCHIVED.equals(state) && individual.getId().equals(
homeFolderService.getHomeFolderResponsible(homeFolder.getId()).getId())) {
for (Individual i : homeFolder.getIndividuals()) {
if (!UserState.ARCHIVED.equals(i.getState()))
throw new CvqModelException("user.state.error.mustArchiveResponsibleLast");
}
}
JsonObject payload = new JsonObject();
payload.addProperty("state", state.toString());
UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, individual.getId(), payload);
individual.getHomeFolder().getActions().add(action);
homeFolderDAO.update(individual.getHomeFolder());
applicationEventPublisher.publishEvent(new UserEvent(this, action));
if (UserState.INVALID.equals(state) && !UserState.INVALID.equals(homeFolder.getState()))
changeState(individual.getHomeFolder(), UserState.INVALID);
else if (UserState.VALID.equals(state) || UserState.ARCHIVED.equals(state)) {
UserState homeFolderState = state;
for (Individual i : individual.getHomeFolder().getIndividuals()) {
if (UserState.VALID.equals(i.getState())) {
homeFolderState = UserState.VALID;
} else if (!UserState.ARCHIVED.equals(i.getState())) {
homeFolderState = null;
break;
}
}
- if (homeFolderState != null
- && homeFolderState.equals(UserState.VALID)
- && !UserState.VALID.equals(individual.getHomeFolder().getState()))
+ if (homeFolderState != null && !homeFolderState.equals(homeFolder.getState()))
changeState(individual.getHomeFolder(), homeFolderState);
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void setLocalAuthorityRegistry(ILocalAuthorityRegistry localAuthorityRegistry) {
this.localAuthorityRegistry = localAuthorityRegistry;
}
public void setTranslationService(ITranslationService translationService) {
this.translationService = translationService;
}
public void setHomeFolderService(IHomeFolderService homeFolderService) {
this.homeFolderService = homeFolderService;
}
public void setHomeFolderDAO(IHomeFolderDAO homeFolderDAO) {
this.homeFolderDAO = homeFolderDAO;
}
}
| true | true | public void changeState(Individual individual, UserState state)
throws CvqModelException, CvqInvalidTransitionException {
if (!isValidTransition(individual.getState(), state))
throw new CvqInvalidTransitionException(
translationService.translate(
"user.state." + individual.getState().toString().toLowerCase()),
translationService.translate(
"user.state." + state.toString().toLowerCase()));
individual.setState(state);
individual.setLastModificationDate(new Date());
if (SecurityContext.isBackOfficeContext()) {
individual.setQoS(null);
}
HomeFolder homeFolder = individual.getHomeFolder();
if (UserState.ARCHIVED.equals(state) && individual.getId().equals(
homeFolderService.getHomeFolderResponsible(homeFolder.getId()).getId())) {
for (Individual i : homeFolder.getIndividuals()) {
if (!UserState.ARCHIVED.equals(i.getState()))
throw new CvqModelException("user.state.error.mustArchiveResponsibleLast");
}
}
JsonObject payload = new JsonObject();
payload.addProperty("state", state.toString());
UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, individual.getId(), payload);
individual.getHomeFolder().getActions().add(action);
homeFolderDAO.update(individual.getHomeFolder());
applicationEventPublisher.publishEvent(new UserEvent(this, action));
if (UserState.INVALID.equals(state) && !UserState.INVALID.equals(homeFolder.getState()))
changeState(individual.getHomeFolder(), UserState.INVALID);
else if (UserState.VALID.equals(state) || UserState.ARCHIVED.equals(state)) {
UserState homeFolderState = state;
for (Individual i : individual.getHomeFolder().getIndividuals()) {
if (UserState.VALID.equals(i.getState())) {
homeFolderState = UserState.VALID;
} else if (!UserState.ARCHIVED.equals(i.getState())) {
homeFolderState = null;
break;
}
}
if (homeFolderState != null
&& homeFolderState.equals(UserState.VALID)
&& !UserState.VALID.equals(individual.getHomeFolder().getState()))
changeState(individual.getHomeFolder(), homeFolderState);
}
}
| public void changeState(Individual individual, UserState state)
throws CvqModelException, CvqInvalidTransitionException {
if (!isValidTransition(individual.getState(), state))
throw new CvqInvalidTransitionException(
translationService.translate(
"user.state." + individual.getState().toString().toLowerCase()),
translationService.translate(
"user.state." + state.toString().toLowerCase()));
individual.setState(state);
individual.setLastModificationDate(new Date());
if (SecurityContext.isBackOfficeContext()) {
individual.setQoS(null);
}
HomeFolder homeFolder = individual.getHomeFolder();
if (UserState.ARCHIVED.equals(state) && individual.getId().equals(
homeFolderService.getHomeFolderResponsible(homeFolder.getId()).getId())) {
for (Individual i : homeFolder.getIndividuals()) {
if (!UserState.ARCHIVED.equals(i.getState()))
throw new CvqModelException("user.state.error.mustArchiveResponsibleLast");
}
}
JsonObject payload = new JsonObject();
payload.addProperty("state", state.toString());
UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, individual.getId(), payload);
individual.getHomeFolder().getActions().add(action);
homeFolderDAO.update(individual.getHomeFolder());
applicationEventPublisher.publishEvent(new UserEvent(this, action));
if (UserState.INVALID.equals(state) && !UserState.INVALID.equals(homeFolder.getState()))
changeState(individual.getHomeFolder(), UserState.INVALID);
else if (UserState.VALID.equals(state) || UserState.ARCHIVED.equals(state)) {
UserState homeFolderState = state;
for (Individual i : individual.getHomeFolder().getIndividuals()) {
if (UserState.VALID.equals(i.getState())) {
homeFolderState = UserState.VALID;
} else if (!UserState.ARCHIVED.equals(i.getState())) {
homeFolderState = null;
break;
}
}
if (homeFolderState != null && !homeFolderState.equals(homeFolder.getState()))
changeState(individual.getHomeFolder(), homeFolderState);
}
}
|
diff --git a/src/com/android/calendar/MonthActivity.java b/src/com/android/calendar/MonthActivity.java
index ed9bee3d..05d0a51f 100644
--- a/src/com/android/calendar/MonthActivity.java
+++ b/src/com/android/calendar/MonthActivity.java
@@ -1,343 +1,343 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar;
import static android.provider.Calendar.EVENT_BEGIN_TIME;
import dalvik.system.VMRuntime;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Calendar.Events;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import android.widget.Gallery.LayoutParams;
import java.util.Calendar;
public class MonthActivity extends Activity implements ViewSwitcher.ViewFactory,
Navigator, AnimationListener {
private static final int INITIAL_HEAP_SIZE = 4 * 1024 * 1024;
private Animation mInAnimationPast;
private Animation mInAnimationFuture;
private Animation mOutAnimationPast;
private Animation mOutAnimationFuture;
private ViewSwitcher mSwitcher;
private Time mTime;
private ContentResolver mContentResolver;
EventLoader mEventLoader;
private int mStartDay;
private ProgressBar mProgressBar;
private static final int DAY_OF_WEEK_LABEL_IDS[] = {
R.id.day0, R.id.day1, R.id.day2, R.id.day3, R.id.day4, R.id.day5, R.id.day6
};
private static final int DAY_OF_WEEK_KINDS[] = {
Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY,
Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY
};
protected void startProgressSpinner() {
// start the progress spinner
mProgressBar.setVisibility(View.VISIBLE);
}
protected void stopProgressSpinner() {
// stop the progress spinner
mProgressBar.setVisibility(View.GONE);
}
/* ViewSwitcher.ViewFactory interface methods */
public View makeView() {
MonthView mv = new MonthView(this, this);
mv.setLayoutParams(new ViewSwitcher.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mv.setSelectedTime(mTime);
return mv;
}
/* Navigator interface methods */
public void goTo(Time time, boolean animate) {
TextView title = (TextView) findViewById(R.id.title);
title.setText(Utils.formatMonthYear(time));
MonthView current = (MonthView) mSwitcher.getCurrentView();
current.dismissPopup();
Time currentTime = current.getTime();
// Compute a month number that is monotonically increasing for any
// two adjacent months.
// This is faster than calling getSelectedTime() because we avoid
// a call to Time#normalize().
if (animate) {
int currentMonth = currentTime.month + currentTime.year * 12;
int nextMonth = time.month + time.year * 12;
if (nextMonth < currentMonth) {
mSwitcher.setInAnimation(mInAnimationPast);
mSwitcher.setOutAnimation(mOutAnimationPast);
} else {
mSwitcher.setInAnimation(mInAnimationFuture);
mSwitcher.setOutAnimation(mOutAnimationFuture);
}
}
MonthView next = (MonthView) mSwitcher.getNextView();
next.setSelectionMode(current.getSelectionMode());
next.setSelectedTime(time);
next.reloadEvents();
next.animationStarted();
mSwitcher.showNext();
next.requestFocus();
mTime = time;
}
public void goToToday() {
Time now = new Time();
now.set(System.currentTimeMillis());
now.minute = 0;
now.second = 0;
now.normalize(false);
TextView title = (TextView) findViewById(R.id.title);
title.setText(Utils.formatMonthYear(now));
mTime = now;
MonthView view = (MonthView) mSwitcher.getCurrentView();
view.setSelectedTime(now);
view.reloadEvents();
}
public long getSelectedTime() {
MonthView mv = (MonthView) mSwitcher.getCurrentView();
return mv.getSelectedTimeInMillis();
}
public boolean getAllDay() {
return false;
}
int getStartDay() {
return mStartDay;
}
void eventsChanged() {
MonthView view = (MonthView) mSwitcher.getCurrentView();
view.reloadEvents();
}
/**
* Listens for intent broadcasts
*/
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED)
|| action.equals(Intent.ACTION_DATE_CHANGED)
|| action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
eventsChanged();
}
}
};
// Create an observer so that we can update the views whenever a
// Calendar event changes.
private ContentObserver mObserver = new ContentObserver(new Handler())
{
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
eventsChanged();
}
};
public void onAnimationStart(Animation animation) {
}
// Notifies the MonthView when an animation has finished.
public void onAnimationEnd(Animation animation) {
MonthView monthView = (MonthView) mSwitcher.getCurrentView();
monthView.animationFinished();
}
public void onAnimationRepeat(Animation animation) {
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Eliminate extra GCs during startup by setting the initial heap size to 4MB.
// TODO: We should restore the old heap size once the activity reaches the idle state
VMRuntime.getRuntime().setMinimumHeapSize(INITIAL_HEAP_SIZE);
setContentView(R.layout.month_activity);
mContentResolver = getContentResolver();
long time;
if (icicle != null) {
time = icicle.getLong(EVENT_BEGIN_TIME);
} else {
time = Utils.timeFromIntentInMillis(getIntent());
}
mTime = new Time();
mTime.set(time);
mTime.normalize(true);
// Get first day of week based on locale and populate the day headers
mStartDay = Calendar.getInstance().getFirstDayOfWeek();
int diff = mStartDay - Calendar.SUNDAY - 1;
final int startDay = Utils.getFirstDayOfWeek();
final int sundayColor = getResources().getColor(R.color.sunday_text_color);
final int saturdayColor = getResources().getColor(R.color.saturday_text_color);
for (int day = 0; day < 7; day++) {
final String dayString = DateUtils.getDayOfWeekString(
- (DAY_OF_WEEK_KINDS[day] + diff) % 7 +1, DateUtils.LENGTH_MEDIUM);
+ (DAY_OF_WEEK_KINDS[day] + diff) % 7 + 1, DateUtils.LENGTH_MEDIUM);
final TextView label = (TextView) findViewById(DAY_OF_WEEK_LABEL_IDS[day]);
label.setText(dayString);
if (Utils.isSunday(day, startDay)) {
label.setTextColor(sundayColor);
} else if (Utils.isSaturday(day, startDay)) {
label.setTextColor(saturdayColor);
}
}
// Set the initial title
TextView title = (TextView) findViewById(R.id.title);
title.setText(Utils.formatMonthYear(mTime));
mEventLoader = new EventLoader(this);
mProgressBar = (ProgressBar) findViewById(R.id.progress_circular);
mSwitcher = (ViewSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.getCurrentView().requestFocus();
mInAnimationPast = AnimationUtils.loadAnimation(this, R.anim.slide_down_in);
mOutAnimationPast = AnimationUtils.loadAnimation(this, R.anim.slide_down_out);
mInAnimationFuture = AnimationUtils.loadAnimation(this, R.anim.slide_up_in);
mOutAnimationFuture = AnimationUtils.loadAnimation(this, R.anim.slide_up_out);
mInAnimationPast.setAnimationListener(this);
mInAnimationFuture.setAnimationListener(this);
}
@Override
protected void onNewIntent(Intent intent) {
long timeMillis = Utils.timeFromIntentInMillis(intent);
if (timeMillis > 0) {
Time time = new Time();
time.set(timeMillis);
goTo(time, false);
}
}
@Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
mEventLoader.stopBackgroundThread();
}
mContentResolver.unregisterContentObserver(mObserver);
unregisterReceiver(mIntentReceiver);
MonthView view = (MonthView) mSwitcher.getCurrentView();
view.dismissPopup();
view = (MonthView) mSwitcher.getNextView();
view.dismissPopup();
mEventLoader.stopBackgroundThread();
// Record Month View as the (new) start view
Utils.setDefaultView(this, CalendarApplication.MONTH_VIEW_ID);
}
@Override
protected void onResume() {
super.onResume();
mEventLoader.startBackgroundThread();
eventsChanged();
MonthView view1 = (MonthView) mSwitcher.getCurrentView();
MonthView view2 = (MonthView) mSwitcher.getNextView();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String str = prefs.getString(CalendarPreferenceActivity.KEY_DETAILED_VIEW,
CalendarPreferenceActivity.DEFAULT_DETAILED_VIEW);
view1.setDetailedView(str);
view2.setDetailedView(str);
// Register for Intent broadcasts
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_DATE_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
registerReceiver(mIntentReceiver, filter);
mContentResolver.registerContentObserver(Events.CONTENT_URI,
true, mObserver);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(EVENT_BEGIN_TIME, mTime.toMillis(true));
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuHelper.onPrepareOptionsMenu(this, menu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuHelper.onCreateOptionsMenu(menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MenuHelper.onOptionsItemSelected(this, item, this);
return super.onOptionsItemSelected(item);
}
}
| true | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Eliminate extra GCs during startup by setting the initial heap size to 4MB.
// TODO: We should restore the old heap size once the activity reaches the idle state
VMRuntime.getRuntime().setMinimumHeapSize(INITIAL_HEAP_SIZE);
setContentView(R.layout.month_activity);
mContentResolver = getContentResolver();
long time;
if (icicle != null) {
time = icicle.getLong(EVENT_BEGIN_TIME);
} else {
time = Utils.timeFromIntentInMillis(getIntent());
}
mTime = new Time();
mTime.set(time);
mTime.normalize(true);
// Get first day of week based on locale and populate the day headers
mStartDay = Calendar.getInstance().getFirstDayOfWeek();
int diff = mStartDay - Calendar.SUNDAY - 1;
final int startDay = Utils.getFirstDayOfWeek();
final int sundayColor = getResources().getColor(R.color.sunday_text_color);
final int saturdayColor = getResources().getColor(R.color.saturday_text_color);
for (int day = 0; day < 7; day++) {
final String dayString = DateUtils.getDayOfWeekString(
(DAY_OF_WEEK_KINDS[day] + diff) % 7 +1, DateUtils.LENGTH_MEDIUM);
final TextView label = (TextView) findViewById(DAY_OF_WEEK_LABEL_IDS[day]);
label.setText(dayString);
if (Utils.isSunday(day, startDay)) {
label.setTextColor(sundayColor);
} else if (Utils.isSaturday(day, startDay)) {
label.setTextColor(saturdayColor);
}
}
// Set the initial title
TextView title = (TextView) findViewById(R.id.title);
title.setText(Utils.formatMonthYear(mTime));
mEventLoader = new EventLoader(this);
mProgressBar = (ProgressBar) findViewById(R.id.progress_circular);
mSwitcher = (ViewSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.getCurrentView().requestFocus();
mInAnimationPast = AnimationUtils.loadAnimation(this, R.anim.slide_down_in);
mOutAnimationPast = AnimationUtils.loadAnimation(this, R.anim.slide_down_out);
mInAnimationFuture = AnimationUtils.loadAnimation(this, R.anim.slide_up_in);
mOutAnimationFuture = AnimationUtils.loadAnimation(this, R.anim.slide_up_out);
mInAnimationPast.setAnimationListener(this);
mInAnimationFuture.setAnimationListener(this);
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Eliminate extra GCs during startup by setting the initial heap size to 4MB.
// TODO: We should restore the old heap size once the activity reaches the idle state
VMRuntime.getRuntime().setMinimumHeapSize(INITIAL_HEAP_SIZE);
setContentView(R.layout.month_activity);
mContentResolver = getContentResolver();
long time;
if (icicle != null) {
time = icicle.getLong(EVENT_BEGIN_TIME);
} else {
time = Utils.timeFromIntentInMillis(getIntent());
}
mTime = new Time();
mTime.set(time);
mTime.normalize(true);
// Get first day of week based on locale and populate the day headers
mStartDay = Calendar.getInstance().getFirstDayOfWeek();
int diff = mStartDay - Calendar.SUNDAY - 1;
final int startDay = Utils.getFirstDayOfWeek();
final int sundayColor = getResources().getColor(R.color.sunday_text_color);
final int saturdayColor = getResources().getColor(R.color.saturday_text_color);
for (int day = 0; day < 7; day++) {
final String dayString = DateUtils.getDayOfWeekString(
(DAY_OF_WEEK_KINDS[day] + diff) % 7 + 1, DateUtils.LENGTH_MEDIUM);
final TextView label = (TextView) findViewById(DAY_OF_WEEK_LABEL_IDS[day]);
label.setText(dayString);
if (Utils.isSunday(day, startDay)) {
label.setTextColor(sundayColor);
} else if (Utils.isSaturday(day, startDay)) {
label.setTextColor(saturdayColor);
}
}
// Set the initial title
TextView title = (TextView) findViewById(R.id.title);
title.setText(Utils.formatMonthYear(mTime));
mEventLoader = new EventLoader(this);
mProgressBar = (ProgressBar) findViewById(R.id.progress_circular);
mSwitcher = (ViewSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.getCurrentView().requestFocus();
mInAnimationPast = AnimationUtils.loadAnimation(this, R.anim.slide_down_in);
mOutAnimationPast = AnimationUtils.loadAnimation(this, R.anim.slide_down_out);
mInAnimationFuture = AnimationUtils.loadAnimation(this, R.anim.slide_up_in);
mOutAnimationFuture = AnimationUtils.loadAnimation(this, R.anim.slide_up_out);
mInAnimationPast.setAnimationListener(this);
mInAnimationFuture.setAnimationListener(this);
}
|
diff --git a/control/src/main/java/org/syphr/mythtv/control/impl/Command0_24QueryVolume.java b/control/src/main/java/org/syphr/mythtv/control/impl/Command0_24QueryVolume.java
index b8ec0ca..db6c2b6 100644
--- a/control/src/main/java/org/syphr/mythtv/control/impl/Command0_24QueryVolume.java
+++ b/control/src/main/java/org/syphr/mythtv/control/impl/Command0_24QueryVolume.java
@@ -1,45 +1,52 @@
/*
* Copyright 2011 Gregory P. Moyer
*
* 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.syphr.mythtv.control.impl;
import java.io.IOException;
import org.syphr.mythtv.util.exception.ProtocolException;
import org.syphr.mythtv.util.exception.ProtocolException.Direction;
import org.syphr.mythtv.util.socket.AbstractCommand;
import org.syphr.mythtv.util.socket.SocketManager;
/* default */class Command0_24QueryVolume extends AbstractCommand<Integer>
{
@Override
protected String getMessage() throws ProtocolException
{
return "query volume";
}
@Override
public Integer send(SocketManager socketManager) throws IOException
{
String response = socketManager.sendAndWait(getMessage());
if (response.indexOf('%') < 0)
{
throw new ProtocolException(response, Direction.RECEIVE);
}
- return Integer.parseInt(response.substring(0, response.length() - 1));
+ try
+ {
+ return Integer.parseInt(response.substring(0, response.length() - 1));
+ }
+ catch (NumberFormatException e)
+ {
+ throw new ProtocolException(response, Direction.RECEIVE, e);
+ }
}
}
| true | true | public Integer send(SocketManager socketManager) throws IOException
{
String response = socketManager.sendAndWait(getMessage());
if (response.indexOf('%') < 0)
{
throw new ProtocolException(response, Direction.RECEIVE);
}
return Integer.parseInt(response.substring(0, response.length() - 1));
}
| public Integer send(SocketManager socketManager) throws IOException
{
String response = socketManager.sendAndWait(getMessage());
if (response.indexOf('%') < 0)
{
throw new ProtocolException(response, Direction.RECEIVE);
}
try
{
return Integer.parseInt(response.substring(0, response.length() - 1));
}
catch (NumberFormatException e)
{
throw new ProtocolException(response, Direction.RECEIVE, e);
}
}
|
diff --git a/native/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java b/native/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
index b128eb25c..9a35e3b22 100644
--- a/native/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
+++ b/native/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
@@ -1,50 +1,50 @@
/*
* Copyright (c) 2012, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.phonegap;
import java.util.List;
import android.test.InstrumentationTestCase;
/**
* Tests for SDKInfoPlugin
*
*/
public class SDKInfoPluginTest extends InstrumentationTestCase {
/**
* Test for getForcePluginsFromXML
*/
public void testGetForcePluginsFromXML() {
List<String> plugins = SDKInfoPlugin.getForcePluginsFromXML(getInstrumentation().getTargetContext());
- assertEquals("Wrong number of force plugins", 2, plugins.size());
+ assertEquals("Wrong number of force plugins", 3, plugins.size());
assertTrue("oauth plugin should have been returned", plugins.contains("com.salesforce.oauth"));
assertTrue("sdkinfo plugin should have been returned", plugins.contains("com.salesforce.sdkinfo"));
}
}
| true | true | public void testGetForcePluginsFromXML() {
List<String> plugins = SDKInfoPlugin.getForcePluginsFromXML(getInstrumentation().getTargetContext());
assertEquals("Wrong number of force plugins", 2, plugins.size());
assertTrue("oauth plugin should have been returned", plugins.contains("com.salesforce.oauth"));
assertTrue("sdkinfo plugin should have been returned", plugins.contains("com.salesforce.sdkinfo"));
}
| public void testGetForcePluginsFromXML() {
List<String> plugins = SDKInfoPlugin.getForcePluginsFromXML(getInstrumentation().getTargetContext());
assertEquals("Wrong number of force plugins", 3, plugins.size());
assertTrue("oauth plugin should have been returned", plugins.contains("com.salesforce.oauth"));
assertTrue("sdkinfo plugin should have been returned", plugins.contains("com.salesforce.sdkinfo"));
}
|
diff --git a/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/TestServlet.java b/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/TestServlet.java
index ad8e05af..2b0c1a44 100644
--- a/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/TestServlet.java
+++ b/jaxrs/async-server/src/main/java/org/javaee7/jaxrs/asyncserver/TestServlet.java
@@ -1,133 +1,133 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.javaee7.jaxrs.asyncserver;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
/**
* @author Arun Gupta
*/
@WebServlet(urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
- out.println("<title>Servlet TestServlet</title>");
+ out.println("<title>JAX-RS Async Server</title>");
out.println("</head>");
out.println("<body>");
- out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
+ out.println("<h1>JAX-RS Async Server</h1>");
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://"
+ request.getServerName()
+ ":"
+ request.getServerPort()
+ request.getContextPath()
+ "/webresources/fruits");
String result = target.request().get(String.class);
out.println("Waited for 3 seconds ...<br>");
out.println("Received response: " + result);
out.println("</body>");
out.println("</html>");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| false | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://"
+ request.getServerName()
+ ":"
+ request.getServerPort()
+ request.getContextPath()
+ "/webresources/fruits");
String result = target.request().get(String.class);
out.println("Waited for 3 seconds ...<br>");
out.println("Received response: " + result);
out.println("</body>");
out.println("</html>");
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>JAX-RS Async Server</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>JAX-RS Async Server</h1>");
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://"
+ request.getServerName()
+ ":"
+ request.getServerPort()
+ request.getContextPath()
+ "/webresources/fruits");
String result = target.request().get(String.class);
out.println("Waited for 3 seconds ...<br>");
out.println("Received response: " + result);
out.println("</body>");
out.println("</html>");
}
|
diff --git a/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java b/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java
index b5768d210..c4045feb2 100644
--- a/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java
+++ b/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/admin/LockssAuthServiceBean.java
@@ -1,189 +1,188 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* LockssServerAuth.java
*
* Created on Mar 23, 2007, 3:13 PM
*
*/
package edu.harvard.iq.dvn.core.admin;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCNetworkServiceLocal;
import edu.harvard.iq.dvn.core.vdc.LockssServer;
import edu.harvard.iq.dvn.core.vdc.LockssConfig;
import edu.harvard.iq.dvn.core.vdc.LockssConfig.ServerAccess;
import edu.harvard.iq.dvn.core.util.DomainMatchUtil;
import java.util.*;
import java.util.logging.*;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
/**
*
* @author landreev
*/
@Stateless
public class LockssAuthServiceBean implements LockssAuthServiceLocal {
@EJB
VDCNetworkServiceLocal vdcNetworkService;
private static Logger dbgLog = Logger.getLogger(LockssAuthServiceBean.class.getPackage().getName());
/* constructor: */
public LockssAuthServiceBean() {
}
/*
* isAuthorizedLockssServer method is used to check if the remote LOCKSS
* server is authorized to crawl this set/dv at all; meaning, at this
* point we are not authorizing them to download any particular files,
* just deciding whether to show them the Manifest page.
*/
public Boolean isAuthorizedLockssServer ( VDC vdc,
HttpServletRequest req ) {
String remoteAddress = req.getRemoteHost();
if (remoteAddress == null || remoteAddress.equals("")) {
return false;
}
LockssConfig lockssConfig = null;
if (vdc != null) {
lockssConfig = vdc.getLockssConfig();
} else {
lockssConfig = vdcNetworkService.getLockssConfig();
}
if (lockssConfig == null) {
return false;
}
if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) {
return true;
}
List<LockssServer> lockssServers = lockssConfig.getLockssServers();
if (lockssServers == null || lockssServers.size() == 0) {
return false;
}
for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) {
LockssServer elem = it.next();
if (elem.getIpAddress() != null) {
if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) {
return true;
}
}
}
return false;
}
/*
* isAuthorizedLockssDownload performs authorization on individual files
* that the crawler is trying to download. This authorization depends on
* how this configuration is configured, whether it's open to all lockss
* servers or an IP group, and whether the file in question is restricted.
*/
public Boolean isAuthorizedLockssDownload ( VDC vdc,
HttpServletRequest req,
Boolean fileIsRestricted) {
String remoteAddress = req.getRemoteHost();
if (remoteAddress == null || remoteAddress.equals("")) {
return false;
}
LockssConfig lockssConfig = null;
if (vdc != null) {
if (vdc.getLockssConfig()!=null) {
lockssConfig = vdc.getLockssConfig();
- } else {
- lockssConfig = vdcNetworkService.getLockssConfig();
- }
+ }
}
if (lockssConfig == null) {
return false;
}
// If this LOCKSS configuration is open to ALL, we allow downloads
- // of public files but not of the restricted ones:
+ // of public files; so if the file is public, we can return true.
+ // We *may* also allow access to restricted ones; but only to
+ // select servers (we'll check for that further below).
if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) {
- if (fileIsRestricted) {
- return false;
+ if (!fileIsRestricted) {
+ return true;
}
- return true;
}
// This is a LOCKSS configuration open only to group of servers.
//
// Before we go through the list of the authorized IP addresses
// and see if the remote address matches, let's first check if
// the file is restricted and if so, whether the LOCKSS config
// allows downloads of restricted files; because if not, we can
// return false right away:
if (fileIsRestricted) {
if (!lockssConfig.isAllowRestricted()) {
return false;
}
}
// Now let's get the list of the authorized servers:
List<LockssServer> lockssServers = lockssConfig.getLockssServers();
if (lockssServers == null || lockssServers.size() == 0) {
return false;
}
for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) {
LockssServer elem = it.next();
if (elem.getIpAddress() != null) {
if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) {
return true;
}
}
}
// We've exhausted the possibilities, returning false:
return false;
}
}
| false | true | public Boolean isAuthorizedLockssDownload ( VDC vdc,
HttpServletRequest req,
Boolean fileIsRestricted) {
String remoteAddress = req.getRemoteHost();
if (remoteAddress == null || remoteAddress.equals("")) {
return false;
}
LockssConfig lockssConfig = null;
if (vdc != null) {
if (vdc.getLockssConfig()!=null) {
lockssConfig = vdc.getLockssConfig();
} else {
lockssConfig = vdcNetworkService.getLockssConfig();
}
}
if (lockssConfig == null) {
return false;
}
// If this LOCKSS configuration is open to ALL, we allow downloads
// of public files but not of the restricted ones:
if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) {
if (fileIsRestricted) {
return false;
}
return true;
}
// This is a LOCKSS configuration open only to group of servers.
//
// Before we go through the list of the authorized IP addresses
// and see if the remote address matches, let's first check if
// the file is restricted and if so, whether the LOCKSS config
// allows downloads of restricted files; because if not, we can
// return false right away:
if (fileIsRestricted) {
if (!lockssConfig.isAllowRestricted()) {
return false;
}
}
// Now let's get the list of the authorized servers:
List<LockssServer> lockssServers = lockssConfig.getLockssServers();
if (lockssServers == null || lockssServers.size() == 0) {
return false;
}
for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) {
LockssServer elem = it.next();
if (elem.getIpAddress() != null) {
if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) {
return true;
}
}
}
// We've exhausted the possibilities, returning false:
return false;
}
| public Boolean isAuthorizedLockssDownload ( VDC vdc,
HttpServletRequest req,
Boolean fileIsRestricted) {
String remoteAddress = req.getRemoteHost();
if (remoteAddress == null || remoteAddress.equals("")) {
return false;
}
LockssConfig lockssConfig = null;
if (vdc != null) {
if (vdc.getLockssConfig()!=null) {
lockssConfig = vdc.getLockssConfig();
}
}
if (lockssConfig == null) {
return false;
}
// If this LOCKSS configuration is open to ALL, we allow downloads
// of public files; so if the file is public, we can return true.
// We *may* also allow access to restricted ones; but only to
// select servers (we'll check for that further below).
if (ServerAccess.ALL.equals(lockssConfig.getserverAccess())) {
if (!fileIsRestricted) {
return true;
}
}
// This is a LOCKSS configuration open only to group of servers.
//
// Before we go through the list of the authorized IP addresses
// and see if the remote address matches, let's first check if
// the file is restricted and if so, whether the LOCKSS config
// allows downloads of restricted files; because if not, we can
// return false right away:
if (fileIsRestricted) {
if (!lockssConfig.isAllowRestricted()) {
return false;
}
}
// Now let's get the list of the authorized servers:
List<LockssServer> lockssServers = lockssConfig.getLockssServers();
if (lockssServers == null || lockssServers.size() == 0) {
return false;
}
for (Iterator<LockssServer> it = lockssServers.iterator(); it.hasNext();) {
LockssServer elem = it.next();
if (elem.getIpAddress() != null) {
if (DomainMatchUtil.isDomainMatch(remoteAddress, elem.getIpAddress())) {
return true;
}
}
}
// We've exhausted the possibilities, returning false:
return false;
}
|
diff --git a/src/test/org/jdesktop/swingx/plaf/PromptTextUITest_Base.java b/src/test/org/jdesktop/swingx/plaf/PromptTextUITest_Base.java
index 2f8e4798..000262ea 100644
--- a/src/test/org/jdesktop/swingx/plaf/PromptTextUITest_Base.java
+++ b/src/test/org/jdesktop/swingx/plaf/PromptTextUITest_Base.java
@@ -1,127 +1,128 @@
package org.jdesktop.swingx.plaf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.awt.Color;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Rectangle;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.text.JTextComponent;
import org.jdesktop.swingx.prompt.PromptSupport;
import org.jdesktop.swingx.util.JVM;
import org.junit.Before;
import org.junit.Test;
public abstract class PromptTextUITest_Base {
protected JTextComponent textComponent;
protected PromptTextUI ui;
@Before
public void setUI() {
setup();
TextUIWrapper.getDefaultWrapper().install(textComponent, true);
ui = (PromptTextUI) textComponent.getUI();
}
public abstract void setup();
@Test
public void testGetBaseLine() {
int baseline = ui.getBaseline(textComponent, textComponent.getWidth(), textComponent.getHeight());
if(JVM.current().isOrLater(JVM.JDK1_6)){
assertNotSame(-2, baseline);
}else{
assertSame(-2, baseline);
}
}
@Test
public void testInstallUI() {
textComponent.setUI(ui);
//ui should already be installed.
assertTrue(Arrays.asList(textComponent.getFocusListeners()).contains(PromptTextUI.focusHandler));
}
@Test
public void testUninstallUI() {
ui.uninstallUI(textComponent);
assertFalse(Arrays.asList(textComponent.getFocusListeners()).contains(PromptTextUI.focusHandler));
}
@Test
public void testShouldPaintLabel() {
assertTrue(ui.shouldPaintPrompt(textComponent));
textComponent.setText("");
assertTrue(ui.shouldPaintPrompt(textComponent));
textComponent.setText("test");
assertFalse(ui.shouldPaintPrompt(textComponent));
}
@Test
public void testCreateLabelComponent() {
assertNotNull(ui.createPromptComponent());
}
@Test
public void testGetLabelComponent() {
PromptSupport.setPrompt("test", textComponent);
PromptSupport.setForeground(Color.BLACK, textComponent);
PromptSupport.setBackground(Color.RED, textComponent);
textComponent.setBorder(BorderFactory.createBevelBorder(1));
textComponent.setEnabled(false);
textComponent.setEditable(false);
textComponent.setOpaque(false);
textComponent.setBounds(new Rectangle(1,1));
textComponent.setBackground(Color.BLACK);
textComponent.setFont(textComponent.getFont().deriveFont(Font.ITALIC, 20));
textComponent.setSelectedTextColor(Color.BLACK);
textComponent.setSelectionColor(Color.BLACK);
textComponent.setMargin(new Insets(1,1,1,1));
JTextComponent lbl = ui.getPromptComponent(textComponent);
assertEquals(PromptSupport.getPrompt(textComponent), lbl.getText());
assertEquals(PromptSupport.getForeground(textComponent), lbl.getForeground());
assertEquals(PromptSupport.getBackground(textComponent), lbl.getBackground());
- assertEquals(textComponent.getBorder(), lbl.getBorder());
+ assertEquals(textComponent.getBorder().getBorderInsets(textComponent),
+ lbl.getBorder().getBorderInsets(lbl));
assertEquals(textComponent.isEnabled(), lbl.isEnabled());
assertEquals(textComponent.isEditable(), lbl.isEditable());
assertEquals(textComponent.isOpaque(), lbl.isOpaque());
assertEquals(textComponent.getBounds(), lbl.getBounds());
assertEquals(textComponent.getFont(), lbl.getFont());
assertEquals(textComponent.getSelectedTextColor(), lbl.getSelectedTextColor());
assertEquals(textComponent.getSelectionColor(), lbl.getSelectionColor());
assertEquals(textComponent.getMargin(), lbl.getMargin());
PromptSupport.setFontStyle(Font.BOLD, textComponent);
lbl = ui.getPromptComponent(textComponent);
assertEquals(textComponent.getFont().deriveFont(Font.BOLD), lbl.getFont());
}
@Test
public void testGetPreferredSize() {
textComponent.setText("label text");
PromptSupport.setPrompt("label text", textComponent);
assertEquals(textComponent.getPreferredSize(), ui.getPromptComponent(textComponent).getPreferredSize());
textComponent.setText("text");
assertFalse(textComponent.getPreferredSize().equals(ui.getPromptComponent(textComponent).getPreferredSize()));
}
@Test
public void testPromptSupportStaysInstalledOnUIChange() {
assertTrue(textComponent.getUI() instanceof PromptTextUI);
textComponent.updateUI();
assertTrue(textComponent.getUI() instanceof PromptTextUI);
}
}
| true | true | public void testGetLabelComponent() {
PromptSupport.setPrompt("test", textComponent);
PromptSupport.setForeground(Color.BLACK, textComponent);
PromptSupport.setBackground(Color.RED, textComponent);
textComponent.setBorder(BorderFactory.createBevelBorder(1));
textComponent.setEnabled(false);
textComponent.setEditable(false);
textComponent.setOpaque(false);
textComponent.setBounds(new Rectangle(1,1));
textComponent.setBackground(Color.BLACK);
textComponent.setFont(textComponent.getFont().deriveFont(Font.ITALIC, 20));
textComponent.setSelectedTextColor(Color.BLACK);
textComponent.setSelectionColor(Color.BLACK);
textComponent.setMargin(new Insets(1,1,1,1));
JTextComponent lbl = ui.getPromptComponent(textComponent);
assertEquals(PromptSupport.getPrompt(textComponent), lbl.getText());
assertEquals(PromptSupport.getForeground(textComponent), lbl.getForeground());
assertEquals(PromptSupport.getBackground(textComponent), lbl.getBackground());
assertEquals(textComponent.getBorder(), lbl.getBorder());
assertEquals(textComponent.isEnabled(), lbl.isEnabled());
assertEquals(textComponent.isEditable(), lbl.isEditable());
assertEquals(textComponent.isOpaque(), lbl.isOpaque());
assertEquals(textComponent.getBounds(), lbl.getBounds());
assertEquals(textComponent.getFont(), lbl.getFont());
assertEquals(textComponent.getSelectedTextColor(), lbl.getSelectedTextColor());
assertEquals(textComponent.getSelectionColor(), lbl.getSelectionColor());
assertEquals(textComponent.getMargin(), lbl.getMargin());
PromptSupport.setFontStyle(Font.BOLD, textComponent);
lbl = ui.getPromptComponent(textComponent);
assertEquals(textComponent.getFont().deriveFont(Font.BOLD), lbl.getFont());
}
| public void testGetLabelComponent() {
PromptSupport.setPrompt("test", textComponent);
PromptSupport.setForeground(Color.BLACK, textComponent);
PromptSupport.setBackground(Color.RED, textComponent);
textComponent.setBorder(BorderFactory.createBevelBorder(1));
textComponent.setEnabled(false);
textComponent.setEditable(false);
textComponent.setOpaque(false);
textComponent.setBounds(new Rectangle(1,1));
textComponent.setBackground(Color.BLACK);
textComponent.setFont(textComponent.getFont().deriveFont(Font.ITALIC, 20));
textComponent.setSelectedTextColor(Color.BLACK);
textComponent.setSelectionColor(Color.BLACK);
textComponent.setMargin(new Insets(1,1,1,1));
JTextComponent lbl = ui.getPromptComponent(textComponent);
assertEquals(PromptSupport.getPrompt(textComponent), lbl.getText());
assertEquals(PromptSupport.getForeground(textComponent), lbl.getForeground());
assertEquals(PromptSupport.getBackground(textComponent), lbl.getBackground());
assertEquals(textComponent.getBorder().getBorderInsets(textComponent),
lbl.getBorder().getBorderInsets(lbl));
assertEquals(textComponent.isEnabled(), lbl.isEnabled());
assertEquals(textComponent.isEditable(), lbl.isEditable());
assertEquals(textComponent.isOpaque(), lbl.isOpaque());
assertEquals(textComponent.getBounds(), lbl.getBounds());
assertEquals(textComponent.getFont(), lbl.getFont());
assertEquals(textComponent.getSelectedTextColor(), lbl.getSelectedTextColor());
assertEquals(textComponent.getSelectionColor(), lbl.getSelectionColor());
assertEquals(textComponent.getMargin(), lbl.getMargin());
PromptSupport.setFontStyle(Font.BOLD, textComponent);
lbl = ui.getPromptComponent(textComponent);
assertEquals(textComponent.getFont().deriveFont(Font.BOLD), lbl.getFont());
}
|
diff --git a/src/java/org/mayocat/shop/payment/PaymentResponse.java b/src/java/org/mayocat/shop/payment/PaymentResponse.java
index fc1df456..7987761e 100644
--- a/src/java/org/mayocat/shop/payment/PaymentResponse.java
+++ b/src/java/org/mayocat/shop/payment/PaymentResponse.java
@@ -1,51 +1,53 @@
package org.mayocat.shop.payment;
import java.util.Map;
import org.mayocat.shop.grails.OrderStatus;
public class PaymentResponse
{
private OrderStatus newStatus;
private Map<String, Object> entityToSave;
private Long orderId;
private String contentType;
private String response;
public PaymentResponse(Long orderId, OrderStatus newStatus, Map<String, Object> entityToSave,
String responseContentType, String response)
{
this.orderId = orderId;
this.newStatus = newStatus;
this.entityToSave = entityToSave;
+ this.contentType = responseContentType;
+ this.response = response;
}
public OrderStatus getNewStatus()
{
return this.newStatus;
}
public Map<String, Object> getEntityToSave()
{
return this.entityToSave;
}
public Long getOrderId()
{
return this.orderId;
}
public String getResponseContentType()
{
return this.contentType;
}
public String getResponseContent()
{
return this.response;
}
}
| true | true | public PaymentResponse(Long orderId, OrderStatus newStatus, Map<String, Object> entityToSave,
String responseContentType, String response)
{
this.orderId = orderId;
this.newStatus = newStatus;
this.entityToSave = entityToSave;
}
| public PaymentResponse(Long orderId, OrderStatus newStatus, Map<String, Object> entityToSave,
String responseContentType, String response)
{
this.orderId = orderId;
this.newStatus = newStatus;
this.entityToSave = entityToSave;
this.contentType = responseContentType;
this.response = response;
}
|
diff --git a/java/de/dfki/lt/mary/modules/ProsodyGeneric.java b/java/de/dfki/lt/mary/modules/ProsodyGeneric.java
index 4b9bb031e..6d3caae4e 100755
--- a/java/de/dfki/lt/mary/modules/ProsodyGeneric.java
+++ b/java/de/dfki/lt/mary/modules/ProsodyGeneric.java
@@ -1,1557 +1,1559 @@
/**
* Copyright 2000-2006 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* Permission is hereby granted, free of charge, to use and distribute
* this software and its documentation without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of this work, and to
* permit persons to whom this work is furnished to do so, subject to
* the following conditions:
*
* 1. The code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Any modifications must be clearly marked as such.
* 3. Original authors' names are not deleted.
* 4. The authors' names are not used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* DFKI GMBH AND THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DFKI GMBH NOR THE
* CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
package de.dfki.lt.mary.modules;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;
import org.w3c.dom.traversal.TreeWalker;
import de.dfki.lt.mary.MaryData;
import de.dfki.lt.mary.MaryDataType;
import de.dfki.lt.mary.MaryProperties;
import de.dfki.lt.mary.MaryXML;
import de.dfki.lt.mary.NoSuchPropertyException;
import de.dfki.lt.mary.util.dom.DomUtils;
import de.dfki.lt.mary.util.dom.MaryDomUtils;
import de.dfki.lt.mary.util.dom.NameNodeFilter;
/**
* The generic prosody module.
* @author Stephanie Becker
*/
public class ProsodyGeneric extends InternalModule {
protected String paragraphDeclination; // name of the config file entry
protected boolean applyParagraphDeclination; // specified per language in mary config files
protected String syllableAccents; // specified in mary config files: ToBI accents on words or syllables?
protected boolean accentedSyllables;
// path to accentPriorities file(contains attribute values(f.e. part of speechs)
// and and a number which reflects the probability for their accentuation) specified in maryrc file
protected String accentPriorities;
protected Properties priorities;
protected String tobiPredFilename; // xml rule file for prosody prediction
protected HashMap tobiPredMap = new HashMap(); // map that will be filled with the rules
protected HashMap listMap = new HashMap(); // map that will contain the lists defined in the xml rule file
public ProsodyGeneric(MaryDataType inputType,MaryDataType outputType,String tobipredFileName,String accentPriorities, String syllableAccents, String paragraphDeclination)
throws IOException {
super("Prosody",inputType,outputType);
this.tobiPredFilename = tobipredFileName;
this.accentPriorities = accentPriorities;
this.syllableAccents = syllableAccents;
this.paragraphDeclination = paragraphDeclination;
}
public void startup() throws Exception {
priorities = new Properties();
if (accentPriorities != null) {
String fileName = MaryProperties.needFilename(accentPriorities);
priorities.load(new FileInputStream(fileName));
}
if (syllableAccents != null) {
accentedSyllables = MaryProperties.getBoolean(syllableAccents);
} else {
accentedSyllables = false;
}
if (paragraphDeclination != null) {
applyParagraphDeclination = MaryProperties.getBoolean(paragraphDeclination);
} else {
applyParagraphDeclination = false;
}
super.startup();
loadTobiPredRules(); // fill the rule map
buildListMap(); // fill the list map
}
protected void loadTobiPredRules () throws FactoryConfigurationError, ParserConfigurationException, org.xml.sax.SAXException, IOException,
NoSuchPropertyException {
// parsing the xml rule file
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setValidating(false);
DocumentBuilder b = f.newDocumentBuilder();
Document tobiPredRules = b.parse(new FileInputStream(MaryProperties.needFilename(tobiPredFilename)));
Element root = tobiPredRules.getDocumentElement();
for (Element e = MaryDomUtils.getFirstChildElement(root);
e != null;
e = MaryDomUtils.getNextSiblingElement(e)) { //HashMap with 4 entries
if (e.getTagName().equals("definitions")) { //list defintions
tobiPredMap.put("definitions",e);
}
if (e.getTagName().equals("accentposition")) { // these rules determine which words receive accents
tobiPredMap.put("accentposition",e);
}
if (e.getTagName().equals("accentshape")) { // these rules determine which type of accent a word receives
tobiPredMap.put("accentshape",e);
}
if (e.getTagName().equals("boundaries")) { // these rules determine locatian and type of boundaries
tobiPredMap.put("boundaries",e);
}
}
}
protected void buildListMap() throws IOException {
Element listDefinitions = null;
listDefinitions = (Element) tobiPredMap.get("definitions");
// search for entries with tag "list"
TreeWalker tw =
((DocumentTraversal) listDefinitions.getOwnerDocument()).createTreeWalker(
listDefinitions,
NodeFilter.SHOW_ELEMENT,
new NameNodeFilter(new String[] {"list"}),
false);
Element list=null;
while((list = (Element) tw.nextNode()) != null) {
String name = list.getAttribute("name"); // list name
if(list.hasAttribute("items")) { // list is defined in the xml file (no external list)
String items = list.getAttribute("items");
HashSet itemSet = new HashSet(); // build a set with the elements in the list
StringTokenizer st = new StringTokenizer(items,":");
while(st.hasMoreTokens()) {
itemSet.add(st.nextToken());
}
listMap.put(name,itemSet); // put the set on the map
}
if(list.hasAttribute("file")) { // external list definition
String fileName = list.getAttribute("file");
listMap.put(name, readListFromFile(fileName));
}
}
}
/**
* Read a list from an external file. This generic implementation
* can read from text files (filenames ending in <code>.txt</code>).
* Subclasses may override this class to provide additional file formats.
* They must make sure that <code>checkList()</code> can deal with all
* list formats.
* @param fileName external file from which to read the list; suffix identifies
* list format.
* @return An Object representing the list; checkList() must be able to
* make sense of this. This base implementation returns a Set.
* @throws IllegalArgumentException if the fileName suffix cannot be
* identified as a list file format.
* @throws IOException if the file given in fileName cannot be found or read from
*/
protected Object readListFromFile(String fileName) throws IOException
{
String suffix = fileName.substring(fileName.length() - 4, fileName.length());
if (suffix.equals(".txt")) { // txt file
StringTokenizer st = new StringTokenizer(fileName, "/");
String txtPath = MaryProperties.maryBase();
while (st.hasMoreTokens()) {
txtPath = txtPath + File.separator + st.nextToken();
}
// build a set that contains every word contained in the
// external text file
HashSet listSet = new HashSet();
BufferedReader in = new BufferedReader(new FileReader(txtPath));
while (in.ready()) {
String line = in.readLine();
listSet.add(line);
}
return listSet; // put the set on the map
} else {
throw new IllegalArgumentException("Unknown list file format: " + suffix);
}
}
public MaryData process(MaryData d) throws Exception {
Document doc = d.getDocument();
// get the sentences
NodeIterator sentenceIt = ((DocumentTraversal)doc).
createNodeIterator(doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, new NameNodeFilter(MaryXML.SENTENCE), false);
Element sentence = null;
while ((sentence = (Element)sentenceIt.nextNode()) != null) {
// And now the actual processing
logger.debug("Processing next sentence");
processSentence(sentence);
}
if(accentedSyllables == true) {
copyAccentsToSyllables(doc); // ToBI accents on syllables or words?
}
if (applyParagraphDeclination) {
NodeList paragraphs = doc.getElementsByTagName(MaryXML.PARAGRAPH);
for (int i=0; i< paragraphs.getLength(); i++) {
Element paragraph = (Element) paragraphs.item(i);
NodeList phrases = paragraph.getElementsByTagName(MaryXML.PHRASE);
int steps = phrases.getLength();
if (steps <= 1) continue;
for (int j=0; j<steps; j++) {
// Paragraph intonation: embed each <phrase> in a <prosody>
// element simulating a paragraph-wide declination phenomenon
// superimposed to the phrase-internal declination.
int pitchDiff = 10; // difference in percent between first and last phrase
int rangeDiff = 40; // difference in percent between first and last phrase
double factor = (0.5 - j/(steps-1f));
int pitchValue = (int) (pitchDiff * factor);
String pitchString = (pitchValue >= 0 ? "+" : "") + pitchValue + "%";
int rangeValue = (int) (rangeDiff * factor);
String rangeString = (rangeValue >= 0 ? "+" : "") + rangeValue + "%";
Element phrase = (Element) phrases.item(j);
Element prosody = MaryXML.createElement(phrase.getOwnerDocument(), MaryXML.PROSODY);
phrase.getParentNode().insertBefore(prosody, phrase);
prosody.appendChild(phrase);
prosody.setAttribute("pitch", pitchString);
prosody.setAttribute("range", rangeString);
}
}
}
MaryData result = new MaryData(outputType());
result.setDocument(doc);
return result;
}
protected void processSentence (Element sentence) {
NodeList tokens = sentence.getElementsByTagName(MaryXML.TOKEN);
if (tokens.getLength() < 1) {
return; // no tokens -- what can we do?
}
Element firstTokenInPhrase = null;
// properties of the whole sentence
// first determine the sentence type
String sentenceType = "decl";
sentenceType = getSentenceType(tokens);
// determine if it is the last sentence in a paragraph
boolean paragraphFinal =
MaryDomUtils.isLastOfItsKindIn(sentence, MaryXML.PARAGRAPH)
&& !MaryDomUtils.isFirstOfItsKindIn(sentence, MaryXML.PARAGRAPH);
// check if it is a sentence with vorfeld
boolean inVorfeld = true; // default
for(int i=0; i<tokens.getLength();i++) { // search for the first word in sentence
Element token = ((Element)tokens.item(i));
if(!token.getAttribute("sampa").equals("")) { // first word found
String posFirstWord = token.getAttribute("pos");
// if pos value of first word in sentence is contained in set noVorfeld, vorfeld doens't exist
HashSet noVorfeld = (HashSet)listMap.get("noVorfeld");
if(noVorfeld != null) {
if(noVorfeld.contains(posFirstWord)) {
inVorfeld = false;
}
}
break;
}
}
// default: no special position
String specialPositionType = "noValue"; // can get the values "endofvorfeld" and "endofpar"(=end of paragraph)
int numEndOfVorfeld = -1;
boolean hasAccent=false; // tests if phrase has an accent
Element bestCandidate = null; // will become token with highest accent priority if a phrase has no accent;
// avoids phrases without accent
// loop over the tokens in sentence
// assignment of accent position and boundaries
for (int i = 0; i < tokens.getLength(); i++) {
Element token = (Element) tokens.item(i);
logger.debug("Now looking at token `"+MaryDomUtils.tokenText(token)+"'");
if(firstTokenInPhrase==null) {
firstTokenInPhrase=token; // begin of an intonation phrase
}
// determine if token is at end of vorfeld
if(inVorfeld != false) { // only if vorfeld exists and if token's position is not after vorfeld
if(i<tokens.getLength()-1) {
Element nextToken = (Element) tokens.item(i+1);
String posNextToken = nextToken.getAttribute("pos");
// if pos value of next token is contained in set beginOfMittelfeld,
// current token is at the end of the vorfeld
HashSet beginOfMittelfeld = (HashSet)listMap.get("beginOfMittelfeld");
if(beginOfMittelfeld != null && beginOfMittelfeld.contains(posNextToken)) {
//for(int z=0; z<attNodes.getLength(); z++) {
//Node el = (Node)attNodes.item(z);
//String currentVal = el.getNodeValue();
//if(beginOfMittelfeld.contains(currentVal)) {
//if(beginOfMittelfeld.contains(posNextToken)) {
specialPositionType = "endofvorfeld";
numEndOfVorfeld = i; // position of current token
inVorfeld = false;
} else specialPositionType = "vorfeld";
}
}
// determine token position in text
boolean isFinalToken = (i >= tokens.getLength() - 1); // last token in sentence?
if(paragraphFinal && isFinalToken) { // last token in sentence and in paragraph?
specialPositionType = "endofpar";
}
boolean applyRules = applyRules(token);
if (applyRules) { // rule application not turned off
// first: assignment of accent = "tone", accent="force"(for force-accents(Druckakzent)) or accent=""
// --> determine if the token receives an accent or not
// the type of accent(f.e. L+H*) is assigend later
/*** begin user input check,accent position ***/
String forceAccent = getForceAccent(token);
- if(forceAccent.equals("word") || forceAccent.equals("syllable")
- || token.getAttribute("accent").equals("unknown")) {
+ if (token.getAttribute("accent").equals("unknown")
+ || !token.hasAttribute("accent") && (forceAccent.equals("word") || forceAccent.equals("syllable"))) {
setAccent(token, "tone"); // the token receives an accent according to user input
} else if(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) {
// no accent according to user input
} else if(!token.getAttribute("accent").equals("")) {
// accent type is already assigned by the user, f.e. accent="L+H*"
/*** end user input check, accent position ***/
// no user input
// the rules in the xml file are applied
} else if(token.getAttribute("sampa").equals("")) { // test if token is punctuation
token.removeAttribute("accent"); // doesn't receive an accent
- } else getAccentPosition(token, tokens, i, sentenceType, specialPositionType);
+ } else { // default behaviour: determine by rule whether to assign an accent
+ getAccentPosition(token, tokens, i, sentenceType, specialPositionType);
+ }
// check if the phrase has an accent (avoid intermediate phrases without accent)
- if(token.getAttribute("accent").equals("tone")) {
+ if(token.hasAttribute("accent") && !token.getAttribute("accent").equals("none")) {
hasAccent = true;
}
// if not, check if current token is the best candidate
if(hasAccent == false &&
!(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) &&
!token.getAttribute("sampa").equals("")) {
if(bestCandidate == null) { // no candidate yet
bestCandidate=token;
} else {
int priorToken = -1;
int priorBestCandidate = -1;
// search for pos in accentPriorities property list
// first check priority for current token
String posCurrentToken = token.getAttribute("pos");
try {
priorToken = Integer.parseInt(priorities.getProperty(posCurrentToken));
} catch (NumberFormatException e) { }
// now check priority for bestCandidate
String posBestCandidate = bestCandidate.getAttribute("pos");
try {
priorBestCandidate = Integer.parseInt(priorities.getProperty(posBestCandidate));
} catch (NumberFormatException e) { }
// if the current token has higher priority than the best candidate,
// current token becomes the best candidate for accentuation
if(priorToken != -1 && priorBestCandidate != -1) {
if(priorToken <= priorBestCandidate) bestCandidate = token;
}
}
}
if(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) {
token.removeAttribute("accent");
}
} // end of accent position assignment
// now the informations relevant only for boundary assignment
boolean invalidXML = false;
if(!isFinalToken) { // We only set a majorIP boundary if the XML structure
// allows the phrase to be closed before the next token
invalidXML =
MaryDomUtils.isAncestor(
MaryDomUtils.closestCommonAncestor(firstTokenInPhrase, tokens.item(i)),
MaryDomUtils.closestCommonAncestor(tokens.item(i), tokens.item(i + 1)));
}
if(applyRules) {
// insertion of ip- and IP-boundaries
// returns value for firstTokenInPhrase(begin of new phrase): if a boundary was inserted, firstTokenInPhrase gets null
// if not, firstTokenInPhrase has the same value as before
firstTokenInPhrase = getBoundary(token,tokens,i,sentenceType,specialPositionType,invalidXML,firstTokenInPhrase);
// check if every intermediate an intonation phrase has at least one accent
// first check if a boundary was inserted
Element boundary = null;
Document doc = token.getOwnerDocument();
TreeWalker tw = ((DocumentTraversal)doc).createTreeWalker(
DomUtils.getAncestor(token, MaryXML.SENTENCE), NodeFilter.SHOW_ELEMENT,
new NameNodeFilter(new String[] {MaryXML.BOUNDARY, MaryXML.TOKEN}), false);
tw.setCurrentNode(token);
logger.debug("Starting treewalker at token " + MaryDomUtils.tokenText(token));
Element next = (Element) tw.nextNode();
if (next != null && next.getTagName().equals(MaryXML.BOUNDARY)) {
logger.debug("tw found a boundary");
boundary = next;
int bi = 0;
try {
bi = Integer.parseInt(boundary.getAttribute("breakindex"));
} catch (NumberFormatException nfe) {}
if(bi>=3) { // is it an intermediate or an intoantion phrase?
if(hasAccent == false && bestCandidate != null) { // no accent!
setAccent(bestCandidate, "tone"); // best candidate receives accent
}
hasAccent=false;
bestCandidate = null;
}
}
}
if(specialPositionType.equals("endofvorfeld")) specialPositionType="noValue";
} // loop tokens for accent position and boundary assignment
/*** user input check, boundaries ***/
NodeList boundaries = sentence.getElementsByTagName(MaryXML.BOUNDARY);
for (int i = 0; i < boundaries.getLength(); i++) {
Element boundary = (Element) boundaries.item(i);
if (boundary.getAttribute("breakindex").equals("none")) { // the boundary is to be deleted
// delete boundary
Node parent = boundary.getParentNode();
parent.removeChild(boundary);
} else if (boundary.getAttribute("tone").equals("unknown")) { // boundary, but no tone is given
// is there a preferred tone for boundaries?
Element prosody =
MaryDomUtils.getClosestAncestorWithAttribute(boundary, MaryXML.PROSODY, "preferred-boundary-type");
String preferred = null;
if (prosody != null) preferred = prosody.getAttribute("preferred-boundary-type");
String h = boundary.getAttribute("breakindex");
int bi = 0;
String tone = null;
try {
bi = Integer.parseInt(h);
} catch (NumberFormatException e) { } // ignore invalid values
if (bi >= 4) {
// major boundary (but we cannot insert a phrase,
// because we don't know where it should start)
if (preferred != null) {
if (preferred.equals("high")) {
HashSet set = (HashSet)listMap.get("high_major_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else { // low
HashSet set = (HashSet)listMap.get("low_major_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else { // there isn't any information about the tone, so we use default values specified in the xml file
if (i == boundaries.getLength() - 1) { // final boundary
if(sentenceType.equals("decl") || sentenceType.equals("excl")) { //declarative or exclamative sentence
HashSet set = (HashSet)listMap.get("default_IP_endOfSent");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else {
HashSet set = (HashSet)listMap.get("default_IP_endOfInterrogSent"); // interrogative
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else { // non-final boundary
HashSet set = (HashSet)listMap.get("default_IP_midOfSent");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
}
} else if (bi == 3) {
// minor boundary
if (preferred != null) {
if (preferred.equals("high")) {
HashSet set = (HashSet)listMap.get("high_minor_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else { // low
HashSet set = (HashSet)listMap.get("low_minor_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else {// there is no information about the tone, so we use the default values specified in the xml file
HashSet set = (HashSet)listMap.get("default_ip");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
}
if (tone != null) boundary.setAttribute("tone", tone);
}
} // for all boundaries
/*** end user input check, boundaries ***/
// now the information relevant for accent type assignment
boolean nucleusAssigned = false;
String lastAssignedTone = null; // for user input preferred-accent-shape="alternating_accents"
for (int j = tokens.getLength() - 1; j >= 0; j--) { // accent type assignment
Element token = (Element) tokens.item(j);
// determine specialpositionType
boolean isFinalToken = (j >= tokens.getLength() - 1); // last token in sentence?
if(paragraphFinal && isFinalToken) { // last token in paragraph?
specialPositionType = "endofpar"; // last token in sentence and in paragraph
}
if(j == numEndOfVorfeld) specialPositionType = "endofvorfeld";
if(token.getAttribute("accent").equals("tone") || token.getAttribute("accent").equals("force")) {
/*** begin user input check, accent type ***/
Element prosody = MaryDomUtils.getClosestAncestorWithAttribute(token, MaryXML.PROSODY, "preferred-accent-shape");
if (prosody != null) {
if(token.getAttribute("accent").equals("tone")) { // no force accents in this case
String tone = null;
String preferred = prosody.getAttribute("preferred-accent-shape");
if (preferred.equals("alternating")) {
HashSet set = (HashSet)listMap.get("alternating_accents");
Iterator it = set.iterator();
while(it.hasNext()) {
String next = (String)it.next();
if(lastAssignedTone == null || !lastAssignedTone.equals(next)) {
tone = next;
}
}
} else if (preferred.equals("rising")) {
HashSet set = (HashSet)listMap.get("rising_accents");
Iterator it = set.iterator();
if(it.hasNext()) tone = (String)it.next();
} else if (preferred.equals("falling")) {
HashSet set = (HashSet)listMap.get("falling_accents");
Iterator it = set.iterator();
if(it.hasNext()) tone = (String)it.next();
}
token.setAttribute("accent",tone);
if(nucleusAssigned == false) nucleusAssigned = true;
}
} else if(!(token.getAttribute("accent").equals("force") || token.getAttribute("accent").equals("tone")||
token.getAttribute("accent").equals(""))) {
nucleusAssigned = true; // user has already assigned an accent type
/*** end user input check, accent type ***/
} else if(token.getAttribute("sampa").equals("")) { // test if token is a word (no punctuation)
// punctuation, doesn't receive an accent
} else // xml file rules are applied
// assignment of accent type
// returns true, if nuclear accent is assigned, false otherwise
nucleusAssigned = getAccentShape(token,tokens,j,sentenceType,specialPositionType,nucleusAssigned);
}
if(token.getAttribute("accent").equals("") || token.getAttribute("accent").equals("force")) {
token.removeAttribute("accent"); // if there is no accent, the accent attribute can be removed
}
if(token.hasAttribute("accent")) {
lastAssignedTone = token.getAttribute("accent");
}
} //loop over tokens for accent type assignment
} //processSentence
/** checks if token receives an accent or not
* the information is contained in the accentposition part of rules in xml file
* the token attribute "accent" receives the value "tone","force"(force accent(Druckakzent)) or ""(no accent)
* @param token (current token)
* @param tokens (list of all tokens in sentence)
* @param position (position in token list)
* @param sentenceType (declarative, exclamative or interrogative)
* @param specialPositionType (end of vorfeld or end of paragraph)
*/
protected void getAccentPosition(Element token, NodeList tokens, int position, String sentenceType, String specialPositionType) {
String tokenText = MaryDomUtils.tokenText((Element) token); // text of current token
Element ruleList = null;
// only the "accentposition" rules are relevant
ruleList = (Element) tobiPredMap.get("accentposition");
// search for concrete rules, with tag "rule"
TreeWalker tw =
((DocumentTraversal) ruleList.getOwnerDocument()).createTreeWalker(
ruleList,
NodeFilter.SHOW_ELEMENT,
new NameNodeFilter(new String[] {"rule"}),
false);
boolean rule_fired = false;
String accent = ""; // default
Element rule = null;
// search for appropriate rules; the top rule has highest prority
// if a rule fires (that is: all the conditions are fulfilled),
// the accent value("tone","force" or "") is assigned and the loop stops
// if no rule is found, the accent value is ""
while (rule_fired == false && (rule = (Element) tw.nextNode()) != null) {
// rule = the whole rule
// currentRulePart = part of the rule (type of condition (f.e. attributes pos="NN") or action)
Element currentRulePart = DomUtils.getFirstChildElement(rule);
while(rule_fired == false && currentRulePart != null) {
boolean conditionSatisfied=false;
// if rule part with tag "action": accent assignment
if(currentRulePart.getTagName().equals("action")) {
accent = currentRulePart.getAttribute("accent");
token.setAttribute("accent",accent);
rule_fired = true;
break;
}
// check if the condition is satisfied
conditionSatisfied = checkRulePart(currentRulePart,token,tokens,position,sentenceType,specialPositionType,tokenText);
if(conditionSatisfied == false) break; // condition violated, try next rule
// the previous conditions are satisfied --> check the next rule part
currentRulePart = DomUtils.getNextSiblingElement(currentRulePart);
} //while loop that checks the rule parts
} // while loop that checks the whole rule
}
/** determines accent types;
* tokens with accent="tone" will receive an accent type (f.e."L+H*"), accent="force" becomes "*"
* the relevant information is contained in the accentshape part of rules in xml file
* @param token (current token)
* @param tokens (list of all tokens in sentence)
* @param position
* @param sentenceType (declarative, exclamative or interrogative)
* @param specialPositionType (position in sentence)
* @param nucleusAssigned (test, if nuclear accent is already assigned)
* @return nucleusAssigned
*/
protected boolean getAccentShape(Element token,NodeList tokens,int position,String sentenceType,
String specialPositionType,boolean nucleusAssigned) {
String tokenText = MaryDomUtils.tokenText((Element) token); // text of current token
// prosodic position (prenuclear, nuclear, postnuclear)
String prosodicPositionType = null;
if(nucleusAssigned == false){ // no nucleus assigned
if(token.getAttribute("accent").equals("tone")) { // current token will become the nucleus
if(specialPositionType.equals("endofpar")) {
prosodicPositionType= "nuclearParagraphFinal";
} else {
prosodicPositionType= "nuclearNonParagraphFinal";
}
} else prosodicPositionType = "postnuclear"; // no nucleus, current token is postnuclear
} else prosodicPositionType = "prenuclear"; // nucleus is assigned --> prenuclear
Element ruleList = null;
// only the "accentshape" rules are relevant
ruleList = (Element) tobiPredMap.get("accentshape");
// search for concrete rules (search for tag "rule")
TreeWalker tw =
((DocumentTraversal) ruleList.getOwnerDocument()).createTreeWalker(
ruleList,
NodeFilter.SHOW_ELEMENT,
new NameNodeFilter(new String[] {"rule"}),
false);
boolean rule_fired = false;
String accent = "";
Element rule = null;
// search for appropriate rules; the top rule has highest prority
// if a rule fires (that is: all the conditions are fulfilled), the accent type (f.e. "L+H*") is assigned and the loop stops
// if no rule is found, the accent value is ""
while (rule_fired == false && (rule = (Element) tw.nextNode()) != null) {
// rule = the whole rule
// currentRulePart = part of the rule (type of condition (f.e. attributes pos="NN") or action)
Element currentRulePart = DomUtils.getFirstChildElement(rule);
while(rule_fired == false && currentRulePart != null) {
boolean conditionSatisfied=false;
// if rule part with tag "action": accent type assignment
if(currentRulePart.getTagName().equals("action")) {
accent = currentRulePart.getAttribute("accent");
token.setAttribute("accent",accent);
rule_fired = true;
if(nucleusAssigned == false && !accent.equals("*")) {
nucleusAssigned = true;
}
break;
}
// check if the condition is satisfied
// special case: prosodic position (only in the accentshape rule part)
// values: prenuclear,nuclearParagraphFinal,nuclearNonParagraphFinal,postnuclear
if(currentRulePart.getTagName().equals("prosodicPosition")) {
if(!checkProsodicPosition(currentRulePart,prosodicPositionType)) {
break;
}
}
// the usual check
conditionSatisfied = checkRulePart(currentRulePart,token,tokens,position,sentenceType,specialPositionType,tokenText);
if(conditionSatisfied == false) break; // condition violated, try next rule
// the previous conditions are satisfied --> check the next rule part
currentRulePart = DomUtils.getNextSiblingElement(currentRulePart);
}//while loop that checks the rule parts
} // while loop that checks the whole rule
return nucleusAssigned;
}
/** checks if a boundary is to be inserted after the current token
* the information is contained in the boundaries part of rules in xml file
* @param token (current token)
* @param tokens (list of tokens in sentence)
* @param position (position in token list)
* @param sentenceType (declarative, exclamative or interrogative)
* @param specialPositionType (endofvorfeld if sentence has vorfeld and the next token is a finite verb or end of paragraph)
* @param invalidXML (true if xml structure allows boundary insertion)
* @param firstTokenInPhrase (begin of intonation phrase)
* @return firstTokenInPhrase (if a boundary was inserted, firstTokenInPhrase gets null)
*/
protected Element getBoundary(Element token,NodeList tokens,int position, String sentenceType, String specialPositionType,
boolean invalidXML, Element firstTokenInPhrase) {
String tokenText = MaryDomUtils.tokenText((Element) token); // text of current token
Element ruleList = null;
// only the "boundaries" rules are relevant
ruleList = (Element) tobiPredMap.get("boundaries");
// search for concrete rules (search for tag "rule")
TreeWalker tw =
((DocumentTraversal) ruleList.getOwnerDocument()).createTreeWalker(
ruleList,
NodeFilter.SHOW_ELEMENT,
new NameNodeFilter(new String[] {"rule"}),
false);
boolean rule_fired = false;
Element rule = null;
// search for appropriate rules; the top rule has highest prority
// if a rule fires (that is: all the conditions are fulfilled), the boundary is inserted and the loop stops
while (rule_fired == false && (rule = (Element) tw.nextNode()) != null) {
// rule = the whole rule
// currentRulePart = part of the rule (condition or action)
Element currentRulePart = DomUtils.getFirstChildElement(rule);
while(rule_fired == false && currentRulePart != null) {
boolean conditionSatisfied = false;
// if rule part with tag "action": boundary insertion
if(currentRulePart.getTagName().equals("action")){
int bi = Integer.parseInt(currentRulePart.getAttribute("bi"));
if(bi == 0) {
// no boundary insertion
} else if(currentRulePart.hasAttribute("tone")) {
String tone = currentRulePart.getAttribute("tone");
if(tone.endsWith("%")) {
if(!invalidXML) {
Element boundary = insertMajorBoundary(tokens,position,firstTokenInPhrase,tone,bi);
if (boundary != null) firstTokenInPhrase = null;
}
} else if(tone.endsWith("-")) {
insertBoundary(token,tone,bi);
} else insertBoundary(token,null,bi);
} else insertBoundary(token,null,bi);
rule_fired = true;
break;
}
// check if the condition is satisfied
conditionSatisfied = checkRulePart(currentRulePart,token,tokens,position,sentenceType,specialPositionType,tokenText);
if(conditionSatisfied == false) break; // condition violated, try next rule
// the previous conditions are satisfied --> check the next rule part
currentRulePart = DomUtils.getNextSiblingElement(currentRulePart);
}//while loop that checks the rule parts
} // while loop that checks the whole rule
return firstTokenInPhrase;
}
protected static final Pattern nextPlusXTextPattern = Pattern.compile("nextPlus[0-9]+Text");
protected static final Pattern previousMinusXTextPattern = Pattern.compile("previousMinus[0-9]+Text");
protected static final Pattern nextPlusXAttributesPattern = Pattern.compile("nextPlus[0-9]+Attributes");
protected static final Pattern previousMinusXAttributesPattern = Pattern.compile("previousMinus[0-9]+Attributes");
/** checks condition of a rule part, f.e. attributes pos="NN"
* @param currentRulePart
* @param token (current token)
* @param tokens (list of all tokens)
* @param position (position in token list)
* @param sentenceType (declarative, exclamative or interrogative)
* @param specialPositionType (special position in sentence(end of vorfeld) or text(end of paragraph))
* @param tokenText (text of token)
* @return true if condition is satisfied
*/
protected boolean checkRulePart(Element currentRulePart,Element token,NodeList tokens,int position,String sentenceType,String specialPositionType,
String tokenText) {
String currentRulePartTagName = currentRulePart.getTagName();
// if rule part with tag text and attribute word, check if text of token equals text in rule
if(currentRulePartTagName.equals("text") & currentRulePart.hasAttribute("word")) { // text of the token
return checkText(currentRulePart,tokenText);
}
// text of following+X token or preceding-X token
else if(currentRulePart.hasAttribute("word") &&
(currentRulePartTagName.equals("nextText") ||
nextPlusXTextPattern.matcher(currentRulePartTagName).find() ||
currentRulePartTagName.equals("previousText") ||
previousMinusXTextPattern.matcher(currentRulePartTagName).find())) {
return checkTextOfOtherToken(currentRulePartTagName,currentRulePart,token,position,tokens);
}
// check number of following tokens
else if(currentRulePartTagName.equals("folTokens") && currentRulePart.hasAttribute("num")) {
return checkFolTokens(currentRulePart,token,position,tokens);
}
// check number of preceding tokens
else if(currentRulePartTagName.equals("prevTokens") && currentRulePart.hasAttribute("num")) {
return checkPrevTokens(currentRulePart,token,position,tokens);
}
// check number of following words
else if(currentRulePartTagName.equals("folWords") && currentRulePart.hasAttribute("num")) {
return checkFolWords(currentRulePart,token,position,tokens);
}
// check number of preceding words
else if(currentRulePartTagName.equals("prevWords") && currentRulePart.hasAttribute("num")) {
return checkPrevWords(currentRulePart,token,position,tokens);
}
// check sentence type (f.e. declarative sentence)
else if(currentRulePartTagName.equals("sentence") && currentRulePart.hasAttribute("type")) {
return checkSentence(currentRulePart,sentenceType);
}
// check for special position of token in sentence/text(endofvorfeld,endofpar)
else if(currentRulePartTagName.equals("specialPosition") && currentRulePart.hasAttribute("type")) {
return checkSpecialPosition(currentRulePart,specialPositionType);
}
// if rule part with tag "attributes"
// --> check the MaryXML attribute values of the token
else if(currentRulePartTagName.equals("attributes")) {
return checkAttributes(currentRulePart,token);
}
// if rule part with tag nextPlusXAttributes or previousMinusXAttributes
// --> check the MaryXML attribute values of the corresponding token
else if(currentRulePartTagName.equals("nextAttributes") ||
nextPlusXAttributesPattern.matcher(currentRulePart.getTagName()).find() ||
currentRulePartTagName.equals("previousAttributes") ||
previousMinusXAttributesPattern.matcher(currentRulePart.getTagName()).find()) {
return checkAttributesOfOtherToken(currentRulePart.getTagName(),currentRulePart,token,position,tokens);
}
else {
// unknown rules always match
return true;
}
}
/** checks rule part with tag "text";
* there is only the "word" attribute right now: checks if text of a token is the same
* as the value of the word attribute in the rule
*/
protected boolean checkText(Element currentRulePart, String tokenText) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
for(int z=0; z<attNodes.getLength(); z++) {
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
if(currentAtt.equals("word")) { // there is only the "word" attribute right now
if(!currentVal.startsWith("INLIST") && !currentVal.startsWith("INFSTLIST")
&& !currentVal.startsWith("!INLIST") && !currentVal.startsWith("!INFSTLIST")) { // no list
if(!currentVal.startsWith("!")) { // no negation
if(!tokenText.equals(currentVal)) return false;
} else { // negation
currentVal = currentVal.substring(1,currentVal.length());
if(tokenText.equals(currentVal)) return false;
}
} else return checkList(currentVal,tokenText); // list
}
} // for-loop
return true;
}
/** checks rule part with tag "nextText","previousText","nextPlusXText" or "previousMinusXText";
* there is only the "word" attribute right now: checks if text of a token is the same
* as the value of the word attribute in the rule
*/
protected boolean checkTextOfOtherToken(String tag, Element currentRulePart, Element token, int position, NodeList tokens) {
Element otherToken = null;
if(tag.equals("nextText")) { // text of next token
if(position<tokens.getLength()-1) {
otherToken = (Element)tokens.item(position+1);
}
}
if(nextPlusXTextPattern.matcher(tag).find()) { // text of some other token following the next token
String tempString = tag.replaceAll("nextPlus","");
String newString = tempString.replaceAll("Text","");
int num = Integer.parseInt(newString);
if(position<tokens.getLength()-(num+1)) otherToken = (Element)tokens.item(position+1+num);
}
if(tag.equals("previousText")) { // text of previous token
if(position>0) otherToken = (Element)tokens.item(position-1);
}
if(previousMinusXTextPattern.matcher(tag).find()) { // text of some other token preceding the previous token
String tempString = tag.replaceAll("previousMinus","");
String newString = tempString.replaceAll("Text","");
int num = Integer.parseInt(newString);
if(position>num) otherToken = (Element)tokens.item(position-(num+1));
}
if(otherToken == null) return false;
String otherTokenText = MaryDomUtils.tokenText(otherToken);
return checkText(currentRulePart,otherTokenText);
}
/** checks rule part with tag "folTokens";
* there is only the "num" attribute right now; checks if the number of the following tokens after the current token
* is the same as the value of the num attribute;
* f.e. the value "3+" means: at least 3 following tokens, "3-": not more than 3, "3": exactly 3
*/
protected boolean checkFolTokens(Element currentRulePart, Element token, int position, NodeList tokens) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
for(int z=0; z<attNodes.getLength(); z++) {
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
if(currentAtt.equals("num")) { // there is only the "num" attribute right now
int num = Integer.parseInt(currentVal.substring(0,1));
int requiredLastTokenPosition = position+num;
if(currentVal.length() == 1) { // rule requires exactly num tokens after current token
if(!(tokens.getLength()-1 == requiredLastTokenPosition))return false;
} else if(currentVal.substring(1,2).equals("+")) { // rule requires at least num tokens after current token
if(!(tokens.getLength()-1 >= requiredLastTokenPosition)) return false;
} else if(currentVal.substring(1,2).equals("-")) { // rule requires not more than num tokens after current token
if(!(tokens.getLength()-1 <= requiredLastTokenPosition)) return false;
}
}
}
return true;
}
/** checks rule part with tag "prevTokens";
* there is only the "num" attribute right now; checks if the number of the tokens preceding the current token
* is the same as the value of the num attribute;
* f.e. the value "3+" means: at least 3 preceding tokens, "3-": not more than 3, "3": exactly 3
*/
protected boolean checkPrevTokens(Element currentRulePart, Element token, int position, NodeList tokens) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
for(int z=0; z<attNodes.getLength(); z++) {
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
if(currentAtt.equals("num")) { // there is only the "num" attribute right now
int num = Integer.parseInt(currentVal.substring(0,1));
int requiredFirstTokenPosition=position-num;
if(currentVal.length() == 1) {// rule requires exactly num tokens preceding current token
if(!(requiredFirstTokenPosition == 0)) return false;
} else if(currentVal.substring(1,2).equals("+")) { // rule requires at least num tokens preceding current token
if(!(0 <= requiredFirstTokenPosition)) return false;
} else if(currentVal.substring(1,2).equals("-")) { // rule requires not more than num tokens preceding current token
if(!(0 >= requiredFirstTokenPosition)) return false;
}
}
}
return true;
}
/** checks rule part with tag "folWords";
* there is only the "num" attribute right now; checks if the number of the following words after the current token
* is the same as the value of the num attribute;
* f.e. the value "3+" means: at least 3 following tokens, "3-": not more than 3, "3": exactly 3
*/
protected boolean checkFolWords(Element currentRulePart, Element token, int position, NodeList tokens) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
for(int z=0; z<attNodes.getLength(); z++) {
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
if(currentAtt.equals("num")) { // there is only the "num" attribute right now
int requiredNum = Integer.parseInt(currentVal.substring(0,1));
int num = 0;
for(int i=position+1;i<tokens.getLength();i++) {
if(!((Element)tokens.item(i)).getAttribute("sampa").equals("")) num++;
}
if(currentVal.length() == 1) { // rule requires exactly num words after current token
if(num != requiredNum) return false;
} else if(currentVal.substring(1,2).equals("+")) { // rule requires at least num words after current token
if(!(num >= requiredNum)) return false;
} else if(currentVal.substring(1,2).equals("-")) { // rule requires not more than num words after current token
if(!(num <= requiredNum)) return false;
}
}
}
return true;
}
/** checks rule part with tag "prevWords";
* there is only the "num" attribute right now; checks if the number of the words preceding the current token
* is the same as the value of the num attribute;
* f.e. the value "3+" means: at least 3 preceding tokens, "3-": not more than 3, "3": exactly 3
*/
protected boolean checkPrevWords(Element currentRulePart, Element token, int position, NodeList tokens) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
for(int z=0; z<attNodes.getLength(); z++) {
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
if(currentAtt.equals("num")) { // there is only the "num" attribute right now
int requiredNum = Integer.parseInt(currentVal.substring(0,1));
int num = 0;
for(int i=position-1;i>=0;i--) {
if(!((Element)tokens.item(i)).getAttribute("sampa").equals("")) num++;
}
if(currentVal.length() == 1) { // rule requires exactly num words after current token
if(num != requiredNum) return false;
} else if(currentVal.substring(1,2).equals("+")) { // rule requires at least num words after current token
if(!(num >= requiredNum)) return false;
} else if(currentVal.substring(1,2).equals("-")) { // rule requires not more than num words after current token
if(!(num <= requiredNum)) return false;
}
}
}
return true;
}
/** checks rule part with tag "sentence";
* there is only the "type" attribute right now: checks if sentence type of a token is the same
* as the value of the type attribute in the rule
*/
protected boolean checkSentence (Element currentRulePart, String sentenceType) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
for(int z=0; z<attNodes.getLength(); z++) {
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
if(currentAtt.equals("type")) { // there is only the "type" attribute right now
if(!currentVal.startsWith("!")) { // no negation
if(!sentenceType.equals(currentVal)) return false;
} else { // negation
currentVal = currentVal.substring(1,currentVal.length());
if(sentenceType.equals(currentVal)) return false;
}
}
}
return true;
}
/** checks rule part with tag "specialPosition";
* there is only the "type" attribute right now: checks if specialPosition value of a token is the same
* as the value of the type attribute in the rule;
* values: endofvorfeld, endofpar (end of paragraph)
*/
protected boolean checkSpecialPosition (Element currentRulePart, String specialPositionType) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
for(int z=0; z<attNodes.getLength(); z++) {
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
if(currentAtt.equals("type")) { // there is only the "type" attribute right now
if(!currentVal.startsWith("!")) { // no negation
if(!specialPositionType.equals(currentVal)) return false;
} else { // negation
currentVal = currentVal.substring(1,currentVal.length());
if(specialPositionType.equals(currentVal)) return false;
}
}
}
return true;
}
/** checks rule part with tag "prosodicPosition";
* there is only the "type" attribute right now: checks if prosodic position of a token is the same
* as the value of the type attribute in the rule;
* values: prenuclear, nuclearParagraphFinal, nuclearParagraphNonFinal, postnuclear
*/
protected boolean checkProsodicPosition (Element currentRulePart, String prosodicPositionType) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
for(int z=0; z<attNodes.getLength(); z++) {
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
if(currentAtt.equals("type")) { // there is only the "type" attribute right now
if(!currentVal.startsWith("!")) { // no negation
if(!prosodicPositionType.equals(currentVal)) return false;
} else { // negation
currentVal = currentVal.substring(1,currentVal.length());
if(prosodicPositionType.equals(currentVal)) return false;
}
}
}
return true;
}
/** checks rule part with tag "attributes";
* checks if the MaryXML attributes and values of current token are the same as in the rule
*/
protected boolean checkAttributes(Element currentRulePart, Element token) {
NamedNodeMap attNodes = currentRulePart.getAttributes();
if(token == null) return false; // token doesn't exist
for(int z=0; z<attNodes.getLength(); z++) { // loop over MaryXML attributes in rule part
Node el = (Node)attNodes.item(z);
String currentAtt = el.getNodeName();
String currentVal = el.getNodeValue();
// first the special cases
if(!token.hasAttribute(currentAtt)) { // token doesn't have attribute
if(currentVal.equals("!")) { // rule says that token shouldn't have it --> return true
return true;
} else { // rule says that token should have it --> return false
return false;
}
} else { // token has attribute ...
if(currentVal.equals("!")) { // .. but rule says that token shouldn't have it --> return false
return false;
} else {
if(currentVal.equals("")) { // rule says that value doesn't matter, but attribute has to be present --> return true
return true;
} else {
// first case: the value of the rule attribute is not a list
if(!currentVal.startsWith("INLIST") && !currentVal.startsWith("INFSTLIST")
&& !currentVal.startsWith("!INLIST") && !currentVal.startsWith("!INFSTLIST")) {
if(!currentVal.startsWith("!")) {
if(!token.getAttribute(currentAtt).equals(currentVal)) { // condition violated
return false;
}
} else { // value is negated --> token shouldn't have the value in currentVal
currentVal = currentVal.substring(1,currentVal.length());
if(token.getAttribute(currentAtt).equals(currentVal)) { // condition violated
return false;
}
}
} else { //second case: the value of the rule attribute is a list
return checkList(currentVal,token.getAttribute(currentAtt));
}
}
}
}
} // for-loop
return true;
}
/** checks rule part with tag "nextAttributes","previousAttributes","nextPlusXAttributes","previousMinusXAttributes";
* checks if the MaryXML attributes and values of other token than the current one
* are the same as in rule (f.e. the 3th token after current token)
*/
protected boolean checkAttributesOfOtherToken(String tag, Element currentRulePart, Element token, int position, NodeList tokens) {
Element otherToken = null;
if(tag.equals("nextAttributes")) { // MaryXML attributes of next token
if(position<tokens.getLength()-1) {
otherToken = (Element)tokens.item(position+1);
}
}
if(nextPlusXAttributesPattern.matcher(tag).find()) { //MaryXML attributes of some token following the next token
String tempString = tag.replaceAll("nextPlus","");
String newString = tempString.replaceAll("Attributes","");
int num = Integer.parseInt(newString);
if(position<tokens.getLength()-(num+1)) {
otherToken = (Element)tokens.item(position+1+num);
}
}
if(tag.equals("previousAttributes")) { // MaryXML attributes of previous token
if(position>0) {
otherToken = (Element)tokens.item(position-1);
}
}
if(previousMinusXAttributesPattern.matcher(tag).find()) { // MaryXML attributes of some token preceding the previous token
String tempString = tag.replaceAll("previousMinus","");
String newString = tempString.replaceAll("Attributes","");
int num = Integer.parseInt(newString);
if(position>num) {
otherToken = (Element)tokens.item(position-(num+1));
}
}
return checkAttributes(currentRulePart,otherToken);
}
/** Checks if tokenValue is contained in list.
* This base implementation is able to deal with list types
* represented as Sets; subclasses may override this method
* to be able to deal with different list representations.
* @param currentVal the condition to check; can be either <code>INLIST:</code>
* or <code>!INLIST:</code> followed by the list name to check.
* @param tokenValue value to look up in the list
* @return whether or not tokenValue is contained in the list.
*/
protected boolean checkList(String currentVal, String tokenValue) {
if (currentVal == null || tokenValue == null) {
throw new NullPointerException("Received null argument");
}
if (!currentVal.startsWith("INLIST") && !currentVal.startsWith("!INLIST")) {
throw new IllegalArgumentException("currentVal does not start with INLIST or !INLIST");
}
boolean negation = currentVal.startsWith("!");
String listName = currentVal.substring(currentVal.indexOf(":")+1);
Object listObj = listMap.get(listName);
if (listObj == null) return false; // no list found
boolean contains;
if (listObj instanceof Set) {
Set set = (Set) listObj;
contains = set.contains(tokenValue);
} else {
throw new IllegalArgumentException("Unknown list representation: " + listObj);
}
if (contains && negation || !contains && !negation) return false;
else return true;
}
/** determination of sentence type
* values: decl, excl, interrog, interrogYN or interrogW
*/
protected String getSentenceType(NodeList tokens) {
String sentenceType="decl";
for (int i = tokens.getLength() - 1; i >= 0; i--) { // search for sentence finishing punctuation mark
Element t = (Element) tokens.item(i);
String punct = MaryDomUtils.tokenText(t);
if(punct.equals(".")) {
sentenceType = "decl";
break;
}
else if(punct.equals("!")) {
sentenceType = "excl";
break;
}
else if(punct.equals("?")) {
sentenceType = "interrog";
break;
}
}
if(sentenceType.equals("interrog")) {
for (int i=0; i<tokens.getLength()-1; i++) { // search for the first word in sentence
Element t = (Element) tokens.item(i);
if(!t.getAttribute("sampa").equals("")) {
Element firstToken = (Element)tokens.item(i);
// setInterrogYN contains possible part of speechs of first word in yes-no question
HashSet setInterrogYN = ((HashSet)listMap.get("firstPosInQuestionYN"));
// setInterrogW contains possible part of speechs of first word in wh-question
HashSet setInterrogW = ((HashSet)listMap.get("firstPosInQuestionW"));
String posFirstWord = firstToken.getAttribute("pos");
if(setInterrogYN != null && setInterrogYN.contains(posFirstWord)) {
sentenceType = "interrogYN";
}
if(setInterrogW != null && setInterrogW.contains(posFirstWord)) {
sentenceType = "interrogW";
}
break;
}
}
}
return sentenceType;
}
/**
* Assign an accent to the given token.
* @param token a token element
* @param accent the accent string to assign.
*/
protected void setAccent(Element token, String accent)
{
token.setAttribute("accent", accent);
}
/**
* Insert a boundary after token, with the given tone and breakindex.
* If a boundary element already exists after token (but before the
* following token), it is used.
* When choosing between the values already given in the existing element
* and the ones passed as arguments to this function, the higher /
* more concrete values are taken:
* Only if bi is higher than an already existing breakindex, the old
* value is replaced with bi. Only if tone is a concrete tone (like "h-")
* and the previous tone was "unknown" or not specified at all,
* tone is taken into account.
* @return the boundary element on success, null on failure.
*/
protected Element insertBoundary(Element token, String tone, int bi) {
// Search for an existing boundary after token
Element boundary = null;
logger.debug("insertBoundary: after token `"+MaryDomUtils.tokenText(token)+"', tone "+tone+", bi "+bi);
Document doc = token.getOwnerDocument();
TreeWalker tw = ((DocumentTraversal)doc).createTreeWalker(
DomUtils.getAncestor(token, MaryXML.SENTENCE), NodeFilter.SHOW_ELEMENT,
new NameNodeFilter(new String[] {MaryXML.BOUNDARY, MaryXML.TOKEN}), false);
tw.setCurrentNode(token);
Element next = (Element) tw.nextNode();
if (next != null && next.getTagName().equals(MaryXML.BOUNDARY)) {
boundary = next;
} else if (isPunctuation(token)) {
// if the current token is punctuation, we also look for a
// boundary before the current token
tw.setCurrentNode(token);
Element prev = (Element) tw.previousNode();
if (prev != null && prev.getTagName().equals(MaryXML.BOUNDARY)) {
boundary = prev;
}
}
if (boundary != null) { // there is a boundary tag after token
// the tone:
if (tone != null) {
String tagTone = boundary.getAttribute("tone");
// Use tone given as parameter to this method:
// - if no tone attribute is given in the tag, or
// - if tone parameter is a concrete tone symbol and
// tagTone is "unknown"
if (tagTone.equals("") || !tone.equals("unknown") && tagTone.equals("unknown")) {
boundary.setAttribute("tone", tone);
}
}
// the break index:
if (bi > 0) {
String tagBIString = boundary.getAttribute("breakindex");
// Use bi given as parameter to this method:
// - if no breakindex attribute is given in the tag
// - if bi is a larger breakindex than tagBI
if (tagBIString.equals("") || tagBIString.equals("unknown")) {
boundary.setAttribute("breakindex", String.valueOf(bi));
} /*else {
try {
int tagBI = Integer.parseInt(tagBIString);
if (tagBI < bi) {
boundary.setAttribute("breakindex", String.valueOf(bi));
}
} catch (NumberFormatException e) {
} // ignore, do nothing
}*/
}
} else { // no boundary tag yet, introduce one
// First verify that we have a valid parent element
if (token.getParentNode() == null) {
return null;
}
// Make sure not to insert the new boundary
// in the middle of an <mtu> element:
Element eIn = (Element) token.getParentNode();
Element eBefore = MaryDomUtils.getNextSiblingElement(token);
// Now change these insertion references in case token
// is the last one in an <mtu> tag.
Element mtu = (Element) MaryDomUtils.getHighestLevelAncestor(token, MaryXML.MTU);
if (mtu != null) {
if (MaryDomUtils.isLastOfItsKindIn(token, mtu)) {
eIn = (Element) mtu.getParentNode();
eBefore = MaryDomUtils.getNextSiblingElement(mtu);
} else {
// token is in the middle of an mtu - don't insert boundary
return null;
}
}
// Now the boundary tag is to be inserted.
boundary = MaryXML.createElement(doc, MaryXML.BOUNDARY);
if (tone != null) {
boundary.setAttribute("tone", tone);
}
if (bi > 0) {
boundary.setAttribute("breakindex", String.valueOf(bi));
}
eIn.insertBefore(boundary, eBefore);
} // add new boundary
return boundary;
}
/**
* Insert a major boundary after token number <code>i</code> in
* <code>tokens</code>.
* <p>
* Also inserts a phrase tag at the appropriate position.
* @return The boundary element.
*/
protected Element insertMajorBoundary(NodeList tokens, int i, Element firstToken, String tone, int breakindex) {
Element boundary = insertBoundary((Element) tokens.item(i), tone, breakindex);
insertPhraseNode(firstToken, boundary);
return boundary;
}
/**
* Inserte a phrase element, enclosing the first and last element,
* into the tree. Typically first element would be a token, last element
* a boundary.
* @return true on success, false on failure.
*/
protected boolean insertPhraseNode(Element first, Element last) {
// Allow for the exotic case that a <phrase> should start with a <boundary/> element:
Element encloseFromHere = first;
Element maybeBoundary = DomUtils.getPreviousSiblingElement(first);
if (maybeBoundary != null && maybeBoundary.getTagName().equals(MaryXML.BOUNDARY)) {
encloseFromHere = maybeBoundary;
}
// Take existing trailing boundary elements into the new phrase:
Element encloseToHere = last;
maybeBoundary = DomUtils.getNextSiblingElement(last);
if (maybeBoundary != null && maybeBoundary.getTagName().equals(MaryXML.BOUNDARY)) {
encloseToHere = maybeBoundary;
}
Element phrase = MaryDomUtils.encloseNodesWithNewElement(encloseFromHere, encloseToHere, MaryXML.PHRASE);
return phrase != null;
}
/**
* Verify whether this Node has a parent preventing the application
* of intonation rules.
* @return <code>true</code> if rules are to be applied,
* <code>false</code> otherwise.
*/
protected boolean applyRules(Node n) {
Element intonation = (Element) MaryDomUtils.getAncestor(n, MaryXML.PROSODY);
if (intonation != null && intonation.getAttribute("rules").equals("off")) {
return false;
} else {
return true;
}
}
/**
* Go through all tokens in a document, and copy any accents to the first
* accented syllable.
*/
protected void copyAccentsToSyllables(Document doc)
{
NodeIterator tIt = ((DocumentTraversal)doc).createNodeIterator
(doc, NodeFilter.SHOW_ELEMENT, new NameNodeFilter(MaryXML.TOKEN), false);
Element t = null;
while ((t = (Element) tIt.nextNode()) != null) {
if (t.hasAttribute("accent")) {
NodeIterator sylIt = ((DocumentTraversal)doc).createNodeIterator
(t, NodeFilter.SHOW_ELEMENT, new NameNodeFilter(MaryXML.SYLLABLE), false);
boolean assignedAccent = false;
Element syl = null;
while ((syl = (Element) sylIt.nextNode()) != null) {
if (syl.getAttribute("stress").equals("1")) {
// found
syl.setAttribute("accent", t.getAttribute("accent"));
assignedAccent = true;
break; // done for this token
}
}
if (!assignedAccent) {
// Hmm, this token does not have a stressed syllable --
// take the first syllable then:
syl = MaryDomUtils.getFirstElementByTagName(t, MaryXML.SYLLABLE);
if (syl != null) {
syl.setAttribute("accent", t.getAttribute("accent"));
}
}
}
}
}
/**
* Check whether <code>token</code> is enclosed by a
* <code><prosody></code> element containing an attribute
* <code>force-accent</code>.
* @return the value of the <code>force-accent</code> attribute,
* if one exists, or the empty string otherwise.
*/
protected String getForceAccent(Element token) {
// Search for the closest ancestor <prosody> element
// which has a "force-accent" attribute:
Element p = (Element) MaryDomUtils.getClosestAncestorWithAttribute(token, MaryXML.PROSODY, "force-accent");
if (p != null)
return p.getAttribute("force-accent");
else
return "";
}
/**
* Verify whether a given token is a punctuation.
* @param token the t element to be tested.
* @return true if token is a punctuation, false otherwise.
*/
protected boolean isPunctuation(Element token) {
if (token == null)
throw new NullPointerException("Received null token");
if (!token.getTagName().equals(MaryXML.TOKEN))
throw new IllegalArgumentException("Expected <" + MaryXML.TOKEN + "> element, got <" + token.getTagName() + ">");
String tokenText = MaryDomUtils.tokenText((Element) token);
if (tokenText.equals(",") || tokenText.equals(".") || tokenText.equals("?") || tokenText.equals("!") || tokenText.equals(":")
|| tokenText.equals(";"))
return true;
else
return false;
}
}
| false | true | protected void processSentence (Element sentence) {
NodeList tokens = sentence.getElementsByTagName(MaryXML.TOKEN);
if (tokens.getLength() < 1) {
return; // no tokens -- what can we do?
}
Element firstTokenInPhrase = null;
// properties of the whole sentence
// first determine the sentence type
String sentenceType = "decl";
sentenceType = getSentenceType(tokens);
// determine if it is the last sentence in a paragraph
boolean paragraphFinal =
MaryDomUtils.isLastOfItsKindIn(sentence, MaryXML.PARAGRAPH)
&& !MaryDomUtils.isFirstOfItsKindIn(sentence, MaryXML.PARAGRAPH);
// check if it is a sentence with vorfeld
boolean inVorfeld = true; // default
for(int i=0; i<tokens.getLength();i++) { // search for the first word in sentence
Element token = ((Element)tokens.item(i));
if(!token.getAttribute("sampa").equals("")) { // first word found
String posFirstWord = token.getAttribute("pos");
// if pos value of first word in sentence is contained in set noVorfeld, vorfeld doens't exist
HashSet noVorfeld = (HashSet)listMap.get("noVorfeld");
if(noVorfeld != null) {
if(noVorfeld.contains(posFirstWord)) {
inVorfeld = false;
}
}
break;
}
}
// default: no special position
String specialPositionType = "noValue"; // can get the values "endofvorfeld" and "endofpar"(=end of paragraph)
int numEndOfVorfeld = -1;
boolean hasAccent=false; // tests if phrase has an accent
Element bestCandidate = null; // will become token with highest accent priority if a phrase has no accent;
// avoids phrases without accent
// loop over the tokens in sentence
// assignment of accent position and boundaries
for (int i = 0; i < tokens.getLength(); i++) {
Element token = (Element) tokens.item(i);
logger.debug("Now looking at token `"+MaryDomUtils.tokenText(token)+"'");
if(firstTokenInPhrase==null) {
firstTokenInPhrase=token; // begin of an intonation phrase
}
// determine if token is at end of vorfeld
if(inVorfeld != false) { // only if vorfeld exists and if token's position is not after vorfeld
if(i<tokens.getLength()-1) {
Element nextToken = (Element) tokens.item(i+1);
String posNextToken = nextToken.getAttribute("pos");
// if pos value of next token is contained in set beginOfMittelfeld,
// current token is at the end of the vorfeld
HashSet beginOfMittelfeld = (HashSet)listMap.get("beginOfMittelfeld");
if(beginOfMittelfeld != null && beginOfMittelfeld.contains(posNextToken)) {
//for(int z=0; z<attNodes.getLength(); z++) {
//Node el = (Node)attNodes.item(z);
//String currentVal = el.getNodeValue();
//if(beginOfMittelfeld.contains(currentVal)) {
//if(beginOfMittelfeld.contains(posNextToken)) {
specialPositionType = "endofvorfeld";
numEndOfVorfeld = i; // position of current token
inVorfeld = false;
} else specialPositionType = "vorfeld";
}
}
// determine token position in text
boolean isFinalToken = (i >= tokens.getLength() - 1); // last token in sentence?
if(paragraphFinal && isFinalToken) { // last token in sentence and in paragraph?
specialPositionType = "endofpar";
}
boolean applyRules = applyRules(token);
if (applyRules) { // rule application not turned off
// first: assignment of accent = "tone", accent="force"(for force-accents(Druckakzent)) or accent=""
// --> determine if the token receives an accent or not
// the type of accent(f.e. L+H*) is assigend later
/*** begin user input check,accent position ***/
String forceAccent = getForceAccent(token);
if(forceAccent.equals("word") || forceAccent.equals("syllable")
|| token.getAttribute("accent").equals("unknown")) {
setAccent(token, "tone"); // the token receives an accent according to user input
} else if(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) {
// no accent according to user input
} else if(!token.getAttribute("accent").equals("")) {
// accent type is already assigned by the user, f.e. accent="L+H*"
/*** end user input check, accent position ***/
// no user input
// the rules in the xml file are applied
} else if(token.getAttribute("sampa").equals("")) { // test if token is punctuation
token.removeAttribute("accent"); // doesn't receive an accent
} else getAccentPosition(token, tokens, i, sentenceType, specialPositionType);
// check if the phrase has an accent (avoid intermediate phrases without accent)
if(token.getAttribute("accent").equals("tone")) {
hasAccent = true;
}
// if not, check if current token is the best candidate
if(hasAccent == false &&
!(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) &&
!token.getAttribute("sampa").equals("")) {
if(bestCandidate == null) { // no candidate yet
bestCandidate=token;
} else {
int priorToken = -1;
int priorBestCandidate = -1;
// search for pos in accentPriorities property list
// first check priority for current token
String posCurrentToken = token.getAttribute("pos");
try {
priorToken = Integer.parseInt(priorities.getProperty(posCurrentToken));
} catch (NumberFormatException e) { }
// now check priority for bestCandidate
String posBestCandidate = bestCandidate.getAttribute("pos");
try {
priorBestCandidate = Integer.parseInt(priorities.getProperty(posBestCandidate));
} catch (NumberFormatException e) { }
// if the current token has higher priority than the best candidate,
// current token becomes the best candidate for accentuation
if(priorToken != -1 && priorBestCandidate != -1) {
if(priorToken <= priorBestCandidate) bestCandidate = token;
}
}
}
if(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) {
token.removeAttribute("accent");
}
} // end of accent position assignment
// now the informations relevant only for boundary assignment
boolean invalidXML = false;
if(!isFinalToken) { // We only set a majorIP boundary if the XML structure
// allows the phrase to be closed before the next token
invalidXML =
MaryDomUtils.isAncestor(
MaryDomUtils.closestCommonAncestor(firstTokenInPhrase, tokens.item(i)),
MaryDomUtils.closestCommonAncestor(tokens.item(i), tokens.item(i + 1)));
}
if(applyRules) {
// insertion of ip- and IP-boundaries
// returns value for firstTokenInPhrase(begin of new phrase): if a boundary was inserted, firstTokenInPhrase gets null
// if not, firstTokenInPhrase has the same value as before
firstTokenInPhrase = getBoundary(token,tokens,i,sentenceType,specialPositionType,invalidXML,firstTokenInPhrase);
// check if every intermediate an intonation phrase has at least one accent
// first check if a boundary was inserted
Element boundary = null;
Document doc = token.getOwnerDocument();
TreeWalker tw = ((DocumentTraversal)doc).createTreeWalker(
DomUtils.getAncestor(token, MaryXML.SENTENCE), NodeFilter.SHOW_ELEMENT,
new NameNodeFilter(new String[] {MaryXML.BOUNDARY, MaryXML.TOKEN}), false);
tw.setCurrentNode(token);
logger.debug("Starting treewalker at token " + MaryDomUtils.tokenText(token));
Element next = (Element) tw.nextNode();
if (next != null && next.getTagName().equals(MaryXML.BOUNDARY)) {
logger.debug("tw found a boundary");
boundary = next;
int bi = 0;
try {
bi = Integer.parseInt(boundary.getAttribute("breakindex"));
} catch (NumberFormatException nfe) {}
if(bi>=3) { // is it an intermediate or an intoantion phrase?
if(hasAccent == false && bestCandidate != null) { // no accent!
setAccent(bestCandidate, "tone"); // best candidate receives accent
}
hasAccent=false;
bestCandidate = null;
}
}
}
if(specialPositionType.equals("endofvorfeld")) specialPositionType="noValue";
} // loop tokens for accent position and boundary assignment
/*** user input check, boundaries ***/
NodeList boundaries = sentence.getElementsByTagName(MaryXML.BOUNDARY);
for (int i = 0; i < boundaries.getLength(); i++) {
Element boundary = (Element) boundaries.item(i);
if (boundary.getAttribute("breakindex").equals("none")) { // the boundary is to be deleted
// delete boundary
Node parent = boundary.getParentNode();
parent.removeChild(boundary);
} else if (boundary.getAttribute("tone").equals("unknown")) { // boundary, but no tone is given
// is there a preferred tone for boundaries?
Element prosody =
MaryDomUtils.getClosestAncestorWithAttribute(boundary, MaryXML.PROSODY, "preferred-boundary-type");
String preferred = null;
if (prosody != null) preferred = prosody.getAttribute("preferred-boundary-type");
String h = boundary.getAttribute("breakindex");
int bi = 0;
String tone = null;
try {
bi = Integer.parseInt(h);
} catch (NumberFormatException e) { } // ignore invalid values
if (bi >= 4) {
// major boundary (but we cannot insert a phrase,
// because we don't know where it should start)
if (preferred != null) {
if (preferred.equals("high")) {
HashSet set = (HashSet)listMap.get("high_major_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else { // low
HashSet set = (HashSet)listMap.get("low_major_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else { // there isn't any information about the tone, so we use default values specified in the xml file
if (i == boundaries.getLength() - 1) { // final boundary
if(sentenceType.equals("decl") || sentenceType.equals("excl")) { //declarative or exclamative sentence
HashSet set = (HashSet)listMap.get("default_IP_endOfSent");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else {
HashSet set = (HashSet)listMap.get("default_IP_endOfInterrogSent"); // interrogative
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else { // non-final boundary
HashSet set = (HashSet)listMap.get("default_IP_midOfSent");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
}
} else if (bi == 3) {
// minor boundary
if (preferred != null) {
if (preferred.equals("high")) {
HashSet set = (HashSet)listMap.get("high_minor_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else { // low
HashSet set = (HashSet)listMap.get("low_minor_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else {// there is no information about the tone, so we use the default values specified in the xml file
HashSet set = (HashSet)listMap.get("default_ip");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
}
if (tone != null) boundary.setAttribute("tone", tone);
}
} // for all boundaries
/*** end user input check, boundaries ***/
// now the information relevant for accent type assignment
boolean nucleusAssigned = false;
String lastAssignedTone = null; // for user input preferred-accent-shape="alternating_accents"
for (int j = tokens.getLength() - 1; j >= 0; j--) { // accent type assignment
Element token = (Element) tokens.item(j);
// determine specialpositionType
boolean isFinalToken = (j >= tokens.getLength() - 1); // last token in sentence?
if(paragraphFinal && isFinalToken) { // last token in paragraph?
specialPositionType = "endofpar"; // last token in sentence and in paragraph
}
if(j == numEndOfVorfeld) specialPositionType = "endofvorfeld";
if(token.getAttribute("accent").equals("tone") || token.getAttribute("accent").equals("force")) {
/*** begin user input check, accent type ***/
Element prosody = MaryDomUtils.getClosestAncestorWithAttribute(token, MaryXML.PROSODY, "preferred-accent-shape");
if (prosody != null) {
if(token.getAttribute("accent").equals("tone")) { // no force accents in this case
String tone = null;
String preferred = prosody.getAttribute("preferred-accent-shape");
if (preferred.equals("alternating")) {
HashSet set = (HashSet)listMap.get("alternating_accents");
Iterator it = set.iterator();
while(it.hasNext()) {
String next = (String)it.next();
if(lastAssignedTone == null || !lastAssignedTone.equals(next)) {
tone = next;
}
}
} else if (preferred.equals("rising")) {
HashSet set = (HashSet)listMap.get("rising_accents");
Iterator it = set.iterator();
if(it.hasNext()) tone = (String)it.next();
} else if (preferred.equals("falling")) {
HashSet set = (HashSet)listMap.get("falling_accents");
Iterator it = set.iterator();
if(it.hasNext()) tone = (String)it.next();
}
token.setAttribute("accent",tone);
if(nucleusAssigned == false) nucleusAssigned = true;
}
} else if(!(token.getAttribute("accent").equals("force") || token.getAttribute("accent").equals("tone")||
token.getAttribute("accent").equals(""))) {
nucleusAssigned = true; // user has already assigned an accent type
/*** end user input check, accent type ***/
} else if(token.getAttribute("sampa").equals("")) { // test if token is a word (no punctuation)
// punctuation, doesn't receive an accent
} else // xml file rules are applied
// assignment of accent type
// returns true, if nuclear accent is assigned, false otherwise
nucleusAssigned = getAccentShape(token,tokens,j,sentenceType,specialPositionType,nucleusAssigned);
}
if(token.getAttribute("accent").equals("") || token.getAttribute("accent").equals("force")) {
token.removeAttribute("accent"); // if there is no accent, the accent attribute can be removed
}
if(token.hasAttribute("accent")) {
lastAssignedTone = token.getAttribute("accent");
}
} //loop over tokens for accent type assignment
} //processSentence
| protected void processSentence (Element sentence) {
NodeList tokens = sentence.getElementsByTagName(MaryXML.TOKEN);
if (tokens.getLength() < 1) {
return; // no tokens -- what can we do?
}
Element firstTokenInPhrase = null;
// properties of the whole sentence
// first determine the sentence type
String sentenceType = "decl";
sentenceType = getSentenceType(tokens);
// determine if it is the last sentence in a paragraph
boolean paragraphFinal =
MaryDomUtils.isLastOfItsKindIn(sentence, MaryXML.PARAGRAPH)
&& !MaryDomUtils.isFirstOfItsKindIn(sentence, MaryXML.PARAGRAPH);
// check if it is a sentence with vorfeld
boolean inVorfeld = true; // default
for(int i=0; i<tokens.getLength();i++) { // search for the first word in sentence
Element token = ((Element)tokens.item(i));
if(!token.getAttribute("sampa").equals("")) { // first word found
String posFirstWord = token.getAttribute("pos");
// if pos value of first word in sentence is contained in set noVorfeld, vorfeld doens't exist
HashSet noVorfeld = (HashSet)listMap.get("noVorfeld");
if(noVorfeld != null) {
if(noVorfeld.contains(posFirstWord)) {
inVorfeld = false;
}
}
break;
}
}
// default: no special position
String specialPositionType = "noValue"; // can get the values "endofvorfeld" and "endofpar"(=end of paragraph)
int numEndOfVorfeld = -1;
boolean hasAccent=false; // tests if phrase has an accent
Element bestCandidate = null; // will become token with highest accent priority if a phrase has no accent;
// avoids phrases without accent
// loop over the tokens in sentence
// assignment of accent position and boundaries
for (int i = 0; i < tokens.getLength(); i++) {
Element token = (Element) tokens.item(i);
logger.debug("Now looking at token `"+MaryDomUtils.tokenText(token)+"'");
if(firstTokenInPhrase==null) {
firstTokenInPhrase=token; // begin of an intonation phrase
}
// determine if token is at end of vorfeld
if(inVorfeld != false) { // only if vorfeld exists and if token's position is not after vorfeld
if(i<tokens.getLength()-1) {
Element nextToken = (Element) tokens.item(i+1);
String posNextToken = nextToken.getAttribute("pos");
// if pos value of next token is contained in set beginOfMittelfeld,
// current token is at the end of the vorfeld
HashSet beginOfMittelfeld = (HashSet)listMap.get("beginOfMittelfeld");
if(beginOfMittelfeld != null && beginOfMittelfeld.contains(posNextToken)) {
//for(int z=0; z<attNodes.getLength(); z++) {
//Node el = (Node)attNodes.item(z);
//String currentVal = el.getNodeValue();
//if(beginOfMittelfeld.contains(currentVal)) {
//if(beginOfMittelfeld.contains(posNextToken)) {
specialPositionType = "endofvorfeld";
numEndOfVorfeld = i; // position of current token
inVorfeld = false;
} else specialPositionType = "vorfeld";
}
}
// determine token position in text
boolean isFinalToken = (i >= tokens.getLength() - 1); // last token in sentence?
if(paragraphFinal && isFinalToken) { // last token in sentence and in paragraph?
specialPositionType = "endofpar";
}
boolean applyRules = applyRules(token);
if (applyRules) { // rule application not turned off
// first: assignment of accent = "tone", accent="force"(for force-accents(Druckakzent)) or accent=""
// --> determine if the token receives an accent or not
// the type of accent(f.e. L+H*) is assigend later
/*** begin user input check,accent position ***/
String forceAccent = getForceAccent(token);
if (token.getAttribute("accent").equals("unknown")
|| !token.hasAttribute("accent") && (forceAccent.equals("word") || forceAccent.equals("syllable"))) {
setAccent(token, "tone"); // the token receives an accent according to user input
} else if(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) {
// no accent according to user input
} else if(!token.getAttribute("accent").equals("")) {
// accent type is already assigned by the user, f.e. accent="L+H*"
/*** end user input check, accent position ***/
// no user input
// the rules in the xml file are applied
} else if(token.getAttribute("sampa").equals("")) { // test if token is punctuation
token.removeAttribute("accent"); // doesn't receive an accent
} else { // default behaviour: determine by rule whether to assign an accent
getAccentPosition(token, tokens, i, sentenceType, specialPositionType);
}
// check if the phrase has an accent (avoid intermediate phrases without accent)
if(token.hasAttribute("accent") && !token.getAttribute("accent").equals("none")) {
hasAccent = true;
}
// if not, check if current token is the best candidate
if(hasAccent == false &&
!(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) &&
!token.getAttribute("sampa").equals("")) {
if(bestCandidate == null) { // no candidate yet
bestCandidate=token;
} else {
int priorToken = -1;
int priorBestCandidate = -1;
// search for pos in accentPriorities property list
// first check priority for current token
String posCurrentToken = token.getAttribute("pos");
try {
priorToken = Integer.parseInt(priorities.getProperty(posCurrentToken));
} catch (NumberFormatException e) { }
// now check priority for bestCandidate
String posBestCandidate = bestCandidate.getAttribute("pos");
try {
priorBestCandidate = Integer.parseInt(priorities.getProperty(posBestCandidate));
} catch (NumberFormatException e) { }
// if the current token has higher priority than the best candidate,
// current token becomes the best candidate for accentuation
if(priorToken != -1 && priorBestCandidate != -1) {
if(priorToken <= priorBestCandidate) bestCandidate = token;
}
}
}
if(token.getAttribute("accent").equals("none") || forceAccent.equals("none")) {
token.removeAttribute("accent");
}
} // end of accent position assignment
// now the informations relevant only for boundary assignment
boolean invalidXML = false;
if(!isFinalToken) { // We only set a majorIP boundary if the XML structure
// allows the phrase to be closed before the next token
invalidXML =
MaryDomUtils.isAncestor(
MaryDomUtils.closestCommonAncestor(firstTokenInPhrase, tokens.item(i)),
MaryDomUtils.closestCommonAncestor(tokens.item(i), tokens.item(i + 1)));
}
if(applyRules) {
// insertion of ip- and IP-boundaries
// returns value for firstTokenInPhrase(begin of new phrase): if a boundary was inserted, firstTokenInPhrase gets null
// if not, firstTokenInPhrase has the same value as before
firstTokenInPhrase = getBoundary(token,tokens,i,sentenceType,specialPositionType,invalidXML,firstTokenInPhrase);
// check if every intermediate an intonation phrase has at least one accent
// first check if a boundary was inserted
Element boundary = null;
Document doc = token.getOwnerDocument();
TreeWalker tw = ((DocumentTraversal)doc).createTreeWalker(
DomUtils.getAncestor(token, MaryXML.SENTENCE), NodeFilter.SHOW_ELEMENT,
new NameNodeFilter(new String[] {MaryXML.BOUNDARY, MaryXML.TOKEN}), false);
tw.setCurrentNode(token);
logger.debug("Starting treewalker at token " + MaryDomUtils.tokenText(token));
Element next = (Element) tw.nextNode();
if (next != null && next.getTagName().equals(MaryXML.BOUNDARY)) {
logger.debug("tw found a boundary");
boundary = next;
int bi = 0;
try {
bi = Integer.parseInt(boundary.getAttribute("breakindex"));
} catch (NumberFormatException nfe) {}
if(bi>=3) { // is it an intermediate or an intoantion phrase?
if(hasAccent == false && bestCandidate != null) { // no accent!
setAccent(bestCandidate, "tone"); // best candidate receives accent
}
hasAccent=false;
bestCandidate = null;
}
}
}
if(specialPositionType.equals("endofvorfeld")) specialPositionType="noValue";
} // loop tokens for accent position and boundary assignment
/*** user input check, boundaries ***/
NodeList boundaries = sentence.getElementsByTagName(MaryXML.BOUNDARY);
for (int i = 0; i < boundaries.getLength(); i++) {
Element boundary = (Element) boundaries.item(i);
if (boundary.getAttribute("breakindex").equals("none")) { // the boundary is to be deleted
// delete boundary
Node parent = boundary.getParentNode();
parent.removeChild(boundary);
} else if (boundary.getAttribute("tone").equals("unknown")) { // boundary, but no tone is given
// is there a preferred tone for boundaries?
Element prosody =
MaryDomUtils.getClosestAncestorWithAttribute(boundary, MaryXML.PROSODY, "preferred-boundary-type");
String preferred = null;
if (prosody != null) preferred = prosody.getAttribute("preferred-boundary-type");
String h = boundary.getAttribute("breakindex");
int bi = 0;
String tone = null;
try {
bi = Integer.parseInt(h);
} catch (NumberFormatException e) { } // ignore invalid values
if (bi >= 4) {
// major boundary (but we cannot insert a phrase,
// because we don't know where it should start)
if (preferred != null) {
if (preferred.equals("high")) {
HashSet set = (HashSet)listMap.get("high_major_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else { // low
HashSet set = (HashSet)listMap.get("low_major_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else { // there isn't any information about the tone, so we use default values specified in the xml file
if (i == boundaries.getLength() - 1) { // final boundary
if(sentenceType.equals("decl") || sentenceType.equals("excl")) { //declarative or exclamative sentence
HashSet set = (HashSet)listMap.get("default_IP_endOfSent");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else {
HashSet set = (HashSet)listMap.get("default_IP_endOfInterrogSent"); // interrogative
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else { // non-final boundary
HashSet set = (HashSet)listMap.get("default_IP_midOfSent");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
}
} else if (bi == 3) {
// minor boundary
if (preferred != null) {
if (preferred.equals("high")) {
HashSet set = (HashSet)listMap.get("high_minor_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
} else { // low
HashSet set = (HashSet)listMap.get("low_minor_boundary");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
} else {// there is no information about the tone, so we use the default values specified in the xml file
HashSet set = (HashSet)listMap.get("default_ip");
Iterator it = set.iterator();
while(it.hasNext()) tone = (String)it.next();
}
}
if (tone != null) boundary.setAttribute("tone", tone);
}
} // for all boundaries
/*** end user input check, boundaries ***/
// now the information relevant for accent type assignment
boolean nucleusAssigned = false;
String lastAssignedTone = null; // for user input preferred-accent-shape="alternating_accents"
for (int j = tokens.getLength() - 1; j >= 0; j--) { // accent type assignment
Element token = (Element) tokens.item(j);
// determine specialpositionType
boolean isFinalToken = (j >= tokens.getLength() - 1); // last token in sentence?
if(paragraphFinal && isFinalToken) { // last token in paragraph?
specialPositionType = "endofpar"; // last token in sentence and in paragraph
}
if(j == numEndOfVorfeld) specialPositionType = "endofvorfeld";
if(token.getAttribute("accent").equals("tone") || token.getAttribute("accent").equals("force")) {
/*** begin user input check, accent type ***/
Element prosody = MaryDomUtils.getClosestAncestorWithAttribute(token, MaryXML.PROSODY, "preferred-accent-shape");
if (prosody != null) {
if(token.getAttribute("accent").equals("tone")) { // no force accents in this case
String tone = null;
String preferred = prosody.getAttribute("preferred-accent-shape");
if (preferred.equals("alternating")) {
HashSet set = (HashSet)listMap.get("alternating_accents");
Iterator it = set.iterator();
while(it.hasNext()) {
String next = (String)it.next();
if(lastAssignedTone == null || !lastAssignedTone.equals(next)) {
tone = next;
}
}
} else if (preferred.equals("rising")) {
HashSet set = (HashSet)listMap.get("rising_accents");
Iterator it = set.iterator();
if(it.hasNext()) tone = (String)it.next();
} else if (preferred.equals("falling")) {
HashSet set = (HashSet)listMap.get("falling_accents");
Iterator it = set.iterator();
if(it.hasNext()) tone = (String)it.next();
}
token.setAttribute("accent",tone);
if(nucleusAssigned == false) nucleusAssigned = true;
}
} else if(!(token.getAttribute("accent").equals("force") || token.getAttribute("accent").equals("tone")||
token.getAttribute("accent").equals(""))) {
nucleusAssigned = true; // user has already assigned an accent type
/*** end user input check, accent type ***/
} else if(token.getAttribute("sampa").equals("")) { // test if token is a word (no punctuation)
// punctuation, doesn't receive an accent
} else // xml file rules are applied
// assignment of accent type
// returns true, if nuclear accent is assigned, false otherwise
nucleusAssigned = getAccentShape(token,tokens,j,sentenceType,specialPositionType,nucleusAssigned);
}
if(token.getAttribute("accent").equals("") || token.getAttribute("accent").equals("force")) {
token.removeAttribute("accent"); // if there is no accent, the accent attribute can be removed
}
if(token.hasAttribute("accent")) {
lastAssignedTone = token.getAttribute("accent");
}
} //loop over tokens for accent type assignment
} //processSentence
|
diff --git a/src/java/org/lwjgl/opengl/MacOSXCanvasPeerInfo.java b/src/java/org/lwjgl/opengl/MacOSXCanvasPeerInfo.java
index 3aab2ddc..959328d1 100644
--- a/src/java/org/lwjgl/opengl/MacOSXCanvasPeerInfo.java
+++ b/src/java/org/lwjgl/opengl/MacOSXCanvasPeerInfo.java
@@ -1,208 +1,210 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
import java.awt.Canvas;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.Insets;
import java.awt.Container;
import java.awt.Component;
import java.awt.Point;
import java.awt.Window;
import java.nio.ByteBuffer;
import javax.swing.SwingUtilities;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
/**
*
* @author elias_naur <[email protected]>
* @author kappaOne <[email protected]>
* @version $Revision$
* $Id$
*/
abstract class MacOSXCanvasPeerInfo extends MacOSXPeerInfo {
private final AWTSurfaceLock awt_surface = new AWTSurfaceLock();
public ByteBuffer window_handle;
protected MacOSXCanvasPeerInfo(PixelFormat pixel_format, ContextAttribs attribs, boolean support_pbuffer) throws LWJGLException {
super(pixel_format, attribs, true, true, support_pbuffer, true);
}
protected void initHandle(Canvas component) throws LWJGLException {
boolean forceCALayer = true;
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.5") || javaVersion.startsWith("1.6")) {
// On Java 7 and newer CALayer mode is the only way to use OpenGL with AWT
// therefore force it on all JVM's except for the older Java 5 and Java 6
// where the older cocoaViewRef NSView method maybe be available.
forceCALayer = false;
}
Insets insets = getInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
window_handle = nInitHandle(awt_surface.lockAndGetHandle(component), getHandle(), window_handle, forceCALayer, component.getX()-left, component.getY()-top);
if (javaVersion.startsWith("1.7")) {
// fix for CALayer position not covering Canvas due to a Java 7 bug
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7172187
addComponentListener(component);
}
}
private void addComponentListener(final Canvas component) {
ComponentListener[] components = component.getComponentListeners();
// avoid adding duplicate listners by checking if one has already been added
for (int i = 0; i < components.length; i++) {
ComponentListener c = components[i];
if (c.toString() == "CanvasPeerInfoListener") {
return; // already contains the listner below return without adding
}
}
ComponentListener comp = new ComponentListener() {
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
if (SwingUtilities.getWindowAncestor(component.getParent()) != null) {
Point componentPosition = SwingUtilities.convertPoint(component, component.getLocation(), null);
Point parentPosition = SwingUtilities.convertPoint(component.getParent(), component.getLocation(), null);
if (componentPosition.getX() == parentPosition.getX() && componentPosition.getY() == parentPosition.getY()) {
Insets insets = getWindowInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
nSetLayerBounds(getHandle(), (int)componentPosition.getX()-left, (int)componentPosition.getY()-top, component.getWidth(), component.getHeight());
return;
}
}
Insets insets = getInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
- nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
+ //nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
+ nSetLayerBounds(getHandle(), component.getX() - left, component.getY() - top, component.getWidth(), component.getHeight());
}
public void componentResized(ComponentEvent e) {
if (SwingUtilities.getWindowAncestor(component.getParent()) != null) {
Point componentPosition = SwingUtilities.convertPoint(component, component.getLocation(), null);
Point parentPosition = SwingUtilities.convertPoint(component.getParent(), component.getLocation(), null);
if (componentPosition.getX() == parentPosition.getX() && componentPosition.getY() == parentPosition.getY()) {
Insets insets = getWindowInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
nSetLayerBounds(getHandle(), (int)componentPosition.getX()-left, (int)componentPosition.getY()-top, component.getWidth(), component.getHeight());
return;
}
}
Insets insets = getInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
- nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
+ //nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
+ nSetLayerBounds(getHandle(), component.getX() - left, component.getY() - top, component.getWidth(), component.getHeight());
}
public void componentShown(ComponentEvent e) {
}
public String toString() {
return "CanvasPeerInfoListener";
}
};
component.addComponentListener(comp);
}
private static native ByteBuffer nInitHandle(ByteBuffer surface_buffer, ByteBuffer peer_info_handle, ByteBuffer window_handle, boolean forceCALayer, int x, int y) throws LWJGLException;
private static native void nSetLayerPosition(ByteBuffer peer_info_handle, int x, int y);
private static native void nSetLayerBounds(ByteBuffer peer_info_handle, int x, int y, int width, int height);
protected void doUnlock() throws LWJGLException {
awt_surface.unlock();
}
/**
* Return the Insets of the Window holding the Canvas
*/
private Insets getWindowInsets(Canvas canvas) {
Container parent = canvas.getParent();
while (parent != null) {
if(parent instanceof Window || parent instanceof java.applet.Applet) {
return parent.getInsets();
}
parent = parent.getParent();
}
// if no parent Window or Applet found, return null
return null;
}
private Insets getInsets(Canvas component) {
Component parent = component.getParent();
while (parent != null) {
if (parent instanceof Container) {
return ((Container)parent).getInsets();
}
parent = parent.getParent();
}
return null;
}
}
| false | true | private void addComponentListener(final Canvas component) {
ComponentListener[] components = component.getComponentListeners();
// avoid adding duplicate listners by checking if one has already been added
for (int i = 0; i < components.length; i++) {
ComponentListener c = components[i];
if (c.toString() == "CanvasPeerInfoListener") {
return; // already contains the listner below return without adding
}
}
ComponentListener comp = new ComponentListener() {
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
if (SwingUtilities.getWindowAncestor(component.getParent()) != null) {
Point componentPosition = SwingUtilities.convertPoint(component, component.getLocation(), null);
Point parentPosition = SwingUtilities.convertPoint(component.getParent(), component.getLocation(), null);
if (componentPosition.getX() == parentPosition.getX() && componentPosition.getY() == parentPosition.getY()) {
Insets insets = getWindowInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
nSetLayerBounds(getHandle(), (int)componentPosition.getX()-left, (int)componentPosition.getY()-top, component.getWidth(), component.getHeight());
return;
}
}
Insets insets = getInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
}
public void componentResized(ComponentEvent e) {
if (SwingUtilities.getWindowAncestor(component.getParent()) != null) {
Point componentPosition = SwingUtilities.convertPoint(component, component.getLocation(), null);
Point parentPosition = SwingUtilities.convertPoint(component.getParent(), component.getLocation(), null);
if (componentPosition.getX() == parentPosition.getX() && componentPosition.getY() == parentPosition.getY()) {
Insets insets = getWindowInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
nSetLayerBounds(getHandle(), (int)componentPosition.getX()-left, (int)componentPosition.getY()-top, component.getWidth(), component.getHeight());
return;
}
}
Insets insets = getInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
}
public void componentShown(ComponentEvent e) {
}
public String toString() {
return "CanvasPeerInfoListener";
}
};
component.addComponentListener(comp);
}
| private void addComponentListener(final Canvas component) {
ComponentListener[] components = component.getComponentListeners();
// avoid adding duplicate listners by checking if one has already been added
for (int i = 0; i < components.length; i++) {
ComponentListener c = components[i];
if (c.toString() == "CanvasPeerInfoListener") {
return; // already contains the listner below return without adding
}
}
ComponentListener comp = new ComponentListener() {
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
if (SwingUtilities.getWindowAncestor(component.getParent()) != null) {
Point componentPosition = SwingUtilities.convertPoint(component, component.getLocation(), null);
Point parentPosition = SwingUtilities.convertPoint(component.getParent(), component.getLocation(), null);
if (componentPosition.getX() == parentPosition.getX() && componentPosition.getY() == parentPosition.getY()) {
Insets insets = getWindowInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
nSetLayerBounds(getHandle(), (int)componentPosition.getX()-left, (int)componentPosition.getY()-top, component.getWidth(), component.getHeight());
return;
}
}
Insets insets = getInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
//nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
nSetLayerBounds(getHandle(), component.getX() - left, component.getY() - top, component.getWidth(), component.getHeight());
}
public void componentResized(ComponentEvent e) {
if (SwingUtilities.getWindowAncestor(component.getParent()) != null) {
Point componentPosition = SwingUtilities.convertPoint(component, component.getLocation(), null);
Point parentPosition = SwingUtilities.convertPoint(component.getParent(), component.getLocation(), null);
if (componentPosition.getX() == parentPosition.getX() && componentPosition.getY() == parentPosition.getY()) {
Insets insets = getWindowInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
nSetLayerBounds(getHandle(), (int)componentPosition.getX()-left, (int)componentPosition.getY()-top, component.getWidth(), component.getHeight());
return;
}
}
Insets insets = getInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
//nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
nSetLayerBounds(getHandle(), component.getX() - left, component.getY() - top, component.getWidth(), component.getHeight());
}
public void componentShown(ComponentEvent e) {
}
public String toString() {
return "CanvasPeerInfoListener";
}
};
component.addComponentListener(comp);
}
|
diff --git a/src/org/oscim/renderer/PolygonRenderer.java b/src/org/oscim/renderer/PolygonRenderer.java
index b9ecccc1..d480ea99 100644
--- a/src/org/oscim/renderer/PolygonRenderer.java
+++ b/src/org/oscim/renderer/PolygonRenderer.java
@@ -1,338 +1,337 @@
/*
* Copyright 2012 Hannes Janetzek
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General License for more details.
*
* You should have received a copy of the GNU Lesser General License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.renderer;
import static android.opengl.GLES20.GL_ALWAYS;
import static android.opengl.GLES20.GL_BLEND;
import static android.opengl.GLES20.GL_EQUAL;
import static android.opengl.GLES20.GL_INVERT;
import static android.opengl.GLES20.GL_LESS;
import static android.opengl.GLES20.GL_SHORT;
import static android.opengl.GLES20.GL_TRIANGLE_FAN;
import static android.opengl.GLES20.GL_TRIANGLE_STRIP;
import static android.opengl.GLES20.GL_ZERO;
import static android.opengl.GLES20.glColorMask;
import static android.opengl.GLES20.glDepthFunc;
import static android.opengl.GLES20.glDepthMask;
import static android.opengl.GLES20.glDisable;
import static android.opengl.GLES20.glDrawArrays;
import static android.opengl.GLES20.glEnable;
import static android.opengl.GLES20.glGetAttribLocation;
import static android.opengl.GLES20.glGetUniformLocation;
import static android.opengl.GLES20.glStencilFunc;
import static android.opengl.GLES20.glStencilMask;
import static android.opengl.GLES20.glStencilOp;
import static android.opengl.GLES20.glUniform4fv;
import static android.opengl.GLES20.glUniformMatrix4fv;
import static android.opengl.GLES20.glUseProgram;
import static android.opengl.GLES20.glVertexAttribPointer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import org.oscim.core.MapPosition;
import org.oscim.renderer.layer.Layer;
import org.oscim.renderer.layer.PolygonLayer;
import org.oscim.utils.GlUtils;
import android.opengl.GLES20;
public final class PolygonRenderer {
// private static final String TAG = "PolygonRenderer";
// private static final int NUM_VERTEX_SHORTS = 2;
private static final int POLYGON_VERTICES_DATA_POS_OFFSET = 0;
private static final int STENCIL_BITS = 8;
private static final float FADE_START = 1.3f;
private static PolygonLayer[] mFillPolys;
private static int polygonProgram;
private static int hPolygonVertexPosition;
private static int hPolygonMatrix;
private static int hPolygonColor;
static boolean init() {
// Set up the program for rendering polygons
polygonProgram = GlUtils.createProgram(Shaders.polygonVertexShader,
Shaders.polygonFragmentShader);
if (polygonProgram == 0) {
// Log.e(TAG, "Could not create polygon program.");
return false;
}
hPolygonMatrix = glGetUniformLocation(polygonProgram, "u_mvp");
hPolygonColor = glGetUniformLocation(polygonProgram, "u_color");
hPolygonVertexPosition = glGetAttribLocation(polygonProgram, "a_position");
mFillPolys = new PolygonLayer[STENCIL_BITS];
return true;
}
private static void fillPolygons(int zoom, float scale) {
boolean blend = false;
/* draw to framebuffer */
glColorMask(true, true, true, true);
/* do not modify stencil buffer */
glStencilMask(0);
for (int c = mStart; c < mCount; c++) {
PolygonLayer l = mFillPolys[c];
float f = 1.0f;
if (l.area.fade >= zoom || l.area.color[3] != 1.0) {
/* fade in/out || draw alpha color */
if (l.area.fade >= zoom) {
f = (scale > FADE_START ? scale : FADE_START) - f;
if (f > 1.0f)
f = 1.0f;
}
if (!blend) {
glEnable(GL_BLEND);
blend = true;
}
if (f != 1) {
f *= l.area.color[3];
GlUtils.setColor(hPolygonColor, l.area.color, f);
} else {
glUniform4fv(hPolygonColor, 1, l.area.color, 0);
}
} else if (l.area.blend == zoom) {
/* blend colors */
f = scale - 1.0f;
if (f > 1.0f)
f = 1.0f;
else if (f < 0)
f = 0;
GlUtils.setBlendColors(hPolygonColor,
l.area.color, l.area.blendColor, f);
} else {
/* draw solid */
if (blend) {
glDisable(GL_BLEND);
blend = false;
}
if (l.area.blend <= zoom && l.area.blend > 0)
glUniform4fv(hPolygonColor, 1, l.area.blendColor, 0);
else
glUniform4fv(hPolygonColor, 1, l.area.color, 0);
}
// if (alpha < 1) {
// if (!blend) {
// glEnable(GL_BLEND);
// blend = true;
// }
// } else if (blend) {
// glDisable(GL_BLEND);
// blend = false;
// }
/* set stencil buffer mask used to draw this layer */
glStencilFunc(GL_EQUAL, 0xff, 1 << c);
/* draw tile fill coordinates */
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
if (blend)
glDisable(GL_BLEND);
}
// layers to fill
private static int mCount;
// stencil buffer index to start fill
private static int mStart;
/**
* draw polygon layers (unil layer.next is not polygon layer)
* using stencil buffer method
* @param pos
* used to fade layers accorind to 'fade'
* in layer.area.
* @param layer
* layer to draw (referencing vertices in current vbo)
* @param matrix
* mvp matrix
* @param first
* pass true to clear stencil buffer region
* @param drawClipped
* clip to first quad in current vbo
* @return
* next layer
*/
public static Layer draw(MapPosition pos, Layer layer,
float[] matrix, boolean first, boolean drawClipped) {
int zoom = pos.zoomLevel;
float scale = pos.scale;
glUseProgram(polygonProgram);
GLState.enableVertexArrays(hPolygonVertexPosition, -1);
glVertexAttribPointer(hPolygonVertexPosition, 2, GL_SHORT,
false, 0, POLYGON_VERTICES_DATA_POS_OFFSET);
glUniformMatrix4fv(hPolygonMatrix, 1, false, matrix, 0);
// reset start when only two layer left in stencil buffer
// if (mCount > 5) {
// mCount = 0;
// mStart = 0;
// }
if (first) {
mCount = 0;
mStart = 0;
} else {
mStart = mCount;
}
Layer l = layer;
for (; l != null && l.type == Layer.POLYGON; l = l.next) {
PolygonLayer pl = (PolygonLayer) l;
// fade out polygon layers (set in RederTheme)
if (pl.area.fade > 0 && pl.area.fade > zoom)
continue;
if (mCount == mStart) {
// clear stencilbuffer (tile region) by drawing
// a quad with func 'always' and op 'zero'
// disable drawing to framebuffer
glColorMask(false, false, false, false);
// never pass the test: always apply fail op
glStencilFunc(GL_ALWAYS, 0, 0xFF);
glStencilMask(0xFF);
glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
if (drawClipped) {
GLState.test(true, true);
// draw clip-region into depth buffer:
// this is used for lines and polygons
// write to depth buffer
glDepthMask(true);
// to prevent overdraw gl_less restricts the
// clip to the area where no other tile has drawn
glDepthFunc(GL_LESS);
}
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
if (drawClipped) {
first = false;
- drawClipped = false;
// do not modify depth buffer anymore
glDepthMask(false);
// only draw to this tile
glDepthFunc(GL_EQUAL);
}
// op for stencil method polygon drawing
glStencilOp(GL_INVERT, GL_INVERT, GL_INVERT);
}
// no need for depth test while drawing stencil
GLState.test(false, true);
mFillPolys[mCount] = pl;
// set stencil mask to draw to
glStencilMask(1 << mCount++);
glDrawArrays(GL_TRIANGLE_FAN, l.offset, l.verticesCnt);
// draw up to 8 layers into stencil buffer
if (mCount == STENCIL_BITS) {
/* only draw where nothing was drawn yet */
if (drawClipped)
GLState.test(true, true);
fillPolygons(zoom, scale);
mCount = 0;
mStart = 0;
}
}
if (mCount > 0) {
/* only draw where nothing was drawn yet */
if (drawClipped)
GLState.test(true, true);
fillPolygons(zoom, scale);
}
if (drawClipped && first) {
GLState.test(true, false);
GLES20.glColorMask(false, false, false, false);
GLES20.glDepthMask(true);
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
GLES20.glDepthMask(false);
GLES20.glColorMask(true, true, true, true);
GLES20.glDepthFunc(GLES20.GL_EQUAL);
}
return l;
}
private static float[] debugFillColor = { 0.3f, 0.0f, 0.0f, 0.3f };
private static float[] debugFillColor2 = { 0.0f, 0.3f, 0.0f, 0.3f };
private static FloatBuffer mDebugFill;
static void debugDraw(float[] matrix, float[] coords, int color) {
GLState.test(false, false);
if (mDebugFill == null)
mDebugFill = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder())
.asFloatBuffer();
mDebugFill.put(coords);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
mDebugFill.position(0);
glUseProgram(polygonProgram);
GLES20.glEnableVertexAttribArray(hPolygonVertexPosition);
glVertexAttribPointer(hPolygonVertexPosition, 2, GLES20.GL_FLOAT,
false, 0, mDebugFill);
glUniformMatrix4fv(hPolygonMatrix, 1, false, matrix, 0);
if (color == 0)
glUniform4fv(hPolygonColor, 1, debugFillColor, 0);
else
glUniform4fv(hPolygonColor, 1, debugFillColor2, 0);
glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
GlUtils.checkGlError("draw debug");
}
}
| true | true | public static Layer draw(MapPosition pos, Layer layer,
float[] matrix, boolean first, boolean drawClipped) {
int zoom = pos.zoomLevel;
float scale = pos.scale;
glUseProgram(polygonProgram);
GLState.enableVertexArrays(hPolygonVertexPosition, -1);
glVertexAttribPointer(hPolygonVertexPosition, 2, GL_SHORT,
false, 0, POLYGON_VERTICES_DATA_POS_OFFSET);
glUniformMatrix4fv(hPolygonMatrix, 1, false, matrix, 0);
// reset start when only two layer left in stencil buffer
// if (mCount > 5) {
// mCount = 0;
// mStart = 0;
// }
if (first) {
mCount = 0;
mStart = 0;
} else {
mStart = mCount;
}
Layer l = layer;
for (; l != null && l.type == Layer.POLYGON; l = l.next) {
PolygonLayer pl = (PolygonLayer) l;
// fade out polygon layers (set in RederTheme)
if (pl.area.fade > 0 && pl.area.fade > zoom)
continue;
if (mCount == mStart) {
// clear stencilbuffer (tile region) by drawing
// a quad with func 'always' and op 'zero'
// disable drawing to framebuffer
glColorMask(false, false, false, false);
// never pass the test: always apply fail op
glStencilFunc(GL_ALWAYS, 0, 0xFF);
glStencilMask(0xFF);
glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
if (drawClipped) {
GLState.test(true, true);
// draw clip-region into depth buffer:
// this is used for lines and polygons
// write to depth buffer
glDepthMask(true);
// to prevent overdraw gl_less restricts the
// clip to the area where no other tile has drawn
glDepthFunc(GL_LESS);
}
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
if (drawClipped) {
first = false;
drawClipped = false;
// do not modify depth buffer anymore
glDepthMask(false);
// only draw to this tile
glDepthFunc(GL_EQUAL);
}
// op for stencil method polygon drawing
glStencilOp(GL_INVERT, GL_INVERT, GL_INVERT);
}
// no need for depth test while drawing stencil
GLState.test(false, true);
mFillPolys[mCount] = pl;
// set stencil mask to draw to
glStencilMask(1 << mCount++);
glDrawArrays(GL_TRIANGLE_FAN, l.offset, l.verticesCnt);
// draw up to 8 layers into stencil buffer
if (mCount == STENCIL_BITS) {
/* only draw where nothing was drawn yet */
if (drawClipped)
GLState.test(true, true);
fillPolygons(zoom, scale);
mCount = 0;
mStart = 0;
}
}
if (mCount > 0) {
/* only draw where nothing was drawn yet */
if (drawClipped)
GLState.test(true, true);
fillPolygons(zoom, scale);
}
if (drawClipped && first) {
GLState.test(true, false);
GLES20.glColorMask(false, false, false, false);
GLES20.glDepthMask(true);
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
GLES20.glDepthMask(false);
GLES20.glColorMask(true, true, true, true);
GLES20.glDepthFunc(GLES20.GL_EQUAL);
}
return l;
}
| public static Layer draw(MapPosition pos, Layer layer,
float[] matrix, boolean first, boolean drawClipped) {
int zoom = pos.zoomLevel;
float scale = pos.scale;
glUseProgram(polygonProgram);
GLState.enableVertexArrays(hPolygonVertexPosition, -1);
glVertexAttribPointer(hPolygonVertexPosition, 2, GL_SHORT,
false, 0, POLYGON_VERTICES_DATA_POS_OFFSET);
glUniformMatrix4fv(hPolygonMatrix, 1, false, matrix, 0);
// reset start when only two layer left in stencil buffer
// if (mCount > 5) {
// mCount = 0;
// mStart = 0;
// }
if (first) {
mCount = 0;
mStart = 0;
} else {
mStart = mCount;
}
Layer l = layer;
for (; l != null && l.type == Layer.POLYGON; l = l.next) {
PolygonLayer pl = (PolygonLayer) l;
// fade out polygon layers (set in RederTheme)
if (pl.area.fade > 0 && pl.area.fade > zoom)
continue;
if (mCount == mStart) {
// clear stencilbuffer (tile region) by drawing
// a quad with func 'always' and op 'zero'
// disable drawing to framebuffer
glColorMask(false, false, false, false);
// never pass the test: always apply fail op
glStencilFunc(GL_ALWAYS, 0, 0xFF);
glStencilMask(0xFF);
glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
if (drawClipped) {
GLState.test(true, true);
// draw clip-region into depth buffer:
// this is used for lines and polygons
// write to depth buffer
glDepthMask(true);
// to prevent overdraw gl_less restricts the
// clip to the area where no other tile has drawn
glDepthFunc(GL_LESS);
}
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
if (drawClipped) {
first = false;
// do not modify depth buffer anymore
glDepthMask(false);
// only draw to this tile
glDepthFunc(GL_EQUAL);
}
// op for stencil method polygon drawing
glStencilOp(GL_INVERT, GL_INVERT, GL_INVERT);
}
// no need for depth test while drawing stencil
GLState.test(false, true);
mFillPolys[mCount] = pl;
// set stencil mask to draw to
glStencilMask(1 << mCount++);
glDrawArrays(GL_TRIANGLE_FAN, l.offset, l.verticesCnt);
// draw up to 8 layers into stencil buffer
if (mCount == STENCIL_BITS) {
/* only draw where nothing was drawn yet */
if (drawClipped)
GLState.test(true, true);
fillPolygons(zoom, scale);
mCount = 0;
mStart = 0;
}
}
if (mCount > 0) {
/* only draw where nothing was drawn yet */
if (drawClipped)
GLState.test(true, true);
fillPolygons(zoom, scale);
}
if (drawClipped && first) {
GLState.test(true, false);
GLES20.glColorMask(false, false, false, false);
GLES20.glDepthMask(true);
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
GLES20.glDepthMask(false);
GLES20.glColorMask(true, true, true, true);
GLES20.glDepthFunc(GLES20.GL_EQUAL);
}
return l;
}
|
diff --git a/image/src/main/java/org/soluvas/image/impl/ImageMagickTransformerImpl.java b/image/src/main/java/org/soluvas/image/impl/ImageMagickTransformerImpl.java
index b424c55a..d6ffaa75 100644
--- a/image/src/main/java/org/soluvas/image/impl/ImageMagickTransformerImpl.java
+++ b/image/src/main/java/org/soluvas/image/impl/ImageMagickTransformerImpl.java
@@ -1,378 +1,378 @@
package org.soluvas.image.impl;
import java.awt.Dimension;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import javax.annotation.Nullable;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soluvas.image.ImageConnector;
import org.soluvas.image.ImageException;
import org.soluvas.image.ImageFactory;
import org.soluvas.image.ImageMagickTransformer;
import org.soluvas.image.ImagePackage;
import org.soluvas.image.ImageTransform;
import org.soluvas.image.ImageVariant;
import org.soluvas.image.ResizeToFill;
import org.soluvas.image.ResizeToFit;
import org.soluvas.image.TransformGravity;
import org.soluvas.image.UploadedImage;
import org.soluvas.image.util.ImageUtils;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Magick Transformer</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.soluvas.image.impl.ImageMagickTransformerImpl#getDestination <em>Destination</em>}</li>
* </ul>
* </p>
*
* @generated
*/
@SuppressWarnings("serial")
public class ImageMagickTransformerImpl extends ImageTransformerImpl implements ImageMagickTransformer {
public final class TransformFunc implements AsyncFunction<Entry<ImageTransform, ImageVariant>, UploadedImage> {
private final String namespace;
private final File originalFile;
private final String imageId;
public TransformFunc(String namespace, File originalFile, String imageId) {
this.namespace = namespace;
this.originalFile = originalFile;
this.imageId = imageId;
}
@Override
public ListenableFuture<UploadedImage> apply(
Entry<ImageTransform, ImageVariant> input) throws Exception {
final ImageTransform transform = input.getKey();
final ImageVariant dest = input.getValue();
// TODO: do not hardcode quality
final float quality = 0.9f;
final ListenableFuture<File> styledFileFuture = getExecutor().submit(new Callable<File>() {
@Override
public File call() throws Exception {
final File styledFile;
try {
styledFile = File.createTempFile(imageId + "_", "_" + dest.getStyleVariant() + "." + dest.getExtension());
} catch (IOException e1) {
throw new ImageException(e1, "Cannot create temporary file for styled %s %s",
dest.getStyleCode(), imageId);
}
try {
if (transform instanceof ResizeToFill) {
final ResizeToFill fx = (ResizeToFill) transform;
final boolean progressive = fx.getWidth() >= 512;
Preconditions.checkNotNull(fx.getWidth(), "ResizeToFill.width must not be null");
Preconditions.checkNotNull(fx.getHeight(), "ResizeToFill.height must not be null");
final String gravity;
switch (Optional.fromNullable(fx.getGravity()).or(TransformGravity.CENTER)) {
case CENTER:
gravity = "Center";
break;
case BOTTOM_CENTER:
gravity = "South";
break;
case BOTTOM_LEFT:
gravity = "SouthWest";
break;
case BOTTOM_RIGHT:
gravity = "SouthEast";
break;
case TOP_LEFT:
gravity = "NorthWest";
break;
case TOP_RIGHT:
gravity = "NorthEast";
break;
case TOP_CENTER:
gravity = "North";
break;
case CENTER_LEFT:
gravity = "West";
break;
case CENTER_RIGHT:
gravity = "East";
break;
default:
throw new ImageException("Unknown gravity: " + fx.getGravity());
}
final CommandLine cmd = new CommandLine("convert");
cmd.addArgument("-verbose");
cmd.addArgument(originalFile.getPath());
+ cmd.addArgument("-gravity");
+ cmd.addArgument(gravity);
cmd.addArgument("-resize");
cmd.addArgument(fx.getWidth() + "x" + fx.getHeight() + "^");
cmd.addArgument("-extent");
cmd.addArgument(fx.getWidth() + "x" + fx.getHeight());
- cmd.addArgument("-gravity");
- cmd.addArgument(gravity);
cmd.addArgument("-quality");
cmd.addArgument(String.valueOf((int)(quality * 100f)));
cmd.addArgument(styledFile.getPath());
log.debug("ResizeToFill {} to {}, {}x{} gravity={} quality={} progressive={} using: {}",
originalFile, styledFile, fx.getWidth(), fx.getHeight(),
gravity, quality, progressive, cmd );
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(new PumpStreamHandler(buffer));
final int executionResult = executor.execute(cmd);
log.info("{} returned {}: {}", cmd, executionResult, buffer);
} else if (transform instanceof ResizeToFit) {
final ResizeToFit fx = (ResizeToFit) transform;
Preconditions.checkArgument(fx.getWidth() != null || fx.getHeight() != null,
"For ResizeToFit, at least one of height or width must be specified");
final boolean progressive = fx.getWidth() != null ? fx.getWidth() >= 512 : fx.getHeight() >= 512;
final CommandLine cmd = new CommandLine("convert");
cmd.addArgument("-verbose");
cmd.addArgument(originalFile.getPath());
cmd.addArgument("-resize");
final String widthStr = fx.getWidth() != null ? fx.getWidth().toString() : "";
final String heightStr = fx.getHeight() != null ? fx.getHeight().toString() : "";
final String onlyShrinkLargerFlag = fx.getOnlyShrinkLarger() ? ">" : "";
cmd.addArgument(widthStr + "x" + heightStr + onlyShrinkLargerFlag);
cmd.addArgument("-quality");
cmd.addArgument(String.valueOf((int)(quality * 100f)));
cmd.addArgument(styledFile.getPath());
log.debug("ResizeToFit {} to {}, {}x{} onlyShrinkLarger={} quality={} progressive={} using: {}",
originalFile, styledFile, fx.getWidth(), fx.getHeight(), fx.getOnlyShrinkLarger(),
quality, progressive, cmd );
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(new PumpStreamHandler(buffer));
final int executionResult = executor.execute(cmd);
log.info("{} returned {}: {}", cmd, executionResult, buffer);
} else {
throw new ImageException("Unsupported transform: " + transform);
}
return styledFile;
} catch (final Exception e) {
throw new ImageException("Error resizing " + imageId + " to " + dest.getStyleCode() + ", destination: " + styledFile, e);
}
}
});
final ListenableFuture<UploadedImage> styledImageFuture = Futures.transform(styledFileFuture, new AsyncFunction<File, UploadedImage>() {
@Override
public ListenableFuture<UploadedImage> apply(File styledFile)
throws Exception {
// Upload the styled image
// final URI styledDavUri = getImageDavUri(imageId, style.getName());
// upload directly for efficiency
// TODO: not hardcode styled content type and extension
final String styledContentType = "image/jpeg";
final String styledExtension = "jpg";
log.debug("Uploading {} {} using {} from {} ({} bytes)",
dest.getStyleCode(), imageId, destination.getClass().getName(),
styledFile, styledFile.length());
final ListenableFuture<UploadedImage> styledUploadFuture = destination.upload(namespace, imageId, dest.getStyleCode(),
dest.getStyleVariant(), styledExtension, styledFile, styledContentType);
return styledUploadFuture;
}
});
final ListenableFuture<UploadedImage> transformedFuture = Futures.transform(styledImageFuture, new Function<UploadedImage, UploadedImage>() {
@Override @Nullable
public UploadedImage apply(@Nullable UploadedImage styledUpload) {
final File styledFile = Futures.getUnchecked(styledFileFuture);
try {
final Dimension styledDim = ImageUtils.getDimension(styledFile);
final int width = (int) styledDim.getWidth();
final int height = (int) styledDim.getHeight();
log.debug("Dimensions of {} is {}x{}", styledFile, width, height);
final String styledOriginUri = styledUpload.getOriginUri();
final String styledCdnUri = styledUpload.getUri();
log.info("Uploaded {} {} as {}/{} from {} ({} bytes)", dest.getStyleCode(), imageId, styledOriginUri, styledCdnUri,
styledFile, styledFile.length());
// final StyledImage styled = new StyledImage(
// style.getName(), style.getCode(), URI.create(styledPublicUri), styledContentType,
// (int)styledFile.length(), width, height);
// return styled;
final UploadedImage uploadedImage = ImageFactory.eINSTANCE.createUploadedImage();
uploadedImage.setStyleCode(dest.getStyleCode());
uploadedImage.setStyleVariant(dest.getStyleVariant());
uploadedImage.setExtension(dest.getExtension());
uploadedImage.setOriginUri(styledOriginUri);
uploadedImage.setUri(styledCdnUri);
uploadedImage.setWidth(width);
uploadedImage.setHeight(height);
uploadedImage.setSize(styledFile.length());
return uploadedImage;
} finally {
log.trace("Deleting temporary {} {} styled image {}", dest.getStyleCode(), imageId, styledFile);
styledFile.delete();
log.debug("Deleted temporary {} {} styled image {}", dest.getStyleCode(), imageId, styledFile);
}
}
}, getExecutor());
return transformedFuture;
}
}
static final Logger log = LoggerFactory
.getLogger(ImageMagickTransformerImpl.class);
/**
* The cached value of the '{@link #getDestination() <em>Destination</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDestination()
* @generated
* @ordered
*/
protected ImageConnector destination;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*/
protected ImageMagickTransformerImpl() {
throw new UnsupportedOperationException();
}
public ImageMagickTransformerImpl(ImageConnector destination) {
super();
this.destination = destination;
}
public ImageMagickTransformerImpl(ExecutorService executor, ImageConnector destination) {
super(executor);
this.destination = destination;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ImagePackage.Literals.IMAGE_MAGICK_TRANSFORMER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ImageConnector getDestination() {
if (destination != null && ((EObject)destination).eIsProxy()) {
InternalEObject oldDestination = (InternalEObject)destination;
destination = (ImageConnector)eResolveProxy(oldDestination);
if (destination != oldDestination) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ImagePackage.IMAGE_MAGICK_TRANSFORMER__DESTINATION, oldDestination, destination));
}
}
return destination;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ImageConnector basicGetDestination() {
return destination;
}
/**
* haidar@haidar ~/tmp $ convert -verbose -resize 64x64^ -extent 64x64 -gravity North *.jpg
* test1.jpg JPEG 527x700 527x700+0+0 8-bit DirectClass 99.9KB 0.010u 0:00.010
* test1.jpg=>test1_n.jpg JPEG 527x700=>64x64 64x64+0+0 8-bit DirectClass 20.5KB 0.000u 0:00.000
*
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*/
@Override
public ListenableFuture<List<UploadedImage>> transform(final ImageConnector source, final File sourceFile, final String namespace,
final String imageId, final ImageVariant sourceVariant, final Map<ImageTransform, ImageVariant> transforms) {
final AsyncFunction<File, List<UploadedImage>> processor = new AsyncFunction<File, List<UploadedImage>>() {
@Override
public ListenableFuture<List<UploadedImage>> apply(final File originalFile)
throws Exception {
final TransformFunc transformFunc = new TransformFunc(namespace, originalFile, imageId);
final List<ListenableFuture<UploadedImage>> taskFutures = new ArrayList<>();
for (Entry<ImageTransform, ImageVariant> entry : transforms.entrySet()) {
taskFutures.add(transformFunc.apply(entry));
}
final ListenableFuture<List<UploadedImage>> styledImagesFuture = Futures.allAsList(taskFutures);
return styledImagesFuture;
}
};
return processLocallyThenDelete(source, sourceFile, namespace, imageId,
sourceVariant, transforms, processor);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ImagePackage.IMAGE_MAGICK_TRANSFORMER__DESTINATION:
if (resolve) return getDestination();
return basicGetDestination();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ImagePackage.IMAGE_MAGICK_TRANSFORMER__DESTINATION:
return destination != null;
}
return super.eIsSet(featureID);
}
} //ImageMagickTransformerImpl
| false | true | public ListenableFuture<UploadedImage> apply(
Entry<ImageTransform, ImageVariant> input) throws Exception {
final ImageTransform transform = input.getKey();
final ImageVariant dest = input.getValue();
// TODO: do not hardcode quality
final float quality = 0.9f;
final ListenableFuture<File> styledFileFuture = getExecutor().submit(new Callable<File>() {
@Override
public File call() throws Exception {
final File styledFile;
try {
styledFile = File.createTempFile(imageId + "_", "_" + dest.getStyleVariant() + "." + dest.getExtension());
} catch (IOException e1) {
throw new ImageException(e1, "Cannot create temporary file for styled %s %s",
dest.getStyleCode(), imageId);
}
try {
if (transform instanceof ResizeToFill) {
final ResizeToFill fx = (ResizeToFill) transform;
final boolean progressive = fx.getWidth() >= 512;
Preconditions.checkNotNull(fx.getWidth(), "ResizeToFill.width must not be null");
Preconditions.checkNotNull(fx.getHeight(), "ResizeToFill.height must not be null");
final String gravity;
switch (Optional.fromNullable(fx.getGravity()).or(TransformGravity.CENTER)) {
case CENTER:
gravity = "Center";
break;
case BOTTOM_CENTER:
gravity = "South";
break;
case BOTTOM_LEFT:
gravity = "SouthWest";
break;
case BOTTOM_RIGHT:
gravity = "SouthEast";
break;
case TOP_LEFT:
gravity = "NorthWest";
break;
case TOP_RIGHT:
gravity = "NorthEast";
break;
case TOP_CENTER:
gravity = "North";
break;
case CENTER_LEFT:
gravity = "West";
break;
case CENTER_RIGHT:
gravity = "East";
break;
default:
throw new ImageException("Unknown gravity: " + fx.getGravity());
}
final CommandLine cmd = new CommandLine("convert");
cmd.addArgument("-verbose");
cmd.addArgument(originalFile.getPath());
cmd.addArgument("-resize");
cmd.addArgument(fx.getWidth() + "x" + fx.getHeight() + "^");
cmd.addArgument("-extent");
cmd.addArgument(fx.getWidth() + "x" + fx.getHeight());
cmd.addArgument("-gravity");
cmd.addArgument(gravity);
cmd.addArgument("-quality");
cmd.addArgument(String.valueOf((int)(quality * 100f)));
cmd.addArgument(styledFile.getPath());
log.debug("ResizeToFill {} to {}, {}x{} gravity={} quality={} progressive={} using: {}",
originalFile, styledFile, fx.getWidth(), fx.getHeight(),
gravity, quality, progressive, cmd );
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(new PumpStreamHandler(buffer));
final int executionResult = executor.execute(cmd);
log.info("{} returned {}: {}", cmd, executionResult, buffer);
} else if (transform instanceof ResizeToFit) {
final ResizeToFit fx = (ResizeToFit) transform;
Preconditions.checkArgument(fx.getWidth() != null || fx.getHeight() != null,
"For ResizeToFit, at least one of height or width must be specified");
final boolean progressive = fx.getWidth() != null ? fx.getWidth() >= 512 : fx.getHeight() >= 512;
final CommandLine cmd = new CommandLine("convert");
cmd.addArgument("-verbose");
cmd.addArgument(originalFile.getPath());
cmd.addArgument("-resize");
final String widthStr = fx.getWidth() != null ? fx.getWidth().toString() : "";
final String heightStr = fx.getHeight() != null ? fx.getHeight().toString() : "";
final String onlyShrinkLargerFlag = fx.getOnlyShrinkLarger() ? ">" : "";
cmd.addArgument(widthStr + "x" + heightStr + onlyShrinkLargerFlag);
cmd.addArgument("-quality");
cmd.addArgument(String.valueOf((int)(quality * 100f)));
cmd.addArgument(styledFile.getPath());
log.debug("ResizeToFit {} to {}, {}x{} onlyShrinkLarger={} quality={} progressive={} using: {}",
originalFile, styledFile, fx.getWidth(), fx.getHeight(), fx.getOnlyShrinkLarger(),
quality, progressive, cmd );
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(new PumpStreamHandler(buffer));
final int executionResult = executor.execute(cmd);
log.info("{} returned {}: {}", cmd, executionResult, buffer);
} else {
throw new ImageException("Unsupported transform: " + transform);
}
return styledFile;
} catch (final Exception e) {
throw new ImageException("Error resizing " + imageId + " to " + dest.getStyleCode() + ", destination: " + styledFile, e);
}
}
});
final ListenableFuture<UploadedImage> styledImageFuture = Futures.transform(styledFileFuture, new AsyncFunction<File, UploadedImage>() {
@Override
public ListenableFuture<UploadedImage> apply(File styledFile)
throws Exception {
// Upload the styled image
// final URI styledDavUri = getImageDavUri(imageId, style.getName());
// upload directly for efficiency
// TODO: not hardcode styled content type and extension
final String styledContentType = "image/jpeg";
final String styledExtension = "jpg";
log.debug("Uploading {} {} using {} from {} ({} bytes)",
dest.getStyleCode(), imageId, destination.getClass().getName(),
styledFile, styledFile.length());
final ListenableFuture<UploadedImage> styledUploadFuture = destination.upload(namespace, imageId, dest.getStyleCode(),
dest.getStyleVariant(), styledExtension, styledFile, styledContentType);
return styledUploadFuture;
}
});
final ListenableFuture<UploadedImage> transformedFuture = Futures.transform(styledImageFuture, new Function<UploadedImage, UploadedImage>() {
@Override @Nullable
public UploadedImage apply(@Nullable UploadedImage styledUpload) {
final File styledFile = Futures.getUnchecked(styledFileFuture);
try {
final Dimension styledDim = ImageUtils.getDimension(styledFile);
final int width = (int) styledDim.getWidth();
final int height = (int) styledDim.getHeight();
log.debug("Dimensions of {} is {}x{}", styledFile, width, height);
final String styledOriginUri = styledUpload.getOriginUri();
final String styledCdnUri = styledUpload.getUri();
log.info("Uploaded {} {} as {}/{} from {} ({} bytes)", dest.getStyleCode(), imageId, styledOriginUri, styledCdnUri,
styledFile, styledFile.length());
// final StyledImage styled = new StyledImage(
// style.getName(), style.getCode(), URI.create(styledPublicUri), styledContentType,
// (int)styledFile.length(), width, height);
// return styled;
final UploadedImage uploadedImage = ImageFactory.eINSTANCE.createUploadedImage();
uploadedImage.setStyleCode(dest.getStyleCode());
uploadedImage.setStyleVariant(dest.getStyleVariant());
uploadedImage.setExtension(dest.getExtension());
uploadedImage.setOriginUri(styledOriginUri);
uploadedImage.setUri(styledCdnUri);
uploadedImage.setWidth(width);
uploadedImage.setHeight(height);
uploadedImage.setSize(styledFile.length());
return uploadedImage;
} finally {
log.trace("Deleting temporary {} {} styled image {}", dest.getStyleCode(), imageId, styledFile);
styledFile.delete();
log.debug("Deleted temporary {} {} styled image {}", dest.getStyleCode(), imageId, styledFile);
}
}
}, getExecutor());
return transformedFuture;
}
| public ListenableFuture<UploadedImage> apply(
Entry<ImageTransform, ImageVariant> input) throws Exception {
final ImageTransform transform = input.getKey();
final ImageVariant dest = input.getValue();
// TODO: do not hardcode quality
final float quality = 0.9f;
final ListenableFuture<File> styledFileFuture = getExecutor().submit(new Callable<File>() {
@Override
public File call() throws Exception {
final File styledFile;
try {
styledFile = File.createTempFile(imageId + "_", "_" + dest.getStyleVariant() + "." + dest.getExtension());
} catch (IOException e1) {
throw new ImageException(e1, "Cannot create temporary file for styled %s %s",
dest.getStyleCode(), imageId);
}
try {
if (transform instanceof ResizeToFill) {
final ResizeToFill fx = (ResizeToFill) transform;
final boolean progressive = fx.getWidth() >= 512;
Preconditions.checkNotNull(fx.getWidth(), "ResizeToFill.width must not be null");
Preconditions.checkNotNull(fx.getHeight(), "ResizeToFill.height must not be null");
final String gravity;
switch (Optional.fromNullable(fx.getGravity()).or(TransformGravity.CENTER)) {
case CENTER:
gravity = "Center";
break;
case BOTTOM_CENTER:
gravity = "South";
break;
case BOTTOM_LEFT:
gravity = "SouthWest";
break;
case BOTTOM_RIGHT:
gravity = "SouthEast";
break;
case TOP_LEFT:
gravity = "NorthWest";
break;
case TOP_RIGHT:
gravity = "NorthEast";
break;
case TOP_CENTER:
gravity = "North";
break;
case CENTER_LEFT:
gravity = "West";
break;
case CENTER_RIGHT:
gravity = "East";
break;
default:
throw new ImageException("Unknown gravity: " + fx.getGravity());
}
final CommandLine cmd = new CommandLine("convert");
cmd.addArgument("-verbose");
cmd.addArgument(originalFile.getPath());
cmd.addArgument("-gravity");
cmd.addArgument(gravity);
cmd.addArgument("-resize");
cmd.addArgument(fx.getWidth() + "x" + fx.getHeight() + "^");
cmd.addArgument("-extent");
cmd.addArgument(fx.getWidth() + "x" + fx.getHeight());
cmd.addArgument("-quality");
cmd.addArgument(String.valueOf((int)(quality * 100f)));
cmd.addArgument(styledFile.getPath());
log.debug("ResizeToFill {} to {}, {}x{} gravity={} quality={} progressive={} using: {}",
originalFile, styledFile, fx.getWidth(), fx.getHeight(),
gravity, quality, progressive, cmd );
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(new PumpStreamHandler(buffer));
final int executionResult = executor.execute(cmd);
log.info("{} returned {}: {}", cmd, executionResult, buffer);
} else if (transform instanceof ResizeToFit) {
final ResizeToFit fx = (ResizeToFit) transform;
Preconditions.checkArgument(fx.getWidth() != null || fx.getHeight() != null,
"For ResizeToFit, at least one of height or width must be specified");
final boolean progressive = fx.getWidth() != null ? fx.getWidth() >= 512 : fx.getHeight() >= 512;
final CommandLine cmd = new CommandLine("convert");
cmd.addArgument("-verbose");
cmd.addArgument(originalFile.getPath());
cmd.addArgument("-resize");
final String widthStr = fx.getWidth() != null ? fx.getWidth().toString() : "";
final String heightStr = fx.getHeight() != null ? fx.getHeight().toString() : "";
final String onlyShrinkLargerFlag = fx.getOnlyShrinkLarger() ? ">" : "";
cmd.addArgument(widthStr + "x" + heightStr + onlyShrinkLargerFlag);
cmd.addArgument("-quality");
cmd.addArgument(String.valueOf((int)(quality * 100f)));
cmd.addArgument(styledFile.getPath());
log.debug("ResizeToFit {} to {}, {}x{} onlyShrinkLarger={} quality={} progressive={} using: {}",
originalFile, styledFile, fx.getWidth(), fx.getHeight(), fx.getOnlyShrinkLarger(),
quality, progressive, cmd );
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(new PumpStreamHandler(buffer));
final int executionResult = executor.execute(cmd);
log.info("{} returned {}: {}", cmd, executionResult, buffer);
} else {
throw new ImageException("Unsupported transform: " + transform);
}
return styledFile;
} catch (final Exception e) {
throw new ImageException("Error resizing " + imageId + " to " + dest.getStyleCode() + ", destination: " + styledFile, e);
}
}
});
final ListenableFuture<UploadedImage> styledImageFuture = Futures.transform(styledFileFuture, new AsyncFunction<File, UploadedImage>() {
@Override
public ListenableFuture<UploadedImage> apply(File styledFile)
throws Exception {
// Upload the styled image
// final URI styledDavUri = getImageDavUri(imageId, style.getName());
// upload directly for efficiency
// TODO: not hardcode styled content type and extension
final String styledContentType = "image/jpeg";
final String styledExtension = "jpg";
log.debug("Uploading {} {} using {} from {} ({} bytes)",
dest.getStyleCode(), imageId, destination.getClass().getName(),
styledFile, styledFile.length());
final ListenableFuture<UploadedImage> styledUploadFuture = destination.upload(namespace, imageId, dest.getStyleCode(),
dest.getStyleVariant(), styledExtension, styledFile, styledContentType);
return styledUploadFuture;
}
});
final ListenableFuture<UploadedImage> transformedFuture = Futures.transform(styledImageFuture, new Function<UploadedImage, UploadedImage>() {
@Override @Nullable
public UploadedImage apply(@Nullable UploadedImage styledUpload) {
final File styledFile = Futures.getUnchecked(styledFileFuture);
try {
final Dimension styledDim = ImageUtils.getDimension(styledFile);
final int width = (int) styledDim.getWidth();
final int height = (int) styledDim.getHeight();
log.debug("Dimensions of {} is {}x{}", styledFile, width, height);
final String styledOriginUri = styledUpload.getOriginUri();
final String styledCdnUri = styledUpload.getUri();
log.info("Uploaded {} {} as {}/{} from {} ({} bytes)", dest.getStyleCode(), imageId, styledOriginUri, styledCdnUri,
styledFile, styledFile.length());
// final StyledImage styled = new StyledImage(
// style.getName(), style.getCode(), URI.create(styledPublicUri), styledContentType,
// (int)styledFile.length(), width, height);
// return styled;
final UploadedImage uploadedImage = ImageFactory.eINSTANCE.createUploadedImage();
uploadedImage.setStyleCode(dest.getStyleCode());
uploadedImage.setStyleVariant(dest.getStyleVariant());
uploadedImage.setExtension(dest.getExtension());
uploadedImage.setOriginUri(styledOriginUri);
uploadedImage.setUri(styledCdnUri);
uploadedImage.setWidth(width);
uploadedImage.setHeight(height);
uploadedImage.setSize(styledFile.length());
return uploadedImage;
} finally {
log.trace("Deleting temporary {} {} styled image {}", dest.getStyleCode(), imageId, styledFile);
styledFile.delete();
log.debug("Deleted temporary {} {} styled image {}", dest.getStyleCode(), imageId, styledFile);
}
}
}, getExecutor());
return transformedFuture;
}
|
diff --git a/src/com/android/providers/calendar/CalendarDebug.java b/src/com/android/providers/calendar/CalendarDebug.java
index 7ce687b..fcc69f3 100644
--- a/src/com/android/providers/calendar/CalendarDebug.java
+++ b/src/com/android/providers/calendar/CalendarDebug.java
@@ -1,188 +1,188 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.calendar;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Calendar;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.view.Window;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Displays info about all the user's calendars, for debugging.
*
* The info is displayed as a ListActivity, where each entry has the calendar name
* followed by information about the calendar.
*/
public class CalendarDebug extends ListActivity {
private static final String[] CALENDARS_PROJECTION = new String[]{
Calendar.Calendars._ID,
Calendar.Calendars.DISPLAY_NAME,
};
private static final int INDEX_ID = 0;
private static final int INDEX_DISPLAY_NAME = 1;
private static final String[] EVENTS_PROJECTION = new String[]{
Calendar.Events._ID,
};
private static final String KEY_TITLE = "title";
private static final String KEY_TEXT = "text";
private ContentResolver mContentResolver;
private ListActivity mActivity;
/**
* Task to fetch info from the database and display as a ListActivity.
*/
private class FetchInfoTask extends AsyncTask<Void, Void, List<Map<String, String>>> {
/**
* Starts spinner while task is running.
*
* @see #onPostExecute
* @see #doInBackground
*/
@Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
/**
* Fetches debugging info from the database
* @param params Void
* @return a Map for each calendar
*/
protected List<Map<String, String>> doInBackground(Void... params) {
Cursor cursor = null;
// items is the list of items to display in the list.
List<Map<String, String>> items = new ArrayList<Map<String, String>>();
try {
cursor = mContentResolver.query(Calendar.Calendars.CONTENT_URI,
CALENDARS_PROJECTION,
null, null /* selectionArgs */,
Calendar.Calendars.DEFAULT_SORT_ORDER);
if (cursor == null) {
addItem(items, mActivity.getString(R.string.calendar_info_error), "");
} else {
while (cursor.moveToNext()) {
// Process each calendar
int id = cursor.getInt(INDEX_ID);
int eventCount = -1;
int dirtyCount = -1;
String displayName = cursor.getString(INDEX_DISPLAY_NAME);
// Compute number of events in the calendar
String where = Calendar.EventsColumns.CALENDAR_ID + "=" + id;
Cursor eventCursor = Calendar.Events.query(mContentResolver,
EVENTS_PROJECTION, where, null);
try {
eventCount = eventCursor.getCount();
} finally {
eventCursor.close();
}
// Compute number of dirty events in the calendar
String dirtyWhere = Calendar.EventsColumns.CALENDAR_ID + "=" + id
- + " AND Events." + Calendar.Events._SYNC_DIRTY + "=1";
+ + " AND " + Calendar.Events._SYNC_DIRTY + "=1";
Cursor dirtyCursor = Calendar.Events.query(mContentResolver,
EVENTS_PROJECTION, dirtyWhere, null);
try {
dirtyCount = dirtyCursor.getCount();
} finally {
dirtyCursor.close();
}
// Format the output
String text;
if (dirtyCount == 0) {
text = mActivity.getString(R.string.calendar_info_events,
eventCount);
} else {
text = mActivity.getString(R.string.calendar_info_events_dirty,
eventCount, dirtyCount);
}
addItem(items, displayName, text);
}
}
} catch (Exception e) {
// Want to catch all exceptions. The point of this code is to debug
// when something bad is happening.
addItem(items, mActivity.getString(R.string.calendar_info_error), e.toString());
} finally {
if (cursor != null) {
cursor.close();
}
}
if (items.size() == 0) {
addItem(items, mActivity.getString(R.string.calendar_info_no_calendars), "");
}
return items;
}
/**
* Runs on the UI thread to display the debugging info.
*
* @param items The info items to display.
* @see #onPreExecute
* @see #doInBackground
*/
@Override
protected void onPostExecute(List<Map<String, String>> items) {
setProgressBarIndeterminateVisibility(false);
ListAdapter adapter = new SimpleAdapter(mActivity, items,
android.R.layout.simple_list_item_2, new String[]{KEY_TITLE, KEY_TEXT},
new int[]{android.R.id.text1, android.R.id.text2});
// Bind to our new adapter.
setListAdapter(adapter);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
mActivity = this;
mContentResolver = getContentResolver();
getListView(); // Instantiate, for spinner
new FetchInfoTask().execute();
}
/**
* Adds an item to the item map
* @param items The item map to update
* @param title Title of the item
* @param text Text of the item
*/
protected void addItem(List<Map<String, String>> items, String title, String text) {
Map<String, String> itemMap = new HashMap<String, String>();
itemMap.put(KEY_TITLE, title);
itemMap.put(KEY_TEXT, text);
items.add(itemMap);
}
}
| true | true | protected List<Map<String, String>> doInBackground(Void... params) {
Cursor cursor = null;
// items is the list of items to display in the list.
List<Map<String, String>> items = new ArrayList<Map<String, String>>();
try {
cursor = mContentResolver.query(Calendar.Calendars.CONTENT_URI,
CALENDARS_PROJECTION,
null, null /* selectionArgs */,
Calendar.Calendars.DEFAULT_SORT_ORDER);
if (cursor == null) {
addItem(items, mActivity.getString(R.string.calendar_info_error), "");
} else {
while (cursor.moveToNext()) {
// Process each calendar
int id = cursor.getInt(INDEX_ID);
int eventCount = -1;
int dirtyCount = -1;
String displayName = cursor.getString(INDEX_DISPLAY_NAME);
// Compute number of events in the calendar
String where = Calendar.EventsColumns.CALENDAR_ID + "=" + id;
Cursor eventCursor = Calendar.Events.query(mContentResolver,
EVENTS_PROJECTION, where, null);
try {
eventCount = eventCursor.getCount();
} finally {
eventCursor.close();
}
// Compute number of dirty events in the calendar
String dirtyWhere = Calendar.EventsColumns.CALENDAR_ID + "=" + id
+ " AND Events." + Calendar.Events._SYNC_DIRTY + "=1";
Cursor dirtyCursor = Calendar.Events.query(mContentResolver,
EVENTS_PROJECTION, dirtyWhere, null);
try {
dirtyCount = dirtyCursor.getCount();
} finally {
dirtyCursor.close();
}
// Format the output
String text;
if (dirtyCount == 0) {
text = mActivity.getString(R.string.calendar_info_events,
eventCount);
} else {
text = mActivity.getString(R.string.calendar_info_events_dirty,
eventCount, dirtyCount);
}
addItem(items, displayName, text);
}
}
} catch (Exception e) {
// Want to catch all exceptions. The point of this code is to debug
// when something bad is happening.
addItem(items, mActivity.getString(R.string.calendar_info_error), e.toString());
} finally {
if (cursor != null) {
cursor.close();
}
}
if (items.size() == 0) {
addItem(items, mActivity.getString(R.string.calendar_info_no_calendars), "");
}
return items;
}
| protected List<Map<String, String>> doInBackground(Void... params) {
Cursor cursor = null;
// items is the list of items to display in the list.
List<Map<String, String>> items = new ArrayList<Map<String, String>>();
try {
cursor = mContentResolver.query(Calendar.Calendars.CONTENT_URI,
CALENDARS_PROJECTION,
null, null /* selectionArgs */,
Calendar.Calendars.DEFAULT_SORT_ORDER);
if (cursor == null) {
addItem(items, mActivity.getString(R.string.calendar_info_error), "");
} else {
while (cursor.moveToNext()) {
// Process each calendar
int id = cursor.getInt(INDEX_ID);
int eventCount = -1;
int dirtyCount = -1;
String displayName = cursor.getString(INDEX_DISPLAY_NAME);
// Compute number of events in the calendar
String where = Calendar.EventsColumns.CALENDAR_ID + "=" + id;
Cursor eventCursor = Calendar.Events.query(mContentResolver,
EVENTS_PROJECTION, where, null);
try {
eventCount = eventCursor.getCount();
} finally {
eventCursor.close();
}
// Compute number of dirty events in the calendar
String dirtyWhere = Calendar.EventsColumns.CALENDAR_ID + "=" + id
+ " AND " + Calendar.Events._SYNC_DIRTY + "=1";
Cursor dirtyCursor = Calendar.Events.query(mContentResolver,
EVENTS_PROJECTION, dirtyWhere, null);
try {
dirtyCount = dirtyCursor.getCount();
} finally {
dirtyCursor.close();
}
// Format the output
String text;
if (dirtyCount == 0) {
text = mActivity.getString(R.string.calendar_info_events,
eventCount);
} else {
text = mActivity.getString(R.string.calendar_info_events_dirty,
eventCount, dirtyCount);
}
addItem(items, displayName, text);
}
}
} catch (Exception e) {
// Want to catch all exceptions. The point of this code is to debug
// when something bad is happening.
addItem(items, mActivity.getString(R.string.calendar_info_error), e.toString());
} finally {
if (cursor != null) {
cursor.close();
}
}
if (items.size() == 0) {
addItem(items, mActivity.getString(R.string.calendar_info_no_calendars), "");
}
return items;
}
|
diff --git a/src/java/fedora/server/storage/translation/METSLikeDODeserializer.java b/src/java/fedora/server/storage/translation/METSLikeDODeserializer.java
index 9c9b97611..4be6ef76e 100755
--- a/src/java/fedora/server/storage/translation/METSLikeDODeserializer.java
+++ b/src/java/fedora/server/storage/translation/METSLikeDODeserializer.java
@@ -1,1276 +1,1276 @@
/* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://www.fedora.info/license/).
*/
package fedora.server.storage.translation;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
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 javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.log4j.Logger;
import fedora.server.errors.ObjectIntegrityException;
import fedora.server.errors.RepositoryConfigurationException;
import fedora.server.errors.StreamIOException;
import fedora.server.errors.ValidationException;
import fedora.server.storage.types.AuditRecord;
import fedora.server.storage.types.DigitalObject;
import fedora.server.storage.types.Datastream;
import fedora.server.storage.types.DatastreamManagedContent;
import fedora.server.storage.types.DatastreamReferencedContent;
import fedora.server.storage.types.DatastreamXMLMetadata;
//import fedora.server.storage.types.Disseminator;
import fedora.server.storage.types.DSBindingMap;
import fedora.server.storage.types.DSBinding;
import fedora.server.utilities.DateUtility;
import fedora.server.utilities.StreamUtility;
import fedora.server.validation.ValidationUtility;
/**
* Deserializes XML digital object encoded in accordance
* with the Fedora extension of the METS schema defined at:
* http://www.fedora.info/definitions/1/0/mets-fedora-ext.xsd.
*
* The METS XML is parsed using SAX and is instantiated into a Fedora
* digital object in memory (see fedora.server.types.DigitalObject).
*
* @author [email protected]
* @author [email protected]
* @version $Id$
*/
public class METSLikeDODeserializer
extends DefaultHandler
implements DODeserializer {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(
METSLikeDODeserializer.class.getName());
/** The namespace for METS */
private final static String M="http://www.loc.gov/METS/";
/** The namespace for XLINK */
private final static String XLINK_NAMESPACE="http://www.w3.org/TR/xlink";
// Mets says the above, but the spec at http://www.w3.org/TR/xlink/
// says it's http://www.w3.org/1999/xlink
/** Namespace declarations for RDF */
public static final String RDF_PREFIX="rdf";
public static final String RDF_NS="http://www.w3.org/1999/02/22-rdf-syntax-ns#";
public static final String RDFS_PREFIX="rdfs";
public static final String RDFS_NS="http://www.w3.org/2000/01/rdf-schema#";
public static final String RELS_PREFIX="fedora";
public static final String RELS_NS="info:fedora/fedora-system:def/relations-internal#";
/** Buffer to build RDF expression of ADMID and DMDID relationships **/
private StringBuffer m_relsBuffer;
private boolean hasRels=false;
/** Hashtables to record DMDID references */
private HashMap m_dsDMDIDs; // key=dsVersionID, value=ArrayList of dsID
/** Hashtables to record ADMID references */
private HashMap m_dsADMIDs; // key=dsVersionID, value=ArrayList of dsID
/** Hashtables to correlate audit record ids to datastreams */
private HashMap m_AuditIdToComponentId;
private SAXParser m_parser;
private String m_characterEncoding;
/** The object to deserialize to. */
private DigitalObject m_obj;
/** Namespace prefix-to-URI mapping info from SAX2 startPrefixMapping events. */
private HashMap<String, String> m_prefixMap;
private HashMap<String, String> m_localPrefixMap;
private ArrayList<String> m_prefixList;
/** Variables to parse into */
private boolean m_rootElementFound;
private String m_agentRole;
private String m_dsId;
private String m_dsVersId;
private Date m_dsCreateDate;
private String m_dissemId;
private String m_dissemState;
private String m_dsState;
private String m_dsInfoType;
private String m_dsOtherInfoType;
private String m_dsLabel;
private int m_dsMDClass;
private long m_dsSize;
private URL m_dsLocationURL;
private String m_dsLocation;
private String m_dsLocationType;
private String m_dsMimeType;
private String m_dsControlGrp;
private boolean m_dsVersionable;
private String m_dsFormatURI;
private String[] m_dsAltIDs;
private String m_dsChecksum;
private String m_dsChecksumType;
private StringBuffer m_dsXMLBuffer;
// are we reading binary in an FContent element? (base64-encoded)
private boolean m_readingContent; // indicates reading element content
private boolean m_readingBinaryContent; // indicates reading binary element content
private File m_binaryContentTempFile;
private StringBuffer m_elementContent; // single element
/** While parsing, are we inside XML metadata? */
private boolean m_inXMLMetadata;
/**
* Used to differentiate between a metadata section in this object
* and a metadata section in an inline XML datastream that happens
* to be a METS document.
*/
private int m_xmlDataLevel;
/** String buffer for audit element contents */
private StringBuffer m_auditBuffer;
private String m_auditProcessType;
private String m_auditAction;
private String m_auditComponentID;
private String m_auditResponsibility;
private String m_auditDate;
private String m_auditJustification;
/** Hashmap for holding disseminators during parsing, keyed
* by structMapId */
private HashMap m_dissems;
// /**
// * Currently-being-initialized disseminator, during structmap parsing.
// */
// private Disseminator m_diss;
/**
* Whether, while in structmap, we've already seen a div
*/
private boolean m_indiv;
/** The structMapId of the dissem currently being parsed. */
private String m_structId;
/**
* For non-inline datastreams, never query the server to get values
* for Content-length and Content-type
*/
public static int QUERY_NEVER=0;
/**
* For non-inline datastreams, conditionally query the server to get values
* for Content-length and Content-type (if either are undefined).
*/
public static int QUERY_IF_UNDEFINED=1;
/**
* For non-inline datastreams, always query the server to get values
* for Content-length and Content-type.
*/
public static int QUERY_ALWAYS=2;
private int m_queryBehavior;
/** The translation context for deserialization */
private int m_transContext;
public METSLikeDODeserializer()
throws FactoryConfigurationError, ParserConfigurationException,
SAXException, UnsupportedEncodingException {
this("UTF-8", false, QUERY_NEVER);
}
/**
* Initializes by setting up a parser that doesn't validate and never
* queries the server for values of DSSize and DSMIME.
*/
public METSLikeDODeserializer(String characterEncoding)
throws FactoryConfigurationError, ParserConfigurationException,
SAXException, UnsupportedEncodingException {
this(characterEncoding, false, QUERY_NEVER);
}
/**
* Initializes by setting up a parser that validates only if validate=true.
* <p></p>
* The character encoding of the XML is auto-determined by SAX, but
* we need it for when we set the byte[] in DatastreamXMLMetadata, so
* we effectively, we need to also specify the encoding of the datastreams.
* this could be different than how the digital object xml was encoded,
* and this class won't care. However, the caller should keep track
* of the byte[] encoding if it plans on doing any translation of
* that to characters (such as in xml serialization)
*/
public METSLikeDODeserializer(String characterEncoding, boolean validate,
int queryBehavior)
throws FactoryConfigurationError, ParserConfigurationException,
SAXException, UnsupportedEncodingException {
m_queryBehavior=queryBehavior;
// ensure the desired encoding is supported before starting
// unsuppenc will be thrown if not
m_characterEncoding=characterEncoding;
StringBuffer buf=new StringBuffer();
buf.append("test");
byte[] temp=buf.toString().getBytes(m_characterEncoding);
// then init sax
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(validate);
spf.setNamespaceAware(true);
m_parser=spf.newSAXParser();
}
public DODeserializer getInstance()
throws RepositoryConfigurationException {
try {
return (DODeserializer) new METSLikeDODeserializer("UTF-8", false, QUERY_NEVER);
} catch (Exception e) {
throw new RepositoryConfigurationException("Error trying to get a "
+ "new METSLikeDODeserializer instance: " + e.getClass().getName()
+ ": " + e.getMessage());
}
}
public void deserialize(InputStream in, DigitalObject obj, String encoding, int transContext)
throws ObjectIntegrityException, StreamIOException, UnsupportedEncodingException {
LOG.debug("Deserializing METS (Fedora extension)...");
m_obj=obj;
m_transContext=transContext;
initialize();
try {
m_parser.parse(in, this);
} catch (IOException ioe) {
throw new StreamIOException("Low-level stream IO problem occurred "
+ "while SAX parsing this object.");
} catch (SAXException se) {
throw new ObjectIntegrityException("METS stream was bad : " + se.getMessage());
}
if (!m_rootElementFound) {
throw new ObjectIntegrityException("METS root element not found :"
+ " Must have 'mets' element in namespace " + M + " as root element.");
}
m_obj.setNamespaceMapping(new HashMap());
// POST-PROCESSING...
// convert audit records to contain component ids
convertAudits();
// preserve ADMID and DMDID relationships in a RELS-INT
// datastream, if one does not already exist.
createRelsInt();
// // DISSEMINATORS... put disseminators in the instantiated digital object
// Iterator dissemIter=m_dissems.values().iterator();
// while (dissemIter.hasNext()) {
// Disseminator diss=(Disseminator) dissemIter.next();
// m_obj.disseminators(diss.dissID).add(diss);
// }
}
public void startPrefixMapping(String prefix, String uri) {
// Keep the prefix map up-to-date throughout the entire parse,
// and maintain a list of newly mapped prefixes on a per-element basis.
m_prefixMap.put(prefix, uri);
if (m_inXMLMetadata) {
m_localPrefixMap.put(prefix, uri);
m_prefixList.add(prefix);
}
}
public void endPrefixMapping(String prefix) {
m_prefixMap.remove(prefix);
if (m_inXMLMetadata) {
m_localPrefixMap.remove(prefix);
}
}
public void startElement(String uri, String localName, String qName,
Attributes a) throws SAXException {
if (uri.equals(M) && !m_inXMLMetadata) {
// a new mets element is starting
if (localName.equals("mets")) {
m_rootElementFound=true;
m_obj.setPid(grab(a, M, "OBJID"));
m_obj.setLabel(grab(a, M, "LABEL"));
m_obj.setContentModelId(grab(a, M, "PROFILE"));
String objType=grab(a, M, "TYPE");
if (objType==null || objType.equals("")) { objType="FedoraObject"; }
if (objType.indexOf("FedoraBDefObject")!= -1)
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_BDEF_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraBMechObject"))
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraCModelObject"))
{
- m_obj.addFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
+ m_obj.addFedoraObjectType(DigitalObject.FEDORA_CONTENT_MODEL_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraObject"))
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_OBJECT);
}
} else if (localName.equals("metsHdr")) {
m_obj.setCreateDate(DateUtility.convertStringToDate(
grab(a, M, "CREATEDATE")));
m_obj.setLastModDate(DateUtility.convertStringToDate(
grab(a, M, "LASTMODDATE")));
m_obj.setState(grab(a, M, "RECORDSTATUS"));
} else if (localName.equals("agent")) {
m_agentRole = grab(a, M, "ROLE");
} else if (localName.equals("name") && m_agentRole.equals("IPOWNER")) {
m_readingContent=true;
m_elementContent = new StringBuffer();
} else if (localName.equals("amdSec")) {
m_dsId=grab(a, M, "ID");
m_dsState=grab(a, M, "STATUS");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
} else if (localName.equals("dmdSecFedora")) {
m_dsId=grab(a, M, "ID");
m_dsState=grab(a, M, "STATUS");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
} else if (localName.equals("techMD") || localName.equals("descMD")
|| localName.equals("sourceMD")
|| localName.equals("rightsMD")
|| localName.equals("digiprovMD")) {
m_dsVersId=grab(a, M, "ID");
if (localName.equals("techMD")) {
m_dsMDClass=DatastreamXMLMetadata.TECHNICAL;
}
if (localName.equals("sourceMD")) {
m_dsMDClass=DatastreamXMLMetadata.SOURCE;
}
if (localName.equals("rightsMD")) {
m_dsMDClass=DatastreamXMLMetadata.RIGHTS;
}
if (localName.equals("digiprovMD")) {
m_dsMDClass=DatastreamXMLMetadata.DIGIPROV;
}
if (localName.equals("descMD")) {
m_dsMDClass=DatastreamXMLMetadata.DESCRIPTIVE;
}
String dateString=grab(a, M, "CREATED");
if (dateString!=null && !dateString.equals("")){
m_dsCreateDate=
DateUtility.convertStringToDate(dateString);
}
} else if (localName.equals("mdWrap")) {
m_dsInfoType=grab(a, M, "MDTYPE");
m_dsOtherInfoType=grab(a, M, "OTHERMDTYPE");
m_dsLabel=grab(a, M, "LABEL");
m_dsMimeType=grab(a, M, "MIMETYPE");
m_dsFormatURI=grab(a, M, "FORMAT_URI");
String altIDs= grab(a, M, "ALT_IDS");
if (altIDs.length() == 0) {
m_dsAltIDs = new String[0];
} else {
m_dsAltIDs = altIDs.split(" ");
}
m_dsChecksum = grab(a, M, "CHECKSUM");
m_dsChecksumType = grab(a, M, "CHECKSUMTYPE");
} else if (localName.equals("xmlData")) {
m_dsXMLBuffer=new StringBuffer();
m_xmlDataLevel=0;
m_inXMLMetadata=true;
} else if (localName.equals("fileGrp")) {
m_dsId=grab(a, M, "ID");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
// reset the values for the next file
m_dsVersId="";
m_dsCreateDate=null;
m_dsMimeType="";
m_dsControlGrp="";
m_dsFormatURI="";
m_dsAltIDs=new String[0];
m_dsState=grab(a,M,"STATUS");
m_dsSize=-1;
m_dsChecksum="";
m_dsChecksumType="";
} else if (localName.equals("file")) {
m_dsVersId=grab(a, M, "ID");
String dateString=grab(a, M, "CREATED");
if (dateString!=null && !dateString.equals("")){
m_dsCreateDate=
DateUtility.convertStringToDate(dateString);
}
m_dsMimeType=grab(a,M,"MIMETYPE");
m_dsControlGrp=grab(a,M,"OWNERID");
String ADMID=grab(a,M,"ADMID");
if ((ADMID!=null) && (!"".equals(ADMID))) {
ArrayList al=new ArrayList();
if (ADMID.indexOf(" ")!=-1) {
String[] admIds=ADMID.split(" ");
for (int idi=0; idi<admIds.length; idi++) {
al.add(admIds[idi]);
}
} else {
al.add(ADMID);
}
m_dsADMIDs.put(m_dsVersId, al);
}
String DMDID=grab(a,M,"DMDID");
if ((DMDID!=null) && (!"".equals(DMDID))) {
ArrayList<String> al=new ArrayList<String>();
if (DMDID.indexOf(" ")!=-1) {
String[] dmdIds=DMDID.split(" ");
for (int idi=0; idi<dmdIds.length; idi++) {
al.add(dmdIds[idi]);
}
} else {
al.add(DMDID);
}
m_dsDMDIDs.put(m_dsVersId, al);
}
String sizeString=grab(a,M,"SIZE");
if (sizeString!=null && !sizeString.equals("")) {
try {
m_dsSize=Long.parseLong(sizeString);
} catch (NumberFormatException nfe) {
throw new SAXException("If specified, a datastream's "
+ "SIZE attribute must be an xsd:long.");
}
}
String formatURI=grab(a, M, "FORMAT_URI");
if (formatURI!=null && !formatURI.equals("")) {
m_dsFormatURI=formatURI;
}
String altIDs=grab(a, M, "ALT_IDS");
if (altIDs.length() == 0) {
m_dsAltIDs = new String[0];
} else {
m_dsAltIDs = altIDs.split(" ");
}
m_dsChecksum = grab(a, M, "CHECKSUM");
m_dsChecksumType = grab(a, M, "CHECKSUMTYPE");
// inside a "file" element, it's either going to be
// FLocat (a reference) or FContent (inline)
} else if (localName.equals("FLocat")) {
m_dsLabel=grab(a,XLINK_NAMESPACE,"title");
String dsLocation=grab(a,XLINK_NAMESPACE,"href");
if (dsLocation==null || dsLocation.equals("")) {
throw new SAXException("xlink:href must be specified in FLocat element");
}
if (m_dsControlGrp.equalsIgnoreCase("E") ||
m_dsControlGrp.equalsIgnoreCase("R") ) {
// URL FORMAT VALIDATION for dsLocation:
// make sure we have a properly formed URL (must have protocol)
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
// system will set dsLocationType for E and R datastreams...
m_dsLocationType="URL";
m_dsInfoType="DATA";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamReferencedContent());
} else if (m_dsControlGrp.equalsIgnoreCase("M")) {
// URL FORMAT VALIDATION for dsLocation:
// For Managed Content the URL is only checked when we are parsing a
// a NEW ingest file because the URL is replaced with an internal identifier
// once the repository has sucked in the content for storage.
if (m_obj.isNew()) {
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
}
m_dsLocationType="INTERNAL_ID";
m_dsInfoType="DATA";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamManagedContent());
}
} else if (localName.equals("FContent")) {
// In the version of METS that Fedora supports, the FContent element
// contains base64 encoded data.
m_readingContent=true;
m_elementContent = new StringBuffer();
if (m_dsControlGrp.equalsIgnoreCase("M"))
{
m_readingBinaryContent=true;
m_binaryContentTempFile = null;
try {
m_binaryContentTempFile = File.createTempFile("binary-datastream", null);
}
catch (IOException ioe)
{
throw new SAXException(new StreamIOException("Unable to create temporary file for binary content"));
}
}
}
// else if (localName.equals("structMap"))
// {
// // this is a component of a disseminator. here we assume the rest
// // of the disseminator's information will be seen later, so we
// // construct a new Disseminator object to hold the structMap...
// // and later, the other info
// //
// // Building up a global map of Disseminators, m_dissems,
// // keyed by bindingmap ID.
// //
// if (grab(a,M,"TYPE").equals("fedora:dsBindingMap"))
// {
// String bmId=grab(a,M,"ID");
// if ( (bmId==null) || (bmId.equals("")) )
// {
// throw new SAXException("structMap with TYPE fedora:dsBindingMap must specify a non-empty ID attribute.");
// }
// else
// {
// Disseminator diss=new Disseminator();
// diss.dsBindMapID=bmId;
// m_dissems.put(bmId,diss);
// m_diss=diss;
// m_diss.dsBindMap=new DSBindingMap();
// m_diss.dsBindMap.dsBindMapID=bmId;
// m_indiv=false; // flag that we're not looking at inner part yet
// }
// } else {
// throw new SAXException("StructMap must have TYPE fedora:dsBindingMap");
// }
// }
// else if (localName.equals("div"))
// {
// if (m_indiv) {
// // inner part of structmap
// DSBinding binding=new DSBinding();
// if (m_diss.dsBindMap.dsBindings==null) {
// // none yet.. create array of size one
// DSBinding[] bindings=new DSBinding[1];
// m_diss.dsBindMap.dsBindings=bindings;
// m_diss.dsBindMap.dsBindings[0]=binding;
// } else {
// // need to expand the array size by one,
// // and do an array copy.
// int curSize=m_diss.dsBindMap.dsBindings.length;
// DSBinding[] oldArray=m_diss.dsBindMap.dsBindings;
// DSBinding[] newArray=new DSBinding[curSize+1];
// for (int i=0; i<curSize; i++) {
// newArray[i]=oldArray[i];
// }
// newArray[curSize]=binding;
// m_diss.dsBindMap.dsBindings=newArray;
// }
// // now populate 'binding' values...we'll have
// // everything at this point except datastreamID...
// // that comes as a child: <fptr FILEID="DS2"/>
// binding.bindKeyName=grab(a,M,"TYPE");
// binding.bindLabel=grab(a,M,"LABEL");
// binding.seqNo=grab(a,M,"ORDER");
// } else {
// m_indiv=true;
// // first (outer div) part of structmap
// m_diss.dsBindMap.dsBindMechanismPID=grab(a,M,"TYPE");
// m_diss.dsBindMap.dsBindMapLabel=grab(a,M,"LABEL");
// }
// }
// else if (localName.equals("fptr"))
// {
// // assume we're inside the inner div... that's the
// // only place the fptr element is valid.
// DSBinding binding=m_diss.dsBindMap.dsBindings[
// m_diss.dsBindMap.dsBindings.length-1];
// binding.datastreamID=grab(a,M,"FILEID");
// }
else if (localName.equals("behaviorSec"))
{
// looks like we're in a disseminator... it should be in the
// hash by now because we've already gone through structmaps
// ...keyed by structmap id... remember the id (group id)
// so we can put it in when parsing serviceBinding
m_dissemId=grab(a,M,"ID");
m_dissemState=grab(a,M,"STATUS");
}
// else if (localName.equals("serviceBinding"))
// {
// // remember the structId so we can grab the right dissem
// // when parsing children
// m_structId=grab(a,M,"STRUCTID");
// // grab the disseminator associated with the provided structId
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// // plug known items in..
// dissem.dissID=m_dissemId;
// dissem.dissState=m_dissemState;
// // then grab the new stuff for the dissem for this element, and
// // put it in.
// dissem.dissVersionID=grab(a,M,"ID");
// dissem.bDefID=grab(a,M,"BTYPE");
// dissem.dissCreateDT=DateUtility.convertStringToDate(grab(a,M,"CREATED"));
// dissem.dissLabel=grab(a,M,"LABEL");
// }
// else if (localName.equals("interfaceMD"))
// {
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// // already have the id from containing element, just need label
// //dissem.bDefLabel=grab(a,M,"LABEL");
// }
// else if (localName.equals("serviceBindMD"))
// {
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// //dissem.bMechLabel=grab(a,M,"LABEL");
// dissem.bMechID=grab(a,XLINK_NAMESPACE,"href");
// }
} else {
if (m_inXMLMetadata) {
// must be in xmlData... just output it, remembering the number
// of METS:xmlData elements we see
appendElementStart(uri, localName, qName, a, m_dsXMLBuffer);
// METS INSIDE METS! we have an inline XML datastream
// that is itself METS. We do not want to parse this!
if (uri.equals(M) && localName.equals("xmlData")) {
m_xmlDataLevel++;
}
// remember this stuff... (we don't have to look at level
// because the audit schema doesn't allow for xml elements inside
// these, so they're never set incorrectly)
// signaling that we're interested in sending char data to
// the m_auditBuffer by making it non-null, and getting
// ready to accept data by allocating a new StringBuffer
if (m_dsId.equals("FEDORA-AUDITTRAIL") || m_dsId.equals("AUDIT")) {
if (localName.equals("process")) {
m_auditProcessType=grab(a, uri, "type");
} else if ( (localName.equals("action"))
|| (localName.equals("componentID"))
|| (localName.equals("responsibility"))
|| (localName.equals("date"))
|| (localName.equals("justification")) ) {
m_auditBuffer=new StringBuffer();
}
}
} else {
// ignore all else
}
}
}
private void appendElementStart(String uri,
String localName,
String qName,
Attributes a,
StringBuffer out) {
out.append("<" + qName);
// add the current qName's namespace to m_localPrefixMap
// and m_prefixList if it's not already in m_localPrefixMap
// This ensures that all namespaces used in inline XML are declared within,
// since it's supposed to be a standalone chunk.
String[] parts = qName.split(":");
if (parts.length == 2) {
String nsuri = (String) m_localPrefixMap.get(parts[0]);
if (nsuri == null) {
m_localPrefixMap.put(parts[0], parts[1]);
m_prefixList.add(parts[0]);
}
}
// do we have any newly-mapped namespaces?
while (m_prefixList.size() > 0) {
String prefix = (String) m_prefixList.remove(0);
out.append(" xmlns");
if (prefix.length() > 0) {
out.append(":");
}
out.append(prefix + "=\"" + StreamUtility.enc((String) m_prefixMap.get(prefix)) + "\"");
}
for (int i = 0; i < a.getLength(); i++) {
out.append(" " + a.getQName(i) + "=\"" + StreamUtility.enc(a.getValue(i)) + "\"");
}
out.append(">");
}
public void characters(char[] ch, int start, int length) {
if (m_inXMLMetadata) {
if (m_auditBuffer!=null) {
m_auditBuffer.append(ch, start, length);
} else {
// since this data is encoded straight back to xml,
// we need to make sure special characters &, <, >, ", and '
// are re-converted to the xml-acceptable equivalents.
StreamUtility.enc(ch, start, length, m_dsXMLBuffer);
}
} else if (m_readingContent) {
// read normal element content into a string buffer
if (m_elementContent !=null)
{
m_elementContent.append(ch, start, length);
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
// first, deal with the situation when we are processing a block of inline XML
if (m_inXMLMetadata)
{
if (uri.equals(M) && localName.equals("xmlData")
&& m_xmlDataLevel==0) {
// finished all xml metadata for this datastream
if (m_dsId.equals("FEDORA-AUDITTRAIL") || m_dsId.equals("AUDIT")) {
// we've been looking at an audit trail... set audit record
AuditRecord a=new AuditRecord();
// In METS each audit record is in its own <digiprovMD>
// element within an <amdSec>. So, pick up the XML ID
// of the <digiprovMD> element for the audit record id.
// This amdSec is treated like a datastream, and each
// digiprovMD is a version, so id was parsed into dsVersId.
a.id=m_dsVersId;
a.processType=m_auditProcessType;
a.action=m_auditAction;
a.componentID=m_auditComponentID;
a.responsibility=m_auditResponsibility;
a.date=DateUtility.convertStringToDate(m_auditDate);
a.justification=m_auditJustification;
m_obj.getAuditRecords().add(a);
m_inXMLMetadata=false; // other stuff is re-initted upon
// startElement for next xml metadata
// element
} else {
// Create the right kind of datastream and add to the object
DatastreamXMLMetadata ds=new DatastreamXMLMetadata();
instantiateXMLDatastream(ds);
m_inXMLMetadata=false;
m_localPrefixMap.clear();
}
} else {
// finished an element within inline xml metadata
m_dsXMLBuffer.append("</" + qName + ">");
// make sure we know when to pay attention to METS again
if (uri.equals(M) && localName.equals("xmlData")) {
m_xmlDataLevel--;
}
if (m_dsId.equals("FEDORA-AUDITTRAIL") || m_dsId.equals("AUDIT")) {
if (localName.equals("action")) {
m_auditAction=m_auditBuffer.toString();
m_auditBuffer=null;
} else if (localName.equals("componentID")) {
m_auditComponentID=m_auditBuffer.toString();
m_auditBuffer=null;
} else if (localName.equals("responsibility")) {
m_auditResponsibility=m_auditBuffer.toString();
m_auditBuffer=null;
} else if (localName.equals("date")) {
m_auditDate=m_auditBuffer.toString();
m_auditBuffer=null;
} else if (localName.equals("justification")) {
m_auditJustification=m_auditBuffer.toString();
m_auditBuffer=null;
}
}
}
// ALL OTHER ELEMENT CASES: we are NOT processing a block of inline XML metadata
} else {
if (m_readingBinaryContent)
{
// In the version of METS Fedora uses, FContent assumes base64-encoded content
if (uri.equals(M) && localName.equals("FContent"))
{
if (m_binaryContentTempFile != null)
{
try {
FileOutputStream os = new FileOutputStream(m_binaryContentTempFile);
// remove all spaces and newlines, this might not be necessary.
String elementStr = m_elementContent.toString().replaceAll("\\s", "");
byte elementBytes[] = StreamUtility.decodeBase64(elementStr);
os.write(elementBytes);
os.close();
m_dsLocationType="INTERNAL_ID";
m_dsLocation="temp://"+m_binaryContentTempFile.getAbsolutePath();
instantiateDatastream(new DatastreamManagedContent());
}
catch (FileNotFoundException fnfe)
{
throw new SAXException(new StreamIOException("Unable to open temporary file created for binary content"));
}
catch (IOException fnfe)
{
throw new SAXException(new StreamIOException("Error writing to temporary file created for binary content"));
}
}
}
m_binaryContentTempFile = null;
m_readingBinaryContent=false;
m_elementContent = null;
// all other cases...
} else {
if (m_readingContent) {
// elements for which we were reading regular content
if (uri.equals(M) && localName.equals("name") && m_agentRole.equals("IPOWNER")) {
m_obj.setOwnerId(m_elementContent.toString());
} else if (uri.equals(M) && localName.equals("agent")) {
m_agentRole = null;
}
m_readingContent=false;
m_elementContent = null;
} else {
// no other processing requirements at this time
}
}
}
}
private void instantiateDatastream(Datastream ds) throws SAXException {
// set datastream variables with values grabbed from the SAX parse
ds.DatastreamID=m_dsId;
ds.DSVersionable=m_dsVersionable;
ds.DSFormatURI=m_dsFormatURI;
ds.DatastreamAltIDs=m_dsAltIDs;
ds.DSVersionID=m_dsVersId;
ds.DSLabel=m_dsLabel;
ds.DSCreateDT=m_dsCreateDate;
ds.DSMIME=m_dsMimeType;
ds.DSControlGrp=m_dsControlGrp;
ds.DSState=m_dsState;
ds.DSLocation=m_dsLocation;
ds.DSLocationType=m_dsLocationType;
ds.DSInfoType=m_dsInfoType;
ds.DSChecksumType=m_dsChecksumType;
LOG.debug("instantiate datastream: dsid = "+ m_dsId +
"checksumType = "+ m_dsChecksumType +
"checksum = "+ m_dsChecksum);
if (m_obj.isNew())
{
if (m_dsChecksum != null && !m_dsChecksum.equals("") && !m_dsChecksum.equals("none"))
{
String tmpChecksum = ds.getChecksum();
LOG.debug("checksum = "+ tmpChecksum);
if (!m_dsChecksum.equals(tmpChecksum))
{
throw new SAXException(new ValidationException("Checksum Mismatch: " + tmpChecksum));
}
}
ds.DSChecksumType=ds.getChecksumType();
}
else
{
ds.DSChecksum = m_dsChecksum;
}
// Normalize the dsLocation for the deserialization context
ds.DSLocation=
(DOTranslationUtility.normalizeDSLocationURLs(
m_obj.getPid(), ds, m_transContext)).DSLocation;
// LOOK! if the query behavior this deserializer instance was activated
// in the constructor, then we will obtain the datastreams's
// content stream to obtain its size and set the ds size attribute
// (done within the ds.getContentStream method implementation).
if (m_queryBehavior!=QUERY_NEVER) {
if ((m_queryBehavior==QUERY_ALWAYS)
|| (m_dsMimeType==null)
|| (m_dsMimeType.equals(""))
|| (m_dsSize==-1)) {
try {
InputStream in=ds.getContentStream();
} catch (StreamIOException e) {
throw new SAXException("Error getting datastream content"
+ " for setting ds size (ds.getContentStream)"
+ " during SAX parse.");
}
}
}
// FINALLY! add the datastream to the digital object instantiation
m_obj.addDatastreamVersion(ds, true);
}
private void instantiateXMLDatastream(DatastreamXMLMetadata ds) throws SAXException
{
// set the attrs common to all datastream versions
ds.DatastreamID=m_dsId;
ds.DSVersionable=m_dsVersionable;
ds.DSFormatURI=m_dsFormatURI;
ds.DatastreamAltIDs=m_dsAltIDs;
ds.DSVersionID=m_dsVersId;
ds.DSLabel=m_dsLabel;
ds.DSCreateDT=m_dsCreateDate;
if (m_dsMimeType==null || m_dsMimeType.equals("")) {
ds.DSMIME="text/xml";
} else {
ds.DSMIME=m_dsMimeType;
}
// set the attrs specific to datastream version
ds.DSControlGrp="X";
ds.DSState=m_dsState;
ds.DSLocation=m_obj.getPid() + "+" + m_dsId + "+" + m_dsVersId;
ds.DSLocationType=m_dsLocationType;
ds.DSInfoType=m_dsInfoType; // METS only
ds.DSMDClass=m_dsMDClass; // METS only
ds.DSChecksumType=m_dsChecksumType;
// now set the xml content stream itself...
try {
String xmlString = m_dsXMLBuffer.toString();
// Relative Repository URL processing...
// For selected inline XML datastreams look for relative repository URLs
// and make them absolute.
if ( m_obj.isFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT) &&
(m_dsId.equals("SERVICE-PROFILE") || m_dsId.equals("WSDL")) )
{
ds.xmlContent=
(DOTranslationUtility.normalizeInlineXML(
xmlString, m_transContext))
.getBytes(m_characterEncoding);
}
else
{
ds.xmlContent = xmlString.getBytes(m_characterEncoding);
}
//LOOK! this sets bytes, not characters. Do we want to set this?
ds.DSSize=ds.xmlContent.length;
} catch (Exception uee) {
LOG.debug("Error processing inline xml content in SAX parse: "
+ uee.getMessage());
}
LOG.debug("instantiate datastream: dsid = "+ m_dsId +
"checksumType = "+ m_dsChecksumType +
"checksum = "+ m_dsChecksum);
if (m_obj.isNew())
{
if (m_dsChecksum != null && !m_dsChecksum.equals("") && !m_dsChecksum.equals("none"))
{
String tmpChecksum = ds.getChecksum();
LOG.debug("checksum = "+ tmpChecksum);
if (!m_dsChecksum.equals(tmpChecksum))
{
throw new SAXException(new ValidationException("Checksum Mismatch: " + tmpChecksum));
}
}
ds.DSChecksumType=ds.getChecksumType();
}
else
{
ds.DSChecksum = m_dsChecksum;
}
// FINALLY! add the xml datastream to the digitalObject
m_obj.addDatastreamVersion(ds, true);
}
/**
* convertAudits: In Fedora 2.0 and beyond, we want self-standing audit
* records. Make sure audit records are converted to new format
* that contains a componentID to show what component in the object
* the audit record is about.
*/
private void convertAudits(){
// Only do this if ADMID values were found in the object.
if (m_dsADMIDs.size()>0){
// Look at datastreams to see if there are audit records for them.
// NOTE: we do not look at disseminators because in pre-2.0
// the disseminators did not point to their audit records as
// did the datastreams.
Iterator dsIdIter=m_obj.datastreamIdIterator();
while (dsIdIter.hasNext()) {
List datastreams=m_obj.datastreams((String) dsIdIter.next());
// The list is a set of versions of the same datastream...
for (int i=0; i<datastreams.size(); i++) {
Datastream ds=(Datastream) datastreams.get(i);
// ADMID processing...
// get list of ADMIDs that go with a datastream version
List admIdList=(List)m_dsADMIDs.get(ds.DSVersionID);
List cleanAdmIdList = new ArrayList();
if (admIdList!=null) {
Iterator admIdIter=admIdList.iterator();
while (admIdIter.hasNext()) {
String admId=(String) admIdIter.next();
// Detect ADMIDs that reference audit records
// vs. regular admin metadata. Drop audits from
// the list. We know we have an audit if the ADMID
// is not a regular datatream in the object.
List matchedDatastreams=m_obj.datastreams(admId);
if (matchedDatastreams.size()<=0) {
// Keep track of audit metadata correlated with the
// datastream version it's about (for later use).
m_AuditIdToComponentId.put(admId, ds.DSVersionID);
} else {
// Keep track of non-audit metadata in a new list.
cleanAdmIdList.add(admId);
}
}
}
if (cleanAdmIdList.size()<=0){
// we keep track of admin metadata references
// for each datastream, but we exclude the audit
// records from this list. If there are no
// non-audit metadata references, remove the
// datastream entry from the master hashmap.
m_dsADMIDs.remove(ds.DSVersionID);
} else {
// otherwise, update the master hashmap with the
// clean list of non-audit metadata
m_dsADMIDs.put(ds.DSVersionID, cleanAdmIdList);
}
}
}
// Now, put component ids on audit records. Pre-Fedora 2.0
// datastream versions pointed to their audit records.
Iterator iter=((ArrayList) m_obj.getAuditRecords()).iterator();
while (iter.hasNext()) {
AuditRecord au=(AuditRecord) iter.next();
if (au.componentID == null || au.componentID.equals("")) {
// Before Fedora 2.0 audit records were associated with
// datastream version ids. From now on, the datastream id
// will be posted as the component id in the audit record,
// and associations to particular datastream versions can
// be derived via the datastream version dates and the audit
// record dates.
String dsVersId = (String)m_AuditIdToComponentId.get(au.id);
if (dsVersId!=null && !dsVersId.equals(""))
{
au.componentID=dsVersId.substring(0, dsVersId.indexOf("."));
}
}
}
}
}
/**
* addRelsInt: Build an RDF relationship datastream to preserve
* DMDID and ADMID references in the digital object when METS
* is converted to FOXML (or other formats in the future).
* If there is no pre-existing RELS-INT, look for DMDID and ADMID
* attributes to create new RELS-INT datastream.
*/
private void createRelsInt(){
// create a new RELS-INT datastream only if one does not already exist.
List metsrels=m_obj.datastreams("RELS-INT");
if (metsrels.size()<=0) {
m_relsBuffer=new StringBuffer();
appendRDFStart(m_relsBuffer);
Iterator dsIds=m_obj.datastreamIdIterator();
while (dsIds.hasNext()) {
// initialize hash sets to keep a list of
// unique DMDIDs or ADMIDs at the datatream id level.
HashSet<String> uniqueDMDIDs = new HashSet<String>();
HashSet uniqueADMIDs = new HashSet();
// get list of datastream *versions*
List dsVersionList=m_obj.datastreams((String) dsIds.next());
for (int i=0; i<dsVersionList.size(); i++) {
Datastream dsVersion=(Datastream) dsVersionList.get(i);
// DMDID processing...
List dmdIdList=(List) m_dsDMDIDs.get(dsVersion.DSVersionID);
if (dmdIdList!=null) {
hasRels=true;
Iterator dmdIdIter=dmdIdList.iterator();
while (dmdIdIter.hasNext()) {
String dmdId=(String) dmdIdIter.next();
// APPEND TO RDF: record the DMDID relationship.
// Relationships will now be recorded at the
// datastream level, not the datastream version level.
// So, is the relationship existed on more than one
// datastream version, only write it once to the RDF.
if (!uniqueDMDIDs.contains(dmdId)){
appendRDFRel(m_relsBuffer, m_obj.getPid(), dsVersion.DatastreamID,
"hasDescMetadata", dmdId);
}
uniqueDMDIDs.add(dmdId);
}
}
// ADMID processing (already cleansed of audit refs)...
List cleanAdmIdList=(List) m_dsADMIDs.get(dsVersion.DSVersionID);
if (cleanAdmIdList!=null) {
hasRels=true;
Iterator admIdIter=cleanAdmIdList.iterator();
while (admIdIter.hasNext()) {
String admId=(String) admIdIter.next();
// APPEND TO RDF: record the ADMID relationship.
// Relationships will now be recorded at the
// datastream level, not the datastream version level.
// So, is the relationship existed on more than one
// datastream version, only write it once to the RDF.
if (!uniqueADMIDs.contains(admId)){
appendRDFRel(m_relsBuffer, m_obj.getPid(), dsVersion.DatastreamID,
"hasAdminMetadata", admId);
}
uniqueADMIDs.add(admId);
}
}
}
}
// APPEND RDF: finish up and add RDF as a system-generated datastream
if (hasRels) {
appendRDFEnd(m_relsBuffer);
setRDFAsDatastream(m_relsBuffer);
} else {
m_relsBuffer=null;
}
}
}
// Create a system-generated datastream from the RDF expression of the
// DMDID and ADMID relationships found in the METS file.
private void setRDFAsDatastream(StringBuffer buf) {
DatastreamXMLMetadata ds = new DatastreamXMLMetadata();
// set the attrs common to all datastream versions
ds.DatastreamID="RELS-INT";
ds.DSVersionable=false;
ds.DSFormatURI=m_dsFormatURI;
ds.DatastreamAltIDs=m_dsAltIDs;
ds.DSVersionID="RELS-INT.0";
ds.DSLabel="DO NOT EDIT: System-generated datastream to preserve METS DMDID/ADMID relationships.";
ds.DSCreateDT=new Date();
ds.DSMIME="text/xml";
// set the attrs specific to datastream version
ds.DSControlGrp="X";
ds.DSState="A";
ds.DSLocation=m_obj.getPid() + "+" + ds.DatastreamID + "+" + ds.DSVersionID;
ds.DSLocationType="INTERNAL_ID";
ds.DSInfoType="DATA";
ds.DSMDClass=DatastreamXMLMetadata.TECHNICAL;
// now set the xml content stream itself...
try {
ds.xmlContent=buf.toString().getBytes(m_characterEncoding);
ds.DSSize=ds.xmlContent.length;
} catch (UnsupportedEncodingException uee) {
LOG.error("Encoding error when creating RELS-INT datastream", uee);
}
// FINALLY! add the RDF and an inline xml datastream in the digital object
m_obj.datastreams(ds.DatastreamID).add(ds);
}
private StringBuffer appendRDFStart(StringBuffer buf) {
buf.append("<" + RDF_PREFIX + ":RDF"
+ " xmlns:" + RDF_PREFIX + "=\"" + RDF_NS + "\""
+ " xmlns:" + RDFS_PREFIX + "=\"" + RDFS_NS + "\""
+ " xmlns:" + RELS_PREFIX + "=\"" + RELS_NS + "\">\n");
return buf;
}
private StringBuffer appendRDFRel(StringBuffer buf, String pid,
String subjectNodeId, String relType, String objectNodeId) {
// RDF subject node
buf.append(" <" + RDF_PREFIX + ":Description "
+ RDF_PREFIX + ":about=\"" + "info:fedora/" + pid + "/" + subjectNodeId + "\">\n");
// RDF relationship property and object node
buf.append(" <" + RELS_PREFIX + ":" + relType + " "
+ RDF_PREFIX + ":resource=\"" + "info:fedora/" + pid + "/" + objectNodeId + "\"/>\n");
buf.append(" </" + RDF_PREFIX + ":Description" + ">\n");
return buf;
}
private StringBuffer appendRDFEnd(StringBuffer buf) {
buf.append("</" + RDF_PREFIX + ":RDF>\n");
return buf;
}
private static String grab(Attributes a, String namespace,
String elementName) {
String ret=a.getValue(namespace, elementName);
if (ret==null) {
ret=a.getValue(elementName);
}
// set null attribute value to empty string since it's
// generally helpful in the code to avoid null pointer exception
// when operations are performed on attributes values.
if (ret==null) {
ret="";
}
return ret;
}
private void initialize(){
//NOTE: variables that are commented out exist in FOXML but not METS
// temporary variables and state variables
m_rootElementFound=false;
//m_objPropertyName="";
//m_readingBinaryContent=false; // future
m_inXMLMetadata=false;
m_prefixMap = new HashMap<String, String>();
m_localPrefixMap = new HashMap();
m_prefixList = new ArrayList();
// temporary variables for processing datastreams
m_dsId="";
//m_dsURI=""; // FOXML only.
m_dsVersionable=true; // FOXML only.
m_dsVersId="";
m_dsCreateDate=null;
m_dsState="";
m_dsFormatURI="";
m_dsAltIDs=new String[0];
m_dsSize=-1;
m_dsLocationType="";
m_dsLocationURL=null;
m_dsLocation="";
m_dsMimeType="";
m_dsControlGrp="";
m_dsInfoType="";
m_dsOtherInfoType="";
m_dsMDClass=0;
m_dsLabel="";
m_dsXMLBuffer=null;
m_dsADMIDs=new HashMap();
m_dsDMDIDs=new HashMap();
m_dsChecksum="";
m_dsChecksumType="";
// temporary variables for processing disseminators
// m_diss=null;
m_dissems=new HashMap();
// temporary variables for processing audit records
m_auditBuffer=null;
m_auditComponentID="";
m_auditProcessType="";
m_auditAction="";
m_auditResponsibility="";
m_auditDate="";
m_auditJustification="";
m_AuditIdToComponentId=new HashMap();
m_relsBuffer=null;
}
}
| true | true | public void startElement(String uri, String localName, String qName,
Attributes a) throws SAXException {
if (uri.equals(M) && !m_inXMLMetadata) {
// a new mets element is starting
if (localName.equals("mets")) {
m_rootElementFound=true;
m_obj.setPid(grab(a, M, "OBJID"));
m_obj.setLabel(grab(a, M, "LABEL"));
m_obj.setContentModelId(grab(a, M, "PROFILE"));
String objType=grab(a, M, "TYPE");
if (objType==null || objType.equals("")) { objType="FedoraObject"; }
if (objType.indexOf("FedoraBDefObject")!= -1)
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_BDEF_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraBMechObject"))
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraCModelObject"))
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraObject"))
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_OBJECT);
}
} else if (localName.equals("metsHdr")) {
m_obj.setCreateDate(DateUtility.convertStringToDate(
grab(a, M, "CREATEDATE")));
m_obj.setLastModDate(DateUtility.convertStringToDate(
grab(a, M, "LASTMODDATE")));
m_obj.setState(grab(a, M, "RECORDSTATUS"));
} else if (localName.equals("agent")) {
m_agentRole = grab(a, M, "ROLE");
} else if (localName.equals("name") && m_agentRole.equals("IPOWNER")) {
m_readingContent=true;
m_elementContent = new StringBuffer();
} else if (localName.equals("amdSec")) {
m_dsId=grab(a, M, "ID");
m_dsState=grab(a, M, "STATUS");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
} else if (localName.equals("dmdSecFedora")) {
m_dsId=grab(a, M, "ID");
m_dsState=grab(a, M, "STATUS");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
} else if (localName.equals("techMD") || localName.equals("descMD")
|| localName.equals("sourceMD")
|| localName.equals("rightsMD")
|| localName.equals("digiprovMD")) {
m_dsVersId=grab(a, M, "ID");
if (localName.equals("techMD")) {
m_dsMDClass=DatastreamXMLMetadata.TECHNICAL;
}
if (localName.equals("sourceMD")) {
m_dsMDClass=DatastreamXMLMetadata.SOURCE;
}
if (localName.equals("rightsMD")) {
m_dsMDClass=DatastreamXMLMetadata.RIGHTS;
}
if (localName.equals("digiprovMD")) {
m_dsMDClass=DatastreamXMLMetadata.DIGIPROV;
}
if (localName.equals("descMD")) {
m_dsMDClass=DatastreamXMLMetadata.DESCRIPTIVE;
}
String dateString=grab(a, M, "CREATED");
if (dateString!=null && !dateString.equals("")){
m_dsCreateDate=
DateUtility.convertStringToDate(dateString);
}
} else if (localName.equals("mdWrap")) {
m_dsInfoType=grab(a, M, "MDTYPE");
m_dsOtherInfoType=grab(a, M, "OTHERMDTYPE");
m_dsLabel=grab(a, M, "LABEL");
m_dsMimeType=grab(a, M, "MIMETYPE");
m_dsFormatURI=grab(a, M, "FORMAT_URI");
String altIDs= grab(a, M, "ALT_IDS");
if (altIDs.length() == 0) {
m_dsAltIDs = new String[0];
} else {
m_dsAltIDs = altIDs.split(" ");
}
m_dsChecksum = grab(a, M, "CHECKSUM");
m_dsChecksumType = grab(a, M, "CHECKSUMTYPE");
} else if (localName.equals("xmlData")) {
m_dsXMLBuffer=new StringBuffer();
m_xmlDataLevel=0;
m_inXMLMetadata=true;
} else if (localName.equals("fileGrp")) {
m_dsId=grab(a, M, "ID");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
// reset the values for the next file
m_dsVersId="";
m_dsCreateDate=null;
m_dsMimeType="";
m_dsControlGrp="";
m_dsFormatURI="";
m_dsAltIDs=new String[0];
m_dsState=grab(a,M,"STATUS");
m_dsSize=-1;
m_dsChecksum="";
m_dsChecksumType="";
} else if (localName.equals("file")) {
m_dsVersId=grab(a, M, "ID");
String dateString=grab(a, M, "CREATED");
if (dateString!=null && !dateString.equals("")){
m_dsCreateDate=
DateUtility.convertStringToDate(dateString);
}
m_dsMimeType=grab(a,M,"MIMETYPE");
m_dsControlGrp=grab(a,M,"OWNERID");
String ADMID=grab(a,M,"ADMID");
if ((ADMID!=null) && (!"".equals(ADMID))) {
ArrayList al=new ArrayList();
if (ADMID.indexOf(" ")!=-1) {
String[] admIds=ADMID.split(" ");
for (int idi=0; idi<admIds.length; idi++) {
al.add(admIds[idi]);
}
} else {
al.add(ADMID);
}
m_dsADMIDs.put(m_dsVersId, al);
}
String DMDID=grab(a,M,"DMDID");
if ((DMDID!=null) && (!"".equals(DMDID))) {
ArrayList<String> al=new ArrayList<String>();
if (DMDID.indexOf(" ")!=-1) {
String[] dmdIds=DMDID.split(" ");
for (int idi=0; idi<dmdIds.length; idi++) {
al.add(dmdIds[idi]);
}
} else {
al.add(DMDID);
}
m_dsDMDIDs.put(m_dsVersId, al);
}
String sizeString=grab(a,M,"SIZE");
if (sizeString!=null && !sizeString.equals("")) {
try {
m_dsSize=Long.parseLong(sizeString);
} catch (NumberFormatException nfe) {
throw new SAXException("If specified, a datastream's "
+ "SIZE attribute must be an xsd:long.");
}
}
String formatURI=grab(a, M, "FORMAT_URI");
if (formatURI!=null && !formatURI.equals("")) {
m_dsFormatURI=formatURI;
}
String altIDs=grab(a, M, "ALT_IDS");
if (altIDs.length() == 0) {
m_dsAltIDs = new String[0];
} else {
m_dsAltIDs = altIDs.split(" ");
}
m_dsChecksum = grab(a, M, "CHECKSUM");
m_dsChecksumType = grab(a, M, "CHECKSUMTYPE");
// inside a "file" element, it's either going to be
// FLocat (a reference) or FContent (inline)
} else if (localName.equals("FLocat")) {
m_dsLabel=grab(a,XLINK_NAMESPACE,"title");
String dsLocation=grab(a,XLINK_NAMESPACE,"href");
if (dsLocation==null || dsLocation.equals("")) {
throw new SAXException("xlink:href must be specified in FLocat element");
}
if (m_dsControlGrp.equalsIgnoreCase("E") ||
m_dsControlGrp.equalsIgnoreCase("R") ) {
// URL FORMAT VALIDATION for dsLocation:
// make sure we have a properly formed URL (must have protocol)
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
// system will set dsLocationType for E and R datastreams...
m_dsLocationType="URL";
m_dsInfoType="DATA";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamReferencedContent());
} else if (m_dsControlGrp.equalsIgnoreCase("M")) {
// URL FORMAT VALIDATION for dsLocation:
// For Managed Content the URL is only checked when we are parsing a
// a NEW ingest file because the URL is replaced with an internal identifier
// once the repository has sucked in the content for storage.
if (m_obj.isNew()) {
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
}
m_dsLocationType="INTERNAL_ID";
m_dsInfoType="DATA";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamManagedContent());
}
} else if (localName.equals("FContent")) {
// In the version of METS that Fedora supports, the FContent element
// contains base64 encoded data.
m_readingContent=true;
m_elementContent = new StringBuffer();
if (m_dsControlGrp.equalsIgnoreCase("M"))
{
m_readingBinaryContent=true;
m_binaryContentTempFile = null;
try {
m_binaryContentTempFile = File.createTempFile("binary-datastream", null);
}
catch (IOException ioe)
{
throw new SAXException(new StreamIOException("Unable to create temporary file for binary content"));
}
}
}
// else if (localName.equals("structMap"))
// {
// // this is a component of a disseminator. here we assume the rest
// // of the disseminator's information will be seen later, so we
// // construct a new Disseminator object to hold the structMap...
// // and later, the other info
// //
// // Building up a global map of Disseminators, m_dissems,
// // keyed by bindingmap ID.
// //
// if (grab(a,M,"TYPE").equals("fedora:dsBindingMap"))
// {
// String bmId=grab(a,M,"ID");
// if ( (bmId==null) || (bmId.equals("")) )
// {
// throw new SAXException("structMap with TYPE fedora:dsBindingMap must specify a non-empty ID attribute.");
// }
// else
// {
// Disseminator diss=new Disseminator();
// diss.dsBindMapID=bmId;
// m_dissems.put(bmId,diss);
// m_diss=diss;
// m_diss.dsBindMap=new DSBindingMap();
// m_diss.dsBindMap.dsBindMapID=bmId;
// m_indiv=false; // flag that we're not looking at inner part yet
// }
// } else {
// throw new SAXException("StructMap must have TYPE fedora:dsBindingMap");
// }
// }
// else if (localName.equals("div"))
// {
// if (m_indiv) {
// // inner part of structmap
// DSBinding binding=new DSBinding();
// if (m_diss.dsBindMap.dsBindings==null) {
// // none yet.. create array of size one
// DSBinding[] bindings=new DSBinding[1];
// m_diss.dsBindMap.dsBindings=bindings;
// m_diss.dsBindMap.dsBindings[0]=binding;
// } else {
// // need to expand the array size by one,
// // and do an array copy.
// int curSize=m_diss.dsBindMap.dsBindings.length;
// DSBinding[] oldArray=m_diss.dsBindMap.dsBindings;
// DSBinding[] newArray=new DSBinding[curSize+1];
// for (int i=0; i<curSize; i++) {
// newArray[i]=oldArray[i];
// }
// newArray[curSize]=binding;
// m_diss.dsBindMap.dsBindings=newArray;
// }
// // now populate 'binding' values...we'll have
// // everything at this point except datastreamID...
// // that comes as a child: <fptr FILEID="DS2"/>
// binding.bindKeyName=grab(a,M,"TYPE");
// binding.bindLabel=grab(a,M,"LABEL");
// binding.seqNo=grab(a,M,"ORDER");
// } else {
// m_indiv=true;
// // first (outer div) part of structmap
// m_diss.dsBindMap.dsBindMechanismPID=grab(a,M,"TYPE");
// m_diss.dsBindMap.dsBindMapLabel=grab(a,M,"LABEL");
// }
// }
// else if (localName.equals("fptr"))
// {
// // assume we're inside the inner div... that's the
// // only place the fptr element is valid.
// DSBinding binding=m_diss.dsBindMap.dsBindings[
// m_diss.dsBindMap.dsBindings.length-1];
// binding.datastreamID=grab(a,M,"FILEID");
// }
else if (localName.equals("behaviorSec"))
{
// looks like we're in a disseminator... it should be in the
// hash by now because we've already gone through structmaps
// ...keyed by structmap id... remember the id (group id)
// so we can put it in when parsing serviceBinding
m_dissemId=grab(a,M,"ID");
m_dissemState=grab(a,M,"STATUS");
}
// else if (localName.equals("serviceBinding"))
// {
// // remember the structId so we can grab the right dissem
// // when parsing children
// m_structId=grab(a,M,"STRUCTID");
// // grab the disseminator associated with the provided structId
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// // plug known items in..
// dissem.dissID=m_dissemId;
// dissem.dissState=m_dissemState;
// // then grab the new stuff for the dissem for this element, and
// // put it in.
// dissem.dissVersionID=grab(a,M,"ID");
// dissem.bDefID=grab(a,M,"BTYPE");
// dissem.dissCreateDT=DateUtility.convertStringToDate(grab(a,M,"CREATED"));
// dissem.dissLabel=grab(a,M,"LABEL");
// }
// else if (localName.equals("interfaceMD"))
// {
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// // already have the id from containing element, just need label
// //dissem.bDefLabel=grab(a,M,"LABEL");
// }
// else if (localName.equals("serviceBindMD"))
// {
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// //dissem.bMechLabel=grab(a,M,"LABEL");
// dissem.bMechID=grab(a,XLINK_NAMESPACE,"href");
// }
} else {
| public void startElement(String uri, String localName, String qName,
Attributes a) throws SAXException {
if (uri.equals(M) && !m_inXMLMetadata) {
// a new mets element is starting
if (localName.equals("mets")) {
m_rootElementFound=true;
m_obj.setPid(grab(a, M, "OBJID"));
m_obj.setLabel(grab(a, M, "LABEL"));
m_obj.setContentModelId(grab(a, M, "PROFILE"));
String objType=grab(a, M, "TYPE");
if (objType==null || objType.equals("")) { objType="FedoraObject"; }
if (objType.indexOf("FedoraBDefObject")!= -1)
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_BDEF_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraBMechObject"))
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_BMECH_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraCModelObject"))
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_CONTENT_MODEL_OBJECT);
}
if (objType.equalsIgnoreCase("FedoraObject"))
{
m_obj.addFedoraObjectType(DigitalObject.FEDORA_OBJECT);
}
} else if (localName.equals("metsHdr")) {
m_obj.setCreateDate(DateUtility.convertStringToDate(
grab(a, M, "CREATEDATE")));
m_obj.setLastModDate(DateUtility.convertStringToDate(
grab(a, M, "LASTMODDATE")));
m_obj.setState(grab(a, M, "RECORDSTATUS"));
} else if (localName.equals("agent")) {
m_agentRole = grab(a, M, "ROLE");
} else if (localName.equals("name") && m_agentRole.equals("IPOWNER")) {
m_readingContent=true;
m_elementContent = new StringBuffer();
} else if (localName.equals("amdSec")) {
m_dsId=grab(a, M, "ID");
m_dsState=grab(a, M, "STATUS");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
} else if (localName.equals("dmdSecFedora")) {
m_dsId=grab(a, M, "ID");
m_dsState=grab(a, M, "STATUS");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
} else if (localName.equals("techMD") || localName.equals("descMD")
|| localName.equals("sourceMD")
|| localName.equals("rightsMD")
|| localName.equals("digiprovMD")) {
m_dsVersId=grab(a, M, "ID");
if (localName.equals("techMD")) {
m_dsMDClass=DatastreamXMLMetadata.TECHNICAL;
}
if (localName.equals("sourceMD")) {
m_dsMDClass=DatastreamXMLMetadata.SOURCE;
}
if (localName.equals("rightsMD")) {
m_dsMDClass=DatastreamXMLMetadata.RIGHTS;
}
if (localName.equals("digiprovMD")) {
m_dsMDClass=DatastreamXMLMetadata.DIGIPROV;
}
if (localName.equals("descMD")) {
m_dsMDClass=DatastreamXMLMetadata.DESCRIPTIVE;
}
String dateString=grab(a, M, "CREATED");
if (dateString!=null && !dateString.equals("")){
m_dsCreateDate=
DateUtility.convertStringToDate(dateString);
}
} else if (localName.equals("mdWrap")) {
m_dsInfoType=grab(a, M, "MDTYPE");
m_dsOtherInfoType=grab(a, M, "OTHERMDTYPE");
m_dsLabel=grab(a, M, "LABEL");
m_dsMimeType=grab(a, M, "MIMETYPE");
m_dsFormatURI=grab(a, M, "FORMAT_URI");
String altIDs= grab(a, M, "ALT_IDS");
if (altIDs.length() == 0) {
m_dsAltIDs = new String[0];
} else {
m_dsAltIDs = altIDs.split(" ");
}
m_dsChecksum = grab(a, M, "CHECKSUM");
m_dsChecksumType = grab(a, M, "CHECKSUMTYPE");
} else if (localName.equals("xmlData")) {
m_dsXMLBuffer=new StringBuffer();
m_xmlDataLevel=0;
m_inXMLMetadata=true;
} else if (localName.equals("fileGrp")) {
m_dsId=grab(a, M, "ID");
String dsVersionable = grab(a, M, "VERSIONABLE");
if (dsVersionable!=null && !dsVersionable.equals("")) {
m_dsVersionable=new Boolean(grab(a, M, "VERSIONABLE")).booleanValue();
} else {
m_dsVersionable = true;
}
// reset the values for the next file
m_dsVersId="";
m_dsCreateDate=null;
m_dsMimeType="";
m_dsControlGrp="";
m_dsFormatURI="";
m_dsAltIDs=new String[0];
m_dsState=grab(a,M,"STATUS");
m_dsSize=-1;
m_dsChecksum="";
m_dsChecksumType="";
} else if (localName.equals("file")) {
m_dsVersId=grab(a, M, "ID");
String dateString=grab(a, M, "CREATED");
if (dateString!=null && !dateString.equals("")){
m_dsCreateDate=
DateUtility.convertStringToDate(dateString);
}
m_dsMimeType=grab(a,M,"MIMETYPE");
m_dsControlGrp=grab(a,M,"OWNERID");
String ADMID=grab(a,M,"ADMID");
if ((ADMID!=null) && (!"".equals(ADMID))) {
ArrayList al=new ArrayList();
if (ADMID.indexOf(" ")!=-1) {
String[] admIds=ADMID.split(" ");
for (int idi=0; idi<admIds.length; idi++) {
al.add(admIds[idi]);
}
} else {
al.add(ADMID);
}
m_dsADMIDs.put(m_dsVersId, al);
}
String DMDID=grab(a,M,"DMDID");
if ((DMDID!=null) && (!"".equals(DMDID))) {
ArrayList<String> al=new ArrayList<String>();
if (DMDID.indexOf(" ")!=-1) {
String[] dmdIds=DMDID.split(" ");
for (int idi=0; idi<dmdIds.length; idi++) {
al.add(dmdIds[idi]);
}
} else {
al.add(DMDID);
}
m_dsDMDIDs.put(m_dsVersId, al);
}
String sizeString=grab(a,M,"SIZE");
if (sizeString!=null && !sizeString.equals("")) {
try {
m_dsSize=Long.parseLong(sizeString);
} catch (NumberFormatException nfe) {
throw new SAXException("If specified, a datastream's "
+ "SIZE attribute must be an xsd:long.");
}
}
String formatURI=grab(a, M, "FORMAT_URI");
if (formatURI!=null && !formatURI.equals("")) {
m_dsFormatURI=formatURI;
}
String altIDs=grab(a, M, "ALT_IDS");
if (altIDs.length() == 0) {
m_dsAltIDs = new String[0];
} else {
m_dsAltIDs = altIDs.split(" ");
}
m_dsChecksum = grab(a, M, "CHECKSUM");
m_dsChecksumType = grab(a, M, "CHECKSUMTYPE");
// inside a "file" element, it's either going to be
// FLocat (a reference) or FContent (inline)
} else if (localName.equals("FLocat")) {
m_dsLabel=grab(a,XLINK_NAMESPACE,"title");
String dsLocation=grab(a,XLINK_NAMESPACE,"href");
if (dsLocation==null || dsLocation.equals("")) {
throw new SAXException("xlink:href must be specified in FLocat element");
}
if (m_dsControlGrp.equalsIgnoreCase("E") ||
m_dsControlGrp.equalsIgnoreCase("R") ) {
// URL FORMAT VALIDATION for dsLocation:
// make sure we have a properly formed URL (must have protocol)
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
// system will set dsLocationType for E and R datastreams...
m_dsLocationType="URL";
m_dsInfoType="DATA";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamReferencedContent());
} else if (m_dsControlGrp.equalsIgnoreCase("M")) {
// URL FORMAT VALIDATION for dsLocation:
// For Managed Content the URL is only checked when we are parsing a
// a NEW ingest file because the URL is replaced with an internal identifier
// once the repository has sucked in the content for storage.
if (m_obj.isNew()) {
try {
ValidationUtility.validateURL(dsLocation, false);
} catch (ValidationException ve) {
throw new SAXException(ve.getMessage());
}
}
m_dsLocationType="INTERNAL_ID";
m_dsInfoType="DATA";
m_dsLocation=dsLocation;
instantiateDatastream(new DatastreamManagedContent());
}
} else if (localName.equals("FContent")) {
// In the version of METS that Fedora supports, the FContent element
// contains base64 encoded data.
m_readingContent=true;
m_elementContent = new StringBuffer();
if (m_dsControlGrp.equalsIgnoreCase("M"))
{
m_readingBinaryContent=true;
m_binaryContentTempFile = null;
try {
m_binaryContentTempFile = File.createTempFile("binary-datastream", null);
}
catch (IOException ioe)
{
throw new SAXException(new StreamIOException("Unable to create temporary file for binary content"));
}
}
}
// else if (localName.equals("structMap"))
// {
// // this is a component of a disseminator. here we assume the rest
// // of the disseminator's information will be seen later, so we
// // construct a new Disseminator object to hold the structMap...
// // and later, the other info
// //
// // Building up a global map of Disseminators, m_dissems,
// // keyed by bindingmap ID.
// //
// if (grab(a,M,"TYPE").equals("fedora:dsBindingMap"))
// {
// String bmId=grab(a,M,"ID");
// if ( (bmId==null) || (bmId.equals("")) )
// {
// throw new SAXException("structMap with TYPE fedora:dsBindingMap must specify a non-empty ID attribute.");
// }
// else
// {
// Disseminator diss=new Disseminator();
// diss.dsBindMapID=bmId;
// m_dissems.put(bmId,diss);
// m_diss=diss;
// m_diss.dsBindMap=new DSBindingMap();
// m_diss.dsBindMap.dsBindMapID=bmId;
// m_indiv=false; // flag that we're not looking at inner part yet
// }
// } else {
// throw new SAXException("StructMap must have TYPE fedora:dsBindingMap");
// }
// }
// else if (localName.equals("div"))
// {
// if (m_indiv) {
// // inner part of structmap
// DSBinding binding=new DSBinding();
// if (m_diss.dsBindMap.dsBindings==null) {
// // none yet.. create array of size one
// DSBinding[] bindings=new DSBinding[1];
// m_diss.dsBindMap.dsBindings=bindings;
// m_diss.dsBindMap.dsBindings[0]=binding;
// } else {
// // need to expand the array size by one,
// // and do an array copy.
// int curSize=m_diss.dsBindMap.dsBindings.length;
// DSBinding[] oldArray=m_diss.dsBindMap.dsBindings;
// DSBinding[] newArray=new DSBinding[curSize+1];
// for (int i=0; i<curSize; i++) {
// newArray[i]=oldArray[i];
// }
// newArray[curSize]=binding;
// m_diss.dsBindMap.dsBindings=newArray;
// }
// // now populate 'binding' values...we'll have
// // everything at this point except datastreamID...
// // that comes as a child: <fptr FILEID="DS2"/>
// binding.bindKeyName=grab(a,M,"TYPE");
// binding.bindLabel=grab(a,M,"LABEL");
// binding.seqNo=grab(a,M,"ORDER");
// } else {
// m_indiv=true;
// // first (outer div) part of structmap
// m_diss.dsBindMap.dsBindMechanismPID=grab(a,M,"TYPE");
// m_diss.dsBindMap.dsBindMapLabel=grab(a,M,"LABEL");
// }
// }
// else if (localName.equals("fptr"))
// {
// // assume we're inside the inner div... that's the
// // only place the fptr element is valid.
// DSBinding binding=m_diss.dsBindMap.dsBindings[
// m_diss.dsBindMap.dsBindings.length-1];
// binding.datastreamID=grab(a,M,"FILEID");
// }
else if (localName.equals("behaviorSec"))
{
// looks like we're in a disseminator... it should be in the
// hash by now because we've already gone through structmaps
// ...keyed by structmap id... remember the id (group id)
// so we can put it in when parsing serviceBinding
m_dissemId=grab(a,M,"ID");
m_dissemState=grab(a,M,"STATUS");
}
// else if (localName.equals("serviceBinding"))
// {
// // remember the structId so we can grab the right dissem
// // when parsing children
// m_structId=grab(a,M,"STRUCTID");
// // grab the disseminator associated with the provided structId
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// // plug known items in..
// dissem.dissID=m_dissemId;
// dissem.dissState=m_dissemState;
// // then grab the new stuff for the dissem for this element, and
// // put it in.
// dissem.dissVersionID=grab(a,M,"ID");
// dissem.bDefID=grab(a,M,"BTYPE");
// dissem.dissCreateDT=DateUtility.convertStringToDate(grab(a,M,"CREATED"));
// dissem.dissLabel=grab(a,M,"LABEL");
// }
// else if (localName.equals("interfaceMD"))
// {
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// // already have the id from containing element, just need label
// //dissem.bDefLabel=grab(a,M,"LABEL");
// }
// else if (localName.equals("serviceBindMD"))
// {
// Disseminator dissem=(Disseminator) m_dissems.get(m_structId);
// //dissem.bMechLabel=grab(a,M,"LABEL");
// dissem.bMechID=grab(a,XLINK_NAMESPACE,"href");
// }
} else {
|
diff --git a/src/carnero/me/fragment/NetworksFragment.java b/src/carnero/me/fragment/NetworksFragment.java
index 8dc8ed0..ae6d9bd 100644
--- a/src/carnero/me/fragment/NetworksFragment.java
+++ b/src/carnero/me/fragment/NetworksFragment.java
@@ -1,120 +1,120 @@
package carnero.me.fragment;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import carnero.me.R;
import carnero.me.data._NetworksList;
import carnero.me.model.Network;
public class NetworksFragment extends Fragment {
private LayoutInflater mInflater;
private PackageManager mPM;
private LinearLayout mLayoutOn;
private LinearLayout mLayoutOff;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
mInflater = inflater;
final View view = inflater.inflate(R.layout.networks, container, false);
mLayoutOn = (LinearLayout) view.findViewById(R.id.networks_layout);
mLayoutOff = (LinearLayout) view.findViewById(R.id.networks_missing_layout);
return view;
}
@Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
int networksOn = 0; // user have installed official client...
int networksOff = 0; // ...user has not
ViewGroup view;
ImageView icon;
TextView title;
TextView description;
for (Network network : _NetworksList.ENTRIES) {
if (isPackageInstalled(network.packageName)) {
- view = (ViewGroup) mInflater.inflate(R.layout.item_network_on, null);
+ view = (ViewGroup) mInflater.inflate(R.layout.item_network_on, mLayoutOn, false);
icon = (ImageView) view.findViewById(R.id.network_icon);
title = (TextView) view.findViewById(R.id.network_title);
description = (TextView) view.findViewById(R.id.network_description);
view.setOnClickListener(new EntryAction(network.tapAction));
icon.setImageResource(network.iconOn);
title.setText(network.title);
description.setText(network.description);
mLayoutOn.addView(view);
networksOn++;
} else {
- view = (ViewGroup) mInflater.inflate(R.layout.item_network_off, null);
+ view = (ViewGroup) mInflater.inflate(R.layout.item_network_off, mLayoutOff, false);
icon = (ImageView) view.findViewById(R.id.network_icon);
title = (TextView) view.findViewById(R.id.network_title);
description = (TextView) view.findViewById(R.id.network_description);
view.setOnClickListener(new EntryAction(network.tapAction));
icon.setImageResource(network.iconOff);
title.setText(network.title);
description.setText(network.description);
mLayoutOff.addView(view);
networksOff++;
}
}
if (networksOn == 0) {
mLayoutOn.setVisibility(View.GONE);
}
if (networksOff == 0) {
mLayoutOff.setVisibility(View.GONE);
}
}
private boolean isPackageInstalled(String clazz) {
if (TextUtils.isEmpty(clazz)) {
return false;
}
if (mPM == null) {
mPM = getActivity().getPackageManager();
}
try {
mPM.getPackageInfo(clazz, 0);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
// classes
private class EntryAction implements View.OnClickListener {
private Intent mIntent;
public EntryAction(Intent intent) {
mIntent = intent;
}
@Override
public void onClick(View v) {
getActivity().startActivity(mIntent);
}
}
}
| false | true | public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
int networksOn = 0; // user have installed official client...
int networksOff = 0; // ...user has not
ViewGroup view;
ImageView icon;
TextView title;
TextView description;
for (Network network : _NetworksList.ENTRIES) {
if (isPackageInstalled(network.packageName)) {
view = (ViewGroup) mInflater.inflate(R.layout.item_network_on, null);
icon = (ImageView) view.findViewById(R.id.network_icon);
title = (TextView) view.findViewById(R.id.network_title);
description = (TextView) view.findViewById(R.id.network_description);
view.setOnClickListener(new EntryAction(network.tapAction));
icon.setImageResource(network.iconOn);
title.setText(network.title);
description.setText(network.description);
mLayoutOn.addView(view);
networksOn++;
} else {
view = (ViewGroup) mInflater.inflate(R.layout.item_network_off, null);
icon = (ImageView) view.findViewById(R.id.network_icon);
title = (TextView) view.findViewById(R.id.network_title);
description = (TextView) view.findViewById(R.id.network_description);
view.setOnClickListener(new EntryAction(network.tapAction));
icon.setImageResource(network.iconOff);
title.setText(network.title);
description.setText(network.description);
mLayoutOff.addView(view);
networksOff++;
}
}
if (networksOn == 0) {
mLayoutOn.setVisibility(View.GONE);
}
if (networksOff == 0) {
mLayoutOff.setVisibility(View.GONE);
}
}
| public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
int networksOn = 0; // user have installed official client...
int networksOff = 0; // ...user has not
ViewGroup view;
ImageView icon;
TextView title;
TextView description;
for (Network network : _NetworksList.ENTRIES) {
if (isPackageInstalled(network.packageName)) {
view = (ViewGroup) mInflater.inflate(R.layout.item_network_on, mLayoutOn, false);
icon = (ImageView) view.findViewById(R.id.network_icon);
title = (TextView) view.findViewById(R.id.network_title);
description = (TextView) view.findViewById(R.id.network_description);
view.setOnClickListener(new EntryAction(network.tapAction));
icon.setImageResource(network.iconOn);
title.setText(network.title);
description.setText(network.description);
mLayoutOn.addView(view);
networksOn++;
} else {
view = (ViewGroup) mInflater.inflate(R.layout.item_network_off, mLayoutOff, false);
icon = (ImageView) view.findViewById(R.id.network_icon);
title = (TextView) view.findViewById(R.id.network_title);
description = (TextView) view.findViewById(R.id.network_description);
view.setOnClickListener(new EntryAction(network.tapAction));
icon.setImageResource(network.iconOff);
title.setText(network.title);
description.setText(network.description);
mLayoutOff.addView(view);
networksOff++;
}
}
if (networksOn == 0) {
mLayoutOn.setVisibility(View.GONE);
}
if (networksOff == 0) {
mLayoutOff.setVisibility(View.GONE);
}
}
|
diff --git a/flex-pmd-ruleset/src/main/java/com/adobe/ac/pmd/rules/maintanability/UselessOverridenFunctionRule.java b/flex-pmd-ruleset/src/main/java/com/adobe/ac/pmd/rules/maintanability/UselessOverridenFunctionRule.java
index cc423032..8e033d47 100644
--- a/flex-pmd-ruleset/src/main/java/com/adobe/ac/pmd/rules/maintanability/UselessOverridenFunctionRule.java
+++ b/flex-pmd-ruleset/src/main/java/com/adobe/ac/pmd/rules/maintanability/UselessOverridenFunctionRule.java
@@ -1,81 +1,82 @@
/**
* Copyright (c) 2009, Adobe Systems, Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of the Adobe Systems, Incorporated. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.ac.pmd.rules.maintanability;
import java.util.List;
import com.adobe.ac.pmd.nodes.IFunction;
import com.adobe.ac.pmd.parser.IParserNode;
import com.adobe.ac.pmd.parser.KeyWords;
import com.adobe.ac.pmd.rules.core.AbstractAstFlexRule;
import com.adobe.ac.pmd.rules.core.ViolationPriority;
public class UselessOverridenFunctionRule extends AbstractAstFlexRule
{
@Override
protected final void findViolations( final IFunction function )
{
final int statementNbAtFirstLevelInBody = function.getStatementNbInBody();
if ( function.getBody() != null
&& function.isOverriden() && statementNbAtFirstLevelInBody == 1 )
{
final List< IParserNode > statements = function.findPrimaryStatementsInBody( KeyWords.SUPER.toString() );
- if ( statements.size() == 1
+ if ( statements != null
+ && statements.size() == 1
&& !areArgumentsModified( function.getBody().getChild( 0 ).getChild( 1 ).getChild( 1 ) ) )
{
addViolation( function );
}
}
}
@Override
protected final ViolationPriority getDefaultPriority()
{
return ViolationPriority.LOW;
}
private boolean areArgumentsModified( final IParserNode args )
{
if ( args.getChildren() != null )
{
for ( final IParserNode arg : args.getChildren() )
{
if ( arg.getChildren() != null )
{
return true;
}
}
}
return false;
}
}
| true | true | protected final void findViolations( final IFunction function )
{
final int statementNbAtFirstLevelInBody = function.getStatementNbInBody();
if ( function.getBody() != null
&& function.isOverriden() && statementNbAtFirstLevelInBody == 1 )
{
final List< IParserNode > statements = function.findPrimaryStatementsInBody( KeyWords.SUPER.toString() );
if ( statements.size() == 1
&& !areArgumentsModified( function.getBody().getChild( 0 ).getChild( 1 ).getChild( 1 ) ) )
{
addViolation( function );
}
}
}
| protected final void findViolations( final IFunction function )
{
final int statementNbAtFirstLevelInBody = function.getStatementNbInBody();
if ( function.getBody() != null
&& function.isOverriden() && statementNbAtFirstLevelInBody == 1 )
{
final List< IParserNode > statements = function.findPrimaryStatementsInBody( KeyWords.SUPER.toString() );
if ( statements != null
&& statements.size() == 1
&& !areArgumentsModified( function.getBody().getChild( 0 ).getChild( 1 ).getChild( 1 ) ) )
{
addViolation( function );
}
}
}
|
diff --git a/gdms/src/main/java/org/gdms/sql/function/alphanumeric/ReplaceString.java b/gdms/src/main/java/org/gdms/sql/function/alphanumeric/ReplaceString.java
index 1e17dc622..214985827 100644
--- a/gdms/src/main/java/org/gdms/sql/function/alphanumeric/ReplaceString.java
+++ b/gdms/src/main/java/org/gdms/sql/function/alphanumeric/ReplaceString.java
@@ -1,103 +1,103 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able
* to manipulate and create vector and raster spatial information. OrbisGIS
* is distributed under GPL 3 license. It is produced by the geo-informatic team of
* the IRSTV Institute <http://www.irstv.cnrs.fr/>, CNRS FR 2488:
* Erwan BOCHER, scientific researcher,
* Thomas LEDUC, scientific researcher,
* Fernando GONZALEZ CORTES, computer engineer.
*
* Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OrbisGIS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult:
* <http://orbisgis.cerma.archi.fr/>
* <http://sourcesup.cru.fr/projects/orbisgis/>
*
* or contact directly:
* erwan.bocher _at_ ec-nantes.fr
* fergonco _at_ gmail.com
* thomas.leduc _at_ cerma.archi.fr
*/
package org.gdms.sql.function.alphanumeric;
import org.gdms.data.DataSourceFactory;
import org.gdms.data.types.InvalidTypeException;
import org.gdms.data.types.Type;
import org.gdms.data.types.TypeFactory;
import org.gdms.data.values.Value;
import org.gdms.data.values.ValueFactory;
import org.gdms.sql.function.Argument;
import org.gdms.sql.function.Arguments;
import org.gdms.sql.function.Function;
import org.gdms.sql.function.FunctionException;
public class ReplaceString implements Function {
public Value evaluate(DataSourceFactory dsf, Value[] arg0) throws FunctionException {
String text;
if (arg0[0].isNull()) {
return ValueFactory.createNullValue();
} else {
// Get the arguments
text = arg0[0].getAsString();
String textFrom = arg0[1].getAsString();
String textTo = arg0[2].getAsString();
- text.replace(textFrom, textTo);
+ text = text.replace(textFrom, textTo);
}
return ValueFactory.createValue(text);
}
public String getDescription() {
return "Replace all occurrences in string of substring from with substring to ";
}
public String getName() {
return "Replace";
}
public String getSqlOrder() {
return "select Replace(string text, from text, to text) from myTable";
}
public Type getType(Type[] arg0) throws InvalidTypeException {
return TypeFactory.createType(Type.STRING);
}
public boolean isAggregate() {
return false;
}
public Arguments[] getFunctionArguments() {
return new Arguments[] { new Arguments(Argument.STRING,
Argument.STRING, Argument.STRING) };
}
@Override
public Value getAggregateResult() {
return null;
}
}
| true | true | public Value evaluate(DataSourceFactory dsf, Value[] arg0) throws FunctionException {
String text;
if (arg0[0].isNull()) {
return ValueFactory.createNullValue();
} else {
// Get the arguments
text = arg0[0].getAsString();
String textFrom = arg0[1].getAsString();
String textTo = arg0[2].getAsString();
text.replace(textFrom, textTo);
}
return ValueFactory.createValue(text);
}
| public Value evaluate(DataSourceFactory dsf, Value[] arg0) throws FunctionException {
String text;
if (arg0[0].isNull()) {
return ValueFactory.createNullValue();
} else {
// Get the arguments
text = arg0[0].getAsString();
String textFrom = arg0[1].getAsString();
String textTo = arg0[2].getAsString();
text = text.replace(textFrom, textTo);
}
return ValueFactory.createValue(text);
}
|
diff --git a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIAdvancedSearchForm.java b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIAdvancedSearchForm.java
index 187c6a24..d9da5e68 100644
--- a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIAdvancedSearchForm.java
+++ b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIAdvancedSearchForm.java
@@ -1,382 +1,383 @@
/**
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
**/
package org.exoplatform.calendar.webui.popup;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.exoplatform.calendar.CalendarUtils;
import org.exoplatform.calendar.service.Calendar;
import org.exoplatform.calendar.service.CalendarEvent;
import org.exoplatform.calendar.service.CalendarService;
import org.exoplatform.calendar.service.EventCategory;
import org.exoplatform.calendar.service.EventPageList;
import org.exoplatform.calendar.service.EventQuery;
import org.exoplatform.calendar.service.GroupCalendarData;
import org.exoplatform.calendar.service.Utils;
import org.exoplatform.calendar.service.impl.NewUserListener;
import org.exoplatform.calendar.webui.UIActionBar;
import org.exoplatform.calendar.webui.UICalendarPortlet;
import org.exoplatform.calendar.webui.UICalendarView;
import org.exoplatform.calendar.webui.UICalendarViewContainer;
import org.exoplatform.calendar.webui.UICalendars;
import org.exoplatform.calendar.webui.UIFormDateTimePicker;
import org.exoplatform.calendar.webui.UIListView;
import org.exoplatform.calendar.webui.UIPreview;
import org.exoplatform.calendar.webui.UIWeekView;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.core.model.SelectItemOption;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.Event.Phase;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormSelectBox;
import org.exoplatform.webui.form.UIFormStringInput;
import org.exoplatform.webui.form.validator.SpecialCharacterValidator;
/**
* Created by The eXo Platform SARL
* Author : Hung Nguyen
* [email protected]
* Aus 01, 2007 2:48:18 PM
*/
@ComponentConfig(
lifecycle = UIFormLifecycle.class,
template = "system:/groovy/webui/form/UIForm.gtmpl",
events = {
@EventConfig(listeners = UIAdvancedSearchForm.SearchActionListener.class),
@EventConfig(listeners = UIAdvancedSearchForm.OnchangeActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIAdvancedSearchForm.CancelActionListener.class, phase = Phase.DECODE)
}
)
public class UIAdvancedSearchForm extends UIForm implements UIPopupComponent{
private static final Log log = ExoLogger.getExoLogger(UIAdvancedSearchForm.class);
final static private String TEXT = "text" ;
final static private String TYPE = "type" ;
final static private String CALENDAR = "calendar" ;
final static private String CATEGORY = "category" ;
final static private String PRIORITY = "priority" ;
final static private String STATE = "state" ;
final static private String FROMDATE = "fromDate" ;
final static private String TODATE = "toDate" ;
public UIAdvancedSearchForm() throws Exception{
addChild(new UIFormStringInput(TEXT, TEXT, "").addValidator(SpecialCharacterValidator.class)) ;
List<SelectItemOption<String>> types = new ArrayList<SelectItemOption<String>>() ;
types.add(new SelectItemOption<String>("", "")) ;
types.add(new SelectItemOption<String>(CalendarEvent.TYPE_EVENT, CalendarEvent.TYPE_EVENT)) ;
types.add(new SelectItemOption<String>(CalendarEvent.TYPE_TASK, CalendarEvent.TYPE_TASK)) ;
UIFormSelectBox type = new UIFormSelectBox(TYPE, TYPE, types) ;
type.setOnChange("Onchange") ;
addChild(type) ;
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
String username = CalendarUtils.getCurrentUser() ;
CalendarService cservice = CalendarUtils.getCalendarService() ;
options.add(new SelectItemOption<String>("", "")) ;
for(Calendar cal : cservice.getUserCalendars(username, true)) {
options.add(new SelectItemOption<String>(cal.getName(), Calendar.TYPE_PRIVATE + CalendarUtils.COLON + cal.getId())) ;
}
List<GroupCalendarData> groupCals = cservice.getGroupCalendars(CalendarUtils.getUserGroups(username), true, username) ;
for(GroupCalendarData groupData : groupCals) {
String groupName = groupData.getName();
if(groupData != null) {
for(Calendar cal : groupData.getCalendars()) {
options.add(new SelectItemOption<String>(CalendarUtils.getGroupCalendarName(groupName.substring(
groupName.lastIndexOf("/") + 1),cal.getName()), Calendar.TYPE_PUBLIC + CalendarUtils.COLON + cal.getId())) ;
}
}
}
GroupCalendarData sharedData = cservice.getSharedCalendars(CalendarUtils.getCurrentUser(), true) ;
if(sharedData != null) {
for(Calendar cal : sharedData.getCalendars()) {
String owner = "" ;
if(cal.getCalendarOwner() != null) owner = cal.getCalendarOwner() + "- " ;
options.add(new SelectItemOption<String>(owner + cal.getName(), Calendar.TYPE_SHARED + CalendarUtils.COLON + cal.getId())) ;
}
}
addChild(new UIFormSelectBox(CALENDAR, CALENDAR, options)) ;
options = new ArrayList<SelectItemOption<String>>() ;
options.add(new SelectItemOption<String>("", "")) ;
for(EventCategory cat : cservice.getEventCategories(CalendarUtils.getCurrentUser())) {
// Check if EventCategory is default event category
boolean isDefaultEventCategory = false;
for (int i = 0; i < NewUserListener.defaultEventCategoryIds.length; i++) {
if (cat.getId().equals(NewUserListener.defaultEventCategoryIds[i])
&& cat.getName().equals(NewUserListener.defaultEventCategoryNames[i])) {
isDefaultEventCategory = true;
break;
}
}
if (isDefaultEventCategory) {
String newName = CalendarUtils.getResourceBundle("UICalendarView.label." + cat.getId(), cat.getId());
options.add(new SelectItemOption<String>(newName, cat.getId())) ;
cat.setName(newName);
} else {
options.add(new SelectItemOption<String>(cat.getName(), cat.getId())) ;
}
}
addChild(new UIFormSelectBox(CATEGORY, CATEGORY, options)) ;
addChild(new UIFormSelectBox(STATE, STATE, getStatus()).setRendered(false)) ;
addChild(new UIFormSelectBox(PRIORITY, PRIORITY, getPriority())) ;
addChild(new UIFormDateTimePicker(FROMDATE, FROMDATE, null, false)) ;
addChild(new UIFormDateTimePicker(TODATE, TODATE, null, false)) ;
}
@Override
public void activate() throws Exception {}
@Override
public void deActivate() throws Exception {
}
public void setSearchValue(String searchValue) {
getUIStringInput(TEXT).setValue(searchValue) ;
}
public UIFormDateTimePicker getUIFormDateTimePicker(String id){
return findComponentById(id) ;
}
public String getFromDateValue() {
return getUIFormDateTimePicker(FROMDATE).getValue() ;
}
public String getToDateValue() {
return getUIFormDateTimePicker(TODATE).getValue() ;
}
public Date getFromDate() {
DateFormat df = new SimpleDateFormat(CalendarUtils.DATEFORMAT) ;
df.setCalendar(CalendarUtils.getInstanceOfCurrentCalendar()) ;
if(getFromDateValue() != null)
try {
return df.parse(getFromDateValue()) ;
} catch (Exception e) {
return null ;
}
return null ;
}
public Date getToDate() {
DateFormat df = new SimpleDateFormat(CalendarUtils.DATEFORMAT) ;
df.setCalendar(CalendarUtils.getInstanceOfCurrentCalendar()) ;
if(getToDateValue() != null)
try {
return df.parse(getToDateValue()) ;
} catch (Exception e) {
return null ;
}
return null ;
}
private List<SelectItemOption<String>> getPriority() throws Exception {
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
options.add(new SelectItemOption<String>("", "")) ;
options.add(new SelectItemOption<String>("normal", "normal")) ;
options.add(new SelectItemOption<String>("high", "high")) ;
options.add(new SelectItemOption<String>("low", "low")) ;
return options ;
}
private List<SelectItemOption<String>> getStatus() {
List<SelectItemOption<String>> status = new ArrayList<SelectItemOption<String>>() ;
status.add(new SelectItemOption<String>("", "")) ;
for(String taskStatus : CalendarEvent.TASK_STATUS) {
status.add(new SelectItemOption<String>(taskStatus, taskStatus)) ;
}
return status ;
}
public String[] getPublicCalendars() throws Exception{
String[] groups = CalendarUtils.getUserGroups(CalendarUtils.getCurrentUser()) ;
CalendarService calendarService = CalendarUtils.getCalendarService() ;
Map<String, String> map = new HashMap<String, String> () ;
for(GroupCalendarData group : calendarService.getGroupCalendars(groups, true, CalendarUtils.getCurrentUser())) {
for(org.exoplatform.calendar.service.Calendar calendar : group.getCalendars()) {
map.put(calendar.getId(), calendar.getId()) ;
}
}
return map.values().toArray(new String[map.values().size()] ) ;
}
public boolean isSearchTask() {
return getUIFormSelectBox(TYPE).getValue().equals(CalendarEvent.TYPE_TASK) ;
}
public String getTaskState() {
return getUIFormSelectBox(STATE).getValue() ;
}
@Override
public String[] getActions() {
return new String[]{"Search","Cancel"} ;
}
public Boolean isValidate(){
String value = getUIStringInput(TEXT).getValue();
if(value == null) value = "" ;
String formData = "";
formData += value;
formData += getUIFormSelectBox(TYPE).getValue();
formData += getUIFormSelectBox(CALENDAR).getValue();
formData += getUIFormSelectBox(CATEGORY).getValue();
formData += getUIFormSelectBox(PRIORITY).getValue();
formData += getFromDateValue() ;
formData += getToDateValue() ;
return !CalendarUtils.isEmpty(formData);
}
static public class SearchActionListener extends EventListener<UIAdvancedSearchForm> {
@Override
public void execute(Event<UIAdvancedSearchForm> event) throws Exception {
UIAdvancedSearchForm uiForm = event.getSource() ;
String fromDateValue = uiForm.getFromDateValue();
Date fromDate = uiForm.getFromDate();
Date toDate = uiForm.getToDate();
if(!CalendarUtils.isEmpty(fromDateValue) && fromDate == null){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.from-date-time-invalid", null)) ;
return ;
}
if(!CalendarUtils.isEmpty(uiForm.getToDateValue()) && uiForm.getToDate() == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.to-date-time-invalid", null)) ;
return ;
}
if(fromDate != null && toDate != null) {
if(fromDate.after(toDate)){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.date-time-invalid", null)) ;
return ;
}
}
String text = uiForm.getUIStringInput(UIAdvancedSearchForm.TEXT).getValue() ;
if(!uiForm.isValidate()){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UISearchForm.msg.no-text-to-search", null)) ;
return ;
}
try {
EventQuery query = new EventQuery() ;
//query.setQueryType(Query.SQL) ;
if(! CalendarUtils.isEmpty(text)) query.setText(CalendarUtils.encodeJCRText(text)) ;
query.setEventType(uiForm.getUIFormSelectBox(UIAdvancedSearchForm.TYPE).getValue()) ;
if(uiForm.isSearchTask()) query.setState(uiForm.getTaskState()) ;
String calendarId = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.CALENDAR).getValue() ;
UICalendars uiCalendars = uiForm.getAncestorOfType(UICalendarPortlet.class).findFirstComponentOfType(UICalendars.class);
List<String> checkedCals = uiCalendars.getCheckedCalendars() ;
if(calendarId != null && calendarId.trim().length() > 0){
try {
query.setCalendarId(new String[]{calendarId.split(CalendarUtils.COLON)[1].trim()}) ;
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Fail to set calendar id", e);
}
}
//if (!checkedCals.contains(calendarId)) query.setCalendarId(new String[]{"null"}) ;
}
String categoryId = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.CATEGORY).getValue() ;
if(categoryId != null && categoryId.trim().length() > 0) query.setCategoryId(new String[]{categoryId}) ;
java.util.Calendar cal = CalendarUtils.getInstanceOfCurrentCalendar() ;
if(fromDate != null && toDate != null) {
cal.setTime(fromDate);
query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
cal.setTime(toDate) ;
query.setToDate(CalendarUtils.getEndDay(cal)) ;
} else if (fromDate !=null) {
cal.setTime(fromDate) ;
query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
//query.setToDate(CalendarUtils.getEndDay(cal)) ;
} else if (toDate !=null) {
cal.setTime(toDate) ;
//query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
query.setToDate(CalendarUtils.getEndDay(cal)) ;
}
String priority = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.PRIORITY).getValue() ;
if(priority != null && priority.trim().length() > 0) query.setPriority(priority) ;
UICalendarPortlet calendarPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class) ;
UICalendarViewContainer calendarViewContainer =
calendarPortlet.findFirstComponentOfType(UICalendarViewContainer.class) ;
String currentView = calendarViewContainer.getRenderedChild().getId() ;
if(calendarViewContainer.getRenderedChild() instanceof UIWeekView) {
if(((UIWeekView)calendarViewContainer.getRenderedChild()).isShowCustomView()) currentView = UICalendarViewContainer.WORKING_VIEW;
}
calendarViewContainer.initView(UICalendarViewContainer.LIST_VIEW) ;
UIListView uiListView = calendarViewContainer.findFirstComponentOfType(UIListView.class) ;
// CS-3610
uiListView.setViewType(UICalendarView.TYPE_BOTH);
uiListView.setSortedField(UIListView.EVENT_START);
uiListView.setIsAscending(false);
calendarPortlet.cancelAction();
if (query.getCalendarId() == null) {
List<String> calendarIds = new ArrayList<String>() ;
for (org.exoplatform.calendar.service.Calendar calendar : uiCalendars.getAllPrivateCalendars())
if (checkedCals.contains(calendar.getId())) calendarIds.add(calendar.getId());
for (org.exoplatform.calendar.service.Calendar calendar : uiCalendars.getAllPublicCalendars())
if (checkedCals.contains(calendar.getId())) calendarIds.add(calendar.getId());
GroupCalendarData shareClas = uiCalendars.getSharedCalendars();
if (shareClas != null)
for (org.exoplatform.calendar.service.Calendar calendar : shareClas.getCalendars())
if (checkedCals.contains(calendar.getId())) {
calendarIds.add(calendar.getId());
}
if (calendarIds.size() > 0)
query.setCalendarId(calendarIds.toArray(new String[] {}));
else {
query.setCalendarId(new String[] {"null"});
}
}
query.setOrderBy(new String[] { Utils.EXO_FROM_DATE_TIME });
query.setOrderType(Utils.DESCENDING);
+ uiListView.setEventQuery(query);
uiListView.setDisplaySearchResult(true) ;
List<CalendarEvent> allEvents = uiListView.getAllEvents(query);
uiListView.update(new EventPageList(allEvents,10));
calendarViewContainer.setRenderedChild(UICalendarViewContainer.LIST_VIEW) ;
if(!uiListView.isDisplaySearchResult()) uiListView.setLastViewId(currentView) ;
uiListView.setSelectedEvent(null) ;
uiListView.setLastUpdatedEventId(null) ;
calendarViewContainer.findFirstComponentOfType(UIPreview.class).setEvent(null) ;
UIActionBar uiActionBar = calendarPortlet.findFirstComponentOfType(UIActionBar.class) ;
uiActionBar.setCurrentView(UICalendarViewContainer.LIST_VIEW) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiActionBar) ;
event.getRequestContext().addUIComponentToUpdateByAjax(calendarViewContainer) ;
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Exception in method execute of class SearchActionListener", e);
}
return ;
}
}
}
static public class OnchangeActionListener extends EventListener<UIAdvancedSearchForm> {
@Override
public void execute(Event<UIAdvancedSearchForm> event) throws Exception {
UIAdvancedSearchForm uiForm = event.getSource() ;
uiForm.getUIFormSelectBox(STATE).setRendered(uiForm.isSearchTask()) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiForm) ;
}
}
static public class CancelActionListener extends EventListener<UIAdvancedSearchForm> {
@Override
public void execute(Event<UIAdvancedSearchForm> event) throws Exception {
UIAdvancedSearchForm uiForm = event.getSource() ;
UICalendarPortlet calendarPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class) ;
calendarPortlet.cancelAction() ;
}
}
}
| true | true | public void execute(Event<UIAdvancedSearchForm> event) throws Exception {
UIAdvancedSearchForm uiForm = event.getSource() ;
String fromDateValue = uiForm.getFromDateValue();
Date fromDate = uiForm.getFromDate();
Date toDate = uiForm.getToDate();
if(!CalendarUtils.isEmpty(fromDateValue) && fromDate == null){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.from-date-time-invalid", null)) ;
return ;
}
if(!CalendarUtils.isEmpty(uiForm.getToDateValue()) && uiForm.getToDate() == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.to-date-time-invalid", null)) ;
return ;
}
if(fromDate != null && toDate != null) {
if(fromDate.after(toDate)){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.date-time-invalid", null)) ;
return ;
}
}
String text = uiForm.getUIStringInput(UIAdvancedSearchForm.TEXT).getValue() ;
if(!uiForm.isValidate()){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UISearchForm.msg.no-text-to-search", null)) ;
return ;
}
try {
EventQuery query = new EventQuery() ;
//query.setQueryType(Query.SQL) ;
if(! CalendarUtils.isEmpty(text)) query.setText(CalendarUtils.encodeJCRText(text)) ;
query.setEventType(uiForm.getUIFormSelectBox(UIAdvancedSearchForm.TYPE).getValue()) ;
if(uiForm.isSearchTask()) query.setState(uiForm.getTaskState()) ;
String calendarId = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.CALENDAR).getValue() ;
UICalendars uiCalendars = uiForm.getAncestorOfType(UICalendarPortlet.class).findFirstComponentOfType(UICalendars.class);
List<String> checkedCals = uiCalendars.getCheckedCalendars() ;
if(calendarId != null && calendarId.trim().length() > 0){
try {
query.setCalendarId(new String[]{calendarId.split(CalendarUtils.COLON)[1].trim()}) ;
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Fail to set calendar id", e);
}
}
//if (!checkedCals.contains(calendarId)) query.setCalendarId(new String[]{"null"}) ;
}
String categoryId = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.CATEGORY).getValue() ;
if(categoryId != null && categoryId.trim().length() > 0) query.setCategoryId(new String[]{categoryId}) ;
java.util.Calendar cal = CalendarUtils.getInstanceOfCurrentCalendar() ;
if(fromDate != null && toDate != null) {
cal.setTime(fromDate);
query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
cal.setTime(toDate) ;
query.setToDate(CalendarUtils.getEndDay(cal)) ;
} else if (fromDate !=null) {
cal.setTime(fromDate) ;
query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
//query.setToDate(CalendarUtils.getEndDay(cal)) ;
} else if (toDate !=null) {
cal.setTime(toDate) ;
//query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
query.setToDate(CalendarUtils.getEndDay(cal)) ;
}
String priority = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.PRIORITY).getValue() ;
if(priority != null && priority.trim().length() > 0) query.setPriority(priority) ;
UICalendarPortlet calendarPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class) ;
UICalendarViewContainer calendarViewContainer =
calendarPortlet.findFirstComponentOfType(UICalendarViewContainer.class) ;
String currentView = calendarViewContainer.getRenderedChild().getId() ;
if(calendarViewContainer.getRenderedChild() instanceof UIWeekView) {
if(((UIWeekView)calendarViewContainer.getRenderedChild()).isShowCustomView()) currentView = UICalendarViewContainer.WORKING_VIEW;
}
calendarViewContainer.initView(UICalendarViewContainer.LIST_VIEW) ;
UIListView uiListView = calendarViewContainer.findFirstComponentOfType(UIListView.class) ;
// CS-3610
uiListView.setViewType(UICalendarView.TYPE_BOTH);
uiListView.setSortedField(UIListView.EVENT_START);
uiListView.setIsAscending(false);
calendarPortlet.cancelAction();
if (query.getCalendarId() == null) {
List<String> calendarIds = new ArrayList<String>() ;
for (org.exoplatform.calendar.service.Calendar calendar : uiCalendars.getAllPrivateCalendars())
if (checkedCals.contains(calendar.getId())) calendarIds.add(calendar.getId());
for (org.exoplatform.calendar.service.Calendar calendar : uiCalendars.getAllPublicCalendars())
if (checkedCals.contains(calendar.getId())) calendarIds.add(calendar.getId());
GroupCalendarData shareClas = uiCalendars.getSharedCalendars();
if (shareClas != null)
for (org.exoplatform.calendar.service.Calendar calendar : shareClas.getCalendars())
if (checkedCals.contains(calendar.getId())) {
calendarIds.add(calendar.getId());
}
if (calendarIds.size() > 0)
query.setCalendarId(calendarIds.toArray(new String[] {}));
else {
query.setCalendarId(new String[] {"null"});
}
}
query.setOrderBy(new String[] { Utils.EXO_FROM_DATE_TIME });
query.setOrderType(Utils.DESCENDING);
uiListView.setDisplaySearchResult(true) ;
List<CalendarEvent> allEvents = uiListView.getAllEvents(query);
uiListView.update(new EventPageList(allEvents,10));
calendarViewContainer.setRenderedChild(UICalendarViewContainer.LIST_VIEW) ;
if(!uiListView.isDisplaySearchResult()) uiListView.setLastViewId(currentView) ;
uiListView.setSelectedEvent(null) ;
uiListView.setLastUpdatedEventId(null) ;
calendarViewContainer.findFirstComponentOfType(UIPreview.class).setEvent(null) ;
UIActionBar uiActionBar = calendarPortlet.findFirstComponentOfType(UIActionBar.class) ;
uiActionBar.setCurrentView(UICalendarViewContainer.LIST_VIEW) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiActionBar) ;
event.getRequestContext().addUIComponentToUpdateByAjax(calendarViewContainer) ;
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Exception in method execute of class SearchActionListener", e);
}
return ;
}
}
| public void execute(Event<UIAdvancedSearchForm> event) throws Exception {
UIAdvancedSearchForm uiForm = event.getSource() ;
String fromDateValue = uiForm.getFromDateValue();
Date fromDate = uiForm.getFromDate();
Date toDate = uiForm.getToDate();
if(!CalendarUtils.isEmpty(fromDateValue) && fromDate == null){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.from-date-time-invalid", null)) ;
return ;
}
if(!CalendarUtils.isEmpty(uiForm.getToDateValue()) && uiForm.getToDate() == null) {
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.to-date-time-invalid", null)) ;
return ;
}
if(fromDate != null && toDate != null) {
if(fromDate.after(toDate)){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UIAdvancedSearchForm.msg.date-time-invalid", null)) ;
return ;
}
}
String text = uiForm.getUIStringInput(UIAdvancedSearchForm.TEXT).getValue() ;
if(!uiForm.isValidate()){
event.getRequestContext().getUIApplication().addMessage(new ApplicationMessage("UISearchForm.msg.no-text-to-search", null)) ;
return ;
}
try {
EventQuery query = new EventQuery() ;
//query.setQueryType(Query.SQL) ;
if(! CalendarUtils.isEmpty(text)) query.setText(CalendarUtils.encodeJCRText(text)) ;
query.setEventType(uiForm.getUIFormSelectBox(UIAdvancedSearchForm.TYPE).getValue()) ;
if(uiForm.isSearchTask()) query.setState(uiForm.getTaskState()) ;
String calendarId = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.CALENDAR).getValue() ;
UICalendars uiCalendars = uiForm.getAncestorOfType(UICalendarPortlet.class).findFirstComponentOfType(UICalendars.class);
List<String> checkedCals = uiCalendars.getCheckedCalendars() ;
if(calendarId != null && calendarId.trim().length() > 0){
try {
query.setCalendarId(new String[]{calendarId.split(CalendarUtils.COLON)[1].trim()}) ;
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Fail to set calendar id", e);
}
}
//if (!checkedCals.contains(calendarId)) query.setCalendarId(new String[]{"null"}) ;
}
String categoryId = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.CATEGORY).getValue() ;
if(categoryId != null && categoryId.trim().length() > 0) query.setCategoryId(new String[]{categoryId}) ;
java.util.Calendar cal = CalendarUtils.getInstanceOfCurrentCalendar() ;
if(fromDate != null && toDate != null) {
cal.setTime(fromDate);
query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
cal.setTime(toDate) ;
query.setToDate(CalendarUtils.getEndDay(cal)) ;
} else if (fromDate !=null) {
cal.setTime(fromDate) ;
query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
//query.setToDate(CalendarUtils.getEndDay(cal)) ;
} else if (toDate !=null) {
cal.setTime(toDate) ;
//query.setFromDate(CalendarUtils.getBeginDay(cal)) ;
query.setToDate(CalendarUtils.getEndDay(cal)) ;
}
String priority = uiForm.getUIFormSelectBox(UIAdvancedSearchForm.PRIORITY).getValue() ;
if(priority != null && priority.trim().length() > 0) query.setPriority(priority) ;
UICalendarPortlet calendarPortlet = uiForm.getAncestorOfType(UICalendarPortlet.class) ;
UICalendarViewContainer calendarViewContainer =
calendarPortlet.findFirstComponentOfType(UICalendarViewContainer.class) ;
String currentView = calendarViewContainer.getRenderedChild().getId() ;
if(calendarViewContainer.getRenderedChild() instanceof UIWeekView) {
if(((UIWeekView)calendarViewContainer.getRenderedChild()).isShowCustomView()) currentView = UICalendarViewContainer.WORKING_VIEW;
}
calendarViewContainer.initView(UICalendarViewContainer.LIST_VIEW) ;
UIListView uiListView = calendarViewContainer.findFirstComponentOfType(UIListView.class) ;
// CS-3610
uiListView.setViewType(UICalendarView.TYPE_BOTH);
uiListView.setSortedField(UIListView.EVENT_START);
uiListView.setIsAscending(false);
calendarPortlet.cancelAction();
if (query.getCalendarId() == null) {
List<String> calendarIds = new ArrayList<String>() ;
for (org.exoplatform.calendar.service.Calendar calendar : uiCalendars.getAllPrivateCalendars())
if (checkedCals.contains(calendar.getId())) calendarIds.add(calendar.getId());
for (org.exoplatform.calendar.service.Calendar calendar : uiCalendars.getAllPublicCalendars())
if (checkedCals.contains(calendar.getId())) calendarIds.add(calendar.getId());
GroupCalendarData shareClas = uiCalendars.getSharedCalendars();
if (shareClas != null)
for (org.exoplatform.calendar.service.Calendar calendar : shareClas.getCalendars())
if (checkedCals.contains(calendar.getId())) {
calendarIds.add(calendar.getId());
}
if (calendarIds.size() > 0)
query.setCalendarId(calendarIds.toArray(new String[] {}));
else {
query.setCalendarId(new String[] {"null"});
}
}
query.setOrderBy(new String[] { Utils.EXO_FROM_DATE_TIME });
query.setOrderType(Utils.DESCENDING);
uiListView.setEventQuery(query);
uiListView.setDisplaySearchResult(true) ;
List<CalendarEvent> allEvents = uiListView.getAllEvents(query);
uiListView.update(new EventPageList(allEvents,10));
calendarViewContainer.setRenderedChild(UICalendarViewContainer.LIST_VIEW) ;
if(!uiListView.isDisplaySearchResult()) uiListView.setLastViewId(currentView) ;
uiListView.setSelectedEvent(null) ;
uiListView.setLastUpdatedEventId(null) ;
calendarViewContainer.findFirstComponentOfType(UIPreview.class).setEvent(null) ;
UIActionBar uiActionBar = calendarPortlet.findFirstComponentOfType(UIActionBar.class) ;
uiActionBar.setCurrentView(UICalendarViewContainer.LIST_VIEW) ;
event.getRequestContext().addUIComponentToUpdateByAjax(uiActionBar) ;
event.getRequestContext().addUIComponentToUpdateByAjax(calendarViewContainer) ;
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Exception in method execute of class SearchActionListener", e);
}
return ;
}
}
|
diff --git a/src/replicatorg/app/ui/modeling/MoveTool.java b/src/replicatorg/app/ui/modeling/MoveTool.java
index c896a5a0..7dc435f0 100644
--- a/src/replicatorg/app/ui/modeling/MoveTool.java
+++ b/src/replicatorg/app/ui/modeling/MoveTool.java
@@ -1,168 +1,172 @@
package replicatorg.app.ui.modeling;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.media.j3d.Transform3D;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFormattedTextField;
import javax.swing.JPanel;
import javax.vecmath.Vector3d;
import net.miginfocom.swing.MigLayout;
import replicatorg.app.Base;
import replicatorg.app.ui.modeling.PreviewPanel.DragMode;
public class MoveTool extends Tool {
public MoveTool(ToolPanel parent) {
super(parent);
}
Transform3D vt;
public Icon getButtonIcon() {
return null;
}
public String getButtonName() {
return "Move";
}
JCheckBox lockZ;
JFormattedTextField transX, transY, transZ;
public JPanel getControls() {
JPanel p = new JPanel(new MigLayout("fillx,filly,gap 0"));
JButton centerButton = createToolButton("Center","images/center-object.png");
centerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
parent.getModel().center();
}
});
p.add(centerButton,"growx,wrap,spanx");
JButton lowerButton = createToolButton("Put on platform","images/center-object.png");
lowerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
parent.getModel().putOnPlatform();
}
});
p.add(lowerButton,"growx,wrap,spanx");
transX = new JFormattedTextField(Base.getLocalFormat());
Dimension d = transX.getPreferredSize();
d.width = 800;
transX.setPreferredSize(d);
transY = new JFormattedTextField(Base.getLocalFormat());
transZ = new JFormattedTextField(Base.getLocalFormat());
transX.setValue(10);
transY.setValue(10);
transZ.setValue(10);
JButton transXplus = new JButton("X+");
JButton transYplus = new JButton("Y+");
JButton transZplus = new JButton("Z+");
JButton transXminus = new JButton("X-");
JButton transYminus = new JButton("Y-");
JButton transZminus = new JButton("Z-");
p.add(transXminus);
p.add(transX,"growx");
p.add(transXplus,"wrap");
p.add(transYminus);
p.add(transY,"growx");
p.add(transYplus,"wrap");
p.add(transZminus);
p.add(transZ,"growx");
p.add(transZplus,"wrap");
transXplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transXval = ((Number)transX.getValue()).doubleValue();
parent.getModel().translateObject(transXval, 0, 0);
}
});
transXminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transXval = ((Number)transX.getValue()).doubleValue();
parent.getModel().translateObject(-transXval, 0, 0);
}
});
transYplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transYval = ((Number)transY.getValue()).doubleValue();
parent.getModel().translateObject(0, transYval, 0);
}
});
transYminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transYval = ((Number)transY.getValue()).doubleValue();
parent.getModel().translateObject(0, -transYval, 0);
}
});
transZplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
+ if(!lockZ.isSelected()){
double transZval = ((Number)transZ.getValue()).doubleValue();
parent.getModel().translateObject(0, 0, transZval);
+ }
}
});
transZminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
+ if(!lockZ.isSelected()){
double transZval = ((Number)transZ.getValue()).doubleValue();
parent.getModel().translateObject(0, 0, -transZval);
+ }
}
});
lockZ = new JCheckBox("Lock height");
p.add(lockZ,"growx,wrap,spanx");
return p;
}
public String getInstructions() {
return Base.isMacOS()?
"<html><body>Drag to move object<br>Shift-drag to rotate view<br>Mouse wheel to zoom</body></html>":
"<html><body>Left drag to move object<br>Right drag to rotate view<br>Mouse wheel to zoom</body></html>";
}
public String getTitle() {
return "Move Object";
}
public void mouseDragged(MouseEvent e) {
if (startPoint == null) return;
Point p = e.getPoint();
DragMode mode = DragMode.NONE;
if (Base.isMacOS()) {
if (button == MouseEvent.BUTTON1 && !e.isShiftDown()) { mode = DragMode.TRANSLATE_OBJECT; }
} else {
if (button == MouseEvent.BUTTON1) { mode = DragMode.TRANSLATE_OBJECT; }
}
double xd = (double)(p.x - startPoint.x);
double yd = -(double)(p.y - startPoint.y);
switch (mode) {
case NONE:
super.mouseDragged(e);
break;
case TRANSLATE_OBJECT:
doTranslate(xd,yd);
break;
}
startPoint = p;
}
public void mousePressed(MouseEvent e) {
// Set up view transform
vt = parent.preview.getViewTransform();
super.mousePressed(e);
}
void doTranslate(double deltaX, double deltaY) {
Vector3d v = new Vector3d(deltaX,deltaY,0d);
vt.transform(v);
if (lockZ.isSelected()) { v.z = 0d; }
parent.getModel().translateObject(v.x,v.y,v.z);
}
}
| false | true | public JPanel getControls() {
JPanel p = new JPanel(new MigLayout("fillx,filly,gap 0"));
JButton centerButton = createToolButton("Center","images/center-object.png");
centerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
parent.getModel().center();
}
});
p.add(centerButton,"growx,wrap,spanx");
JButton lowerButton = createToolButton("Put on platform","images/center-object.png");
lowerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
parent.getModel().putOnPlatform();
}
});
p.add(lowerButton,"growx,wrap,spanx");
transX = new JFormattedTextField(Base.getLocalFormat());
Dimension d = transX.getPreferredSize();
d.width = 800;
transX.setPreferredSize(d);
transY = new JFormattedTextField(Base.getLocalFormat());
transZ = new JFormattedTextField(Base.getLocalFormat());
transX.setValue(10);
transY.setValue(10);
transZ.setValue(10);
JButton transXplus = new JButton("X+");
JButton transYplus = new JButton("Y+");
JButton transZplus = new JButton("Z+");
JButton transXminus = new JButton("X-");
JButton transYminus = new JButton("Y-");
JButton transZminus = new JButton("Z-");
p.add(transXminus);
p.add(transX,"growx");
p.add(transXplus,"wrap");
p.add(transYminus);
p.add(transY,"growx");
p.add(transYplus,"wrap");
p.add(transZminus);
p.add(transZ,"growx");
p.add(transZplus,"wrap");
transXplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transXval = ((Number)transX.getValue()).doubleValue();
parent.getModel().translateObject(transXval, 0, 0);
}
});
transXminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transXval = ((Number)transX.getValue()).doubleValue();
parent.getModel().translateObject(-transXval, 0, 0);
}
});
transYplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transYval = ((Number)transY.getValue()).doubleValue();
parent.getModel().translateObject(0, transYval, 0);
}
});
transYminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transYval = ((Number)transY.getValue()).doubleValue();
parent.getModel().translateObject(0, -transYval, 0);
}
});
transZplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transZval = ((Number)transZ.getValue()).doubleValue();
parent.getModel().translateObject(0, 0, transZval);
}
});
transZminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transZval = ((Number)transZ.getValue()).doubleValue();
parent.getModel().translateObject(0, 0, -transZval);
}
});
lockZ = new JCheckBox("Lock height");
p.add(lockZ,"growx,wrap,spanx");
return p;
}
| public JPanel getControls() {
JPanel p = new JPanel(new MigLayout("fillx,filly,gap 0"));
JButton centerButton = createToolButton("Center","images/center-object.png");
centerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
parent.getModel().center();
}
});
p.add(centerButton,"growx,wrap,spanx");
JButton lowerButton = createToolButton("Put on platform","images/center-object.png");
lowerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
parent.getModel().putOnPlatform();
}
});
p.add(lowerButton,"growx,wrap,spanx");
transX = new JFormattedTextField(Base.getLocalFormat());
Dimension d = transX.getPreferredSize();
d.width = 800;
transX.setPreferredSize(d);
transY = new JFormattedTextField(Base.getLocalFormat());
transZ = new JFormattedTextField(Base.getLocalFormat());
transX.setValue(10);
transY.setValue(10);
transZ.setValue(10);
JButton transXplus = new JButton("X+");
JButton transYplus = new JButton("Y+");
JButton transZplus = new JButton("Z+");
JButton transXminus = new JButton("X-");
JButton transYminus = new JButton("Y-");
JButton transZminus = new JButton("Z-");
p.add(transXminus);
p.add(transX,"growx");
p.add(transXplus,"wrap");
p.add(transYminus);
p.add(transY,"growx");
p.add(transYplus,"wrap");
p.add(transZminus);
p.add(transZ,"growx");
p.add(transZplus,"wrap");
transXplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transXval = ((Number)transX.getValue()).doubleValue();
parent.getModel().translateObject(transXval, 0, 0);
}
});
transXminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transXval = ((Number)transX.getValue()).doubleValue();
parent.getModel().translateObject(-transXval, 0, 0);
}
});
transYplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transYval = ((Number)transY.getValue()).doubleValue();
parent.getModel().translateObject(0, transYval, 0);
}
});
transYminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double transYval = ((Number)transY.getValue()).doubleValue();
parent.getModel().translateObject(0, -transYval, 0);
}
});
transZplus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(!lockZ.isSelected()){
double transZval = ((Number)transZ.getValue()).doubleValue();
parent.getModel().translateObject(0, 0, transZval);
}
}
});
transZminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(!lockZ.isSelected()){
double transZval = ((Number)transZ.getValue()).doubleValue();
parent.getModel().translateObject(0, 0, -transZval);
}
}
});
lockZ = new JCheckBox("Lock height");
p.add(lockZ,"growx,wrap,spanx");
return p;
}
|
diff --git a/src/main/java/hex/DLSM.java b/src/main/java/hex/DLSM.java
index 8d85a39ae..3bc8e4f85 100644
--- a/src/main/java/hex/DLSM.java
+++ b/src/main/java/hex/DLSM.java
@@ -1,368 +1,369 @@
package hex;
import hex.DGLM.Cholesky;
import hex.DGLM.Gram;
import java.util.Arrays;
import water.Iced;
import water.MemoryManager;
import com.google.gson.JsonObject;
/**
* Distributed least squares solvers
* @author tomasnykodym
*
*/
public class DLSM {
public enum LSMSolverType {
AUTO, // AUTO: (len(beta) < 1000)?ADMM:GenGradient
ADMM,
GenGradient
}
public static abstract class LSMSolver extends Iced {
public double _lambda;
public final double _alpha;
public LSMSolver(double lambda, double alpha){
_lambda = lambda;
_alpha = alpha;
}
/**
* @param xx - gram matrix. gaussian: X'X, binomial:(1/4)X'X
* @param xy - guassian: -X'y binomial: -(1/4)X'(XB + (y-p)/(p*1-p))
* @param yy - <y,y>/2
* @param beta - previous vector of coefficients, will be modified/destroyed
* @param newBeta - resulting vector of coefficients
* @return true if converged
*
*/
public abstract boolean solve(Gram gram, double [] newBeta);
public abstract JsonObject toJson();
protected boolean _converged;
public final boolean converged(){return _converged;}
public static class LSMSolverException extends RuntimeException {
public LSMSolverException(String msg){super(msg);}
}
public abstract String name();
}
private static double shrinkage(double x, double kappa) {
return Math.max(0, x - kappa) - Math.max(0, -x - kappa);
}
static final double[] mul(double[][] X, double[] y, double[] z) {
final int M = X.length;
final int N = y.length;
for( int i = 0; i < M; ++i ) {
z[i] = X[i][0] * y[0];
for( int j = 1; j < N; ++j )
z[i] += X[i][j] * y[j];
}
return z;
}
static final double[] mul(double[] x, double a, double[] z) {
for( int i = 0; i < x.length; ++i )
z[i] = a * x[i];
return z;
}
static final double[] plus(double[] x, double[] y, double[] z) {
for( int i = 0; i < x.length; ++i )
z[i] = x[i] + y[i];
return z;
}
static final double[] minus(double[] x, double[] y, double[] z) {
for( int i = 0; i < x.length; ++i )
z[i] = x[i] - y[i];
return z;
}
static final double[] shrink(double[] x, double[] z, double kappa) {
for( int i = 0; i < x.length - 1; ++i )
z[i] = shrinkage(x[i], kappa);
z[x.length - 1] = x[x.length - 1]; // do not penalize intercept!
return z;
}
public static final class ADMMSolver extends LSMSolver {
public static final double DEFAULT_LAMBDA = 1e-5;
public static final double DEFAULT_ALPHA = 0.5;
public double _orlx = 1;//1.4; // over relaxation param
public double _rho = 1e-3;
public boolean normalize() {
return _lambda != 0;
}
public ADMMSolver (double lambda, double alpha) {
super(lambda,alpha);
}
public JsonObject toJson(){
JsonObject res = new JsonObject();
res.addProperty("lambda",_lambda);
res.addProperty("alpha",_alpha);
return res;
}
public static class NonSPDMatrixException extends LSMSolverException {
public NonSPDMatrixException(){
super("Matrix is not SPD, can't solve without regularization");
}
}
@Override
public boolean solve(Gram gram, double[] z) {
final int N = gram._xy.length;
Arrays.fill(z, 0);
if(_lambda>0)gram.addDiag(_lambda*(1-_alpha)*0.5 + _rho);
int attempts = 0;
Cholesky chol = gram.cholesky(null);
double rhoAdd = 0;
while(!chol._isSPD && attempts < 10){
double rhoIncrement = _rho*(1<< ++attempts);
gram.addDiag(rhoIncrement); // try to add L2 penalty to make the Gram issp
rhoAdd += rhoIncrement;
+ gram.cholesky(chol);
}
if(!chol._isSPD) throw new NonSPDMatrixException();
_rho += rhoAdd;
if(_alpha == 0 || _lambda == 0){ // no l1 penalty
System.arraycopy(gram._xy, 0, z, 0, gram._xy.length);
chol.solve(z);
return _converged = true;
}
final double ABSTOL = Math.sqrt(N) * 1e-4;
final double RELTOL = 1e-2;
double[] u = MemoryManager.malloc8d(N);
double [] xyPrime = gram._xy.clone();
double kappa = _lambda*_alpha / _rho;
for( int i = 0; i < 1000; ++i ) {
// first compute the x update
// add rho*(z-u) to A'*y
for( int j = 0; j < N-1; ++j )xyPrime[j] = gram._xy[j] + _rho * (z[j] - u[j]);
xyPrime[N-1] = gram._xy[N-1];
// updated x
chol.solve(xyPrime);
// vars to be used for stopping criteria
double x_norm = 0;
double z_norm = 0;
double u_norm = 0;
double r_norm = 0;
double s_norm = 0;
double eps_pri = 0; // epsilon primal
double eps_dual = 0;
// compute u and z update
for( int j = 0; j < N-1; ++j ) {
double x_hat = xyPrime[j];
x_norm += x_hat * x_hat;
x_hat = x_hat * _orlx + (1 - _orlx) * z[j];
double zold = z[j];
z[j] = shrinkage(x_hat + u[j], kappa);
z_norm += z[j] * z[j];
s_norm += (z[j] - zold) * (z[j] - zold);
r_norm += (xyPrime[j] - z[j]) * (xyPrime[j] - z[j]);
u[j] += x_hat - z[j];
u_norm += u[j] * u[j];
}
z[N-1] = xyPrime[N-1];
// compute variables used for stopping criterium
r_norm = Math.sqrt(r_norm);
s_norm = _rho * Math.sqrt(s_norm);
eps_pri = ABSTOL + RELTOL * Math.sqrt(Math.max(x_norm, z_norm));
eps_dual = ABSTOL + _rho * RELTOL * Math.sqrt(u_norm);
if( r_norm < eps_pri && s_norm < eps_dual )
return _converged = true;
}
return false;
}
@Override
public String name() {
return "ADMM";
}
}
/**
* Generalized gradient solver for solving LSM problem with combination of L1 and L2 penalty.
*
* @author tomasnykodym
*
*/
public static final class GeneralizedGradientSolver extends LSMSolver {
public final double _kappa; // _lambda*_alpha
public final double _betaEps;
private double[] _beta;
private double[] _betaGradient;
double _objVal;
double _t = 1.0;
int _iterations = 0;
public static final int MAX_ITER = 1000;
public static final double EPS = 1e-5;
public GeneralizedGradientSolver(double lambda, double alpha) {
this(lambda,alpha,1e-5);
}
public GeneralizedGradientSolver(double lambda, double alpha, double betaEps) {
super(lambda,alpha);
_kappa = _lambda * _alpha;
_betaEps = betaEps;
}
/**
* Compute least squares objective function value: g(beta) = 0.5*(y - X*b)'*(y
* - X*b) = 0.5*y'y - (X'y)'*b + 0.5*b'*X'X*b)
* @param xx: X'X
* @param xy: -X'y
* @param yy: 0.5*y'y
* @param beta: b (vector of coefficients)
* @return 0.5*(y - X*b)'*(y - X*b)
*/
private double g_beta(double[][] xx, double[] xy, double yy, double[] beta) {
final int n = xy.length;
double res = yy;
for( int i = 0; i < n; ++i ) {
double x = 0;
for( int j = 0; j < n; ++j ){
x += xx[i][j] * beta[j];
}
res += (0.5*x + xy[i]) * beta[i];
}
if(!(res >= 0))
throw new LSMSolverException("Generalized Gradient: Can not solved this problem.");
return res;
}
/*
* Compute beta gradient.
*/
private void g_beta_gradient(double[][] xx, double[] xy, double t) {
mul(xx, _beta, _betaGradient);
plus(xy, _betaGradient, _betaGradient);
mul(_betaGradient, -t, _betaGradient);
}
/**
* Compute new beta according to:
* B = B -t*G_t(B), where G(t) = (B - S(B-t*gradient(B),lambda,t)
* @param newBeta: vector to be filled with the new value of beta
* @param t: step size
* @return newBeta
*/
private double[] beta_update(double[] newBeta, double t) {
// S(b - t*g_beta_gradient(b),_kappa*t)/(1+ (1 - alpha)*0.5*t)
double div = 1 / (1 + ((1 - _alpha) * 0.5 * _lambda * t));
shrink(plus(_beta, _betaGradient, newBeta), newBeta, _kappa*t);
for(int i = 0; i < newBeta.length-1; ++i)
newBeta[i] *= div;
return newBeta;
}
/**
* Compute right hand side of Armijo rule updated for generalized gradient.
* Used as a threshold for backtracking (finding optimal step t).
*
* @param gbeta
* @param newBeta
* @param t
* @return
*/
private double backtrack_cond_rs(double gbeta, double[] newBeta, double t) {
double norm = 0;
double zg = 0;
double t_inv = 1.0 / t;
for( int i = 0; i < _beta.length; ++i ) {
double diff = _beta[i] - newBeta[i];
norm += diff * diff;
zg += _betaGradient[i] * diff;
}
return gbeta + (norm * 0.5 + zg) * t_inv;
}
double l1norm(double[] v) {
double res = Math.abs(v[0]);
for( int i = 1; i < v.length - 1; ++i )
res += Math.abs(v[i]);
return res;
}
/**
* @param xx: gram matrix. gaussian: X'X, binomial:(1/4)X'X
* @param xy: -X'y (LSM) l or -(1/4)X'(XB + (y-p)/(p*1-p))(IRLSM
* @param yy: 0.5*y'*y gaussian, 0.25*z'*z IRLSM
* @param beta: previous vector of coefficients, will be modified/destroyed
* @param newBeta: resulting vector of coefficients
* @return true if converged
*/
@Override
public boolean solve(Gram gram, double[] newBeta) {
double [][] xx = gram.getXX();
double [] xy = gram._xy;
double yy = gram._yy;
if(_beta == null || _beta.length != newBeta.length){
_beta = MemoryManager.malloc8d(newBeta.length);
_betaGradient = MemoryManager.malloc8d(newBeta.length);
}
int i = 0;
_converged = false;
_iterations = 0;
_objVal = Double.MAX_VALUE;
mul(xy, -1, xy);
while( !_converged && _iterations != MAX_ITER ) {
double gbeta = g_beta(xx, xy, yy, _beta);
// use backtracking to find proper step size t
double t = _t;
for( int k = 0; k < 100; ++k ) {
g_beta_gradient(xx, xy, t);
newBeta = beta_update(newBeta, t);
if( g_beta(xx, xy, yy, newBeta) <= backtrack_cond_rs(gbeta, newBeta, t) ) {
if( _t > t ) {
_t = t;
break;
}
t = 1.25 * t;
} else {
_t = t;
t = 0.8 * t;
}
}
// compare objective function values between the runs
double newObjVal = g_beta(xx, xy, yy, newBeta) + _kappa * l1norm(newBeta);
System.arraycopy(newBeta, 0, _beta, 0, _beta.length);
_converged = (1 - newObjVal / _objVal) <= EPS;
_objVal = newObjVal;
_iterations = ++i;
}
// return xy back to its original state
mul(xy, -1, xy);
return _converged;
}
@Override
public JsonObject toJson() {
JsonObject json = new JsonObject();
return json;
}
@Override
public String name() {
return "GeneralizedGradient";
}
}
}
| true | true | public boolean solve(Gram gram, double[] z) {
final int N = gram._xy.length;
Arrays.fill(z, 0);
if(_lambda>0)gram.addDiag(_lambda*(1-_alpha)*0.5 + _rho);
int attempts = 0;
Cholesky chol = gram.cholesky(null);
double rhoAdd = 0;
while(!chol._isSPD && attempts < 10){
double rhoIncrement = _rho*(1<< ++attempts);
gram.addDiag(rhoIncrement); // try to add L2 penalty to make the Gram issp
rhoAdd += rhoIncrement;
}
if(!chol._isSPD) throw new NonSPDMatrixException();
_rho += rhoAdd;
if(_alpha == 0 || _lambda == 0){ // no l1 penalty
System.arraycopy(gram._xy, 0, z, 0, gram._xy.length);
chol.solve(z);
return _converged = true;
}
final double ABSTOL = Math.sqrt(N) * 1e-4;
final double RELTOL = 1e-2;
double[] u = MemoryManager.malloc8d(N);
double [] xyPrime = gram._xy.clone();
double kappa = _lambda*_alpha / _rho;
for( int i = 0; i < 1000; ++i ) {
// first compute the x update
// add rho*(z-u) to A'*y
for( int j = 0; j < N-1; ++j )xyPrime[j] = gram._xy[j] + _rho * (z[j] - u[j]);
xyPrime[N-1] = gram._xy[N-1];
// updated x
chol.solve(xyPrime);
// vars to be used for stopping criteria
double x_norm = 0;
double z_norm = 0;
double u_norm = 0;
double r_norm = 0;
double s_norm = 0;
double eps_pri = 0; // epsilon primal
double eps_dual = 0;
// compute u and z update
for( int j = 0; j < N-1; ++j ) {
double x_hat = xyPrime[j];
x_norm += x_hat * x_hat;
x_hat = x_hat * _orlx + (1 - _orlx) * z[j];
double zold = z[j];
z[j] = shrinkage(x_hat + u[j], kappa);
z_norm += z[j] * z[j];
s_norm += (z[j] - zold) * (z[j] - zold);
r_norm += (xyPrime[j] - z[j]) * (xyPrime[j] - z[j]);
u[j] += x_hat - z[j];
u_norm += u[j] * u[j];
}
z[N-1] = xyPrime[N-1];
// compute variables used for stopping criterium
r_norm = Math.sqrt(r_norm);
s_norm = _rho * Math.sqrt(s_norm);
eps_pri = ABSTOL + RELTOL * Math.sqrt(Math.max(x_norm, z_norm));
eps_dual = ABSTOL + _rho * RELTOL * Math.sqrt(u_norm);
if( r_norm < eps_pri && s_norm < eps_dual )
return _converged = true;
}
return false;
}
| public boolean solve(Gram gram, double[] z) {
final int N = gram._xy.length;
Arrays.fill(z, 0);
if(_lambda>0)gram.addDiag(_lambda*(1-_alpha)*0.5 + _rho);
int attempts = 0;
Cholesky chol = gram.cholesky(null);
double rhoAdd = 0;
while(!chol._isSPD && attempts < 10){
double rhoIncrement = _rho*(1<< ++attempts);
gram.addDiag(rhoIncrement); // try to add L2 penalty to make the Gram issp
rhoAdd += rhoIncrement;
gram.cholesky(chol);
}
if(!chol._isSPD) throw new NonSPDMatrixException();
_rho += rhoAdd;
if(_alpha == 0 || _lambda == 0){ // no l1 penalty
System.arraycopy(gram._xy, 0, z, 0, gram._xy.length);
chol.solve(z);
return _converged = true;
}
final double ABSTOL = Math.sqrt(N) * 1e-4;
final double RELTOL = 1e-2;
double[] u = MemoryManager.malloc8d(N);
double [] xyPrime = gram._xy.clone();
double kappa = _lambda*_alpha / _rho;
for( int i = 0; i < 1000; ++i ) {
// first compute the x update
// add rho*(z-u) to A'*y
for( int j = 0; j < N-1; ++j )xyPrime[j] = gram._xy[j] + _rho * (z[j] - u[j]);
xyPrime[N-1] = gram._xy[N-1];
// updated x
chol.solve(xyPrime);
// vars to be used for stopping criteria
double x_norm = 0;
double z_norm = 0;
double u_norm = 0;
double r_norm = 0;
double s_norm = 0;
double eps_pri = 0; // epsilon primal
double eps_dual = 0;
// compute u and z update
for( int j = 0; j < N-1; ++j ) {
double x_hat = xyPrime[j];
x_norm += x_hat * x_hat;
x_hat = x_hat * _orlx + (1 - _orlx) * z[j];
double zold = z[j];
z[j] = shrinkage(x_hat + u[j], kappa);
z_norm += z[j] * z[j];
s_norm += (z[j] - zold) * (z[j] - zold);
r_norm += (xyPrime[j] - z[j]) * (xyPrime[j] - z[j]);
u[j] += x_hat - z[j];
u_norm += u[j] * u[j];
}
z[N-1] = xyPrime[N-1];
// compute variables used for stopping criterium
r_norm = Math.sqrt(r_norm);
s_norm = _rho * Math.sqrt(s_norm);
eps_pri = ABSTOL + RELTOL * Math.sqrt(Math.max(x_norm, z_norm));
eps_dual = ABSTOL + _rho * RELTOL * Math.sqrt(u_norm);
if( r_norm < eps_pri && s_norm < eps_dual )
return _converged = true;
}
return false;
}
|
diff --git a/src/java/com/omniti/reconnoiter/EventHandler.java b/src/java/com/omniti/reconnoiter/EventHandler.java
index be907ca..3329f4e 100644
--- a/src/java/com/omniti/reconnoiter/EventHandler.java
+++ b/src/java/com/omniti/reconnoiter/EventHandler.java
@@ -1,74 +1,74 @@
package com.omniti.reconnoiter;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.UpdateListener;
import com.omniti.reconnoiter.broker.IMQBroker;
import com.omniti.reconnoiter.event.*;
public class EventHandler {
private EPServiceProvider epService;
private ConcurrentHashMap<UUID, StratconQueryBase> queries;
private IMQBroker broker;
public EventHandler(ConcurrentHashMap<UUID,StratconQueryBase> queries, EPServiceProvider epService, IMQBroker broker) {
this.epService = epService;
this.queries = queries;
this.broker = broker;
}
public void processMessage(String xml) throws Exception {
StratconMessage m = StratconMessage.makeMessage(xml);
if(m == null) {
System.err.println("Can't grok:\n" + xml);
}
if(m instanceof StratconStatement) {
StratconStatement sq = (StratconStatement) m;
if(queries.containsKey(sq.getUUID())) throw (new Exception("Duplicate Query"));
EPStatement statement = epService.getEPAdministrator().createEPL(sq.getExpression());
sq.setStatement(statement);
queries.put(sq.getUUID(), sq);
System.err.println("Creating Statement: " + sq.getUUID());
}
else if(m instanceof StratconQuery) {
StratconQuery sq = (StratconQuery) m;
if(queries.containsKey(sq.getUUID())) throw (new Exception("Duplicate Query"));
EPStatement statement = epService.getEPAdministrator().createEPL(sq.getExpression());
UpdateListener o = broker.getListener(this.epService, sq);
statement.addListener(o);
sq.setStatement(statement);
sq.setListener(o);
queries.put(sq.getUUID(), sq);
System.err.println("Creating Query: " + sq.getUUID());
}
else if(m instanceof StratconQueryStop) {
/* QueryStop stops both queries and statements */
StratconQueryBase sq = queries.get(((StratconQueryStop) m).getUUID());
if(sq != null) {
queries.remove(sq.getUUID());
sq.destroy();
}
}
else if(m instanceof NoitMetricText) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitMetricNumeric) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitCheck) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitStatus) {
epService.getEPRuntime().sendEvent(m);
}
- }
+ }
}
| true | true | public void processMessage(String xml) throws Exception {
StratconMessage m = StratconMessage.makeMessage(xml);
if(m == null) {
System.err.println("Can't grok:\n" + xml);
}
if(m instanceof StratconStatement) {
StratconStatement sq = (StratconStatement) m;
if(queries.containsKey(sq.getUUID())) throw (new Exception("Duplicate Query"));
EPStatement statement = epService.getEPAdministrator().createEPL(sq.getExpression());
sq.setStatement(statement);
queries.put(sq.getUUID(), sq);
System.err.println("Creating Statement: " + sq.getUUID());
}
else if(m instanceof StratconQuery) {
StratconQuery sq = (StratconQuery) m;
if(queries.containsKey(sq.getUUID())) throw (new Exception("Duplicate Query"));
EPStatement statement = epService.getEPAdministrator().createEPL(sq.getExpression());
UpdateListener o = broker.getListener(this.epService, sq);
statement.addListener(o);
sq.setStatement(statement);
sq.setListener(o);
queries.put(sq.getUUID(), sq);
System.err.println("Creating Query: " + sq.getUUID());
}
else if(m instanceof StratconQueryStop) {
/* QueryStop stops both queries and statements */
StratconQueryBase sq = queries.get(((StratconQueryStop) m).getUUID());
if(sq != null) {
queries.remove(sq.getUUID());
sq.destroy();
}
}
else if(m instanceof NoitMetricText) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitMetricNumeric) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitCheck) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitStatus) {
epService.getEPRuntime().sendEvent(m);
}
}
| public void processMessage(String xml) throws Exception {
StratconMessage m = StratconMessage.makeMessage(xml);
if(m == null) {
System.err.println("Can't grok:\n" + xml);
}
if(m instanceof StratconStatement) {
StratconStatement sq = (StratconStatement) m;
if(queries.containsKey(sq.getUUID())) throw (new Exception("Duplicate Query"));
EPStatement statement = epService.getEPAdministrator().createEPL(sq.getExpression());
sq.setStatement(statement);
queries.put(sq.getUUID(), sq);
System.err.println("Creating Statement: " + sq.getUUID());
}
else if(m instanceof StratconQuery) {
StratconQuery sq = (StratconQuery) m;
if(queries.containsKey(sq.getUUID())) throw (new Exception("Duplicate Query"));
EPStatement statement = epService.getEPAdministrator().createEPL(sq.getExpression());
UpdateListener o = broker.getListener(this.epService, sq);
statement.addListener(o);
sq.setStatement(statement);
sq.setListener(o);
queries.put(sq.getUUID(), sq);
System.err.println("Creating Query: " + sq.getUUID());
}
else if(m instanceof StratconQueryStop) {
/* QueryStop stops both queries and statements */
StratconQueryBase sq = queries.get(((StratconQueryStop) m).getUUID());
if(sq != null) {
queries.remove(sq.getUUID());
sq.destroy();
}
}
else if(m instanceof NoitMetricText) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitMetricNumeric) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitCheck) {
epService.getEPRuntime().sendEvent(m);
}
else if(m instanceof NoitStatus) {
epService.getEPRuntime().sendEvent(m);
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.