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/pn-dispatcher/src/main/java/info/papyri/dispatch/browse/facet/StringSearchFacet.java b/pn-dispatcher/src/main/java/info/papyri/dispatch/browse/facet/StringSearchFacet.java
index 95186007..74689a1a 100644
--- a/pn-dispatcher/src/main/java/info/papyri/dispatch/browse/facet/StringSearchFacet.java
+++ b/pn-dispatcher/src/main/java/info/papyri/dispatch/browse/facet/StringSearchFacet.java
@@ -1,980 +1,980 @@
package info.papyri.dispatch.browse.facet;
import info.papyri.dispatch.FileUtils;
import info.papyri.dispatch.browse.SolrField;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
/**
* Replicates the functioning of <code>info.papyri.dispatch.Search</code> in a
* manner compatible with the faceted browse framework and codebase.
*
* Note that although the algorithm used for the search process is intended to
* replicate that defined in <code>info.papyri.dispatch.Search</code> it is implemented
* very differently. The logic for string-handling is all encapsulated in the inner
* SearchConfiguration class, below and more specific documentation is provided there.
*
* @author thill
* @version 2011.08.19
* @see info.papyri.dispatch.Search
*/
public class StringSearchFacet extends Facet{
enum SearchType{ PHRASE, SUBSTRING, LEMMAS, PROXIMITY, WITHIN, USER_DEFINED };
enum SearchTarget{ ALL, METADATA, TEXT, TRANSLATIONS, USER_DEFINED };
enum SearchOption{ NO_CAPS, NO_MARKS };
private HashMap<Integer, SearchConfiguration> searchConfigurations = new HashMap<Integer, SearchConfiguration>();
private static String morphSearch = "morph-search/";
public StringSearchFacet(){
super(SolrField.transcription_ngram_ia, FacetParam.STRING, "String search");
}
@Override
public SolrQuery buildQueryContribution(SolrQuery solrQuery){
Iterator<SearchConfiguration> scit = searchConfigurations.values().iterator();
while(scit.hasNext()){
SearchConfiguration nowConfig = scit.next();
solrQuery.addFilterQuery(nowConfig.getSearchString());
}
return solrQuery;
}
@Override
public String generateWidget() {
StringBuilder html = new StringBuilder("<div class=\"facet-widget\" id=\"text-search-widget\" title=\"");
html.append(getToolTipText());
html.append("\">");
html.append(generateHiddenFields());
// textbox HTML
html.append("<p class=\"ui-corner-all\" id=\"facet-stringsearch-wrapper\">");
html.append("<input type=\"text\" name=\"");
html.append(formName.name());
html.append("\" size=\"50\" maxlength=\"250\" id=\"keyword\"></input>");
html.append("</p>");
// search options control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input type=\"checkbox\" name=\"beta-on\" id=\"beta-on\" value=\"on\"></input>");
html.append("<label for=\"beta-on\" id=\"marks-label\">Convert from betacode as you type</label><br/>");
html.append("<input type=\"checkbox\" name=\"");
html.append(SearchOption.NO_CAPS.name().toLowerCase());
html.append("\" id=\"caps\" value=\"on\" checked></input>");
html.append("<label for=\"caps\" id=\"caps-label\">ignore capitalization</label><br/>");
html.append("<input type=\"checkbox\" name=\"");
html.append(SearchOption.NO_MARKS.name().toLowerCase());
html.append("\" id=\"marks\" value=\"on\" checked></input>");
html.append("<label for=\"marks\" id=\"marks-label\">ignore diacritics/accents</label>");
html.append("</p>");
html.append("</div><!-- closing .stringsearch-section -->");
// search type control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.PHRASE.name().toLowerCase());
html.append("\" id=\"phrase\"/> ");
html.append("<label for=\"phrase\" id=\"phrase-label\">Word/Phrase search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.SUBSTRING.name().toLowerCase());
html.append("\" id=\"substring\" checked/> ");
html.append("<label for=\"substring\" id=\"substring-label\">Substring search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.LEMMAS.name().toLowerCase());
- html.append("\" id=\"lemmas\"/>");
+ html.append("\" id=\"lemmas\"/> ");
html.append("<label for=\"lemmas\" id=\"lemmas-label\">Lemmatized search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.PROXIMITY.name().toLowerCase());
html.append("\" id=\"proximity\"/>");
html.append("<label for=\"proximity\" id=\"proximity-label\"> Proximity: find within</label>");
html.append(" <input type=\"text\" name=\"");
html.append(SearchType.WITHIN.name().toLowerCase());
html.append("\" value=\"10\" id=\"within\" size=\"2\" style=\"width:1.5em\"/> words");
html.append("</p>");
html.append("</div><!-- closing .stringsearch section -->");
// search target control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.TEXT.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-text\" class=\"target\" checked/>");
html.append("<label for=\"");
html.append(SearchTarget.TEXT.name().toLowerCase());
html.append("\" id=\"text-label\">Text</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.METADATA.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-metadata\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.METADATA.name().toLowerCase());
html.append("\" id=\"metadata-label\">Metadata</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.TRANSLATIONS.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-translations\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.TRANSLATIONS.name().toLowerCase());
html.append("\" id=\"translation-label\">Translations</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.ALL.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-all\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.ALL.name().toLowerCase());
html.append("\" id=\"all-label\">All</label>");
html.append("</p>");
html.append("</div><!-- closing .stringsearch-section -->");
html.append("</div><!-- closing .facet-widget -->");
return html.toString();
}
@Override
public Boolean addConstraints(Map<String, String[]> params){
searchConfigurations = pullApartParams(params);
return !searchConfigurations.isEmpty();
}
@Override
String generateHiddenFields(){
StringBuilder html = new StringBuilder();
Iterator<SearchConfiguration> scit = searchConfigurations.values().iterator();
int counter = 1;
while(scit.hasNext()){
String inp = "<input type='hidden' name='";
String v = "' value='";
String c = "'/>";
SearchConfiguration config = scit.next();
html.append(inp);
html.append(formName.name());
html.append(String.valueOf(counter));
html.append(v);
html.append(config.getRawString());
html.append(c);
html.append(inp);
html.append("target");
html.append(String.valueOf(counter));
html.append(v);
html.append(config.getSearchTarget());
html.append(c);
html.append(inp);
html.append("type");
html.append(String.valueOf(counter));
html.append(v);
html.append(config.getSearchType());
html.append(c);
if(config.getSearchType().equals(SearchType.PROXIMITY)){
html.append(inp);
html.append(SearchType.WITHIN.name().toLowerCase());
html.append(String.valueOf(counter));
html.append(v);
html.append(String.valueOf(config.getProximityDistance()));
html.append(c);
}
if(config.getIgnoreCaps()){
html.append(inp);
html.append(SearchOption.NO_CAPS.name().toLowerCase());
html.append(String.valueOf(counter));
html.append(v);
html.append("on");
html.append(c);
}
if(config.getIgnoreMarks()){
html.append(inp);
html.append(SearchOption.NO_MARKS.name().toLowerCase());
html.append(String.valueOf(counter));
html.append(v);
html.append("on");
html.append(c);
}
counter++;
}
return html.toString();
}
HashMap<Integer, SearchConfiguration> pullApartParams(Map<String, String[]> params){
HashMap<Integer, SearchConfiguration> configs = new HashMap<Integer, SearchConfiguration>();
Pattern pattern = Pattern.compile(formName.name() + "([\\d]*)");
Iterator<String> kit = params.keySet().iterator();
while(kit.hasNext()){
String key = kit.next();
Matcher matcher = pattern.matcher(key);
if(matcher.matches()){
String matchSuffix = matcher.group(1);
String keywordGetter = formName.name() + matchSuffix;
String typeGetter = "type" + matchSuffix;
String withinGetter = SearchType.WITHIN.name().toLowerCase() + matchSuffix;
String targetGetter = "target" + matchSuffix;
String capsGetter = SearchOption.NO_CAPS.name().toLowerCase() + matchSuffix;
String marksGetter = SearchOption.NO_MARKS.name().toLowerCase() + matchSuffix;
if(!params.containsKey(typeGetter) || !params.containsKey(targetGetter)) continue;
String keyword = params.get(keywordGetter)[0];
if(keyword == null || "".equals(keyword)) continue;
String rawSearchType = params.get(typeGetter)[0].toUpperCase();
String rawSearchTarget = params.get(targetGetter)[0].toUpperCase();
SearchType ty = null;
SearchTarget trgt = null;
try{
ty = SearchType.valueOf(rawSearchType);
trgt = SearchTarget.valueOf(rawSearchTarget);
} catch(IllegalArgumentException iae){
continue;
}
String[] rawCaps = params.get(capsGetter);
String[] rawMarks = params.get(marksGetter);
String[] rawDistance = params.get(withinGetter);
int distance = rawDistance == null ? 0 : rawDistance[0].matches("\\d+") ? Integer.valueOf(rawDistance[0]) : 0;
Boolean caps = rawCaps == null ? false : "on".equals(rawCaps[0]);
Boolean marks = rawMarks == null ? false : "on".equals(rawMarks[0]);
SearchConfiguration searchConfig = new SearchConfiguration(keyword, matchSuffix.equals("") ? 0 : Integer.valueOf(matchSuffix), trgt, ty, caps, marks, distance);
Integer matchNumber = matchSuffix.equals("") ? 0 : Integer.valueOf(matchSuffix);
configs.put(matchNumber, searchConfig);
}
}
return configs;
}
@Override
public ArrayList<String> getFacetConstraints(String facetParam){
String paramNumber = "0";
Pattern pattern = Pattern.compile("^.+?(\\d+)$");
Matcher matcher = pattern.matcher(facetParam);
if(matcher.matches()){
paramNumber = matcher.group(1);
}
ArrayList<String> constraints = new ArrayList<String>();
constraints.add(paramNumber);
return constraints;
}
@Override
public String getDisplayValue(String facetValue){
Integer k = Integer.valueOf(facetValue);
if(!searchConfigurations.containsKey(k)) return "Facet value not found";
SearchConfiguration config = searchConfigurations.get(k);
String rs = config.getRawString();
Pattern pattern = Pattern.compile(".*identifier:([\\d]+).*");
Matcher matcher = pattern.matcher(rs);
if(matcher.matches()) return getTrismegistosDisplayValue(matcher);
StringBuilder dv = new StringBuilder();
dv.append(rs.replaceAll("\\^", "#"));
dv.append("<br/>");
dv.append("Target: ");
dv.append(config.getSearchTarget().name().toLowerCase().replace("_", "-"));
dv.append("<br/>");
if(config.getIgnoreCaps()) dv.append("No Caps: On<br/>");
if(config.getIgnoreMarks()) dv.append("No Marks: On<br/>");
if(config.getSearchType().equals(SearchType.PROXIMITY)){
dv.append("Within: ");
dv.append(String.valueOf(config.getProximityDistance()));
}
return dv.toString();
}
String getTrismegistosDisplayValue(Matcher matcher){
String tmNumber = matcher.group(1);
StringBuilder tmsb = new StringBuilder();
tmsb.append("Trismegistos Identifier: ");
tmsb.append(tmNumber);
return tmsb.toString();
}
@Override
public String getDisplayName(String param, java.lang.String facetValue){
String paramNumber = "0";
Pattern pattern = Pattern.compile(this.formName.toString() + "(\\d+)$");
Matcher matcher = pattern.matcher(param);
if(matcher.matches()){
paramNumber = matcher.group(1);
}
SearchConfiguration config = searchConfigurations.get(Integer.valueOf(paramNumber));
String searchType = config.getSearchType().name().toLowerCase().replaceAll("_", "-");
String firstCap = searchType.substring(0, 1).toUpperCase();
return firstCap + searchType.substring(1, searchType.length());
}
@Override
public String getAsQueryString(){
if(searchConfigurations.size() < 1) return "";
StringBuilder qs = new StringBuilder();
for(Map.Entry<Integer, SearchConfiguration> entry : searchConfigurations.entrySet()){
Integer paramNumber = entry.getKey();
SearchConfiguration config = entry.getValue();
qs.append(getConfigurationAsQueryString(paramNumber, config));
qs.append("&");
}
String queryString = qs.toString();
queryString = queryString.substring(0, queryString.length() - 1);
return queryString;
}
@Override
public String getAsFilteredQueryString(String filterParam, String filterValue){
// filterValue is index to search configuration
StringBuilder qs = new StringBuilder();
for(Map.Entry<Integer, SearchConfiguration> entry : searchConfigurations.entrySet()){
Integer paramNumber = entry.getKey();
if(!String.valueOf(paramNumber).equals(filterValue)){
SearchConfiguration config = entry.getValue();
qs.append(getConfigurationAsQueryString(paramNumber, config));
qs.append("&");
}
}
String queryString = qs.toString();
if(queryString.endsWith("&")) queryString = queryString.substring(0, queryString.length() - 1);
return queryString;
}
private String getConfigurationAsQueryString(Integer pn, SearchConfiguration config){
String paramNumber = pn == 0 ? "" : String.valueOf(pn);
StringBuilder qs = new StringBuilder();
String kwParam = formName.name() + paramNumber;
String typeParam = "type" + paramNumber;
String targetParam = "target" + paramNumber;
qs.append(kwParam);
qs.append("=");
qs.append(config.getRawString());
qs.append("&");
qs.append(typeParam);
qs.append("=");
qs.append(config.getSearchType().name());
qs.append("&");
qs.append(targetParam);
qs.append("=");
qs.append(config.getSearchTarget().name());
if(config.getIgnoreCaps()){
qs.append("&");
qs.append(SearchOption.NO_CAPS.name().toLowerCase());
qs.append(paramNumber);
qs.append("=on");
}
if(config.getIgnoreMarks()){
qs.append("&");
qs.append(SearchOption.NO_MARKS.name().toLowerCase());
qs.append(paramNumber);
qs.append("=on");
}
if(config.getSearchType().equals(SearchType.PROXIMITY)){
qs.append("&");
qs.append(SearchType.PROXIMITY.name().toLowerCase());
qs.append(paramNumber);
qs.append("=on");
qs.append("&");
qs.append(SearchType.WITHIN.name().toLowerCase());
qs.append(paramNumber);
qs.append("=");
qs.append(String.valueOf(config.getProximityDistance()));
}
return qs.toString();
}
@Override
public String getCSSSelectorID(){
return super.getCSSSelectorID() + String.valueOf(searchConfigurations.size());
}
@Override
public void addConstraint(String newValue){
if(newValue.equals(Facet.defaultValue) || "".equals(newValue)) return;
super.addConstraint(newValue);
}
@Override
public String[] getFormNames(){
String[] formNames = new String[searchConfigurations.size()];
Iterator<Integer> pnit = searchConfigurations.keySet().iterator();
int counter = 0;
while(pnit.hasNext()){
Integer paramNumber = pnit.next();
String paramSuffix = paramNumber.equals(0) ? "" : String.valueOf(paramNumber);
String param = formName.name().toString() + paramSuffix;
formNames[counter] = param;
counter++;
}
return formNames;
}
@Override
public void setWidgetValues(QueryResponse queryResponse){}
@Override
public String getToolTipText(){
return "Performs a substring search, as though using the standard Search page. Capitalisation and diacritcs are ignored.";
}
public String getHighlightString(){
String highlightString = "";
for(SearchConfiguration searchConfiguration : searchConfigurations.values()){
highlightString += searchConfiguration.getHighlightString();
}
return highlightString;
}
/**
* This inner class handles the logic for string-searching previously found
* in <code>info.papyri.dispatch.Search</code>.
*
* Note that while the logic is intended to be the same, the implementation
* is very different. In particular, the search query is understood to be made
* up of three parts, which are dealt with separately, as far as this is possible.
* (1) The search type (substring, phrase, lemmatised, or proximity)
* (2) The search target (text, metadata, translations, or all three)
* (3) Transformations to be made to the string itself (e.g., because it is in
* betacode format, caps should be ignored, etc.)
*
* In practice these three are inter-related in a cascading fashion - the search type
* affects the possible search targets and relevant transformations, while
* the search target affects the possible transformations.
*
*
*/
class SearchConfiguration{
/** The search string as submitted by the user */
private String rawString;
/** The search string: i.e., the rawWord, after it has been
* subjected to the relevant transformations
*/
private String searchString;
/**
* The search target (text, metadata, translation, or all three)
*/
private SearchTarget target;
/**
* The search type (phrase, substring, lemmatized, proximity)
*/
private SearchType type;
/**
* The search window used for proximity searches; defaults to 0 for
* non-proximity searches
*/
private int proximityDistance;
/** <code>True</code> if capitalisation is to be ignored; <code>False</code>
* otherwise.
*/
private Boolean ignoreCaps;
/**
* <code>True</code> if diacritics are to be ignored; <code>False</code>
* otherwise.
*/
private Boolean ignoreMarks;
/**
* The SolrField that should be used in the search
*
*/
private SolrField field;
private String[] SEARCH_OPERATORS = {"AND", "OR", "NOT", "&&", "||", "+", "-", "WITHIN", "BEFORE", "AFTER", "IMMEDIATELY-BEFORE", "IMMEDIATELY-AFTER"};
private HashMap<String, String> STRINGOPS_TO_SOLROPS = new HashMap<String, String>();
SearchConfiguration(String kw, Integer no, SearchTarget tgt, SearchType ty, Boolean caps, Boolean marks, int wi){
target = tgt;
type = ty;
ignoreCaps = caps;
ignoreMarks = marks;
proximityDistance = wi;
rawString = kw;
searchString = transformSearchString();
STRINGOPS_TO_SOLROPS.put("NOT", "-");
STRINGOPS_TO_SOLROPS.put("WITHIN", "~");
}
String transformSearchString(){
checkBetacodeSlip();
ArrayList<String> keywords = harvestKeywords(this.rawString);
ArrayList<String> transWords = transformKeywords(keywords);
String swappedTerms = substituteTerms(keywords, transWords);
String swappedOps = substituteOperators(swappedTerms);
String swappedFields = substituteFields(swappedOps);
swappedFields = swappedFields.replaceAll("#", "^");
swappedFields = swappedFields.replaceAll("\\^", "\\\\^");
return swappedFields;
}
private void checkBetacodeSlip(){
rawString = rawString.replaceAll(" ΑΝΔ ", " AND ").replaceAll(" ΟΡ ", " OR ").replaceAll(" ΝΟΤ ", " NOT ");
}
ArrayList<String> harvestKeywords(String rawInput){
if(rawInput == null) return new ArrayList<String>();
String cleanedInput = rawInput;
cleanedInput = cleanedInput.replaceAll("[()#^]", " ");
cleanedInput = cleanedInput.replaceAll("~[\\s]*[\\d]+", " ");
for(String operator : this.SEARCH_OPERATORS){
try{
String operatorPattern = operator;
if("||".equals(operator)){
operatorPattern = "\\|\\|";
}
else if(operator.matches("[A-Z-]+") && !operator.equals("-")){
operatorPattern = "\\b" + operator + "\\b";
}
cleanedInput = cleanedInput.replaceAll(operatorPattern, " ");
}
catch(PatternSyntaxException pse){
String operatorPattern = "\\" + operator;
cleanedInput = cleanedInput.replaceAll(operatorPattern, " ");
}
}
cleanedInput = cleanedInput.replaceAll("[^\\s]+?:", " ");
cleanedInput = cleanedInput.trim();
ArrayList<String> inputBits = new ArrayList<String>(Arrays.asList(cleanedInput.split("(\\s)+")));
return inputBits;
}
ArrayList<String> transformKeywords(ArrayList<String> keywords){
ArrayList<String> transformedKeywords = new ArrayList<String>();
if(keywords == null) return transformedKeywords;
int counter = 0;
for(String keyword : keywords){
if(ignoreCaps){
keyword = keyword.toLowerCase();
}
if(lemmatizeWord(keywords, counter)){
try{
String keywordExpanded = this.expandLemmas(keyword);
keyword = "(" + keywordExpanded + ")";
}
catch(Exception e){
transformedKeywords.add(keyword);
continue;
}
}
if(ignoreMarks) keyword = FileUtils.stripDiacriticals(keyword);
keyword = keyword.replaceAll("ς", "σ");
transformedKeywords.add(keyword);
counter++;
}
return transformedKeywords;
}
String substituteOperators(String expandedString){
String smallString = expandedString;
if(type.equals(SearchType.PROXIMITY)){
smallString = smallString + "~" + String.valueOf(proximityDistance);
}
smallString = transformProximitySearch(smallString);
return smallString;
}
String transformProximitySearch(String searchString){
if(!searchString.contains("~")) return searchString;
searchString = searchString.replaceAll("\\s*~\\s*(\\d+)", "~$1");
String[] searchBits = searchString.split("~");
if(searchBits.length < 2) return searchString;
String prelimSearchTerms = searchBits[0];
String[] medSearchTerms = prelimSearchTerms.split(" ");
if(medSearchTerms.length < 2) return searchString;
String searchTerms = medSearchTerms[medSearchTerms.length - 2] + " " + medSearchTerms[medSearchTerms.length - 1];
if(searchTerms.indexOf("\"") != 0) searchTerms = "\"" + searchTerms;
if(searchTerms.lastIndexOf("\"") != (searchTerms.length() - 1)) searchTerms = searchTerms + "\"";
String newSearchString = searchTerms + "~" + searchBits[1];
return newSearchString;
}
String substituteTerms(ArrayList<String> initialTerms, ArrayList<String> transformedTerms){
String remainingString = rawString;
ArrayList<String> subBits = new ArrayList<String>();
for(int i = 0; i < initialTerms.size(); i++){
String iTerm = initialTerms.get(i).replace("?", "\\?").replace("*", "\\*");
String sTerm = transformedTerms.get(i);
String[] remBits = remainingString.split(iTerm, 2);
String newClause = remBits[0] + sTerm;
remainingString = remBits[1];
subBits.add(newClause);
}
subBits.add(remainingString);
String swapString = "";
for(String bit : subBits){
swapString += bit;
}
return swapString;
}
String substituteFields(String fieldString){
if(type.equals(SearchType.USER_DEFINED)){
fieldString = fieldString.replaceAll("\\blem:", "transcription_ia:");
return fieldString;
}
String fieldDesignator = "";
if(type.equals(SearchType.SUBSTRING)){
fieldDesignator = SolrField.transcription_ngram_ia.name();
}
else if(type.equals(SearchType.LEMMAS)){
fieldDesignator = SolrField.transcription_ia.name();
}
// henceforth only proximity and phrase searches possible
else if(target.equals(SearchTarget.TEXT)){
if(ignoreCaps && ignoreMarks){
fieldDesignator = SolrField.transcription_ia.name();
}
else if(ignoreCaps){
fieldDesignator = SolrField.transcription_ic.name();
}
else if(ignoreMarks){
fieldDesignator = SolrField.transcription_id.name();
}
else{
fieldDesignator = SolrField.transcription.name();
}
}
else if(target.equals(SearchTarget.METADATA)){
fieldDesignator = SolrField.metadata.name();
}
else if(target.equals(SearchTarget.TRANSLATIONS)){
fieldDesignator = SolrField.translation.name();
}
else if(target.equals(SearchTarget.ALL)){
fieldDesignator = SolrField.all.name();
}
if(!fieldDesignator.equals("")) fieldString = fieldDesignator + ":(" + fieldString + ")";
return fieldString;
}
Boolean lemmatizeWord(ArrayList<String> keywords, int currentIteration){
if(type.equals(SearchType.LEMMAS)) return true;
if(!type.equals(SearchType.USER_DEFINED)) return false;
String keyword = keywords.get(currentIteration);
int previousOccurrences = 0;
for(int i = 0; i < currentIteration; i++){
if(keywords.get(i).equals(keyword)) previousOccurrences++;
}
int index = 0;
String lemSub = rawString.substring(index);
int counter = 0;
while(lemSub.contains(keyword)){
index = lemSub.indexOf(keyword);
if(counter == previousOccurrences) break;
lemSub = lemSub.substring(index + keyword.length());
counter++;
}
if(index - "lem:".length() < 0) return false;
String lemcheck = lemSub.substring(index - "lem:".length(), index);
if(lemcheck.equals("lem:")) return true;
return false;
}
private String extractLemmaWord(String rawInput){
String lemmaWord = rawString;
lemmaWord = lemmaWord.replaceAll("#", "^");
lemmaWord = lemmaWord.replaceAll("\\^", "\\\\^");
if(!lemmaWord.contains("lem:")) return "";
String lemmaWordStart = lemmaWord.substring(lemmaWord.indexOf("lem:") + "lem:".length());
if(!lemmaWordStart.contains(" ")) return lemmaWordStart;
lemmaWord = lemmaWordStart.substring(0, lemmaWordStart.indexOf(" "));
return lemmaWord;
}
public String expandLemmas(String query) throws MalformedURLException, SolrServerException {
SolrServer solr = new CommonsHttpSolrServer("http://localhost:8083/solr/" + morphSearch);
StringBuilder exp = new StringBuilder();
SolrQuery sq = new SolrQuery();
String[] lemmas = query.split("\\s+");
for (String lemma : lemmas) {
exp.append(" lemma:");
exp.append(lemma);
}
sq.setQuery(exp.toString());
sq.setRows(1000);
QueryResponse rs = solr.query(sq);
SolrDocumentList forms = rs.getResults();
Set<String> formSet = new HashSet<String>();
if (forms.size() > 0) {
for (int i = 0; i < forms.size(); i++) {
formSet.add(FileUtils.stripDiacriticals((String)forms.get(i).getFieldValue("form")).replaceAll("[_^]", "").toLowerCase());
}
return FileUtils.interpose(formSet, " OR ");
}
return query;
}
/* getters and setters */
public SearchTarget getSearchTarget(){ return target; }
public String getSearchString(){ return searchString; }
public String getHighlightString(){
String highlightString = searchString;
return highlightString;
}
public SearchType getSearchType(){ return type; }
public int getProximityDistance(){ return proximityDistance; }
public String getRawString(){ return rawString; }
public Boolean getIgnoreCaps(){ return ignoreCaps; }
public Boolean getIgnoreMarks(){ return ignoreMarks; }
public SolrField getField(){ return field; }
}
}
| true | true | public String generateWidget() {
StringBuilder html = new StringBuilder("<div class=\"facet-widget\" id=\"text-search-widget\" title=\"");
html.append(getToolTipText());
html.append("\">");
html.append(generateHiddenFields());
// textbox HTML
html.append("<p class=\"ui-corner-all\" id=\"facet-stringsearch-wrapper\">");
html.append("<input type=\"text\" name=\"");
html.append(formName.name());
html.append("\" size=\"50\" maxlength=\"250\" id=\"keyword\"></input>");
html.append("</p>");
// search options control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input type=\"checkbox\" name=\"beta-on\" id=\"beta-on\" value=\"on\"></input>");
html.append("<label for=\"beta-on\" id=\"marks-label\">Convert from betacode as you type</label><br/>");
html.append("<input type=\"checkbox\" name=\"");
html.append(SearchOption.NO_CAPS.name().toLowerCase());
html.append("\" id=\"caps\" value=\"on\" checked></input>");
html.append("<label for=\"caps\" id=\"caps-label\">ignore capitalization</label><br/>");
html.append("<input type=\"checkbox\" name=\"");
html.append(SearchOption.NO_MARKS.name().toLowerCase());
html.append("\" id=\"marks\" value=\"on\" checked></input>");
html.append("<label for=\"marks\" id=\"marks-label\">ignore diacritics/accents</label>");
html.append("</p>");
html.append("</div><!-- closing .stringsearch-section -->");
// search type control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.PHRASE.name().toLowerCase());
html.append("\" id=\"phrase\"/> ");
html.append("<label for=\"phrase\" id=\"phrase-label\">Word/Phrase search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.SUBSTRING.name().toLowerCase());
html.append("\" id=\"substring\" checked/> ");
html.append("<label for=\"substring\" id=\"substring-label\">Substring search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.LEMMAS.name().toLowerCase());
html.append("\" id=\"lemmas\"/>");
html.append("<label for=\"lemmas\" id=\"lemmas-label\">Lemmatized search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.PROXIMITY.name().toLowerCase());
html.append("\" id=\"proximity\"/>");
html.append("<label for=\"proximity\" id=\"proximity-label\"> Proximity: find within</label>");
html.append(" <input type=\"text\" name=\"");
html.append(SearchType.WITHIN.name().toLowerCase());
html.append("\" value=\"10\" id=\"within\" size=\"2\" style=\"width:1.5em\"/> words");
html.append("</p>");
html.append("</div><!-- closing .stringsearch section -->");
// search target control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.TEXT.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-text\" class=\"target\" checked/>");
html.append("<label for=\"");
html.append(SearchTarget.TEXT.name().toLowerCase());
html.append("\" id=\"text-label\">Text</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.METADATA.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-metadata\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.METADATA.name().toLowerCase());
html.append("\" id=\"metadata-label\">Metadata</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.TRANSLATIONS.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-translations\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.TRANSLATIONS.name().toLowerCase());
html.append("\" id=\"translation-label\">Translations</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.ALL.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-all\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.ALL.name().toLowerCase());
html.append("\" id=\"all-label\">All</label>");
html.append("</p>");
html.append("</div><!-- closing .stringsearch-section -->");
html.append("</div><!-- closing .facet-widget -->");
return html.toString();
}
| public String generateWidget() {
StringBuilder html = new StringBuilder("<div class=\"facet-widget\" id=\"text-search-widget\" title=\"");
html.append(getToolTipText());
html.append("\">");
html.append(generateHiddenFields());
// textbox HTML
html.append("<p class=\"ui-corner-all\" id=\"facet-stringsearch-wrapper\">");
html.append("<input type=\"text\" name=\"");
html.append(formName.name());
html.append("\" size=\"50\" maxlength=\"250\" id=\"keyword\"></input>");
html.append("</p>");
// search options control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input type=\"checkbox\" name=\"beta-on\" id=\"beta-on\" value=\"on\"></input>");
html.append("<label for=\"beta-on\" id=\"marks-label\">Convert from betacode as you type</label><br/>");
html.append("<input type=\"checkbox\" name=\"");
html.append(SearchOption.NO_CAPS.name().toLowerCase());
html.append("\" id=\"caps\" value=\"on\" checked></input>");
html.append("<label for=\"caps\" id=\"caps-label\">ignore capitalization</label><br/>");
html.append("<input type=\"checkbox\" name=\"");
html.append(SearchOption.NO_MARKS.name().toLowerCase());
html.append("\" id=\"marks\" value=\"on\" checked></input>");
html.append("<label for=\"marks\" id=\"marks-label\">ignore diacritics/accents</label>");
html.append("</p>");
html.append("</div><!-- closing .stringsearch-section -->");
// search type control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.PHRASE.name().toLowerCase());
html.append("\" id=\"phrase\"/> ");
html.append("<label for=\"phrase\" id=\"phrase-label\">Word/Phrase search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.SUBSTRING.name().toLowerCase());
html.append("\" id=\"substring\" checked/> ");
html.append("<label for=\"substring\" id=\"substring-label\">Substring search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.LEMMAS.name().toLowerCase());
html.append("\" id=\"lemmas\"/> ");
html.append("<label for=\"lemmas\" id=\"lemmas-label\">Lemmatized search</label><br/>");
html.append("<input class=\"type\" type=\"radio\" name=\"type\" value=\"");
html.append(SearchType.PROXIMITY.name().toLowerCase());
html.append("\" id=\"proximity\"/>");
html.append("<label for=\"proximity\" id=\"proximity-label\"> Proximity: find within</label>");
html.append(" <input type=\"text\" name=\"");
html.append(SearchType.WITHIN.name().toLowerCase());
html.append("\" value=\"10\" id=\"within\" size=\"2\" style=\"width:1.5em\"/> words");
html.append("</p>");
html.append("</div><!-- closing .stringsearch section -->");
// search target control
html.append("<div class=\"stringsearch-section\">");
html.append("<p>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.TEXT.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-text\" class=\"target\" checked/>");
html.append("<label for=\"");
html.append(SearchTarget.TEXT.name().toLowerCase());
html.append("\" id=\"text-label\">Text</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.METADATA.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-metadata\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.METADATA.name().toLowerCase());
html.append("\" id=\"metadata-label\">Metadata</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.TRANSLATIONS.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-translations\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.TRANSLATIONS.name().toLowerCase());
html.append("\" id=\"translation-label\">Translations</label>");
html.append("<input type=\"radio\" name=\"target\" value=\"");
html.append(SearchTarget.ALL.name().toLowerCase());
html.append("\" value=\"on\" id=\"target-all\" class=\"target\"/>");
html.append("<label for=\"");
html.append(SearchTarget.ALL.name().toLowerCase());
html.append("\" id=\"all-label\">All</label>");
html.append("</p>");
html.append("</div><!-- closing .stringsearch-section -->");
html.append("</div><!-- closing .facet-widget -->");
return html.toString();
}
|
diff --git a/Herbal/src/tw/edu/ntust/dt/herbal/ShopActivity.java b/Herbal/src/tw/edu/ntust/dt/herbal/ShopActivity.java
index 595b15b..eae6a17 100644
--- a/Herbal/src/tw/edu/ntust/dt/herbal/ShopActivity.java
+++ b/Herbal/src/tw/edu/ntust/dt/herbal/ShopActivity.java
@@ -1,229 +1,229 @@
package tw.edu.ntust.dt.herbal;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.sileria.android.Kit;
import com.sileria.android.Tools;
import com.sileria.android.view.SlidingTray;
import com.sileria.util.Side;
public class ShopActivity extends Activity {
public static final String EXTRA_PRAM_PERSCRIPTION_NUM = "EXTRA_PRAM_PERSCRIPTION_NUM";
private Context mContext;
private LinearLayout herbalList;
private ImageView mHeadButtonBackground;
private Button mShop1Button;
private Button mShop2Button;
private Button mShop3Button;
private Button mShop4Button;
private ImageView mTrayContent;
private SlidingTray mSlidingTray;
private List<String> carts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Kit.init(getApplicationContext());
setContentView(R.layout.shop);
mHeadButtonBackground = (ImageView) findViewById(R.id.shop_head_button_background);
herbalList = (LinearLayout) findViewById(R.id.shop_herbal_list);
mShop1Button = (Button) findViewById(R.id.shop_button_1);
mShop2Button = (Button) findViewById(R.id.shop_button_2);
mShop3Button = (Button) findViewById(R.id.shop_button_3);
mShop4Button = (Button) findViewById(R.id.shop_button_4);
mShop1Button.setOnClickListener(mButtonClickListener);
mShop2Button.setOnClickListener(mButtonClickListener);
mShop3Button.setOnClickListener(mButtonClickListener);
mShop4Button.setOnClickListener(mButtonClickListener);
ImageView mBuyButton = (ImageView) findViewById(R.id.buy_button);
mBuyButton.setOnClickListener(buyButtonListner);
carts = new ArrayList<String>();
mContext = this;
createSlidingTray();
createHerbalListFromPerscription();
}
private void createHerbalListFromPerscription() {
herbalList.removeAllViews();
int num = getIntent().getIntExtra(EXTRA_PRAM_PERSCRIPTION_NUM, 0);
List<String> herbals = Constants.perscriptionToHerbal.get(num);
for (String herbal : herbals) {
ImageView imageView = new ImageView(this);
int drawableId = Constants.herbalToNormalDrawableId.get(herbal);
imageView.setImageResource(drawableId);
imageView.setAdjustViewBounds(true);
imageView.setTag(Pair.create(herbal, 0));
imageView.setOnLongClickListener(triggerHerbalDetail);
imageView.setOnClickListener(toggleHerbalSelected);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1);
herbalList.addView(imageView, params);
}
}
private void createSlidingTray() {
mTrayContent = new Tools(this).newImage(R.drawable.shop_store_info1);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
ImageView handler = new Tools(this).newImage(R.drawable.shop_handle);
handler.setAdjustViewBounds(true);
handler.setScaleType(ImageView.ScaleType.CENTER_CROP);
mSlidingTray = new WrappingSlidingTray(this, handler, mTrayContent,
SlidingTray.TOP);
RelativeLayout parent = (RelativeLayout) this
.findViewById(R.id.tray_parent);
mSlidingTray.setHandlePosition(Side.TOP);
parent.addView(mSlidingTray, new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.shop, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_logout:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private OnClickListener mButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.shop_button_1:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_1);
mTrayContent.setImageResource(R.drawable.shop_store_info1);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_2:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_2);
- mTrayContent.setImageResource(R.drawable.shop_store_info3);
+ mTrayContent.setImageResource(R.drawable.shop_store_info2);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_3:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_3);
- mTrayContent.setImageResource(R.drawable.shop_store_info2);
+ mTrayContent.setImageResource(R.drawable.shop_store_info3);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_4:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_4);
mTrayContent.setImageResource(R.drawable.shop_store_info4);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
}
}
};
private OnLongClickListener triggerHerbalDetail = new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
/* name and status */
@SuppressWarnings("unchecked")
Pair<String, Integer> pair = (Pair<String, Integer>) v.getTag();
if (pair != null) {
int drawableId = Constants.herbalToNormalDrawableId
.get(pair.first);
int detailId = Constants.herbalDrawableIdToDetailId
.get(drawableId);
Intent intent = new Intent(ShopActivity.this,
HerbalDetailActivity.class);
intent.putExtra(
HerbalDetailActivity.EXTRA_PRAM_HERBAL_DETAIL_ID,
detailId);
ShopActivity.this.startActivity(intent);
}
return false;
}
};
private OnClickListener toggleHerbalSelected = new OnClickListener() {
@Override
public void onClick(View v) {
@SuppressWarnings("unchecked")
Pair<String, Integer> pair = (Pair<String, Integer>) v.getTag();
if (pair != null) {
String herbal = pair.first;
int status = pair.second;
int changeId = -1;
switch (status) {
case 0:
changeId = Constants.herbalToPressedDrawableId.get(herbal);
carts.add(herbal);
break;
case 1:
changeId = Constants.herbalToNormalDrawableId.get(herbal);
carts.remove(herbal);
break;
}
if (changeId != -1) {
((ImageView) v).setImageResource(changeId);
v.setTag(Pair.create(herbal, 1 - status));
}
}
}
};
private OnClickListener buyButtonListner = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ShopActivity.this, ConfirmActivity.class);
intent.putExtra("cart", carts.toArray(new String[carts.size()]));
mContext.startActivity(intent);
}
};
}
| false | true | public void onClick(View v) {
switch (v.getId()) {
case R.id.shop_button_1:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_1);
mTrayContent.setImageResource(R.drawable.shop_store_info1);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_2:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_2);
mTrayContent.setImageResource(R.drawable.shop_store_info3);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_3:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_3);
mTrayContent.setImageResource(R.drawable.shop_store_info2);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_4:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_4);
mTrayContent.setImageResource(R.drawable.shop_store_info4);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
}
}
| public void onClick(View v) {
switch (v.getId()) {
case R.id.shop_button_1:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_1);
mTrayContent.setImageResource(R.drawable.shop_store_info1);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_2:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_2);
mTrayContent.setImageResource(R.drawable.shop_store_info2);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_3:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_3);
mTrayContent.setImageResource(R.drawable.shop_store_info3);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
case R.id.shop_button_4:
mHeadButtonBackground.setImageResource(R.drawable.shop_button_4);
mTrayContent.setImageResource(R.drawable.shop_store_info4);
mTrayContent.setAdjustViewBounds(true);
mTrayContent.setScaleType(ImageView.ScaleType.CENTER_CROP);
mTrayContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
break;
}
}
|
diff --git a/srcj/com/sun/electric/tool/io/output/Spice.java b/srcj/com/sun/electric/tool/io/output/Spice.java
index 69173027d..264a11e2a 100644
--- a/srcj/com/sun/electric/tool/io/output/Spice.java
+++ b/srcj/com/sun/electric/tool/io/output/Spice.java
@@ -1,2969 +1,2970 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Spice.java
* Original C Code written by Steven M. Rubin and Sid Penstone
* Translated to Java by Steven M. Rubin, Sun Microsystems.
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.output;
import com.sun.electric.database.geometry.GeometryHandler;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.PolyBase;
import com.sun.electric.database.geometry.PolyMerge;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.HierarchyEnumerator;
import com.sun.electric.database.hierarchy.Nodable;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.network.Global;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.text.Version;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.CodeExpression;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.Foundry;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitiveNodeSize;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.TransistorSize;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.generator.sclibrary.SCLibraryGen;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.input.Simulate;
import com.sun.electric.tool.io.input.spicenetlist.SpiceNetlistReader;
import com.sun.electric.tool.io.input.spicenetlist.SpiceSubckt;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations.NamePattern;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.Exec;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.ExecDialog;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.waveform.WaveformWindow;
import java.awt.geom.AffineTransform;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This is the Simulation Interface tool.
*/
public class Spice extends Topology
{
private static final boolean DETECT_SPICE_PARAMS = true;
private static final boolean USE_JAVA_CODE = true;
/** key of Variable holding generic Spice templates. */ public static final Variable.Key SPICE_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template");
/** key of Variable holding Spice 2 templates. */ public static final Variable.Key SPICE_2_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice2");
/** key of Variable holding Spice 3 templates. */ public static final Variable.Key SPICE_3_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice3");
/** key of Variable holding HSpice templates. */ public static final Variable.Key SPICE_H_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_hspice");
/** key of Variable holding PSpice templates. */ public static final Variable.Key SPICE_P_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_pspice");
/** key of Variable holding GnuCap templates. */ public static final Variable.Key SPICE_GC_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_gnucap");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_SM_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_smartspice");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_A_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_assura");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_C_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_calibre");
/** key of Variable holding Spice model file. */ public static final Variable.Key SPICE_NETLIST_FILE_KEY = Variable.newKey("ATTR_SPICE_netlist_file");
/** key of Variable holding SPICE code. */ public static final Variable.Key SPICE_CARD_KEY = Variable.newKey("SIM_spice_card");
/** key of Variable holding SPICE declaration. */ public static final Variable.Key SPICE_DECLARATION_KEY = Variable.newKey("SIM_spice_declaration");
/** key of Variable holding SPICE model. */ public static final Variable.Key SPICE_MODEL_KEY = Variable.newKey("SIM_spice_model");
/** key of Variable holding SPICE flat code. */ public static final Variable.Key SPICE_CODE_FLAT_KEY = Variable.newKey("SIM_spice_code_flat");
/** key of Variable holding generic CDL templates. */ public static final Variable.Key CDL_TEMPLATE_KEY = Variable.newKey("ATTR_CDL_template");
/** Prefix for spice extension. */ public static final String SPICE_EXTENSION_PREFIX = "Extension ";
/** Prefix for spice null extension. */ public static final String SPICE_NOEXTENSION_PREFIX = "N O N E ";
/** maximum subcircuit name length */ private static final int SPICEMAXLENSUBCKTNAME = 70;
/** maximum subcircuit name length */ private static final int CDLMAXLENSUBCKTNAME = 40;
/** maximum subcircuit name length */ private static final int SPICEMAXLENLINE = 78;
/** legal characters in a spice deck */ private static final String SPICELEGALCHARS = "!#$%*+-/<>[]_@";
/** legal characters in a spice deck */ private static final String PSPICELEGALCHARS = "!#$%*+-/<>[]_";
/** legal characters in a CDL deck */ private static final String CDLNOBRACKETLEGALCHARS = "!#$%*+-/<>_";
/** if CDL writes out empty subckt definitions */ private static final boolean CDLWRITESEMPTYSUBCKTS = false;
/** A mark for uniquify */ private static final Set<Variable.Key> UNIQUIFY_MARK = Collections.emptySet();
/** default Technology to use. */ private Technology layoutTechnology;
/** Mask shrink factor (default =1) */ private double maskScale;
/** True to write CDL format */ private boolean useCDL;
/** Legal characters */ private String legalSpiceChars;
/** Template Key for current spice engine */ private Variable.Key preferedEngineTemplateKey;
/** Special case for HSpice for Assura */ private boolean assuraHSpice = false;
/** Spice type: 2, 3, H, P, etc */ private Simulation.SpiceEngine spiceEngine;
/** those cells that have overridden models */ private Map<Cell,String> modelOverrides = new HashMap<Cell,String>();
/** Parameters used for Spice */ private Map<NodeProto,Set<Variable.Key>> allSpiceParams = new HashMap<NodeProto,Set<Variable.Key>>();
/** for RC parasitics */ private SpiceParasiticsGeneral parasiticInfo;
/** Networks exempted during parasitic ext */ private SpiceExemptedNets exemptedNets;
/** Whether or not to write empty subckts */ private boolean writeEmptySubckts = true;
/** max length per line */ private int spiceMaxLenLine = SPICEMAXLENLINE;
/** Flat measurements file */ private FlatSpiceCodeVisitor spiceCodeFlat = null;
/** map of "parameterized" cells not covered by Topology */ private Map<Cell,Cell> uniquifyCells;
/** uniqueID */ private int uniqueID;
/** map of shortened instance names */ private Map<String,Integer> uniqueNames;
/**
* Constructor for the Spice netlister.
*/
Spice() {}
/**
* The main entry point for Spice deck writing.
* @param cell the top-level cell to write.
* @param context the hierarchical context to the cell.
* @param filePath the disk file to create.
* @param cdl true if this is CDL output (false for Spice).
*/
public static void writeSpiceFile(Cell cell, VarContext context, String filePath, boolean cdl)
{
Spice out = new Spice();
out.useCDL = cdl;
if (out.openTextOutputStream(filePath)) return;
if (out.writeCell(cell, context)) return;
if (out.closeTextOutputStream()) return;
System.out.println(filePath + " written");
// write CDL support file if requested
if (out.useCDL)
{
// write the control files
String deckFile = filePath;
String deckPath = "";
int lastDirSep = deckFile.lastIndexOf(File.separatorChar);
if (lastDirSep > 0)
{
deckPath = deckFile.substring(0, lastDirSep);
deckFile = deckFile.substring(lastDirSep+1);
}
String templateFile = deckPath + File.separator + cell.getName() + ".cdltemplate";
if (out.openTextOutputStream(templateFile)) return;
String libName = Simulation.getCDLLibName();
String libPath = Simulation.getCDLLibPath();
out.printWriter.print("cdlInKeys = list(nil\n");
out.printWriter.print(" 'searchPath \"" + deckFile + "");
if (libPath.length() > 0)
out.printWriter.print("\n " + libPath);
out.printWriter.print("\"\n");
out.printWriter.print(" 'cdlFile \"" + deckPath + File.separator + deckFile + "\"\n");
out.printWriter.print(" 'userSkillFile \"\"\n");
out.printWriter.print(" 'opusLib \"" + libName + "\"\n");
out.printWriter.print(" 'primaryCell \"" + cell.getName() + "\"\n");
out.printWriter.print(" 'caseSensitivity \"lower\"\n");
out.printWriter.print(" 'hierarchy \"flatten\"\n");
out.printWriter.print(" 'cellTable \"\"\n");
out.printWriter.print(" 'viewName \"netlist\"\n");
out.printWriter.print(" 'viewType \"\"\n");
out.printWriter.print(" 'pr nil\n");
out.printWriter.print(" 'skipDevice nil\n");
out.printWriter.print(" 'schemaLib \"sample\"\n");
out.printWriter.print(" 'refLib \"\"\n");
out.printWriter.print(" 'globalNodeExpand \"full\"\n");
out.printWriter.print(")\n");
if (out.closeTextOutputStream()) return;
System.out.println(templateFile + " written");
}
String runSpice = Simulation.getSpiceRunChoice();
if (!runSpice.equals(Simulation.spiceRunChoiceDontRun)) {
String command = Simulation.getSpiceRunProgram() + " " + Simulation.getSpiceRunProgramArgs();
// see if user specified custom dir to run process in
String workdir = User.getWorkingDirectory();
String rundir = workdir;
if (Simulation.getSpiceUseRunDir()) {
rundir = Simulation.getSpiceRunDir();
}
File dir = new File(rundir);
int start = filePath.lastIndexOf(File.separator);
if (start == -1) start = 0; else {
start++;
if (start > filePath.length()) start = filePath.length();
}
int end = filePath.lastIndexOf(".");
if (end == -1) end = filePath.length();
String filename_noext = filePath.substring(start, end);
String filename = filePath.substring(start, filePath.length());
// replace vars in command and args
command = command.replaceAll("\\$\\{WORKING_DIR}", workdir);
command = command.replaceAll("\\$\\{USE_DIR}", rundir);
command = command.replaceAll("\\$\\{FILENAME}", filename);
command = command.replaceAll("\\$\\{FILENAME_NO_EXT}", filename_noext);
// set up run probe
FileType type = Simulate.getCurrentSpiceOutputType();
String [] extensions = type.getExtensions();
String outFile = rundir + File.separator + filename_noext + "." + extensions[0];
Exec.FinishedListener l = new SpiceFinishedListener(cell, type, outFile);
if (runSpice.equals(Simulation.spiceRunChoiceRunIgnoreOutput)) {
Exec e = new Exec(command, null, dir, null, null);
if (Simulation.getSpiceRunProbe()) e.addFinishedListener(l);
e.start();
}
if (runSpice.equals(Simulation.spiceRunChoiceRunReportOutput)) {
ExecDialog dialog = new ExecDialog(TopLevel.getCurrentJFrame(), false);
if (Simulation.getSpiceRunProbe()) dialog.addFinishedListener(l);
dialog.startProcess(command, null, dir);
}
System.out.println("Running spice command: "+command);
}
if (Simulation.isParasiticsBackAnnotateLayout() && out.parasiticInfo != null)
{
out.parasiticInfo.backAnnotate();
}
}
/**
* Method called once by the traversal mechanism.
* Initializes Spice netlisting and writes headers.
*/
protected void start()
{
// find the proper technology to use if this is schematics
if (topCell.getTechnology().isLayout())
layoutTechnology = topCell.getTechnology();
else
layoutTechnology = Schematics.getDefaultSchematicTechnology();
// make sure key is cached
spiceEngine = Simulation.getSpiceEngine();
preferedEngineTemplateKey = SPICE_TEMPLATE_KEY;
assuraHSpice = false;
switch (spiceEngine)
{
case SPICE_ENGINE_2: preferedEngineTemplateKey = SPICE_2_TEMPLATE_KEY; break;
case SPICE_ENGINE_3: preferedEngineTemplateKey = SPICE_3_TEMPLATE_KEY; break;
case SPICE_ENGINE_H: preferedEngineTemplateKey = SPICE_H_TEMPLATE_KEY; break;
case SPICE_ENGINE_P: preferedEngineTemplateKey = SPICE_P_TEMPLATE_KEY; break;
case SPICE_ENGINE_G: preferedEngineTemplateKey = SPICE_GC_TEMPLATE_KEY; break;
case SPICE_ENGINE_S: preferedEngineTemplateKey = SPICE_SM_TEMPLATE_KEY; break;
case SPICE_ENGINE_H_ASSURA: preferedEngineTemplateKey = SPICE_A_TEMPLATE_KEY; assuraHSpice = true; break;
case SPICE_ENGINE_H_CALIBRE: preferedEngineTemplateKey = SPICE_C_TEMPLATE_KEY; assuraHSpice = true; break;
}
if (useCDL) {
preferedEngineTemplateKey = CDL_TEMPLATE_KEY;
}
if (assuraHSpice || (useCDL && !CDLWRITESEMPTYSUBCKTS) ||
(!useCDL && !Simulation.isSpiceWriteEmtpySubckts())) {
writeEmptySubckts = false;
}
// get the mask scale
maskScale = 1.0;
// Variable scaleVar = layoutTechnology.getVar("SIM_spice_mask_scale");
// if (scaleVar != null) maskScale = TextUtils.atof(scaleVar.getObject().toString());
// set up the parameterized cells
uniquifyCells = new HashMap<Cell,Cell>();
uniqueID = 0;
uniqueNames = new HashMap<String,Integer>();
markCellsToUniquify(topCell);
// setup the legal characters
legalSpiceChars = SPICELEGALCHARS;
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) legalSpiceChars = PSPICELEGALCHARS;
// start writing the spice deck
if (useCDL)
{
// setup bracket conversion for CDL
if (Simulation.isCDLConvertBrackets())
legalSpiceChars = CDLNOBRACKETLEGALCHARS;
multiLinePrint(true, "* First line is ignored\n");
// see if include file specified
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
String filePart = Simulation.getCDLIncludeFile();
if (!filePart.equals("")) {
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Primitives described in this file:\n");
addIncludeFile(filePart);
} else {
System.out.println("Warning: CDL Include file not found: "+fileName);
}
}
} else
{
writeHeader(topCell);
spiceCodeFlat = new FlatSpiceCodeVisitor(filePath+".flatcode", this);
HierarchyEnumerator.enumerateCell(topCell, VarContext.globalContext, spiceCodeFlat, getShortResistorsFlat());
spiceCodeFlat.close();
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
exemptedNets = new SpiceExemptedNets(new File(headerPath + File.separator + "exemptedNets.txt"));
}
}
/**
* Method called once at the end of netlisting.
*/
protected void done()
{
if (!useCDL)
{
writeTrailer(topCell);
if (Simulation.isSpiceWriteFinalDotEnd())
multiLinePrint(false, ".END\n");
}
}
/**
* Method called by traversal mechanism to write one level of hierarchy in the Spice netlist.
* This could be the top level or a subcircuit.
* The bulk of the Spice netlisting happens here.
*/
protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
// if this is the top level cell, write globals
if (cell == topCell)
{
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
// make sure power and ground appear at the top level
if (!Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
}
// create electrical nets (SpiceNet) for every Network in the cell
Netlist netList = cni.getNetList();
Map<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = new SpiceNet(net);
spiceNetMap.put(net, spNet);
}
// for non-simple parasitics, create a SpiceSegmentedNets object to deal with them
Simulation.SpiceParasitics spLevel = Simulation.getSpiceParasiticsLevel();
if (useCDL || cell.getView() != View.LAYOUT) spLevel = Simulation.SpiceParasitics.SIMPLE;
SpiceSegmentedNets segmentedNets = null;
if (spLevel != Simulation.SpiceParasitics.SIMPLE)
{
// make the parasitics info object if it does not already exist
if (parasiticInfo == null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo = new SpiceParasitic();
} else if (spLevel == Simulation.SpiceParasitics.RC_CONSERVATIVE)
{
parasiticInfo = new SpiceRCSimple();
}
}
segmentedNets = parasiticInfo.initializeSegments(cell, cni, layoutTechnology, exemptedNets, info);
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun.isNTypeTransistor()) nmosTrans++; else
if (fun.isPTypeTransistor()) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
boolean forceEval = useCDL || !Simulation.isSpiceUseCellParameters() || detectSpiceParams(cell) == UNIQUIFY_MARK;
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (!cs.isGlobal() && cs.getExport() == null) continue;
// special case for parasitic extraction
if (parasiticInfo != null && !cs.isGlobal() && cs.getExport() != null)
{
parasiticInfo.writeSubcircuitHeader(cs, infstr);
} else
{
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
Set<Variable.Key> spiceParams = detectSpiceParams(cell);
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
String value = paramVar.getPureValue(-1);
if (USE_JAVA_CODE) {
value = evalParam(context, info.getParentInst(), paramVar, forceEval);
} else if (!isNetlistableParam(paramVar))
continue;
infstr.append(" " + paramVar.getTrueName() + "=" + value);
}
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
+// boolean includePwrVdd = Simulation.isSpiceWritePwrGndInTopCell();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// get the SPICE template on the prototype (if any)
Variable varTemplate = getEngineTemplate(subCell);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts)
{
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto)) continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
if (ignoreSubcktPort(subCS)) continue;
PortProto pp = subCS.getExport();
if (!subCS.isGlobal() && pp == null) continue;
// If global pwr/vdd will be included in the subcircuit
// Preparing code for bug #1828
// if (!Simulation.isSpiceWritePwrGndInTopCell() && pp!= null && subCS.isGlobal() && (subCS.isGround() || subCS.isPower()))
// continue;
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with swapped-in layout subcells
if (pp != null && cell.isSchematic() && (subCni.getCell().getView() == View.LAYOUT))
{
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); )
{
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++)
{
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName()))
{
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found)
{
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (subCS.isGlobal())
{
net = netList.getNetwork(no, subCS.getGlobal());
}
else
net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
SpiceSegmentedNets subSN = null;
if (parasiticInfo != null && !cs.isGlobal())
subSN = parasiticInfo.getSegmentedNets((Cell)no.getProto());
if (subSN != null)
{
parasiticInfo.getParasiticName(no, subCS.getNetwork(), subSN, infstr);
} else
{
String name = cs.getName();
if (parasiticInfo != null)
{
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) infstr.append(" /"); else infstr.append(" ");
infstr.append(subCni.getParameterizedName());
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
Set<Variable.Key> spiceParams = detectSpiceParams(subCell);
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
if (!USE_JAVA_CODE && !isNetlistableParam(paramVar)) continue;
Variable instVar = no.getParameter(paramVar.getKey());
String paramStr = "??";
if (instVar != null)
{
if (USE_JAVA_CODE)
{
paramStr = evalParam(context, no, instVar, forceEval);
} else
{
Object obj = null;
if (isNetlistableParam(instVar))
{
obj = context.evalSpice(instVar, false);
} else
{
obj = context.evalVar(instVar, no);
}
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit(), false);
}
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, ni, resistVar, forceEval);
} else {
if (resistVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit(), false);
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
else if (fun == PrimitiveNode.Function.WRESIST) {
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) {
extra = "rnwod "+extra;
}
if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) {
extra = "rpwod "+extra;
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, capacVar, forceEval);
} else {
if (capacVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit(), false);
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, inductVar, forceEval);
} else {
if (inductVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit(), false);
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets != null) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets != null && ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (segmentedNets != null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo.writeNewSpiceCode(cell, cni, layoutTechnology, this);
} else {
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SpiceSegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.getCap() > cell.getTechnology().getMinCapacitance()) {
if (netInfo.getName().equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.getName() + " 0 " + TextUtils.formatDouble(netInfo.getCap()) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.getRes(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SpiceSegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue()) + "\n");
resCount++;
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
/****************************** PARAMETERS ******************************/
/**
* Method to create a parameterized name for node instance "ni".
* If the node is not parameterized, returns zero.
* If it returns a name, that name must be deallocated when done.
*/
protected String parameterizedName(Nodable no, VarContext context)
{
Cell cell = (Cell)no.getProto();
StringBuffer uniqueCellName = new StringBuffer(getUniqueCellName(cell));
if (uniquifyCells.get(cell) != null && modelOverrides.get(cell) == null) {
// if this cell is marked to be make unique, make a unique name out of the var context
VarContext vc = context.push(no);
uniqueCellName.append("_"+vc.getInstPath("."));
} else {
boolean useCellParams = !useCDL && Simulation.isSpiceUseCellParameters();
if (canParameterizeNames() && no.isCellInstance() && !SCLibraryGen.isStandardCell(cell))
{
// if there are parameters, append them to this name
Set<Variable.Key> spiceParams = detectSpiceParams(cell);
List<Variable> paramValues = new ArrayList<Variable>();
for(Iterator<Variable> it = no.getDefinedParameters(); it.hasNext(); )
{
Variable var = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(var.getKey())) continue;
if (USE_JAVA_CODE) {
if (useCellParams && !spiceParams.contains(null)) continue;
} else {
if (useCellParams && !var.isJava()) continue;
}
paramValues.add(var);
}
for(Variable var : paramValues)
{
String eval = var.describe(context, no);
//Object eval = context.evalVar(var, no);
if (eval == null) continue;
//uniqueCellName += "-" + var.getTrueName() + "-" + eval.toString();
uniqueCellName.append("-" + eval.toString());
}
}
}
// if it is over the length limit, truncate it
int limit = maxNameLength();
if (limit > 0 && uniqueCellName.length() > limit)
{
Integer i = uniqueNames.get(uniqueCellName.toString());
if (i == null) {
i = new Integer(uniqueID);
uniqueID++;
uniqueNames.put(uniqueCellName.toString(), i);
}
uniqueCellName = uniqueCellName.delete(limit-10, uniqueCellName.length());
uniqueCellName.append("-ID"+i);
}
// make it safe
return getSafeCellName(uniqueCellName.toString());
}
/**
* Returns true if variable can be netlisted as a spice parameter (unevaluated expression).
* If not, it should be evaluated before netlisting.
* @param var the var to check
* @return true if the variable should be netlisted as a spice parameter
*/
private boolean isNetlistableParam(Variable var)
{
if (USE_JAVA_CODE)
{
CodeExpression ce = var.getCodeExpression();
if (ce == null) return true;
if (ce.getHSpiceText(false) != null) return true;
return false;
}
if (var.isJava()) return false;
return true;
}
/**
* Returns text representation of instance parameter
* on specified Nodable in specified VarContext
* The text representation can be either spice parameter expression or
* a value evaluated in specified VarContext
* @param context specified VarContext
* @param no specified Nodable
* @param instParam instance parameter
* @param forceEval true to always evaluate param
* @return true if the variable should be netlisted as a spice parameter
*/
private String evalParam(VarContext context, Nodable no, Variable instParam, boolean forceEval)
{
return evalParam(context, no, instParam, forceEval, false, false);
}
/**
* Returns text representation of instance parameter
* on specified Nodable in specified VarContext
* The text representation can be either spice parameter expression or
* a value evaluated in specified VarContext
* @param context specified VarContext
* @param no specified Nodable
* @param instParam instance parameter
* @param forceEval true to always evaluate param
* @param wrapped true if the string is already "wrapped" (with parenthesis) and does not need to have quotes around it.
* @return true if the variable should be netlisted as a spice parameter
*/
private String evalParam(VarContext context, Nodable no, Variable instParam, boolean forceEval, boolean inPars, boolean wrapped) {
assert USE_JAVA_CODE;
Object obj = null;
if (!forceEval) {
CodeExpression ce = instParam.getCodeExpression();
if (ce != null)
obj = ce.getHSpiceText(inPars);
}
if (obj == null)
obj = context.evalVar(instParam, no);
if (obj instanceof Number)
obj = TextUtils.formatDoublePostFix(((Number)obj).doubleValue());
return formatParam(String.valueOf(obj), instParam.getUnit(), wrapped);
}
private Set<Variable.Key> detectSpiceParams(NodeProto np)
{
Set<Variable.Key> params = allSpiceParams.get(np);
if (params != null) return params;
if (np instanceof PrimitiveNode) {
params = getImportantVars((PrimitiveNode)np);
// if (!params.isEmpty())
// printlnParams(pn + " depends on:", params);
} else {
Cell cell = (Cell)np;
params = getTemplateVars(cell);
if (params == null) {
if (cell.isIcon() && cell.contentsView() != null) {
Cell schCell = cell.contentsView();
params = detectSpiceParams(schCell);
// printlnParams(cell + " inherits from " + schCell, params);
} else {
params = new HashSet<Variable.Key>();
boolean uniquify = false;
for (Iterator<NodeInst> nit = cell.getNodes(); nit.hasNext();) {
NodeInst ni = nit.next();
if (ni.isIconOfParent()) continue;
Set<Variable.Key> protoParams = detectSpiceParams(ni.getProto());
if (protoParams == UNIQUIFY_MARK)
uniquify = true;
for (Variable.Key protoParam: protoParams) {
Variable var = ni.getParameterOrVariable(protoParam);
if (var == null) continue;
CodeExpression ce = var.getCodeExpression();
if (ce == null) continue;
if (!isNetlistableParam(var)) uniquify = true;
Set<Variable.Key> depends = ce.dependsOn();
params.addAll(depends);
// if (!depends.isEmpty())
// printlnParams("\t" + ni + " added", depends);
}
if (ni.getProto() == Generic.tech().invisiblePinNode) {
findVarsInTemplate(ni.getVar(Spice.SPICE_DECLARATION_KEY), cell, false, params);
findVarsInTemplate(ni.getVar(Spice.SPICE_CARD_KEY), cell, false, params);
}
}
if (uniquify/* && USE_UNIQUIFY_MARK*/)
params = UNIQUIFY_MARK;
// printlnParams(cell + " collected params", params);
}
}
}
allSpiceParams.put(np, params);
return params;
}
// private static void printlnParams(String message, Set<Variable.Key> varKeys) {
// System.out.print(message);
// for (Variable.Key varKey: varKeys)
// System.out.print(" " + varKey);
// System.out.println();
// }
/**
* Method to tell which Variables are important for primitive node in this netlister
* @param pn primitive node to tell
* @return a set of important variables or null if all variables may be important
*/
protected Set<Variable.Key> getImportantVars(PrimitiveNode pn)
{
Set<Variable.Key> importantVars = new HashSet<Variable.Key>();
// look for a SPICE template on the primitive
String line = pn.getSpiceTemplate();
if (line != null) {
findVarsInLine(line, pn, true, importantVars);
// Writing MFactor if available. Not sure here
// No, this causes problems because "ATTR_M" does not actually exist on proto
//importantVars.add(Simulation.M_FACTOR_KEY);
return importantVars;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = pn.getFunction();
if (fun.isResistor()) {
importantVars.add(Schematics.SCHEM_RESISTANCE);
} else if (fun.isCapacitor()) {
importantVars.add(Schematics.SCHEM_CAPACITANCE);
} else if (fun == PrimitiveNode.Function.INDUCT) {
importantVars.add(Schematics.SCHEM_INDUCTANCE);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ) {
importantVars.add(Schematics.SCHEM_DIODE);
} else if (pn.getGroupFunction() == PrimitiveNode.Function.TRANS) {
// model information
importantVars.add(SPICE_MODEL_KEY);
// compute length and width (or area for nonMOS transistors)
if (pn.getTechnology() instanceof Schematics) {
importantVars.add(Schematics.ATTR_LENGTH);
importantVars.add(Schematics.ATTR_WIDTH);
importantVars.add(Schematics.ATTR_AREA);
} else {
importantVars.add(NodeInst.TRACE);
}
importantVars.add(Simulation.M_FACTOR_KEY);
} else if (pn == Generic.tech().invisiblePinNode) {
importantVars.add(Spice.SPICE_DECLARATION_KEY);
importantVars.add(Spice.SPICE_CARD_KEY);
}
return importantVars;
}
/****************************** TEMPLATE WRITING ******************************/
private void emitEmbeddedSpice(Variable cardVar, VarContext context, SpiceSegmentedNets segNets, HierarchyEnumerator.CellInfo info, boolean flatNetNames, boolean forceEval)
{
Object obj = cardVar.getObject();
if (!(obj instanceof String) && !(obj instanceof String[])) return;
if (!cardVar.isDisplay()) return;
if (obj instanceof String)
{
StringBuffer buf = replacePortsAndVars((String)obj, context.getNodable(), context.pop(), null, segNets, info, flatNetNames, forceEval);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
} else
{
String [] strings = (String [])obj;
for(int i=0; i<strings.length; i++)
{
StringBuffer buf = replacePortsAndVars(strings[i], context.getNodable(), context.pop(), null, segNets, info, flatNetNames, forceEval);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
}
}
}
/**
* Method to determine which Spice engine is being targeted and to get the proper
* template variable.
* @param cell the Cell being netlisted.
* @return a Variable on that Cell with the proper Spice template (null if none).
*/
private Variable getEngineTemplate(Cell cell)
{
Variable varTemplate = cell.getVar(preferedEngineTemplateKey);
// Any of the following spice templates, if missing, will default to the generic spice template
if (varTemplate == null)
{
if (preferedEngineTemplateKey == SPICE_2_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_3_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_H_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_P_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_GC_TEMPLATE_KEY ||
preferedEngineTemplateKey == SPICE_SM_TEMPLATE_KEY)
varTemplate = cell.getVar(SPICE_TEMPLATE_KEY);
}
return varTemplate;
}
private Set<Variable.Key> getTemplateVars(Cell cell)
{
Variable varTemplate = getEngineTemplate(cell);
if (varTemplate == null) return null;
Set<Variable.Key> depends = new HashSet<Variable.Key>();
findVarsInTemplate(varTemplate, cell, true, depends);
//depends.add(Simulation.M_FACTOR_KEY);
return depends;
}
private void findVarsInTemplate(Variable varTemplate, NodeProto cell, boolean isPortReplacement, Set<Variable.Key> vars)
{
if (varTemplate == null) return;
Object value = varTemplate.getObject();
if (value instanceof Object[])
{
for (Object o : ((Object[]) value))
{
findVarsInLine(o.toString(), cell, isPortReplacement, vars);
}
} else
{
findVarsInLine(value.toString(), cell, isPortReplacement, vars);
}
}
/**
* Replace ports and vars in 'line'. Ports and Vars should be
* referenced via $(name)
* @param line the string to search and replace within
* @param no the nodable up the hierarchy that has the parameters on it
* @param context the context of the nodable
* @param cni the cell net info of cell in which the nodable exists (if cni is
* null, no port name replacement will be done)
* @param segNets
* @param info
* @param flatNetNames
* @param forceEval alsways evaluate parameters to numbers
* @return the modified line
*/
private StringBuffer replacePortsAndVars(String line, Nodable no, VarContext context,
CellNetInfo cni, SpiceSegmentedNets segNets,
HierarchyEnumerator.CellInfo info, boolean flatNetNames, boolean forceEval) {
StringBufferQuoteParity infstr = new StringBufferQuoteParity();
NodeProto prototype = null;
PrimitiveNode prim = null;
if (no != null)
{
prototype = no.getProto();
if (prototype instanceof PrimitiveNode) prim = (PrimitiveNode)prototype;
}
for(int pt = 0; pt < line.length(); pt++)
{
// see if the character is part of a substitution expression
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(')
{
// not part of substitution: just emit it
infstr.append(chr);
continue;
}
// may be part of substitution expression: look for closing parenthesis
int start = pt + 2;
for(pt = start; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
// do the parameter substitution
String paramName = line.substring(start, pt);
PortProto pp = null;
if (prototype != null) {
pp = prototype.findPortProto(paramName);
}
Variable.Key varKey;
if (paramName.equalsIgnoreCase("node_name") && no != null)
{
String nodeName = getSafeNetName(no.getName(), false);
// nodeName = nodeName.replaceAll("[\\[\\]]", "_");
infstr.append(nodeName);
} else if (paramName.equalsIgnoreCase("width") && prim != null)
{
NodeInst ni = (NodeInst)no;
PrimitiveNodeSize npSize = ni.getPrimitiveDependentNodeSize(context);
if (npSize != null) infstr.append(npSize.getWidth().toString());
} else if (paramName.equalsIgnoreCase("length") && prim != null)
{
NodeInst ni = (NodeInst)no;
PrimitiveNodeSize npSize = ni.getPrimitiveDependentNodeSize(context);
if (npSize != null) infstr.append(npSize.getLength().toString());
} else if (cni != null && pp != null)
{
// port name found: use its spice node
Network net = cni.getNetList().getNetwork(no, pp, 0);
CellSignal cs = cni.getCellSignal(net);
String portName = cs.getName();
if (segNets != null) {
PortInst pi = no.getNodeInst().findPortInstFromProto(pp);
portName = segNets.getNetName(pi);
}
if (flatNetNames) {
portName = info.getUniqueNetName(net, ".");
}
infstr.append(portName);
} else if (no != null && (varKey = Variable.findKey("ATTR_" + paramName)) != null)
{
// no port name found, look for variable name
Variable attrVar = null;
//Variable.Key varKey = Variable.findKey("ATTR_" + paramName);
if (varKey != null) {
attrVar = no.getParameterOrVariable(varKey);
}
if (attrVar == null) infstr.append("??"); else
{
String pVal = "?";
Variable parentVar = attrVar;
if (prototype != null && prototype instanceof Cell)
parentVar = ((Cell)prototype).getParameterOrVariable(attrVar.getKey());
if (USE_JAVA_CODE) {
pVal = evalParam(context, no, attrVar, forceEval, true, infstr.inParens());
if (infstr.inQuotes()) pVal = trimSingleQuotes(pVal);
} else {
if (!useCDL && Simulation.isSpiceUseCellParameters() &&
parentVar.getCode() == CodeExpression.Code.SPICE) {
Object obj = context.evalSpice(attrVar, false);
if (obj != null)
pVal = obj.toString();
} else {
pVal = String.valueOf(context.evalVar(attrVar, no));
}
// if (attrVar.getCode() != TextDescriptor.Code.NONE)
if (infstr.inQuotes()) pVal = trimSingleQuotes(pVal); else
pVal = formatParam(pVal, attrVar.getUnit(), infstr.inParens());
}
infstr.append(pVal);
}
} else {
// look for the network name
boolean found = false;
String hierName = null;
String [] names = paramName.split("\\.");
if (names.length > 1 && flatNetNames) {
// hierarchical name, down hierarchy
Netlist thisNetlist = info.getNetlist();
VarContext thisContext = context;
if (no != null) {
// push it back on, it got popped off in "embedSpice..."
thisContext = thisContext.push(no);
}
for (int i=0; i<names.length-1; i++) {
boolean foundno = false;
for (Iterator<Nodable> it = thisNetlist.getNodables(); it.hasNext(); ) {
Nodable subno = it.next();
if (subno.getName().equals(names[i])) {
if (subno.getProto() instanceof Cell) {
thisNetlist = thisNetlist.getNetlist(subno);
thisContext = thisContext.push(subno);
}
foundno = true;
continue;
}
}
if (!foundno) {
System.out.println("Unable to find "+names[i]+" in "+paramName);
break;
}
}
Network net = findNet(thisNetlist, names[names.length-1]);
if (net != null) {
HierarchyEnumerator.NetNameProxy proxy = new HierarchyEnumerator.NetNameProxy(
thisContext, ".x", net);
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
}
} else {
// net may be exported and named at higher level, use getUniqueName
Network net = findNet(info.getNetlist(), paramName);
if (net != null) {
if (flatNetNames) {
HierarchyEnumerator.NetNameProxy proxy = info.getUniqueNetNameProxy(net, ".x");
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
} else {
hierName = cni.getCellSignal(net).getName();
}
}
}
// convert to spice format
if (hierName != null) {
if (flatNetNames) {
if (hierName.indexOf(".x") > 0) {
hierName = "x"+hierName;
}
// remove x in front of net name
int i = hierName.lastIndexOf(".x");
if (i > 0)
hierName = hierName.substring(0, i+1) + hierName.substring(i+2);
else {
i = hierName.lastIndexOf("."+paramName);
if (i > 0) {
hierName = hierName.substring(0, i) + "_" + hierName.substring(i+1);
}
}
}
infstr.append(hierName);
found = true;
}
if (!found) {
System.out.println("Unable to lookup key $("+paramName+") in cell "+context.getInstPath("."));
}
}
}
return infstr.getStringBuffer();
}
private static class StringBufferQuoteParity
{
private StringBuffer sb = new StringBuffer();
private int quoteCount;
private int parenDepth;
void append(String str)
{
sb.append(str);
for(int i=0; i<str.length(); i++)
{
char ch = str.charAt(i);
if (ch == '\'') quoteCount++; else
if (ch == '(') parenDepth++; else
if (ch == ')') parenDepth--;
}
}
void append(char c)
{
sb.append(c);
if (c == '\'') quoteCount++; else
if (c == '(') parenDepth++; else
if (c == ')') parenDepth--;
}
boolean inQuotes() { return (quoteCount&1) != 0; }
boolean inParens() { return parenDepth > 0; }
StringBuffer getStringBuffer() { return sb; }
}
/**
* Find vars in 'line'. Ports and Vars should be referenced via $(name)
* @param line the string to search and replace within
* @param prototype of instance that has the parameters on it
* @param isPortReplacement true if port name replacement will be done)
* @parm
*/
private void findVarsInLine(String line, NodeProto prototype, boolean isPortReplacement, Set<Variable.Key> vars) {
PrimitiveNode prim = null;
if (prototype != null) {
if (prototype instanceof PrimitiveNode) prim = (PrimitiveNode)prototype;
}
for(int pt = 0; pt < line.length(); pt++) {
// see if the character is part of a substitution expression
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(') {
// not part of substitution: just emit it
continue;
}
// may be part of substitution expression: look for closing parenthesis
int start = pt + 2;
for(pt = start; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
// do the parameter substitution
String paramName = line.substring(start, pt);
PortProto pp = null;
if (prototype != null) {
pp = prototype.findPortProto(paramName);
}
Variable.Key varKey;
if (paramName.equalsIgnoreCase("node_name") && prototype != null) continue;
if (paramName.equalsIgnoreCase("width") && prim != null) continue;
if (paramName.equalsIgnoreCase("length") && prim != null) continue;
if (isPortReplacement && pp != null) continue;
if (prototype != null && (varKey = Variable.findKey("ATTR_" + paramName)) != null) {
if (prototype instanceof PrimitiveNode || ((Cell) prototype).getParameterOrVariable(varKey) != null)
vars.add(varKey);
}
}
}
private Network findNet(Netlist netlist, String netName)
{
Network foundnet = null;
for (Iterator<Network> it = netlist.getNetworks(); it.hasNext(); ) {
Network net = it.next();
if (net.hasName(netName)) {
foundnet = net;
break;
}
}
return foundnet;
}
/**
* Get the global associated with this net. Returns null if net is
* not a global.
* @param net
* @return global associated with this net, or null if not global
*/
private Global getGlobal(Network net)
{
Netlist netlist = net.getNetlist();
for (int i=0; i<netlist.getGlobals().size(); i++) {
Global g = netlist.getGlobals().get(i);
if (netlist.getNetwork(g) == net)
return g;
}
return null;
}
/****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/
/**
* Method to adjust a cell name to be safe for Spice output.
* @param name the cell name.
* @return the name, adjusted for Spice output.
*/
protected String getSafeCellName(String name)
{
return getSafeNetName(name, false);
}
/** Method to return the proper name of Power */
protected String getPowerName(Network net)
{
if (net != null)
{
// favor "vdd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("vdd")) return "vdd";
}
}
return null;
}
/** Method to return the proper name of Ground */
protected String getGroundName(Network net)
{
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) return "0";
if (net != null)
{
// favor "gnd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("gnd")) return "gnd";
}
}
return null;
}
/** Method to return the proper name of a Global signal */
protected String getGlobalName(Global glob) { return glob.getName(); }
/** Method to report that export names do NOT take precedence over
* arc names when determining the name of the network. */
protected boolean isNetworksUseExportedNames() { return false; }
/** Method to report that library names are NOT always prepended to cell names. */
protected boolean isLibraryNameAlwaysAddedToCellName() { return false; }
/** Method to report that aggregate names (busses) are not used. */
protected boolean isAggregateNamesSupported() { return false; }
/** Abstract method to decide whether aggregate names (busses) can have gaps in their ranges. */
protected boolean isAggregateNameGapsSupported() { return false; }
/** Method to report whether input and output names are separated. */
protected boolean isSeparateInputAndOutput() { return false; }
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
protected String getSafeNetName(String name, boolean bus)
{
return getSafeNetName(name, bus, legalSpiceChars, spiceEngine);
}
/**
* Method called during hierarchy traversal.
* Called at the end of the enter cell phase.
*/
protected void enterCell(HierarchyEnumerator.CellInfo info)
{
if (exemptedNets != null)
exemptedNets.setExemptedNets(info);
}
/** Method to report that not to choose best export name among exports connected to signal. */
protected boolean isChooseBestExportName() { return false; }
/** If the netlister has requirments not to netlist certain cells and their
* subcells, override this method.
* If this cell has a spice template, skip it
*/
protected boolean skipCellAndSubcells(Cell cell)
{
// skip if there is a template
Variable varTemplate = null;
varTemplate = getEngineTemplate(cell);
if (varTemplate != null) return true;
// look for a model file for the current cell, can come from pref or on cell
String fileName = null;
if (CellModelPrefs.spiceModelPrefs.isUseModelFromFile(cell)) {
fileName = CellModelPrefs.spiceModelPrefs.getModelFile(cell);
}
varTemplate = cell.getVar(SPICE_NETLIST_FILE_KEY);
if (varTemplate != null) {
Object obj = varTemplate.getObject();
if (obj instanceof String) {
String str = (String)obj;
if (!str.equals("") && !str.equals("*Undefined"))
fileName = str;
}
}
if (fileName != null) {
if (!modelOverrides.containsKey(cell))
{
String absFileName = fileName;
if (!fileName.startsWith("/") && !fileName.startsWith("\\")) {
File spiceFile = new File(filePath);
absFileName = (new File(spiceFile.getParent(), fileName)).getPath();
}
boolean alreadyIncluded = false;
for (String includeFile : modelOverrides.values()) {
if (absFileName.equals(includeFile))
alreadyIncluded = true;
}
if (alreadyIncluded) {
multiLinePrint(true, "\n* " + cell + " is described in this file:\n");
multiLinePrint(true, "* "+fileName+" (already included) \n");
} else {
multiLinePrint(true, "\n* " + cell + " is described in this file:\n");
addIncludeFile(fileName);
}
modelOverrides.put(cell, absFileName);
}
return true;
}
return false;
}
/**
* Method called when a cell is skipped.
* Performs any checking to validate that no error occurs.
*/
protected void validateSkippedCell(HierarchyEnumerator.CellInfo info) {
String fileName = modelOverrides.get(info.getCell());
if (fileName != null) {
// validate included file
SpiceNetlistReader reader = new SpiceNetlistReader();
try {
reader.readFile(fileName, false);
HierarchyEnumerator.CellInfo parentInfo = info.getParentInfo();
Nodable no = info.getParentInst();
String parameterizedName = info.getCell().getName();
if (no != null && parentInfo != null) {
parameterizedName = parameterizedName(no, parentInfo.getContext());
}
CellNetInfo cni = getCellNetInfo(parameterizedName);
SpiceSubckt subckt = reader.getSubckt(parameterizedName);
if (cni != null && subckt != null) {
if (subckt == null) {
System.out.println("Error: No subckt for "+parameterizedName+" found in included file: "+fileName);
} else {
List<String> signals = new ArrayList<String>();
for (Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); ) {
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
signals.add(cs.getName());
}
List<String> subcktSignals = subckt.getPorts();
if (signals.size() != subcktSignals.size()) {
System.out.println("Warning: wrong number of ports for subckt "+
parameterizedName+": expected "+signals.size()+", but found "+
subcktSignals.size()+", in included file "+fileName);
}
int len = Math.min(signals.size(), subcktSignals.size());
for (int i=0; i<len; i++) {
String s1 = signals.get(i);
String s2 = subcktSignals.get(i);
if (!s1.equalsIgnoreCase(s2)) {
System.out.println("Warning: port "+i+" of subckt "+parameterizedName+
" is named "+s1+" in Electric, but "+s2+" in included file "+fileName);
}
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Error validating included file for cell "+info.getCell().describe(true)+": "+e.getMessage());
}
}
}
/** Tell the Hierarchy enumerator how to short resistors */
@Override
protected Netlist.ShortResistors getShortResistors() {
// TODO use the value of Simulation.getSpiceShortResistors()
// switch (Simulation.getSpiceShortResistors())
// {
// case 0: return Netlist.ShortResistors.NO;
// case 1: return Netlist.ShortResistors.PARASITIC;
// case 2: return Netlist.ShortResistors.ALL;
// }
if (useCDL && Simulation.getCDLIgnoreResistors())
return Netlist.ShortResistors.PARASITIC;
// this option is used for writing spice netlists for LVS and RCX
if (Simulation.isSpiceIgnoreParasiticResistors())
return Netlist.ShortResistors.PARASITIC;
return Netlist.ShortResistors.NO;
}
/**
* Method to tell whether the topological analysis should mangle cell names that are parameterized.
*/
protected boolean canParameterizeNames() { return true; } //return !useCDL; }
/**
* Method to tell set a limit on the number of characters in a name.
* @return the limit to name size (SPICE limits to 32 character names?????).
*/
protected int maxNameLength() { if (useCDL) return CDLMAXLENSUBCKTNAME; return SPICEMAXLENSUBCKTNAME; }
protected boolean enumerateLayoutView(Cell cell) {
return (CellModelPrefs.spiceModelPrefs.isUseLayoutView(cell));
}
private Netlist.ShortResistors getShortResistorsFlat() {
return Netlist.ShortResistors.ALL;
}
/******************** DECK GENERATION SUPPORT ********************/
/**
* Method to write M factor information into a given string buffer
* @param context the context of the nodable for finding M-factors farther up the hierarchy.
* @param no Nodable representing the node
* @param infstr Buffer where to write to
*/
private void writeMFactor(VarContext context, Nodable no, StringBuffer infstr)
{
Variable mVar = no.getVar(Simulation.M_FACTOR_KEY);
if (mVar == null) return;
Object value = context.evalVar(mVar);
// check for M=@M, and warn user that this is a bad idea, and we will not write it out
if (mVar.getObject().toString().equals("@M") || (mVar.getObject().toString().equals("P(\"M\")")))
{
System.out.println("Warning: M=@M [eval=" + value + "] on " + no.getName() +
" is a bad idea, not writing it out: " + context.push(no).getInstPath("."));
return;
}
infstr.append(" M=" + formatParam(value.toString(), TextDescriptor.Unit.NONE, false));
}
/**
* write a header for "cell" to spice deck "sim_spice_file"
* The model cards come from a file specified by tech:~.SIM_spice_model_file
* or else tech:~.SIM_spice_header_level%ld
* The spice model file can be located in el_libdir
*/
private void writeHeader(Cell cell)
{
// Print the header line for SPICE
multiLinePrint(true, "*** SPICE deck for cell " + cell.noLibDescribe() +
" from library " + cell.getLibrary().getName() + "\n");
emitCopyright("*** ", "");
if (User.isIncludeDateAndVersionInOutput())
{
multiLinePrint(true, "*** Created on " + TextUtils.formatDate(topCell.getCreationDate()) + "\n");
multiLinePrint(true, "*** Last revised on " + TextUtils.formatDate(topCell.getRevisionDate()) + "\n");
multiLinePrint(true, "*** Written on " + TextUtils.formatDate(new Date()) +
" by Electric VLSI Design System, version " + Version.getVersion() + "\n");
} else
{
multiLinePrint(true, "*** Written by Electric VLSI Design System\n");
}
String foundry = layoutTechnology.getSelectedFoundry() == null ? "" : (", foundry "+layoutTechnology.getSelectedFoundry().toString());
multiLinePrint(true, "*** Layout tech: "+layoutTechnology.getTechName()+foundry+"\n");
multiLinePrint(true, "*** UC SPICE *** , MIN_RESIST " + layoutTechnology.getMinResistance() +
", MIN_CAPAC " + layoutTechnology.getMinCapacitance() + "FF\n");
boolean useParasitics = !useCDL &&
Simulation.getSpiceParasiticsLevel() != Simulation.SpiceParasitics.SIMPLE &&
cell.getView() == View.LAYOUT;
if (useParasitics) {
for (Layer layer : layoutTechnology.getLayersSortedByHeight()) {
if (layer.isPseudoLayer()) continue;
double edgecap = layer.getEdgeCapacitance();
double areacap = layer.getCapacitance();
double res = layer.getResistance();
if (edgecap != 0 || areacap != 0 || res != 0) {
multiLinePrint(true, "*** "+layer.getName()+":\tareacap="+areacap+"FF/um^2,\tedgecap="+edgecap+"FF/um,\tres="+res+"ohms/sq\n");
}
}
}
multiLinePrint(false, ".OPTIONS NOMOD NOPAGE\n");
if (Simulation.isSpiceUseCellParameters()) {
multiLinePrint(false, ".options parhier=local\n");
}
// if sizes to be written in lambda, tell spice conversion factor
if (Simulation.isSpiceWriteTransSizeInLambda())
{
double scale = layoutTechnology.getScale();
multiLinePrint(true, "*** Lambda Conversion ***\n");
multiLinePrint(false, ".opt scale=" + TextUtils.formatDouble(scale / 1000.0) + "U\n\n");
}
// see if spice model/option cards from file if specified
String headerFile = Simulation.getSpiceHeaderCardInfo();
if (headerFile.length() > 0 && !headerFile.startsWith(SPICE_NOEXTENSION_PREFIX))
{
if (headerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String headerPath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = headerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Header Card '" + fileName + "' is included");
return;
}
System.out.println("Spice Header Card '" + fileName + "' cannot be loaded");
} else
{
// normal header file specified
File test = new File(headerFile);
if (!test.exists())
System.out.println("Warning: cannot find model file '" + headerFile + "'");
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(headerFile);
return;
}
}
// no header files: write predefined header for this level and technology
int level = TextUtils.atoi(Simulation.getSpiceLevel());
String [] header = null;
switch (level)
{
case 1: header = layoutTechnology.getSpiceHeaderLevel1(); break;
case 2: header = layoutTechnology.getSpiceHeaderLevel2(); break;
case 3: header = layoutTechnology.getSpiceHeaderLevel3(); break;
}
if (header != null)
{
for(int i=0; i<header.length; i++)
multiLinePrint(false, header[i] + "\n");
return;
}
System.out.println("WARNING: no model cards for SPICE level " + level +
" in " + layoutTechnology.getTechName() + " technology");
}
/**
* Write a trailer from an external file, defined as a variable on
* the current technology in this library: tech:~.SIM_spice_trailer_file
* if it is available.
*/
private void writeTrailer(Cell cell)
{
// get spice trailer cards from file if specified
String trailerFile = Simulation.getSpiceTrailerCardInfo();
if (trailerFile.length() > 0 && !trailerFile.startsWith(SPICE_NOEXTENSION_PREFIX))
{
if (trailerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String trailerpath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = trailerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = trailerpath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Trailer Card '" + fileName + "' is included");
}
else
System.out.println("Spice Trailer Card '" + fileName + "' cannot be loaded");
} else
{
// normal trailer file specified
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(trailerFile);
System.out.println("Spice Trailer Card '" + trailerFile + "' is included");
}
}
}
/**
* Function to write a two port device to the file. Complain about any missing connections.
* Determine the port connections from the portprotos in the instance
* prototype. Get the part number from the 'part' number value;
* increment it. The type of device is declared in type; extra is the string
* data acquired before calling here.
* If the device is connected to the same net at both ends, do not
* write it. Is this OK?
*/
private void writeTwoPort(NodeInst ni, String partName, String extra, CellNetInfo cni, Netlist netList,
VarContext context, SpiceSegmentedNets segmentedNets)
{
PortInst port0 = ni.getPortInst(0);
PortInst port1 = ni.getPortInst(1);
Network net0 = netList.getNetwork(port0);
Network net1 = netList.getNetwork(port1);
CellSignal cs0 = cni.getCellSignal(net0);
CellSignal cs1 = cni.getCellSignal(net1);
// make sure the component is connected to nets
if (cs0 == null || cs1 == null)
{
String message = "WARNING: " + ni + " component not fully connected in " + ni.getParent();
dumpErrorMessage(message);
}
if (cs0 != null && cs1 != null && cs0 == cs1)
{
String message = "WARNING: " + ni + " component appears to be shorted on net " + net0.toString() +
" in " + ni.getParent();
dumpErrorMessage(message);
return;
}
if (ni.getName() != null) partName += getSafeNetName(ni.getName(), false);
// add Mfactor if there
StringBuffer sbExtra = new StringBuffer(extra);
writeMFactor(context, ni, sbExtra);
String name0 = cs0.getName();
String name1 = cs1.getName();
if (segmentedNets != null) {
name0 = segmentedNets.getNetName(port0);
name1 = segmentedNets.getNetName(port1);
}
multiLinePrint(false, partName + " " + name1 + " " + name0 + " " + sbExtra.toString() + "\n");
}
/******************** SIMPLE PARASITIC CALCULATIONS (AREA/PERIM) ********************/
/**
* Method to recursively determine the area of diffusion and capacitance
* associated with port "pp" of nodeinst "ni". If the node is mult_layer, then
* determine the dominant capacitance layer, and add its area; all other
* layers will be added as well to the extra_area total.
* Continue out of the ports on a complex cell
*/
private void addNodeInformation(Netlist netList, Map<Network,SpiceNet> spiceNets, NodeInst ni)
{
// cells have no area or capacitance (for now)
if (ni.isCellInstance()) return; // No area for complex nodes
PrimitiveNode.Function function = ni.getFunction();
// initialize to examine the polygons on this node
Technology tech = ni.getProto().getTechnology();
AffineTransform trans = ni.rotateOut();
// make linked list of polygons
Poly [] polyList = tech.getShapeOfNode(ni, true, true, null);
int tot = polyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = polyList[i];
// make sure this layer connects electrically to the desired port
PortProto pp = poly.getPort();
if (pp == null) continue;
Network net = netList.getNetwork(ni, pp, 0);
// don't bother with layers without capacity
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != Technology.getCurrent()) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() == 0.0) continue;
// leave out the gate capacitance of transistors
if (layer.getFunction() == Layer.Function.GATE) continue;
SpiceNet spNet = spiceNets.get(net);
if (spNet == null) continue;
// get the area of this polygon
poly.transform(trans);
spNet.merge.addPolygon(layer, poly);
// count the number of transistors on this net
if (layer.isDiffusionLayer() && function.isTransistor()) spNet.transistorCount++;
}
}
/**
* Method to recursively determine the area of diffusion, capacitance, (NOT
* resistance) on arc "ai". If the arc contains active device diffusion, then
* it will contribute to the area of sources and drains, and the other layers
* will be ignored. This is not quite the same as the rule used for
* contact (node) structures. Note: the earlier version of this
* function assumed that diffusion arcs would always have zero capacitance
* values for the other layers; this produces an error if any of these layers
* have non-zero values assigned for other reasons. So we will check for the
* function of the arc, and if it contains active device, we will ignore any
* other layers
*/
private void addArcInformation(PolyMerge merge, ArcInst ai)
{
boolean isDiffArc = ai.isDiffusionArc(); // check arc function
if (!isDiffArc) {
// all cap besides diffusion is handled by segmented nets
return;
}
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != Technology.getCurrent()) continue;
if (layer.isDiffusionLayer() ||
(!isDiffArc && layer.getCapacitance() > 0.0))
merge.addPolygon(layer, poly);
}
}
/******************** SUPPORT ********************/
private boolean ignoreSubcktPort(CellSignal cs)
{
if (Simulation.isSpiceUseNodeNames() && spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) return true;
}
return false;
}
/**
* Finds cells that must be uniquified during netlisting. These are
* cells that have parameters which are Java Code. Because the Java Code
* expression can return values that are different for different instances
* in the hierarchy, the hierarchy must be flattened above that instance.
* @param cell the cell hierarchy to check
* @return true if the cell has been marked to unquify (which is true if
* any cell below it has been marked).
*/
private boolean markCellsToUniquify(Cell cell)
{
//System.out.println("Checking Cell "+cell.describe());
if (uniquifyCells.containsKey(cell)) return uniquifyCells.get(cell) != null;
boolean mark = false;
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
if (ni.isIconOfParent()) continue;
Set<Variable.Key> varkeys = detectSpiceParams(ni.getProto());
// check vars on instance; only uniquify cells that contain instances with Java params
for (Variable.Key key : varkeys) {
Variable var = ni.getVar(key);
if (var != null && !isNetlistableParam(var)) mark = true;
}
if (!ni.isCellInstance()) continue;
Cell proto = ((Cell)ni.getProto()).contentsView();
if (proto == null) proto = (Cell)ni.getProto();
if (markCellsToUniquify(proto)) { mark = true; }
}
assert mark == (detectSpiceParams(cell) == UNIQUIFY_MARK);
if (mark)
uniquifyCells.put(cell, cell);
else
uniquifyCells.put(cell, null);
//System.out.println("---> "+cell.describe(false)+" is marked "+mark);
return mark;
}
private static final boolean CELLISEMPTYDEBUG = false;
private Map<Cell,Boolean> checkedCells = new HashMap<Cell,Boolean>();
private boolean cellIsEmpty(Cell cell)
{
Boolean b = checkedCells.get(cell);
if (b != null) return b.booleanValue();
boolean empty = true;
boolean useParasitics = !useCDL &&
Simulation.getSpiceParasiticsLevel() != Simulation.SpiceParasitics.SIMPLE &&
cell.getView() == View.LAYOUT;
if (useParasitics) return false;
List<Cell> emptyCells = new ArrayList<Cell>();
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
// if node is a cell, check if subcell is empty
if (ni.isCellInstance()) {
// ignore own icon
if (ni.isIconOfParent()) {
continue;
}
Cell iconCell = (Cell)ni.getProto();
Cell schCell = iconCell.contentsView();
if (schCell == null) schCell = iconCell;
if (cellIsEmpty(schCell)) {
if (CELLISEMPTYDEBUG) emptyCells.add(schCell);
continue;
}
empty = false;
break;
}
// otherwise, this is a primitive
PrimitiveNode.Function fun = ni.getFunction();
// Passive devices used by spice/CDL
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
empty = false;
break;
}
// active devices used by Spice/CDL
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
empty = false;
break;
}
// check for spice code on pins
if (ni.getVar(SPICE_CARD_KEY) != null) {
empty = false;
break;
}
}
// look for a model file on the current cell
if (modelOverrides.get(cell) != null) {
empty = false;
}
// check for spice template
if (getEngineTemplate(cell) != null) {
empty = false;
}
// empty
if (CELLISEMPTYDEBUG && empty) {
System.out.println(cell+" is empty and contains the following empty cells:");
for (Cell c : emptyCells)
System.out.println(" "+c.describe(true));
}
checkedCells.put(cell, Boolean.valueOf(empty));
return empty;
}
/******************** TEXT METHODS ********************/
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
public static String getSafeNetName(String name)
{
String legalSpiceChars = SPICELEGALCHARS;
if (Simulation.getSpiceEngine() == Simulation.SpiceEngine.SPICE_ENGINE_P)
legalSpiceChars = PSPICELEGALCHARS;
return getSafeNetName(name, false, legalSpiceChars, Simulation.getSpiceEngine());
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
private static String getSafeNetName(String name, boolean bus, String legalSpiceChars, Simulation.SpiceEngine spiceEngine)
{
// simple names are trivially accepted as is
boolean allAlNum = true;
int len = name.length();
if (len <= 0) return name;
for(int i=0; i<len; i++)
{
boolean valid = TextUtils.isLetterOrDigit(name.charAt(i));
if (i == 0) valid = Character.isLetter(name.charAt(i));
if (!valid)
{
allAlNum = false;
break;
}
}
if (allAlNum) return name;
StringBuffer sb = new StringBuffer();
if (TextUtils.isDigit(name.charAt(0)) &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_G &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_P &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_2) sb.append('_');
for(int t=0; t<name.length(); t++)
{
char chr = name.charAt(t);
boolean legalChar = TextUtils.isLetterOrDigit(chr);
if (!legalChar)
{
for(int j=0; j<legalSpiceChars.length(); j++)
{
char legalChr = legalSpiceChars.charAt(j);
if (chr == legalChr) { legalChar = true; break; }
}
}
if (!legalChar) chr = '_';
sb.append(chr);
}
return sb.toString();
}
/**
* This adds formatting to a Spice parameter value. It adds single quotes
* around the param string if they do not already exist.
* @param param the string param value (without the name= part).
* @param wrapped true if the string is already "wrapped" (with parenthesis) and does not need to have quotes around it.
* @return a param string with single quotes around it
*/
private String formatParam(String param, TextDescriptor.Unit u, boolean wrapped)
{
// first remove quotes
String value = trimSingleQuotes(param);
// see if the result evaluates to a number
if (TextUtils.isANumberPostFix(value)) return value;
// if purely numeric, try converting to proper units
try {
Double v = Double.valueOf(value);
if (u == TextDescriptor.Unit.DISTANCE)
return TextUtils.formatDoublePostFix(v.doubleValue());
return value;
} catch (NumberFormatException e) {}
// not a number: if Spice engine cannot handle quotes, return stripped value
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3) return value;
// not a number but Spice likes quotes, enclose it
if (!wrapped) value = "'" + value + "'";
return value;
}
private String trimSingleQuotes(String param)
{
if (param.startsWith("'") && param.endsWith("'")) {
return param.substring(1, param.length()-1);
}
return param;
}
/**
* Method to insert an "include" of file "filename" into the stream "io".
*/
private void addIncludeFile(String fileName)
{
if (useCDL) {
multiLinePrint(false, ".include "+ fileName + "\n");
return;
}
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_S)
{
multiLinePrint(false, ".include " + fileName + "\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_CALIBRE)
{
multiLinePrint(false, ".include '" + fileName + "'\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P)
{
multiLinePrint(false, ".INC " + fileName + "\n");
}
}
/**
* Method to report an error that is built in the infinite string.
* The error is sent to the messages window and also to the SPICE deck "f".
*/
private void dumpErrorMessage(String message)
{
multiLinePrint(true, "*** " + message + "\n");
System.out.println(message);
}
/**
* Formatted output to file "stream". All spice output is in upper case.
* The buffer can contain no more than 1024 chars including the newlinelastMoveTo
* and null characters.
* Doesn't return anything.
*/
public void multiLinePrint(boolean isComment, String str)
{
// put in line continuations, if over 78 chars long
char contChar = '+';
if (isComment) contChar = '*';
int lastSpace = -1;
int count = 0;
boolean insideQuotes = false;
int lineStart = 0;
for (int pt = 0; pt < str.length(); pt++)
{
char chr = str.charAt(pt);
// if (sim_spice_machine == SPICE2)
// {
// if (islower(*pt)) *pt = toupper(*pt);
// }
if (chr == '\n')
{
printWriter.print(str.substring(lineStart, pt+1));
count = 0;
lastSpace = -1;
lineStart = pt+1;
} else
{
if (chr == ' ' && !insideQuotes) lastSpace = pt;
if (chr == '\'') insideQuotes = !insideQuotes;
count++;
if (count >= spiceMaxLenLine && !insideQuotes && lastSpace > -1)
{
String partial = str.substring(lineStart, lastSpace+1);
printWriter.print(partial + "\n" + contChar);
count = count - partial.length();
lineStart = lastSpace+1;
lastSpace = -1;
}
}
}
if (lineStart < str.length())
{
String partial = str.substring(lineStart);
printWriter.print(partial);
}
}
/******************** SUPPORT CLASSES ********************/
private static class SpiceNet
{
/** network object associated with this */ Network network;
/** merged geometry for this network */ PolyMerge merge;
/** area of diffusion */ double diffArea;
/** perimeter of diffusion */ double diffPerim;
/** amount of capacitance in non-diff */ float nonDiffCapacitance;
/** number of transistors on the net */ int transistorCount;
SpiceNet(Network net)
{
network = net;
transistorCount = 0;
diffArea = 0;
diffPerim = 0;
nonDiffCapacitance = 0;
merge = new PolyMerge();
}
}
private static class SpiceFinishedListener implements Exec.FinishedListener
{
private Cell cell;
private FileType type;
private String file;
private SpiceFinishedListener(Cell cell, FileType type, String file) {
this.cell = cell;
this.type = type;
this.file = file;
}
public void processFinished(Exec.FinishedEvent e) {
URL fileURL = TextUtils.makeURLToFile(file);
// create a new waveform window
WaveformWindow ww = WaveformWindow.findWaveformWindow(cell);
Simulate.plotSimulationResults(type, cell, fileURL, ww);
}
}
public static class FlatSpiceCodeVisitor extends HierarchyEnumerator.Visitor {
private PrintWriter printWriter;
private PrintWriter spicePrintWriter;
private String filePath;
Spice spice; // just used for file writing and formatting
SpiceSegmentedNets segNets;
public FlatSpiceCodeVisitor(String filePath, Spice spice) {
this.spice = spice;
this.spicePrintWriter = spice.printWriter;
this.filePath = filePath;
spice.spiceMaxLenLine = 1000;
segNets = null;
}
public boolean enterCell(HierarchyEnumerator.CellInfo info) {
return true;
}
public void exitCell(HierarchyEnumerator.CellInfo info) {
Cell cell = info.getCell();
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CODE_FLAT_KEY);
if (cardVar != null) {
if (printWriter == null) {
try {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath)));
} catch (IOException e) {
System.out.println("Unable to open "+filePath+" for write.");
return;
}
spice.printWriter = printWriter;
segNets = new SpiceSegmentedNets(null, false, null, Simulation.SpiceParasitics.SIMPLE);
}
spice.emitEmbeddedSpice(cardVar, info.getContext(), segNets, info, true, true);
}
}
}
public boolean visitNodeInst(Nodable ni, HierarchyEnumerator.CellInfo info) {
return true;
}
public void close() {
if (printWriter != null) {
System.out.println(filePath+" written");
spice.printWriter = spicePrintWriter;
printWriter.close();
}
spice.spiceMaxLenLine = SPICEMAXLENLINE;
}
}
}
| true | true | protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
// if this is the top level cell, write globals
if (cell == topCell)
{
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
// make sure power and ground appear at the top level
if (!Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
}
// create electrical nets (SpiceNet) for every Network in the cell
Netlist netList = cni.getNetList();
Map<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = new SpiceNet(net);
spiceNetMap.put(net, spNet);
}
// for non-simple parasitics, create a SpiceSegmentedNets object to deal with them
Simulation.SpiceParasitics spLevel = Simulation.getSpiceParasiticsLevel();
if (useCDL || cell.getView() != View.LAYOUT) spLevel = Simulation.SpiceParasitics.SIMPLE;
SpiceSegmentedNets segmentedNets = null;
if (spLevel != Simulation.SpiceParasitics.SIMPLE)
{
// make the parasitics info object if it does not already exist
if (parasiticInfo == null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo = new SpiceParasitic();
} else if (spLevel == Simulation.SpiceParasitics.RC_CONSERVATIVE)
{
parasiticInfo = new SpiceRCSimple();
}
}
segmentedNets = parasiticInfo.initializeSegments(cell, cni, layoutTechnology, exemptedNets, info);
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun.isNTypeTransistor()) nmosTrans++; else
if (fun.isPTypeTransistor()) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
boolean forceEval = useCDL || !Simulation.isSpiceUseCellParameters() || detectSpiceParams(cell) == UNIQUIFY_MARK;
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (!cs.isGlobal() && cs.getExport() == null) continue;
// special case for parasitic extraction
if (parasiticInfo != null && !cs.isGlobal() && cs.getExport() != null)
{
parasiticInfo.writeSubcircuitHeader(cs, infstr);
} else
{
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
Set<Variable.Key> spiceParams = detectSpiceParams(cell);
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
String value = paramVar.getPureValue(-1);
if (USE_JAVA_CODE) {
value = evalParam(context, info.getParentInst(), paramVar, forceEval);
} else if (!isNetlistableParam(paramVar))
continue;
infstr.append(" " + paramVar.getTrueName() + "=" + value);
}
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// get the SPICE template on the prototype (if any)
Variable varTemplate = getEngineTemplate(subCell);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts)
{
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto)) continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
if (ignoreSubcktPort(subCS)) continue;
PortProto pp = subCS.getExport();
if (!subCS.isGlobal() && pp == null) continue;
// If global pwr/vdd will be included in the subcircuit
// Preparing code for bug #1828
// if (!Simulation.isSpiceWritePwrGndInTopCell() && pp!= null && subCS.isGlobal() && (subCS.isGround() || subCS.isPower()))
// continue;
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with swapped-in layout subcells
if (pp != null && cell.isSchematic() && (subCni.getCell().getView() == View.LAYOUT))
{
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); )
{
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++)
{
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName()))
{
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found)
{
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (subCS.isGlobal())
{
net = netList.getNetwork(no, subCS.getGlobal());
}
else
net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
SpiceSegmentedNets subSN = null;
if (parasiticInfo != null && !cs.isGlobal())
subSN = parasiticInfo.getSegmentedNets((Cell)no.getProto());
if (subSN != null)
{
parasiticInfo.getParasiticName(no, subCS.getNetwork(), subSN, infstr);
} else
{
String name = cs.getName();
if (parasiticInfo != null)
{
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) infstr.append(" /"); else infstr.append(" ");
infstr.append(subCni.getParameterizedName());
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
Set<Variable.Key> spiceParams = detectSpiceParams(subCell);
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
if (!USE_JAVA_CODE && !isNetlistableParam(paramVar)) continue;
Variable instVar = no.getParameter(paramVar.getKey());
String paramStr = "??";
if (instVar != null)
{
if (USE_JAVA_CODE)
{
paramStr = evalParam(context, no, instVar, forceEval);
} else
{
Object obj = null;
if (isNetlistableParam(instVar))
{
obj = context.evalSpice(instVar, false);
} else
{
obj = context.evalVar(instVar, no);
}
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit(), false);
}
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, ni, resistVar, forceEval);
} else {
if (resistVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit(), false);
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
else if (fun == PrimitiveNode.Function.WRESIST) {
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) {
extra = "rnwod "+extra;
}
if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) {
extra = "rpwod "+extra;
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, capacVar, forceEval);
} else {
if (capacVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit(), false);
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, inductVar, forceEval);
} else {
if (inductVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit(), false);
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets != null) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets != null && ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (segmentedNets != null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo.writeNewSpiceCode(cell, cni, layoutTechnology, this);
} else {
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SpiceSegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.getCap() > cell.getTechnology().getMinCapacitance()) {
if (netInfo.getName().equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.getName() + " 0 " + TextUtils.formatDouble(netInfo.getCap()) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.getRes(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SpiceSegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue()) + "\n");
resCount++;
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
| protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
// if this is the top level cell, write globals
if (cell == topCell)
{
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
// make sure power and ground appear at the top level
if (!Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
}
// create electrical nets (SpiceNet) for every Network in the cell
Netlist netList = cni.getNetList();
Map<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = new SpiceNet(net);
spiceNetMap.put(net, spNet);
}
// for non-simple parasitics, create a SpiceSegmentedNets object to deal with them
Simulation.SpiceParasitics spLevel = Simulation.getSpiceParasiticsLevel();
if (useCDL || cell.getView() != View.LAYOUT) spLevel = Simulation.SpiceParasitics.SIMPLE;
SpiceSegmentedNets segmentedNets = null;
if (spLevel != Simulation.SpiceParasitics.SIMPLE)
{
// make the parasitics info object if it does not already exist
if (parasiticInfo == null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo = new SpiceParasitic();
} else if (spLevel == Simulation.SpiceParasitics.RC_CONSERVATIVE)
{
parasiticInfo = new SpiceRCSimple();
}
}
segmentedNets = parasiticInfo.initializeSegments(cell, cni, layoutTechnology, exemptedNets, info);
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun.isNTypeTransistor()) nmosTrans++; else
if (fun.isPTypeTransistor()) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
boolean forceEval = useCDL || !Simulation.isSpiceUseCellParameters() || detectSpiceParams(cell) == UNIQUIFY_MARK;
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (!cs.isGlobal() && cs.getExport() == null) continue;
// special case for parasitic extraction
if (parasiticInfo != null && !cs.isGlobal() && cs.getExport() != null)
{
parasiticInfo.writeSubcircuitHeader(cs, infstr);
} else
{
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
Set<Variable.Key> spiceParams = detectSpiceParams(cell);
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
String value = paramVar.getPureValue(-1);
if (USE_JAVA_CODE) {
value = evalParam(context, info.getParentInst(), paramVar, forceEval);
} else if (!isNetlistableParam(paramVar))
continue;
infstr.append(" " + paramVar.getTrueName() + "=" + value);
}
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// boolean includePwrVdd = Simulation.isSpiceWritePwrGndInTopCell();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// get the SPICE template on the prototype (if any)
Variable varTemplate = getEngineTemplate(subCell);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts)
{
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto)) continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
if (ignoreSubcktPort(subCS)) continue;
PortProto pp = subCS.getExport();
if (!subCS.isGlobal() && pp == null) continue;
// If global pwr/vdd will be included in the subcircuit
// Preparing code for bug #1828
// if (!Simulation.isSpiceWritePwrGndInTopCell() && pp!= null && subCS.isGlobal() && (subCS.isGround() || subCS.isPower()))
// continue;
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with swapped-in layout subcells
if (pp != null && cell.isSchematic() && (subCni.getCell().getView() == View.LAYOUT))
{
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); )
{
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++)
{
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName()))
{
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found)
{
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (subCS.isGlobal())
{
net = netList.getNetwork(no, subCS.getGlobal());
}
else
net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
SpiceSegmentedNets subSN = null;
if (parasiticInfo != null && !cs.isGlobal())
subSN = parasiticInfo.getSegmentedNets((Cell)no.getProto());
if (subSN != null)
{
parasiticInfo.getParasiticName(no, subCS.getNetwork(), subSN, infstr);
} else
{
String name = cs.getName();
if (parasiticInfo != null)
{
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) infstr.append(" /"); else infstr.append(" ");
infstr.append(subCni.getParameterizedName());
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
Set<Variable.Key> spiceParams = detectSpiceParams(subCell);
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
if (!USE_JAVA_CODE && !isNetlistableParam(paramVar)) continue;
Variable instVar = no.getParameter(paramVar.getKey());
String paramStr = "??";
if (instVar != null)
{
if (USE_JAVA_CODE)
{
paramStr = evalParam(context, no, instVar, forceEval);
} else
{
Object obj = null;
if (isNetlistableParam(instVar))
{
obj = context.evalSpice(instVar, false);
} else
{
obj = context.evalVar(instVar, no);
}
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit(), false);
}
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun == PrimitiveNode.Function.PRESIST && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, ni, resistVar, forceEval);
} else {
if (resistVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit(), false);
}
} else {
if (fun == PrimitiveNode.Function.PRESIST) {
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology())) {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "GND rpporpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "GND rnporpo"+extra;
}
} else {
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) {
extra = "rppo1rpo"+extra;
}
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) {
extra = "rnpo1rpo"+extra;
}
}
}
else if (fun == PrimitiveNode.Function.WRESIST) {
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) {
extra = "rnwod "+extra;
}
if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) {
extra = "rpwod "+extra;
}
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, capacVar, forceEval);
} else {
if (capacVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit(), false);
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, inductVar, forceEval);
} else {
if (inductVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit(), false);
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets != null) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets != null && ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (segmentedNets != null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo.writeNewSpiceCode(cell, cni, layoutTechnology, this);
} else {
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SpiceSegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.getCap() > cell.getTechnology().getMinCapacitance()) {
if (netInfo.getName().equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.getName() + " 0 " + TextUtils.formatDouble(netInfo.getCap()) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.getRes(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SpiceSegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue()) + "\n");
resCount++;
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
|
diff --git a/Java/Skynet.java b/Java/Skynet.java
index dc12b96..ceb5147 100644
--- a/Java/Skynet.java
+++ b/Java/Skynet.java
@@ -1,119 +1,120 @@
import java.util.*;
public abstract class Skynet {
protected Board curBoard;
public Skynet(String mapStr) {
curBoard = new Board(mapStr);
}
public abstract String plan();
public int score() {
return curBoard.robby.getScore();
}
public static abstract class AStarSkynet extends Skynet {
AStar pathfinder;
TerminationConditions.TerminationCondition terminator;
public AStarSkynet(String mapStr) {
super(mapStr);
}
}
public static class GreedySkynet extends AStarSkynet {
public GreedySkynet(String mapStr) {
super(mapStr);
}
public String plan() {
Path totalPath = new Path();
while (curBoard.lambdaPos.size() > 0) {
if (Main.gotSIGINT)
break;
- System.out.println("Starting a new journey");
+ System.out.println("Starting a new journey" + curBoard.lambdaPos.size());
int bestLength = Integer.MAX_VALUE;
Board bestBoard = curBoard;
Path bestPath = null;
for (Point lambdaPt : curBoard.lambdaPos) {
Board newBoard = new Board(curBoard);
terminator = new TerminationConditions.PointTermination(lambdaPt);
pathfinder = new AStar(new CostFunctions.BoardSensingCost(),
new CostFunctions.ManhattanCost(),
terminator);
pathfinder.findPath(newBoard, lambdaPt);
Path path = terminator.getPath();
if (path.size() < bestLength) {
bestBoard = terminator.getBoard();
bestPath = terminator.getPath();
bestLength = path.size();
}
}
curBoard = bestBoard;
totalPath.addAll(bestPath);
}
Board newBoard = new Board(curBoard);
terminator = new TerminationConditions.PointTermination(curBoard.liftLocation);
- pathfinder = new AStar(new CostFunctions.TrivialCost(), new CostFunctions.TrivialCost(), terminator);
+ System.out.println("lift: " + curBoard.liftLocation);
+ pathfinder = new AStar(new CostFunctions.BoardSensingCost(), new CostFunctions.ManhattanCost(), terminator);
pathfinder.findPath(newBoard, curBoard.liftLocation);
totalPath.addAll(terminator.getPath());
return totalPath.toString();
}
}
/*
* DOES NOT WORK YET!
*/
class AnnealingSkynet extends AStarSkynet {
Random rand = new Random();
static final int MAX_TIME = 1000;
public AnnealingSkynet(String mapStr) {
super(mapStr);
}
public String plan() {
double curEnergy = energy(curBoard);
for (int time = 0; time < MAX_TIME; time++) {
double temperature = temperature((double)time/MAX_TIME);
Board newBoard = pickNeighbor();
double newEnergy = energy(newBoard);
if (evaluate(curEnergy, newEnergy, temperature) > rand.nextDouble()) {
curBoard = newBoard;
curEnergy = newEnergy;
}
}
return curBoard.toString();
}
double energy(Board b) {
return 1.0;
}
double temperature(double timeRatio) {
return 1-timeRatio;
}
Board pickNeighbor() {
int i = rand.nextInt(curBoard.lambdaPos.size());
pathfinder.findPath(curBoard, curBoard.lambdaPos.get(i));
Board newBoard = new Board(curBoard);
//newBoard.move(path);
return newBoard;
}
double evaluate(double curEnergy, double newEnergy, double temperature) {
return 1.0;
}
}
}
| false | true | public String plan() {
Path totalPath = new Path();
while (curBoard.lambdaPos.size() > 0) {
if (Main.gotSIGINT)
break;
System.out.println("Starting a new journey");
int bestLength = Integer.MAX_VALUE;
Board bestBoard = curBoard;
Path bestPath = null;
for (Point lambdaPt : curBoard.lambdaPos) {
Board newBoard = new Board(curBoard);
terminator = new TerminationConditions.PointTermination(lambdaPt);
pathfinder = new AStar(new CostFunctions.BoardSensingCost(),
new CostFunctions.ManhattanCost(),
terminator);
pathfinder.findPath(newBoard, lambdaPt);
Path path = terminator.getPath();
if (path.size() < bestLength) {
bestBoard = terminator.getBoard();
bestPath = terminator.getPath();
bestLength = path.size();
}
}
curBoard = bestBoard;
totalPath.addAll(bestPath);
}
Board newBoard = new Board(curBoard);
terminator = new TerminationConditions.PointTermination(curBoard.liftLocation);
pathfinder = new AStar(new CostFunctions.TrivialCost(), new CostFunctions.TrivialCost(), terminator);
pathfinder.findPath(newBoard, curBoard.liftLocation);
totalPath.addAll(terminator.getPath());
return totalPath.toString();
}
| public String plan() {
Path totalPath = new Path();
while (curBoard.lambdaPos.size() > 0) {
if (Main.gotSIGINT)
break;
System.out.println("Starting a new journey" + curBoard.lambdaPos.size());
int bestLength = Integer.MAX_VALUE;
Board bestBoard = curBoard;
Path bestPath = null;
for (Point lambdaPt : curBoard.lambdaPos) {
Board newBoard = new Board(curBoard);
terminator = new TerminationConditions.PointTermination(lambdaPt);
pathfinder = new AStar(new CostFunctions.BoardSensingCost(),
new CostFunctions.ManhattanCost(),
terminator);
pathfinder.findPath(newBoard, lambdaPt);
Path path = terminator.getPath();
if (path.size() < bestLength) {
bestBoard = terminator.getBoard();
bestPath = terminator.getPath();
bestLength = path.size();
}
}
curBoard = bestBoard;
totalPath.addAll(bestPath);
}
Board newBoard = new Board(curBoard);
terminator = new TerminationConditions.PointTermination(curBoard.liftLocation);
System.out.println("lift: " + curBoard.liftLocation);
pathfinder = new AStar(new CostFunctions.BoardSensingCost(), new CostFunctions.ManhattanCost(), terminator);
pathfinder.findPath(newBoard, curBoard.liftLocation);
totalPath.addAll(terminator.getPath());
return totalPath.toString();
}
|
diff --git a/WebsiteReader/src/Screen.java b/WebsiteReader/src/Screen.java
index bf05f30..2bb5f87 100644
--- a/WebsiteReader/src/Screen.java
+++ b/WebsiteReader/src/Screen.java
@@ -1,194 +1,199 @@
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Screen {
public static int MAXCHAR = 10;
public static URL z = null;
private static String URLstring = "";
JPanel contentPane;
final static String READER = "Card where words are displayed";
final static String TYPER = "Where you type in you URL";
private JTextField inputTextField;
private JTextArea wordFrequencyTextArea;
private static JFrame frame;
public void createCards() throws IOException {
JPanel inputPanel = new JPanel();
inputTextField = new JTextField();
inputTextField.setFont(new Font("Serif", Font.ITALIC, 16));
inputTextField.setColumns(20);
inputPanel.add(inputTextField);
JButton enter = new JButton("enter");
SubmitButtonActionListener v = new SubmitButtonActionListener(this.inputTextField, this);
enter.addActionListener(v);
inputPanel.add(enter);
contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1));
contentPane.add(inputPanel);
//contentPane.add(myCards);
try{
}
catch(Exception e){
createErrorLabel(e.getMessage());
}
// create main pane
frame.setContentPane(contentPane);
}
public static void main(String[] args) throws Exception {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
setUp();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public static void setUp() throws IOException {
frame = new JFrame("LeaderBoard");
// frame.setBounds(50, 50, 600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Screen scr = new Screen();
scr.createCards();
frame.pack();
frame.setVisible(true);
}
public static String format(String rough) {
while(rough.contains(" "))
rough = rough.replace(" ", "");
rough = rough.replace("\"", "");
rough = rough.replace("(", "");
rough = rough.replace(")", "");
rough = rough.replace(",", "");
rough = rough.replace(":", "");
rough = rough.replace("^", "");
rough = rough.replace(";", "");
rough = rough.replaceAll("\t", "");
return rough;
}
public static void setURL(String url) throws MalformedURLException {
URLstring = url;
z = new URL(URLstring);
}
public static BufferedReader buff() throws IOException{
BufferedReader in;
in = new BufferedReader(new InputStreamReader(z.openStream()));
return in;
}
public static String parse(BufferedReader b) throws IOException{
String htmlLine;
StringBuilder massive = new StringBuilder();
while ((htmlLine = b.readLine()) != null) {
massive.append(htmlLine);
}
b.close();
String massiveString = massive.toString();
MyHashMap w = new MyHashMap(MAXCHAR);
ArrayList<String> fixedText = new ArrayList<String>();
fixedText = (ArrayList<String>) Splitter.split(massiveString);
w = WordCounter.reader(fixedText, w);
+ ArrayList<KeyValuePairs> x;
+ for(int i = 0; i < w.getKeys().size(); i++){
+ String key = w.getKeys().get(i);
+ String value = Integer.toString(key.length());
+ }
- ArrayList<KeyValuePairs> x = (ArrayList<KeyValuePairs>) BubbleSort.sort(w.getKeyValuePairs());
+ //ArrayList<KeyValuePairs> x = (ArrayList<KeyValuePairs>) BubbleSort.sort(w.getKeyValuePairs());
MyHashMap t = new MyHashMap(MAXCHAR);
for (int i = 0; i < x.size(); i++){
String key = x.get(i).getKey();
String value = x.get(i).getValue();
t.set(key,value);
}
StringBuilder resort = new StringBuilder();
List<String> allList = t.getKeys();
for (int i = 0; i < allList.size(); i++){
String myWord;
String myValue;
myWord = allList.get(i);
myValue = t.get(myWord);
resort.append(format(myWord) + " " + myValue + "\n");
}
String finalSort = resort.toString();
return finalSort;
}
public void createErrorLabel(String e){
JLabel x = new JLabel(e);
contentPane.add(x);
}
public void action() {
String finalSort = null;
try {
finalSort = parse(buff());
} catch (IOException e) {
String q = e.getMessage();
createErrorLabel(q);
}
contentPane = new JPanel();
wordFrequencyTextArea = new JTextArea(finalSort);
wordFrequencyTextArea.setFont(new Font("Serif", Font.ITALIC, 16));
wordFrequencyTextArea.setLineWrap(true);
wordFrequencyTextArea.setWrapStyleWord(true);
JScrollPane textAreaScrollPane = new JScrollPane(wordFrequencyTextArea);
textAreaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
textAreaScrollPane.setPreferredSize(new Dimension(400, 600));
contentPane.add(textAreaScrollPane);
frame.setContentPane(contentPane);
frame.pack();
}
}
| false | true | public static String parse(BufferedReader b) throws IOException{
String htmlLine;
StringBuilder massive = new StringBuilder();
while ((htmlLine = b.readLine()) != null) {
massive.append(htmlLine);
}
b.close();
String massiveString = massive.toString();
MyHashMap w = new MyHashMap(MAXCHAR);
ArrayList<String> fixedText = new ArrayList<String>();
fixedText = (ArrayList<String>) Splitter.split(massiveString);
w = WordCounter.reader(fixedText, w);
ArrayList<KeyValuePairs> x = (ArrayList<KeyValuePairs>) BubbleSort.sort(w.getKeyValuePairs());
MyHashMap t = new MyHashMap(MAXCHAR);
for (int i = 0; i < x.size(); i++){
String key = x.get(i).getKey();
String value = x.get(i).getValue();
t.set(key,value);
}
StringBuilder resort = new StringBuilder();
List<String> allList = t.getKeys();
for (int i = 0; i < allList.size(); i++){
String myWord;
String myValue;
myWord = allList.get(i);
myValue = t.get(myWord);
resort.append(format(myWord) + " " + myValue + "\n");
}
String finalSort = resort.toString();
return finalSort;
}
| public static String parse(BufferedReader b) throws IOException{
String htmlLine;
StringBuilder massive = new StringBuilder();
while ((htmlLine = b.readLine()) != null) {
massive.append(htmlLine);
}
b.close();
String massiveString = massive.toString();
MyHashMap w = new MyHashMap(MAXCHAR);
ArrayList<String> fixedText = new ArrayList<String>();
fixedText = (ArrayList<String>) Splitter.split(massiveString);
w = WordCounter.reader(fixedText, w);
ArrayList<KeyValuePairs> x;
for(int i = 0; i < w.getKeys().size(); i++){
String key = w.getKeys().get(i);
String value = Integer.toString(key.length());
}
//ArrayList<KeyValuePairs> x = (ArrayList<KeyValuePairs>) BubbleSort.sort(w.getKeyValuePairs());
MyHashMap t = new MyHashMap(MAXCHAR);
for (int i = 0; i < x.size(); i++){
String key = x.get(i).getKey();
String value = x.get(i).getValue();
t.set(key,value);
}
StringBuilder resort = new StringBuilder();
List<String> allList = t.getKeys();
for (int i = 0; i < allList.size(); i++){
String myWord;
String myValue;
myWord = allList.get(i);
myValue = t.get(myWord);
resort.append(format(myWord) + " " + myValue + "\n");
}
String finalSort = resort.toString();
return finalSort;
}
|
diff --git a/src/net/sf/freecol/server/control/InGameInputHandler.java b/src/net/sf/freecol/server/control/InGameInputHandler.java
index f74085be8..ce2d29109 100644
--- a/src/net/sf/freecol/server/control/InGameInputHandler.java
+++ b/src/net/sf/freecol/server/control/InGameInputHandler.java
@@ -1,2394 +1,2396 @@
package net.sf.freecol.server.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;
import java.util.logging.Logger;
import net.sf.freecol.common.model.Building;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsContainer;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.LostCityRumour;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Tension;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.WorkLocation;
import net.sf.freecol.common.model.Map.Position;
import net.sf.freecol.common.networking.Connection;
import net.sf.freecol.common.networking.Message;
import net.sf.freecol.common.networking.NetworkConstants;
import net.sf.freecol.server.FreeColServer;
import net.sf.freecol.server.ai.AIPlayer;
import net.sf.freecol.server.model.ServerPlayer;
import org.w3c.dom.Element;
/**
* Handles the network messages that arrives while
* {@link FreeColServer#IN_GAME in game}.
*/
public final class InGameInputHandler extends InputHandler implements NetworkConstants {
private static Logger logger = Logger.getLogger(InGameInputHandler.class.getName());
public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
public static Random attackCalculator;
public static final Random random = new Random();
/**
* The constructor to use.
* @param freeColServer The main server object.
*/
public InGameInputHandler(FreeColServer freeColServer) {
super(freeColServer);
attackCalculator = new Random();
}
/**
* Handles a network message.
*
* @param connection The <code>Connection</code> the message came from.
* @param element The message to be processed.
* @return The reply.
*/
public synchronized Element handle(Connection connection, Element element) {
Element reply = null;
FreeColServer freeColServer = getFreeColServer();
String type = element.getTagName();
try {
if (element != null) {
// The first messages you see here are the ones that are supported even
// though it is NOT the sender's turn:
if (type.equals("logout")) {
reply = logout(connection, element);
} else if (type.equals("createUnit")) {
reply = createUnit(connection, element);
} else if (type.equals("getRandom")) {
reply = getRandom(connection, element);
} else if (type.equals("getVacantEntryLocation")) {
reply = getVacantEntryLocation(connection, element);
} else if (type.equals("disconnect")) {
reply = disconnect(connection, element);
} else if (freeColServer.getGame().getCurrentPlayer().equals(freeColServer.getPlayer(connection))) {
if (type.equals("chat")) {
reply = chat(connection, element);
} else if (type.equals("move")) {
reply = move(connection, element);
} else if (type.equals("explore")) {
reply = explore(connection, element);
} else if (type.equals("askSkill")) {
reply = askSkill(connection, element);
} else if (type.equals("attack")) {
reply = attack(connection, element);
} else if (type.equals("embark")) {
reply = embark(connection, element);
} else if (type.equals("boardShip")) {
reply = boardShip(connection, element);
} else if (type.equals("learnSkillAtSettlement")) {
reply = learnSkillAtSettlement(connection, element);
} else if (type.equals("scoutIndianSettlement")) {
reply = scoutIndianSettlement(connection, element);
} else if (type.equals("missionaryAtSettlement")) {
reply = missionaryAtSettlement(connection, element);
} else if (type.equals("inciteAtSettlement")) {
reply = inciteAtSettlement(connection, element);
} else if (type.equals("leaveShip")) {
reply = leaveShip(connection, element);
} else if (type.equals("loadCargo")) {
reply = loadCargo(connection, element);
} else if (type.equals("unloadCargo")) {
reply = unloadCargo(connection, element);
} else if (type.equals("buyGoods")) {
reply = buyGoods(connection, element);
} else if (type.equals("sellGoods")) {
reply = sellGoods(connection, element);
} else if (type.equals("moveToEurope")) {
reply = moveToEurope(connection, element);
} else if (type.equals("moveToAmerica")) {
reply = moveToAmerica(connection, element);
} else if (type.equals("buildColony")) {
reply = buildColony(connection, element);
} else if (type.equals("recruitUnitInEurope")) {
reply = recruitUnitInEurope(connection, element);
} else if (type.equals("emigrateUnitInEurope")) {
reply = emigrateUnitInEurope(connection, element);
} else if (type.equals("trainUnitInEurope")) {
reply = trainUnitInEurope(connection, element);
} else if (type.equals("equipunit")) {
reply = equipUnit(connection, element);
} else if (type.equals("work")) {
reply = work(connection, element);
} else if (type.equals("changeWorkType")) {
reply = changeWorkType(connection, element);
} else if (type.equals("setCurrentlyBuilding")) {
reply = setCurrentlyBuilding(connection, element);
} else if (type.equals("changeState")) {
reply = changeState(connection, element);
} else if (type.equals("putOutsideColony")) {
reply = putOutsideColony(connection, element);
} else if (type.equals("clearSpeciality")) {
reply = clearSpeciality(connection, element);
} else if (type.equals("setNewLandName")) {
reply = setNewLandName(connection, element);
} else if (type.equals("endTurn")) {
reply = endTurn(connection, element);
} else if (type.equals("disbandUnit")) {
reply = disbandUnit(connection, element);
} else if (type.equals("cashInTreasureTrain")) {
reply = cashInTreasureTrain(connection, element);
} else if (type.equals("tradeProposition")) {
reply = tradeProposition(connection, element);
} else if (type.equals("trade")) {
reply = trade(connection, element);
} else if (type.equals("deliverGift")) {
reply = deliverGift(connection, element);
} else if (type.equals("indianDemand")) {
reply = indianDemand(connection, element);
} else if (type.equals("buyLand")) {
reply = buyLand(connection, element);
} else if (type.equals("payForBuilding")) {
reply = payForBuilding(connection, element);
} else if (type.equals("payArrears")) {
reply = payArrears(connection, element);
} else if (type.equals("toggleExports")) {
reply = toggleExports(connection, element);
} else if (type.equals("declareIndependence")) {
reply = declareIndependence(connection, element);
} else if (type.equals("giveIndependence")) {
reply = giveIndependence(connection, element);
} else if (type.equals("setDestination")) {
reply = setDestination(connection, element);
} else {
logger.warning("Unknown request from client " + element.getTagName());
}
} else {
// The message we've received is probably a good one, but
// it was sent when it was not the sender's turn.
reply = Message.createNewRootElement("error");
reply.setAttribute("message", "Not your turn.");
logger.warning("Received message when not in turn: " + element.getTagName());
}
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
Element reconnect = Message.createNewRootElement("reconnect");
try {
connection.send(reconnect);
} catch (IOException ex) {
logger.warning("Could not send reconnect message!");
}
return null;
}
return reply;
}
/**
* Handles a "buyLand"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*
*/
private Element buyLand(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Tile tile = (Tile) game.getFreeColGameObject(element.getAttribute("tile"));
if (tile == null) {
throw new NullPointerException();
}
player.buyLand(tile);
return null;
}
/**
* Handles a "setNewLandName"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*
*/
private Element setNewLandName(Connection connection, Element element) {
ServerPlayer player = getFreeColServer().getPlayer(connection);
player.setNewLandName(element.getAttribute("newLandName"));
// TODO: Send name to all other players.
return null;
}
/**
* Handles a "createUnit"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*
*/
private Element createUnit(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
logger.info("Receiving \"createUnit\"-request.");
String taskID = element.getAttribute("taskID");
Location location = (Location) game.getFreeColGameObject(element.getAttribute("location"));
Player owner = (Player) game.getFreeColGameObject(element.getAttribute("owner"));
int type = Integer.parseInt(element.getAttribute("type"));
if (location == null) {
throw new NullPointerException();
}
if (owner == null) {
throw new NullPointerException();
}
Unit unit = getFreeColServer().getModelController().createUnit(taskID, location, owner, type, false, connection);
Element reply = Message.createNewRootElement("createUnitConfirmed");
reply.appendChild(unit.toXMLElement(owner, reply.getOwnerDocument()));
return reply;
}
/**
* Handles a "getRandom"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*
*/
private Element getRandom(Connection connection, Element element) {
logger.info("Receiving \"getRandom\"-request.");
String taskID = element.getAttribute("taskID");
int n = Integer.parseInt(element.getAttribute("n"));
int result = getFreeColServer().getModelController().getRandom(taskID, n);
Element reply = Message.createNewRootElement("getRandomConfirmed");
reply.setAttribute("result", Integer.toString(result));
logger.info("Result: " + result);
return reply;
}
/**
* Handles a "getVacantEntryLocation"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*
*/
private Element getVacantEntryLocation(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
Player owner = unit.getOwner();
if (owner != getFreeColServer().getPlayer(connection)) {
throw new IllegalStateException();
}
Location entryLocation = getFreeColServer().getModelController().setToVacantEntryLocation(unit);
Element reply = Message.createNewRootElement("getVacantEntryLocationConfirmed");
reply.setAttribute("location", entryLocation.getID());
return reply;
}
/**
* Handles a "chat"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*
*/
private Element chat(Connection connection, Element element) {
// TODO: Add support for private chat.
element.setAttribute("sender", getFreeColServer().getPlayer(connection).getID());
getFreeColServer().getServer().sendToAll(element, connection);
return null;
}
/**
* Handles a "move"-message from a client.
*
* @param connection The connection the message came from.
* @param moveElement The element containing the request.
* @exception IllegalArgumentException If the data format of the message is invalid.
* @exception IllegalStateException If the request is not accepted by the model.
*
*/
private Element move(Connection connection, Element moveElement) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(moveElement.getAttribute("unit"));
int direction = Integer.parseInt(moveElement.getAttribute("direction"));
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + moveElement.getAttribute("unit"));
}
if (unit.getTile() == null) {
throw new IllegalArgumentException("'Unit' not on map: ID: " + moveElement.getAttribute("unit") + " (" + unit.getName() + ")");
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile newTile = game.getMap().getNeighbourOrNull(direction, unit.getTile());
//boolean disembark = !unit.getTile().isLand() && newTile.isLand() && newTile.getSettlement() == null;
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
try {
if (unit.isVisibleTo(enemyPlayer)) { // && !disembark
Element opponentMoveElement = Message.createNewRootElement("opponentMove");
opponentMoveElement.setAttribute("direction", Integer.toString(direction));
opponentMoveElement.setAttribute("unit", unit.getID());
enemyPlayer.getConnection().send(opponentMoveElement);
} else if (enemyPlayer.canSee(newTile) && (newTile.getSettlement() == null || !game.getGameOptions().getBoolean(GameOptions.UNIT_HIDING))) {
Element opponentMoveElement = Message.createNewRootElement("opponentMove");
opponentMoveElement.setAttribute("direction", Integer.toString(direction));
opponentMoveElement.setAttribute("tile", newTile.getID());
opponentMoveElement.appendChild(unit.toXMLElement(enemyPlayer, opponentMoveElement.getOwnerDocument()));
enemyPlayer.getConnection().send(opponentMoveElement);
}
} catch (IOException e) {
logger.warning("Could not send message to: " + enemyPlayer.getName() + " with connection " + enemyPlayer.getConnection());
}
}
unit.move(direction);
Element reply = Message.createNewRootElement("update");
Vector surroundingTiles = game.getMap().getSurroundingTiles(unit.getTile(), unit.getLineOfSight());
for (int i=0; i<surroundingTiles.size(); i++) {
Tile t = (Tile) surroundingTiles.get(i);
reply.appendChild(t.toXMLElement(player, reply.getOwnerDocument()));
}
return reply;
}
/**
* Returns a type of Lost City Rumour. The type of rumour depends
* on the exploring unit, as well as player settings.
*
* @param tile The <code>Tile</code> containing the lost city rumour.
* @param unit The <code>Unit</code> exploring the lost city rumour.
* @return A Lost City Rumour type.
*/
public static int exploreLostCityRumour(Tile tile, Unit unit) {
/**
* Random numbers can be generated by this method since it is
* only invoked by the explore method of the server's
* InGameInputHandler.
*/
Player player = unit.getOwner();
int type = unit.getType();
// difficulty is in range 0-4, dx in range 2-6
int dx = player.getDifficulty() + 2;
// seasoned scouts should be more successful
int bonus = 0;
if (type == Unit.SEASONED_SCOUT && unit.isScout()) {
bonus += 3;
dx--;
}
// dx is now in range 1-6
int max = 7; // maximum dx + 1
/** The higher the difficulty, the more likely bad things are
* to happen.
*/
int[] probability = new int[LostCityRumour.NUMBER_OF_RUMOURS];
probability[LostCityRumour.BURIAL_GROUND] = dx;
probability[LostCityRumour.EXPEDITION_VANISHES] = dx * 2;
probability[LostCityRumour.NOTHING] = dx * 5;
// only these units can be promoted
if (type == Unit.FREE_COLONIST
|| type == Unit.INDENTURED_SERVANT
|| type == Unit.PETTY_CRIMINAL) {
probability[LostCityRumour.SEASONED_SCOUT] = ( max - dx ) * 3;
} else {
probability[LostCityRumour.SEASONED_SCOUT] = 0;
}
/** The higher the difficulty, the less likely good things are
* to happen.
*/
probability[LostCityRumour.TRIBAL_CHIEF] = ( max - dx ) * 3;
probability[LostCityRumour.COLONIST] = ( max - dx ) * 2;
probability[LostCityRumour.TREASURE_TRAIN] = ( max - dx ) * 2 + bonus;
probability[LostCityRumour.FOUNTAIN_OF_YOUTH] = ( max - dx ) + bonus / 2;
int start;
if (player.hasFather(FoundingFather.HERNANDO_DE_SOTO)) {
// rumours are always positive
start = 3;
} else {
start = 0;
}
/*
* It should not be possible to find an indian burial ground
* outside indian territory:
*/
if (tile.getNationOwner() == Player.NO_NATION
|| !tile.getGame().getPlayer(tile.getNationOwner()).isIndian()) {
probability[LostCityRumour.BURIAL_GROUND] = 0;
}
int accumulator = 0;
for ( int i = start; i < LostCityRumour.NUMBER_OF_RUMOURS; i++ ) {
accumulator += probability[i];
probability[i] = accumulator;
}
int randomInt = random.nextInt(accumulator);
for ( int j = start; j < LostCityRumour.NUMBER_OF_RUMOURS; j++ ) {
if (randomInt < probability[j]) {
return j;
}
}
return LostCityRumour.NO_SUCH_RUMOUR;
}
/**
* Handles an "explore"-message from a client.
*
* @param connection The connection the message came from.
* @param exploreElement The element containing the request.
* @exception IllegalArgumentException If the data format of the message is invalid.
* @exception IllegalStateException If the request is not accepted by the model.
*
*/
private Element explore(Connection connection, Element exploreElement) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(exploreElement.getAttribute("unit"));
if (unit == null) {
throw new IllegalArgumentException("Unit is null.");
}
Tile tile = unit.getTile();
if (tile.hasLostCityRumour()) {
tile.setLostCityRumour(false);
} else {
throw new IllegalStateException("No rumour to explore.");
}
int type = exploreLostCityRumour(tile, unit);
Element rumourElement = Message.createNewRootElement("lostCityRumour");
rumourElement.setAttribute("type", Integer.toString(type));
rumourElement.setAttribute("unit", unit.getID());
Unit newUnit;
int dx = 10 - player.getDifficulty(); // 6-10
switch (type) {
case LostCityRumour.BURIAL_GROUND:
Player indianPlayer = game.getPlayer(unit.getTile().getNationOwner());
indianPlayer.modifyTension(player, Tension.TENSION_HATEFUL);
case LostCityRumour.EXPEDITION_VANISHES:
unit.dispose();
break;
case LostCityRumour.NOTHING:
break;
case LostCityRumour.SEASONED_SCOUT:
unit.setType(Unit.SEASONED_SCOUT);
break;
case LostCityRumour.TRIBAL_CHIEF:
int amount = attackCalculator.nextInt(dx * 10) + dx * 5;
player.modifyGold(amount);
rumourElement.setAttribute("amount", Integer.toString(amount));
break;
case LostCityRumour.COLONIST:
newUnit = new Unit(game, tile, player, Unit.FREE_COLONIST, Unit.ACTIVE);
unit.getTile().add(newUnit);
rumourElement.appendChild(newUnit.toXMLElement(player, rumourElement.getOwnerDocument()));
break;
case LostCityRumour.TREASURE_TRAIN:
int treasure = attackCalculator.nextInt(dx * 600) + dx * 300;
newUnit = new Unit(game, tile, player, Unit.TREASURE_TRAIN, Unit.ACTIVE);
newUnit.setTreasureAmount(treasure);
unit.getTile().add(newUnit);
rumourElement.setAttribute("amount", Integer.toString(treasure));
rumourElement.appendChild(newUnit.toXMLElement(player, rumourElement.getOwnerDocument()));
break;
case LostCityRumour.FOUNTAIN_OF_YOUTH:
for (int k = 0; k < dx; k++) {
newUnit = new Unit(game, player.getEurope(), player,
player.generateRecruitable(), Unit.SENTRY);
player.getEurope().add(newUnit);
rumourElement.appendChild(newUnit.toXMLElement(player, rumourElement.getOwnerDocument()));
}
break;
default:
throw new IllegalStateException( "No such rumour." );
}
// tell everyone the rumour has been explored
Iterator updateIterator = game.getPlayerIterator();
while (updateIterator.hasNext()) {
ServerPlayer updatePlayer = (ServerPlayer) updateIterator.next();
if (player.equals(updatePlayer) || updatePlayer.getConnection() == null) {
continue;
} else if (updatePlayer.canSee(tile)) {
try {
Element rumourUpdate = Message.createNewRootElement("update");
rumourUpdate.appendChild(tile.toXMLElement(updatePlayer, rumourUpdate.getOwnerDocument()));
updatePlayer.getConnection().send(rumourUpdate);
} catch (IOException e) {
logger.warning("Could not send update message to: " +
updatePlayer.getName() + " with connection " +
updatePlayer.getConnection());
}
}
}
return rumourElement;
}
/**
* Handles an "askSkill"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*
* @exception IllegalArgumentException If the data format of the message is invalid.
* @exception IllegalStateException If the request is not accepted by the model.
*/
private Element askSkill(Connection connection, Element element) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
Map map = game.getMap();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
int direction = Integer.parseInt(element.getAttribute("direction"));
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + element.getAttribute("unit"));
}
if (unit.getMovesLeft() == 0) {
throw new IllegalArgumentException("Unit has no moves left.");
}
if (unit.getTile() == null) {
throw new IllegalArgumentException("'Unit' not on map: ID: " + element.getAttribute("unit"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
IndianSettlement settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile()).getSettlement();
if (settlement.getLearnableSkill() != IndianSettlement.UNKNOWN) {
unit.setMovesLeft(0);
if (settlement.getLearnableSkill() != IndianSettlement.NONE) {
// We now put the unit on the indian settlement. Normally we shouldn't have
// to this, but the movesLeft are set to 0 for unit and if the player decides
// to learn a skill with a learnSkillAtSettlement message then we have to be
// able to check if the unit can learn the skill.
unit.setLocation(settlement);
}
Element reply = Message.createNewRootElement("provideSkill");
reply.setAttribute("skill", Integer.toString(settlement.getLearnableSkill()));
// Set the Tile.PlayerExploredTile attribute.
settlement.getTile().updateIndianSettlementSkill(player);
return reply;
} else {
throw new IllegalStateException("Learnable skill from Indian settlement is unknown at server.");
}
}
/**
* Handles an "attack"-message from a client.
*
* @param connection The connection the message came from.
* @param attackElement The element containing the request.
* @exception IllegalArgumentException If the data format of the message is invalid.
* @exception IllegalStateException If the request is not accepted by the model.
*
*/
private Element attack(Connection connection, Element attackElement) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
ServerPlayer player = freeColServer.getPlayer(connection);
// Get parameters:
Unit unit = (Unit) game.getFreeColGameObject(attackElement.getAttribute("unit"));
int direction = Integer.parseInt(attackElement.getAttribute("direction"));
// Test the parameters:
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + attackElement.getAttribute("unit"));
}
if (unit.getTile() == null) {
throw new IllegalArgumentException("'Unit' is not on the map: " + unit.toString());
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
Tile newTile = game.getMap().getNeighbourOrNull(direction, unit.getTile());
if (newTile == null) {
throw new IllegalArgumentException("Could not find tile in direction " + direction + " from unit with ID " + attackElement.getAttribute("unit"));
}
Element dowElement = null;
Unit defender = newTile.getDefendingUnit(unit);
if (defender == null) {
throw new IllegalStateException("Nothing to attack in direction " +
direction + " from unit with ID " +
attackElement.getAttribute("unit"));
}
int result = generateAttackResult(unit, defender);
int plunderGold = -1;
if (result == Unit.ATTACK_DONE_SETTLEMENT) {
plunderGold = newTile.getSettlement().getOwner().getGold()/10; // 10% of their gold
}
// Inform the players (other then the player attacking) about the attack:
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
if (dowElement != null) {
try {
enemyPlayer.getConnection().send(dowElement);
} catch (IOException e) {
logger.warning("Could not send message to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}
Element opponentAttackElement = Message.createNewRootElement("opponentAttack");
if (unit.isVisibleTo(enemyPlayer) || defender.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("direction", Integer.toString(direction));
opponentAttackElement.setAttribute("result", Integer.toString(result));
opponentAttackElement.setAttribute("plunderGold", Integer.toString(plunderGold));
opponentAttackElement.setAttribute("unit", unit.getID());
opponentAttackElement.setAttribute("defender", defender.getID());
if (!defender.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("update", "defender");
if (!enemyPlayer.canSee(defender.getTile())) {
enemyPlayer.setExplored(defender.getTile());
opponentAttackElement.appendChild(defender.getTile().toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
}
opponentAttackElement.appendChild(defender.toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
} else if (!unit.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("update", "unit");
opponentAttackElement.appendChild(unit.toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
}
try {
enemyPlayer.getConnection().send(opponentAttackElement);
} catch (IOException e) {
logger.warning("Could not send message to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}
}
// Create the reply for the attacking player:
Element reply = Message.createNewRootElement("attackResult");
reply.setAttribute("result", Integer.toString(result));
reply.setAttribute("plunderGold", Integer.toString(plunderGold));
if (result == Unit.ATTACK_DONE_SETTLEMENT && newTile.getColony() != null) { // If a colony will been won, send an updated tile:
reply.appendChild(newTile.toXMLElement(newTile.getColony().getOwner(), reply.getOwnerDocument()));
}
if (!defender.isVisibleTo(player)) {
reply.appendChild(defender.toXMLElement(player, reply.getOwnerDocument()));
}
int[] oldGoodsCounts = new int[Goods.NUMBER_OF_TYPES];
- for (int i=0; i < oldGoodsCounts.length; i++) {
- oldGoodsCounts[i] = unit.getGoodsContainer().getGoodsCount(i);
+ if (unit.canCaptureGoods() && game.getGameOptions().getBoolean(GameOptions.UNIT_HIDING)) {
+ for (int i=0; i < oldGoodsCounts.length; i++) {
+ oldGoodsCounts[i] = unit.getGoodsContainer().getGoodsCount(i);
+ }
}
unit.attack(defender, result, plunderGold);
// Send capturedGoods if UNIT_HIDING is true
// because when it's false unit is already sent with carried goods and units
if (unit.canCaptureGoods() && game.getGameOptions().getBoolean(GameOptions.UNIT_HIDING)) {
Iterator goodsIt = unit.getGoodsContainer().getCompactGoodsIterator();
while (goodsIt.hasNext()) {
Goods newGoods = (Goods) goodsIt.next();
int capturedGoods = newGoods.getAmount() - oldGoodsCounts[newGoods.getType()];
if (capturedGoods > 0) {
Element captured = reply.getOwnerDocument().createElement("capturedGoods");
captured.setAttribute("type", Integer.toString(newGoods.getType()));
captured.setAttribute("amount", Integer.toString(capturedGoods));
reply.appendChild(captured);
}
}
}
// TODO: REMOVE MAGIC: This should not really be necessary:
/*if (result == Unit.ATTACK_DONE_SETTLEMENT) {
Element updateElement = Message.createNewRootElement("update");
updateElement.appendChild(newTile.toXMLElement(newTile.getColony().getOwner(), updateElement.getOwnerDocument()));
ServerPlayer enemyPlayer = (ServerPlayer) defender.getOwner();
try {
enemyPlayer.getConnection().send(updateElement);
} catch (IOException e) {
logger.warning("Could not send message (2) to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}*/
if (result >= Unit.ATTACK_EVADES && unit.getTile().equals(newTile)) { // In other words, we moved...
Element update = reply.getOwnerDocument().createElement("update");
int lineOfSight = unit.getLineOfSight();
if (result == Unit.ATTACK_DONE_SETTLEMENT
&& newTile.getSettlement() != null) {
lineOfSight = Math.max(lineOfSight, newTile.getSettlement().getLineOfSight());
}
Vector surroundingTiles = game.getMap().getSurroundingTiles(unit.getTile(), lineOfSight);
for (int i=0; i<surroundingTiles.size(); i++) {
Tile t = (Tile) surroundingTiles.get(i);
update.appendChild(t.toXMLElement(player, update.getOwnerDocument()));
}
reply.appendChild(update);
}
return reply;
}
/**
* Generates a result of an attack.
*/
private int generateAttackResult(Unit unit, Unit defender) {
int attackPower = unit.getOffensePower(defender);
int totalProbability = attackPower + defender.getDefensePower(unit);
int result;
int r = attackCalculator.nextInt(totalProbability+1);
if (r > attackPower) {
result = Unit.ATTACK_LOSS;
} else if(r == attackPower) {
if (defender.isNaval()) {
result = Unit.ATTACK_EVADES;
} else {
result = Unit.ATTACK_WIN;
}
} else { // (r < attackPower)
result = Unit.ATTACK_WIN;
}
if (result == Unit.ATTACK_WIN) {
int diff = defender.getDefensePower(unit)*2-attackPower;
int r2 = attackCalculator.nextInt((diff<3) ? 3 : diff);
if (r2 == 0) {
result = Unit.ATTACK_GREAT_WIN;
} else {
result = Unit.ATTACK_WIN;
}
}
if (result == Unit.ATTACK_LOSS) {
int diff = attackPower*2-defender.getDefensePower(unit);
int r2 = attackCalculator.nextInt((diff<3) ? 3 : diff);
if (r2 == 0) {
result = Unit.ATTACK_GREAT_LOSS;
} else {
result = Unit.ATTACK_LOSS;
}
}
if ((result == Unit.ATTACK_WIN || result == Unit.ATTACK_GREAT_WIN) && (
defender.getTile().getSettlement() != null && defender.getTile().getSettlement() instanceof IndianSettlement
&& ((IndianSettlement) defender.getTile().getSettlement()).getUnitCount()+defender.getTile().getUnitCount() <= 1
|| defender.getTile().getColony() != null && !defender.isArmed() && !defender.isMounted() && defender.getType() != Unit.ARTILLERY
&& defender.getType() != Unit.DAMAGED_ARTILLERY)) {
result = Unit.ATTACK_DONE_SETTLEMENT;
}
return result;
}
/**
* Handles an "embark"-message from a client.
*
* @param connection The connection the message came from.
* @param embarkElement The element containing the request.
* @exception IllegalArgumentException If the data format of the message is invalid.
*/
private Element embark(Connection connection, Element embarkElement) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(embarkElement.getAttribute("unit"));
int direction = Integer.parseInt(embarkElement.getAttribute("direction"));
Unit destinationUnit = (Unit) game.getFreeColGameObject(embarkElement.getAttribute("embarkOnto"));
if (unit == null || destinationUnit == null || game.getMap().getNeighbourOrNull(direction, unit.getTile()) != destinationUnit.getTile()) {
throw new IllegalArgumentException("Invalid data format in client message.");
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
unit.embark(destinationUnit);
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
try {
if (enemyPlayer.canSee(oldTile)) {
Element removeElement = Message.createNewRootElement("remove");
Element removeUnit = removeElement.getOwnerDocument().createElement("removeObject");
removeUnit.setAttribute("ID", unit.getID());
removeElement.appendChild(removeUnit);
enemyPlayer.getConnection().send(removeElement);
}
} catch (IOException e) {
logger.warning("Could not send message to: " + enemyPlayer.getName() + " with connection " + enemyPlayer.getConnection());
}
}
return null;
}
/**
* Handles an "boardShip"-message from a client.
*
* @param connection The connection the message came from.
* @param boardShipElement The element containing the request.
*/
private Element boardShip(Connection connection, Element boardShipElement) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(boardShipElement.getAttribute("unit"));
Unit carrier = (Unit) game.getFreeColGameObject(boardShipElement.getAttribute("carrier"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
boolean tellEnemyPlayers = true;
if (oldTile == null || oldTile.getSettlement() != null) {
tellEnemyPlayers = false;
}
if (unit.isCarrier()) {
logger.warning("Tried to load a carrier onto another carrier.");
return null;
}
unit.boardShip(carrier);
if (tellEnemyPlayers) {
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
try {
if (enemyPlayer.canSee(oldTile)) {
Element removeElement = Message.createNewRootElement("remove");
Element removeUnit = removeElement.getOwnerDocument().createElement("removeObject");
removeUnit.setAttribute("ID", unit.getID());
removeElement.appendChild(removeUnit);
enemyPlayer.getConnection().send(removeElement);
}
} catch (IOException e) {
logger.warning("Could not send message to: " + enemyPlayer.getName() + " with connection " + enemyPlayer.getConnection());
}
}
}
return null;
}
/**
* Handles a "learnSkillAtSettlement"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*/
private Element learnSkillAtSettlement(Connection connection, Element element) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
Map map = game.getMap();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
int direction = Integer.parseInt(element.getAttribute("direction"));
boolean cancelAction = false;
if (element.getAttribute("action").equals("cancel")) {
cancelAction = true;
}
if (unit.getTile() == null) {
throw new IllegalArgumentException("'Unit' not on map: ID: " + element.getAttribute("unit"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
// The unit was relocated to the indian settlement. See askSkill for more info.
IndianSettlement settlement = (IndianSettlement) unit.getLocation();
Tile tile = map.getNeighbourOrNull(Map.getReverseDirection(direction), unit.getTile());
unit.setLocation(tile);
if (!cancelAction) {
unit.setType(settlement.getLearnableSkill());
settlement.setLearnableSkill(IndianSettlement.NONE);
// Set the Tile.PlayerExploredTile attribute.
settlement.getTile().updateIndianSettlementSkill(player);
}
return null;
}
/**
* Handles a "scoutIndianSettlement"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*/
private Element scoutIndianSettlement(Connection connection, Element element) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
Map map = game.getMap();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
int direction = Integer.parseInt(element.getAttribute("direction"));
String action = element.getAttribute("action");
IndianSettlement settlement;
if (action.equals("basic")) {
settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile()).getSettlement();
// Move the unit onto the settlement's Tile.
unit.setLocation(settlement.getTile());
unit.setMovesLeft(0);
} else {
settlement = (IndianSettlement) unit.getTile().getSettlement();
// Move the unit back to its original Tile.
unit.setLocation(map.getNeighbourOrNull(Map.getReverseDirection(direction), unit.getTile()));
}
Element reply = Message.createNewRootElement("scoutIndianSettlementResult");
if (action.equals("basic")) {
// Just return the skill and wanted goods.
reply.setAttribute("skill", Integer.toString(settlement.getLearnableSkill()));
settlement.updateWantedGoods();
reply.setAttribute("highlyWantedGoods", Integer.toString(settlement.getHighlyWantedGoods()));
reply.setAttribute("wantedGoods1", Integer.toString(settlement.getWantedGoods1()));
reply.setAttribute("wantedGoods2", Integer.toString(settlement.getWantedGoods2()));
// Set the Tile.PlayerExploredTile attribute.
settlement.getTile().updateIndianSettlementInformation(player);
} else if (action.equals("speak")) {
if (!settlement.hasBeenVisited()) {
// This can probably be randomized, I don't think the AI needs to do anything here.
double random = Math.random();
if (random < 0.33) {
reply.setAttribute("result", "tales");
Element update = reply.getOwnerDocument().createElement("update");
Position center = new Position(settlement.getTile().getX(), settlement.getTile().getY());
Iterator circleIterator = map.getCircleIterator(center, true, 6);
while (circleIterator.hasNext()) {
Position position = (Position)circleIterator.next();
if ((!position.equals(center)) && map.getTile(position).isLand()) {
Tile t = map.getTile(position);
player.setExplored(t);
update.appendChild(t.toXMLElement(player, update.getOwnerDocument()));
}
}
reply.appendChild(update);
} else {
int beadsGold = (int) (Math.random() * (400 * settlement.getBonusMultiplier())) + 50;
if (unit.getType() == Unit.SEASONED_SCOUT) {
beadsGold = (beadsGold * 11) / 10;
}
reply.setAttribute("result", "beads");
reply.setAttribute("amount", Integer.toString(beadsGold));
player.modifyGold(beadsGold);
}
/* This should only happen if you have "Searched for a treasure in the burial mounds":
else {
reply.setAttribute("result", "die");
unit.dispose();
}
*/
settlement.setVisited();
} else {
reply.setAttribute("result", "nothing");
}
} else if (action.equals("tribute")) {
// TODO: the AI needs to determine whether or not we want to pay and how much.
double random = Math.random();
if (random < 0.5 && settlement.getOwner().getGold() >= 100) {
reply.setAttribute("result", "agree");
reply.setAttribute("amount", "100");
settlement.getOwner().modifyGold(-100);
player.modifyGold(100);
} else {
reply.setAttribute("result", "disagree");
}
settlement.getOwner().modifyTension(player, Tension.TENSION_ADD_MINOR);
} else if (action.equals("attack")) {
// The movesLeft has been set to 0 when the scout initiated its action.
// If it wants to attack then it can and it will need some moves to do it.
unit.setMovesLeft(1);
return null;
} else if (action.equals("cancel")) {
return null;
}
return reply;
}
/**
* Handles a "missionaryAtSettlement"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*/
private Element missionaryAtSettlement(Connection connection, Element element) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
Map map = game.getMap();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
int direction = Integer.parseInt(element.getAttribute("direction"));
String action = element.getAttribute("action");
IndianSettlement settlement = (IndianSettlement) map.getNeighbourOrNull(direction, unit.getTile()).getSettlement();
unit.setMovesLeft(0);
if (action.equals("cancel")) {
return null;
} else if (action.equals("establish")) {
sendRemoveUnitToAll(unit, player);
settlement.setMissionary(unit);
return null;
} else if (action.equals("heresy")) {
Element reply = Message.createNewRootElement("missionaryReply");
sendRemoveUnitToAll(unit, player);
// TODO: chance needs to depend on amount of crosses that the players who are involved have.
double random = Math.random();
if (settlement.getMissionary().getType() == Unit.JESUIT_MISSIONARY
|| settlement.getMissionary().getOwner().hasFather(FoundingFather.FATHER_JEAN_DE_BREBEUF)) {
random += 0.2;
}
if (unit.getType() == Unit.JESUIT_MISSIONARY
|| unit.getOwner().hasFather(FoundingFather.FATHER_JEAN_DE_BREBEUF)) {
random -= 0.2;
}
if (random < 0.5) {
reply.setAttribute("success", "true");
settlement.setMissionary(unit);
} else {
reply.setAttribute("success", "false");
unit.dispose();
}
return reply;
} else if (action.equals("incite")) {
Element reply = Message.createNewRootElement("missionaryReply");
Player enemy = (Player) game.getFreeColGameObject(element.getAttribute("incite"));
reply.setAttribute("amount", String.valueOf(Game.getInciteAmount(player, enemy, settlement.getOwner())));
// Move the unit into the settlement while we wait for the client's response.
unit.setLocation(settlement);
return reply;
} else {
return null;
}
}
private void sendRemoveUnitToAll(Unit unit, Player player) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
try {
if (unit.isVisibleTo(enemyPlayer)) {
Element removeElement = Message.createNewRootElement("remove");
Element removeUnit = removeElement.getOwnerDocument().createElement("removeObject");
removeUnit.setAttribute("ID", unit.getID());
removeElement.appendChild(removeUnit);
enemyPlayer.getConnection().send(removeElement);
}
} catch (IOException e) {
logger.warning("Could not send message to: " + enemyPlayer.getName() + " with connection " + enemyPlayer.getConnection());
}
}
}
/**
* Handles a "inciteAtSettlement"-message from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*/
private Element inciteAtSettlement(Connection connection, Element element) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
Map map = game.getMap();
ServerPlayer player = freeColServer.getPlayer(connection);
Unit unit = (Unit)game.getFreeColGameObject(element.getAttribute("unit"));
int direction = Integer.parseInt(element.getAttribute("direction"));
String confirmed = element.getAttribute("confirmed");
IndianSettlement settlement = (IndianSettlement) unit.getTile().getSettlement();
// Move the unit back to its original Tile.
unit.setLocation(map.getNeighbourOrNull(Map.getReverseDirection(direction), unit.getTile()));
if (confirmed.equals("true")) {
Player enemy = (Player)game.getFreeColGameObject(element.getAttribute("enemy"));
int amount = Game.getInciteAmount(player, enemy, settlement.getOwner());
player.modifyGold(-amount);
// Set the indian player at war with the european player (and vice versa).
settlement.getOwner().setStance(enemy, Player.WAR);
// Increase tension levels:
settlement.getOwner().modifyTension(enemy, 500);
enemy.modifyTension(settlement.getOwner(), 500);
enemy.modifyTension(player, 250);
}
// else: no need to do anything: unit's moves are already zero.
return null;
}
/**
* Handles a "leaveShip"-message from a client.
*
* @param connection The connection the message came from.
* @param leaveShipElement The element containing the request.
*/
private Element leaveShip(Connection connection, Element leaveShipElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(leaveShipElement.getAttribute("unit"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
unit.leaveShip();
Tile newTile = unit.getTile();
if (newTile != null) {
sendUpdatedTileToAll(newTile, player);
}
return null;
}
/**
* Handles a "loadCargo"-message from a client.
*
* @param connection The connection the message came from.
* @param loadCargoElement The element containing the request.
*/
private Element loadCargo(Connection connection, Element loadCargoElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit carrier = (Unit) game.getFreeColGameObject(loadCargoElement.getAttribute("carrier"));
Goods goods = new Goods(game, (Element) loadCargoElement.getChildNodes().item(0));
goods.loadOnto(carrier);
return null;
}
/**
* Handles an "unloadCargo"-message from a client.
*
* @param connection The connection the message came from.
* @param unloadCargoElement The element containing the request.
*/
private Element unloadCargo(Connection connection, Element unloadCargoElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Goods goods = new Goods(game, (Element) unloadCargoElement.getChildNodes().item(0));
if (goods.getLocation() instanceof Unit && ((Unit) goods.getLocation()).getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
goods.unload();
return null;
}
/**
* Handles a "buyGoods"-message from a client.
*
* @param connection The connection the message came from.
* @param buyGoodsElement The element containing the request.
*/
private Element buyGoods(Connection connection, Element buyGoodsElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit carrier = (Unit) game.getFreeColGameObject(buyGoodsElement.getAttribute("carrier"));
int type = Integer.parseInt(buyGoodsElement.getAttribute("type"));
int amount = Integer.parseInt(buyGoodsElement.getAttribute("amount"));
if (carrier.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
if (carrier.getOwner() != player) {
throw new IllegalStateException();
}
carrier.buyGoods(type, amount);
return null;
}
/**
* Handles a "sellGoods"-message from a client.
*
* @param connection The connection the message came from.
* @param sellGoodsElement The element containing the request.
*/
private Element sellGoods(Connection connection, Element sellGoodsElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Goods goods = new Goods(game, (Element) sellGoodsElement.getChildNodes().item(0));
if (goods.getLocation() instanceof Unit && ((Unit) goods.getLocation()).getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
game.getMarket().sell(goods, player);
return null;
}
/**
* Handles a "moveToEurope"-message from a client.
*
* @param connection The connection the message came from.
* @param moveToEuropeElement The element containing the request.
*/
private Element moveToEurope(Connection connection, Element moveToEuropeElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(moveToEuropeElement.getAttribute("unit"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
unit.moveToEurope();
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
try {
if (enemyPlayer.canSee(oldTile)) {
Element removeElement = Message.createNewRootElement("remove");
Element removeUnit = removeElement.getOwnerDocument().createElement("removeObject");
removeUnit.setAttribute("ID", unit.getID());
removeElement.appendChild(removeUnit);
enemyPlayer.getConnection().send(removeElement);
}
} catch (IOException e) {
logger.warning("Could not send message to: " + enemyPlayer.getName() + " with connection " + enemyPlayer.getConnection());
}
}
return null;
}
/**
* Handles a "moveToAmerica"-message from a client.
*
* @param connection The connection the message came from.
* @param moveToAmericaElement The element containing the request.
*/
private Element moveToAmerica(Connection connection, Element moveToAmericaElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(moveToAmericaElement.getAttribute("unit"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
unit.moveToAmerica();
return null;
}
/**
* Handles a "buildColony"-request from a client.
*
* @param connection The connection the message came from.
* @param buildColonyElement The element containing the request.
*/
private Element buildColony(Connection connection, Element buildColonyElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
String name = buildColonyElement.getAttribute("name");
Unit unit = (Unit) game.getFreeColGameObject(buildColonyElement.getAttribute("unit"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
if (unit.canBuildColony()) {
Colony colony = new Colony(game, player, name, unit.getTile());
Element reply = Message.createNewRootElement("buildColonyConfirmed");
reply.appendChild(colony.toXMLElement(player, reply.getOwnerDocument()));
if (colony.getLineOfSight() > unit.getLineOfSight()) {
Element updateElement = reply.getOwnerDocument().createElement("update");
Vector surroundingTiles = game.getMap().getSurroundingTiles(unit.getTile(), colony.getLineOfSight());
for (int i=0; i<surroundingTiles.size(); i++) {
Tile t = (Tile) surroundingTiles.get(i);
if (t != unit.getTile()) {
updateElement.appendChild(t.toXMLElement(player, reply.getOwnerDocument()));
}
}
reply.appendChild(updateElement);
}
unit.buildColony(colony);
sendUpdatedTileToAll(unit.getTile(), player);
return reply;
} else {
logger.warning("A client is requesting to build a colony, but the operation is not permitted! (unsynchronized?)");
return null;
}
}
/**
* Handles a "recruitUnitInEurope"-request from a client.
*
* @param connection The connection the message came from.
* @param recruitUnitInEuropeElement The element containing the request.
*/
private Element recruitUnitInEurope(Connection connection, Element recruitUnitInEuropeElement) {
Game game = getFreeColServer().getGame();
Player player = getFreeColServer().getPlayer(connection);
Europe europe = player.getEurope();
int slot = Integer.parseInt(recruitUnitInEuropeElement.getAttribute("slot"));
int recruitable = europe.getRecruitable(slot);
int newRecruitable = player.generateRecruitable();
Unit unit = new Unit(game, player, recruitable);
Element reply = Message.createNewRootElement("recruitUnitInEuropeConfirmed");
reply.setAttribute("newRecruitable", Integer.toString(newRecruitable));
reply.appendChild(unit.toXMLElement(player, reply.getOwnerDocument()));
europe.recruit(slot, unit, newRecruitable);
return reply;
}
/**
* Handles an "emigrateUnitInEurope"-request from a client.
*
* @param connection The connection the message came from.
* @param emigrateUnitInEuropeElement The element containing the request.
*/
private Element emigrateUnitInEurope(Connection connection, Element emigrateUnitInEuropeElement) {
Game game = getFreeColServer().getGame();
Player player = getFreeColServer().getPlayer(connection);
Europe europe = player.getEurope();
int slot;
if (player.hasFather(FoundingFather.WILLIAM_BREWSTER)) {
slot = Integer.parseInt(emigrateUnitInEuropeElement.getAttribute("slot"));
} else {
slot = (int) ((Math.random() * 3) + 1);
}
int recruitable = europe.getRecruitable(slot);
int newRecruitable = player.generateRecruitable();
Unit unit = new Unit(game, player, recruitable);
Element reply = Message.createNewRootElement("emigrateUnitInEuropeConfirmed");
if (!player.hasFather(FoundingFather.WILLIAM_BREWSTER)) {
reply.setAttribute("slot", Integer.toString(slot));
}
reply.setAttribute("newRecruitable", Integer.toString(newRecruitable));
reply.appendChild(unit.toXMLElement(player, reply.getOwnerDocument()));
europe.emigrate(slot, unit, newRecruitable);
return reply;
}
/**
* Handles a "trainUnitInEurope"-request from a client.
*
* @param connection The connection the message came from.
* @param trainUnitInEuropeElement The element containing the request.
*/
private Element trainUnitInEurope(Connection connection, Element trainUnitInEuropeElement) {
Game game = getFreeColServer().getGame();
Player player = getFreeColServer().getPlayer(connection);
Europe europe = player.getEurope();
int unitType = Integer.parseInt(trainUnitInEuropeElement.getAttribute("unitType"));
Unit unit = new Unit(game, player, unitType);
Element reply = Message.createNewRootElement("trainUnitInEuropeConfirmed");
reply.appendChild(unit.toXMLElement(player, reply.getOwnerDocument()));
europe.train(unit);
return reply;
}
/**
* Handles a "equipunit"-request from a client.
*
* @param connection The connection the message came from.
* @param workElement The element containing the request.
*/
private Element equipUnit(Connection connection, Element workElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(workElement.getAttribute("unit"));
int type = Integer.parseInt(workElement.getAttribute("type"));
int amount = Integer.parseInt(workElement.getAttribute("amount"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
switch(type) {
case Goods.CROSSES:
unit.setMissionary((amount > 0));
break;
case Goods.MUSKETS:
unit.setArmed((amount > 0)); // So give them muskets if the amount we want is greater than zero.
break;
case Goods.HORSES:
unit.setMounted((amount > 0)); // As above.
break;
case Goods.TOOLS:
int actualAmount = amount;
if ((actualAmount % 20) > 0) {
logger.warning("Trying to set a number of tools that is not a multiple of 20.");
actualAmount -= (actualAmount % 20);
}
unit.setNumberOfTools(actualAmount);
break;
default:
logger.warning("Invalid type of goods to equip.");
return null;
}
if (unit.getLocation() instanceof Tile) {
sendUpdatedTileToAll(unit.getTile(), player);
}
return null;
}
/**
* Handles a "work"-request from a client.
*
* @param connection The connection the message came from.
* @param workElement The element containing the request.
*/
private Element work(Connection connection, Element workElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(workElement.getAttribute("unit"));
WorkLocation workLocation = (WorkLocation) game.getFreeColGameObject(workElement.getAttribute("workLocation"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
if (workLocation == null) {
throw new NullPointerException();
}
unit.work(workLocation);
// For updating the number of colonist:
sendUpdatedTileToAll(unit.getTile(), player);
return null;
}
/**
* Handles a "changeWorkType"-request from a client.
*
* @param connection The connection the message came from.
* @param workElement The element containing the request.
*/
private Element changeWorkType(Connection connection, Element workElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(workElement.getAttribute("unit"));
int workType = Integer.parseInt(workElement.getAttribute("workType"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
// No reason to send an update to other players: this is always hidden.
unit.setWorkType(workType);
return null;
}
/**
* Handles a "setCurrentlyBuilding"-request from a client.
*
* @param connection The connection the message came from.
* @param setCurrentlyBuildingElement The element containing the request.
*/
private Element setCurrentlyBuilding(Connection connection, Element setCurrentlyBuildingElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Colony colony = (Colony) game.getFreeColGameObject(setCurrentlyBuildingElement.getAttribute("colony"));
int type = Integer.parseInt(setCurrentlyBuildingElement.getAttribute("type"));
if (colony.getOwner() != player) {
throw new IllegalStateException("Not your colony!");
}
colony.setCurrentlyBuilding(type);
sendUpdatedTileToAll(colony.getTile(), player);
return null;
}
/**
* Handles a "changeState"-message from a client.
*
* @param connection The connection the message came from.
* @param changeStateElement The element containing the request.
* @exception IllegalArgumentException If the data format of the message is invalid.
* @exception IllegalStateException If the request is not accepted by the model.
*
*/
private Element changeState(Connection connection, Element changeStateElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(changeStateElement.getAttribute("unit"));
int state = Integer.parseInt(changeStateElement.getAttribute("state"));
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + changeStateElement.getAttribute("unit"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
if (!unit.checkSetState(state)) {
// Oh, really, Mr. Client? I'll show YOU!
// kickPlayer(player);
logger.warning("Can't set state " + state + ". Possible cheating attempt?");
return null;
}
unit.setState(state);
sendUpdatedTileToAll(oldTile, player);
return null;
}
/**
* Handles a "putOutsideColony"-request from a client.
*
* @param connection The connection the message came from.
* @param putOutsideColonyElement The element containing the request.
*/
private Element putOutsideColony(Connection connection, Element putOutsideColonyElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(putOutsideColonyElement.getAttribute("unit"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
unit.putOutsideColony();
sendUpdatedTileToAll(unit.getTile(), player);
return null;
}
/**
* Handles a "payForBuilding"-request from a client.
*
* @param connection The connection the message came from.
* @param payForBuildingElement The element containing the request.
*/
private Element payForBuilding(Connection connection, Element payForBuildingElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Colony colony = (Colony) game.getFreeColGameObject(payForBuildingElement.getAttribute("colony"));
if (colony.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
colony.payForBuilding();
return null;
}
/**
* Handles a "payArrears"-request from a client.
*
* @param connection The connection the message came from.
* @param payArrearsElement The element containing the request.
*/
private Element payArrears(Connection connection, Element payArrearsElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
int goods = new Integer(payArrearsElement.getAttribute("goodsType")).intValue();
int arrears = player.getArrears(goods);
if (player.getGold() < arrears) {
throw new IllegalStateException("Not enough gold to pay tax arrears!");
} else {
player.modifyGold(-arrears);
player.setArrears(goods, 0);
}
return null;
}
/**
* Handles a "toggleExports"-request from a client.
*
* @param connection The connection the message came from.
* @param toggleExportsElement The element containing the request.
*/
private Element toggleExports(Connection connection, Element toggleExportsElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Colony colony = (Colony) game.getFreeColGameObject(toggleExportsElement.getAttribute("colony"));
if (colony == null) {
throw new IllegalArgumentException("Found no colony with ID " +
toggleExportsElement.getAttribute("colony"));
} else if (colony.getOwner() != player) {
throw new IllegalStateException("Not your colony!");
} else if (!colony.getBuilding(Building.CUSTOM_HOUSE).isBuilt()) {
throw new IllegalStateException("Colony has no custom house!");
}
int goods = new Integer(toggleExportsElement.getAttribute("goods")).intValue();
colony.toggleExports(goods);
return null;
}
/**
* Handles a "clearSpeciality"-request from a client.
*
* @param connection The connection the message came from.
* @param clearSpecialityElement The element containing the request.
*/
private Element clearSpeciality(Connection connection, Element clearSpecialityElement) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(clearSpecialityElement.getAttribute("unit"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
unit.clearSpeciality();
if (unit.getLocation() instanceof Tile) {
sendUpdatedTileToAll(unit.getTile(), player);
}
return null;
}
/**
* Handles an "endTurn" notification from a client.
*
* @param connection The connection the message came from.
* @param element The element containing the request.
*/
private Element endTurn(Connection connection, Element element) {
ServerPlayer player = getFreeColServer().getPlayer(connection);
getFreeColServer().getInGameController().endTurn(player);
return null;
}
/**
* Handles a "disbandUnit"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element disbandUnit(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + element.getAttribute("unit"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
unit.dispose();
sendUpdatedTileToAll(oldTile, player);
return null;
}
/**
* Handles a "cashInTreasureTrain"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element cashInTreasureTrain(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + element.getAttribute("unit"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
unit.cashInTreasureTrain();
sendUpdatedTileToAll(oldTile, player);
return null;
}
/**
* Handles a "declareIndependence"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element declareIndependence(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
player.declareIndependence();
return null;
}
/**
* Handles a "giveIndependence"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element giveIndependence(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Player independent = (Player) game.getFreeColGameObject(element.getAttribute("player"));
if (independent.getREFPlayer() != player) {
throw new IllegalStateException("Cannot give independence to a country we do not own.");
}
independent.giveIndependence();
Element giveIndependenceElement = Message.createNewRootElement("giveIndependence");
giveIndependenceElement.setAttribute("player", independent.getID());
getFreeColServer().getServer().sendToAll(giveIndependenceElement, connection);
return null;
}
/**
* Handles a "setDestination"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element setDestination(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
if (unit.getOwner() != player) {
throw new IllegalStateException("Not the owner of the unit.");
}
Location destination = null;
if (element.hasAttribute("destination")) {
destination = (Location) game.getFreeColGameObject(element.getAttribute("destination"));
}
unit.setDestination(destination);
return null;
}
/**
* Handles a "tradeProposition"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element tradeProposition(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
Settlement settlement = (Settlement) game.getFreeColGameObject(element.getAttribute("settlement"));
Goods goods = new Goods(game, Message.getChildElement(element, Goods.getXMLElementTagName()));
int gold = -1;
if (element.hasAttribute("gold")) {
gold = Integer.parseInt(element.getAttribute("gold"));
}
if (goods.getAmount() > 100) {
throw new IllegalArgumentException();
}
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + element.getAttribute("unit"));
}
if (unit.getMovesLeft() <= 0) {
throw new IllegalStateException("No moves left!");
}
if (settlement == null) {
throw new IllegalArgumentException("Could not find 'Settlement' with specified ID: " + element.getAttribute("settlement"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
if (unit.getTile().getDistanceTo(settlement.getTile()) > 1) {
throw new IllegalStateException("Not adjacent to settlemen!");
}
int returnGold = ((AIPlayer) getFreeColServer().getAIMain().getAIObject(settlement.getOwner())).tradeProposition(unit, settlement, goods, gold);
Element tpaElement = Message.createNewRootElement("tradePropositionAnswer");
tpaElement.setAttribute("gold", Integer.toString(returnGold));
return tpaElement;
}
/**
* Handles a "trade"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element trade(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
Settlement settlement = (Settlement) game.getFreeColGameObject(element.getAttribute("settlement"));
Goods goods = new Goods(game, Message.getChildElement(element, Goods.getXMLElementTagName()));
int gold = Integer.parseInt(element.getAttribute("gold"));
if (gold <= 0) {
throw new IllegalArgumentException();
}
if (goods.getAmount() > 100) {
throw new IllegalArgumentException();
}
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + element.getAttribute("unit"));
}
if (unit.getMovesLeft() <= 0) {
throw new IllegalStateException("No moves left!");
}
if (settlement == null) {
throw new IllegalArgumentException("Could not find 'Settlement' with specified ID: " + element.getAttribute("settlement"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
if (unit.getTile().getDistanceTo(settlement.getTile()) > 1) {
throw new IllegalStateException("Not adjacent to settlemen!");
}
int returnGold = ((AIPlayer) getFreeColServer().getAIMain().getAIObject(settlement.getOwner())).tradeProposition(unit, settlement, goods, gold);
if (returnGold != gold) {
throw new IllegalArgumentException("This was not the price we agreed upon! Cheater?");
}
unit.trade(settlement, goods, gold);
return null;
}
/**
* Handles a "deliverGift"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element deliverGift(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
Settlement settlement = (Settlement) game.getFreeColGameObject(element.getAttribute("settlement"));
Goods goods = new Goods(game, Message.getChildElement(element, Goods.getXMLElementTagName()));
if (goods.getAmount() > 100) {
throw new IllegalArgumentException();
}
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + element.getAttribute("unit"));
}
if (unit.getMovesLeft() <= 0) {
throw new IllegalStateException("No moves left!");
}
if (settlement == null) {
throw new IllegalArgumentException("Could not find 'Settlement' with specified ID: " + element.getAttribute("settlement"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
if (unit.getTile().getDistanceTo(settlement.getTile()) > 1) {
throw new IllegalStateException("Not adjacent to settlemen!");
}
ServerPlayer receiver = (ServerPlayer) settlement.getOwner();
if (!receiver.isAI() && receiver.isConnected()) {
Element deliverGiftElement = Message.createNewRootElement("deliverGift");
Element unitElement = unit.toXMLElement(receiver, deliverGiftElement.getOwnerDocument());
Element goodsContainerElement = unit.getGoodsContainer().toXMLElement(receiver, deliverGiftElement.getOwnerDocument());
unitElement.replaceChild(goodsContainerElement, unitElement.getElementsByTagName(GoodsContainer.getXMLElementTagName()).item(0));
deliverGiftElement.appendChild(unitElement);
deliverGiftElement.setAttribute("settlement", settlement.getID());
deliverGiftElement.appendChild(goods.toXMLElement(receiver, deliverGiftElement.getOwnerDocument()));
try {
receiver.getConnection().send(deliverGiftElement);
} catch (IOException e) {
logger.warning("Could not send \"deliverGift\"-message!");
}
}
unit.deliverGift(settlement, goods);
return null;
}
/**
* Handles an "indianDemand"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param element The element containing the request.
*/
private Element indianDemand(Connection connection, Element element) {
Game game = getFreeColServer().getGame();
ServerPlayer player = getFreeColServer().getPlayer(connection);
Unit unit = (Unit) game.getFreeColGameObject(element.getAttribute("unit"));
Colony colony = (Colony) game.getFreeColGameObject(element.getAttribute("colony"));
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " +
element.getAttribute("unit"));
}
if (unit.getMovesLeft() <= 0) {
throw new IllegalStateException("No moves left!");
}
if (colony == null) {
throw new IllegalArgumentException("Could not find 'Colony' with specified ID: " +
element.getAttribute("colony"));
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
if (unit.getTile().getDistanceTo(colony.getTile()) > 1) {
throw new IllegalStateException("Not adjacent to colony!");
}
ServerPlayer receiver = (ServerPlayer) colony.getOwner();
if (receiver.isConnected()) {
int gold = 0;
Goods goods = null;
Element goodsElement = Message.getChildElement(element, Goods.getXMLElementTagName());
if (goodsElement == null) {
gold = Integer.parseInt(element.getAttribute("gold"));
} else {
goods = new Goods(game, goodsElement);
}
try {
Element reply = receiver.getConnection().ask(element);
boolean accepted = Boolean.valueOf(reply.getAttribute("accepted")).booleanValue();
if (accepted) {
if (goods == null) {
receiver.modifyGold(-gold);
} else {
colony.getGoodsContainer().removeGoods(goods);
}
}
return reply;
} catch (IOException e) {
logger.warning("Could not send \"demand\"-message!");
}
}
return null;
}
/**
* Handles a "logout"-message.
*
* @param connection The <code>Connection</code> the message was received on.
* @param logoutElement The element (root element in a DOM-parsed XML tree) that
* holds all the information.
* @return The reply.
*/
protected Element logout(Connection connection, Element logoutElement) {
ServerPlayer player = getFreeColServer().getPlayer(connection);
logger.info("Logout by: " + connection + ((player != null) ? " (" + player.getName() + ") " : ""));
if (player == null) {
return null;
}
// TODO
// Remove the player's units/colonies from the map and send map updates to the
// players that can see such units or colonies.
// SHOULDN'T THIS WAIT UNTIL THE CURRENT PLAYER HAS FINISHED HIS TURN?
/*
player.setDead(true);
Element setDeadElement = Message.createNewRootElement("setDead");
setDeadElement.setAttribute("player", player.getID());
freeColServer.getServer().sendToAll(setDeadElement, connection);
*/
/*
TODO: Setting the player dead directly should be a server option,
but for now - allow the player to reconnect:
*/
player.setConnected(false);
if (getFreeColServer().getGame().getCurrentPlayer() == player && !getFreeColServer().isSingleplayer() && isHumanPlayersLeft()) {
getFreeColServer().getInGameController().endTurn(player);
}
getFreeColServer().updateMetaServer();
return null;
}
private boolean isHumanPlayersLeft() {
Iterator playerIterator = getFreeColServer().getGame().getPlayerIterator();
while (playerIterator.hasNext()) {
Player p = (Player) playerIterator.next();
if (!p.isDead() && !p.isAI()) {
return true;
}
}
return false;
}
private void sendUpdatedTileToAll(Tile newTile, Player player) {
Game game = getFreeColServer().getGame();
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player != null && player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
try {
if (enemyPlayer.canSee(newTile)) {
Element updateElement = Message.createNewRootElement("update");
updateElement.appendChild(newTile.toXMLElement(enemyPlayer, updateElement.getOwnerDocument()));
enemyPlayer.getConnection().send(updateElement);
}
} catch (IOException e) {
logger.warning("Could not send message to: " + enemyPlayer.getName() + " with connection " + enemyPlayer.getConnection());
}
}
}
private void sendErrorToAll(String message, Player player) {
Game game = getFreeColServer().getGame();
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if ((player != null) && (player.equals(enemyPlayer)) || enemyPlayer.getConnection() == null) {
continue;
}
try {
Element errorElement = Message.createNewRootElement("error");
errorElement.setAttribute("message", message);
enemyPlayer.getConnection().send(errorElement);
} catch (IOException e) {
logger.warning("Could not send message to: " + enemyPlayer.getName() + " with connection " + enemyPlayer.getConnection());
}
}
}
}
| true | true | private Element attack(Connection connection, Element attackElement) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
ServerPlayer player = freeColServer.getPlayer(connection);
// Get parameters:
Unit unit = (Unit) game.getFreeColGameObject(attackElement.getAttribute("unit"));
int direction = Integer.parseInt(attackElement.getAttribute("direction"));
// Test the parameters:
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + attackElement.getAttribute("unit"));
}
if (unit.getTile() == null) {
throw new IllegalArgumentException("'Unit' is not on the map: " + unit.toString());
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
Tile newTile = game.getMap().getNeighbourOrNull(direction, unit.getTile());
if (newTile == null) {
throw new IllegalArgumentException("Could not find tile in direction " + direction + " from unit with ID " + attackElement.getAttribute("unit"));
}
Element dowElement = null;
Unit defender = newTile.getDefendingUnit(unit);
if (defender == null) {
throw new IllegalStateException("Nothing to attack in direction " +
direction + " from unit with ID " +
attackElement.getAttribute("unit"));
}
int result = generateAttackResult(unit, defender);
int plunderGold = -1;
if (result == Unit.ATTACK_DONE_SETTLEMENT) {
plunderGold = newTile.getSettlement().getOwner().getGold()/10; // 10% of their gold
}
// Inform the players (other then the player attacking) about the attack:
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
if (dowElement != null) {
try {
enemyPlayer.getConnection().send(dowElement);
} catch (IOException e) {
logger.warning("Could not send message to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}
Element opponentAttackElement = Message.createNewRootElement("opponentAttack");
if (unit.isVisibleTo(enemyPlayer) || defender.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("direction", Integer.toString(direction));
opponentAttackElement.setAttribute("result", Integer.toString(result));
opponentAttackElement.setAttribute("plunderGold", Integer.toString(plunderGold));
opponentAttackElement.setAttribute("unit", unit.getID());
opponentAttackElement.setAttribute("defender", defender.getID());
if (!defender.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("update", "defender");
if (!enemyPlayer.canSee(defender.getTile())) {
enemyPlayer.setExplored(defender.getTile());
opponentAttackElement.appendChild(defender.getTile().toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
}
opponentAttackElement.appendChild(defender.toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
} else if (!unit.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("update", "unit");
opponentAttackElement.appendChild(unit.toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
}
try {
enemyPlayer.getConnection().send(opponentAttackElement);
} catch (IOException e) {
logger.warning("Could not send message to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}
}
// Create the reply for the attacking player:
Element reply = Message.createNewRootElement("attackResult");
reply.setAttribute("result", Integer.toString(result));
reply.setAttribute("plunderGold", Integer.toString(plunderGold));
if (result == Unit.ATTACK_DONE_SETTLEMENT && newTile.getColony() != null) { // If a colony will been won, send an updated tile:
reply.appendChild(newTile.toXMLElement(newTile.getColony().getOwner(), reply.getOwnerDocument()));
}
if (!defender.isVisibleTo(player)) {
reply.appendChild(defender.toXMLElement(player, reply.getOwnerDocument()));
}
int[] oldGoodsCounts = new int[Goods.NUMBER_OF_TYPES];
for (int i=0; i < oldGoodsCounts.length; i++) {
oldGoodsCounts[i] = unit.getGoodsContainer().getGoodsCount(i);
}
unit.attack(defender, result, plunderGold);
// Send capturedGoods if UNIT_HIDING is true
// because when it's false unit is already sent with carried goods and units
if (unit.canCaptureGoods() && game.getGameOptions().getBoolean(GameOptions.UNIT_HIDING)) {
Iterator goodsIt = unit.getGoodsContainer().getCompactGoodsIterator();
while (goodsIt.hasNext()) {
Goods newGoods = (Goods) goodsIt.next();
int capturedGoods = newGoods.getAmount() - oldGoodsCounts[newGoods.getType()];
if (capturedGoods > 0) {
Element captured = reply.getOwnerDocument().createElement("capturedGoods");
captured.setAttribute("type", Integer.toString(newGoods.getType()));
captured.setAttribute("amount", Integer.toString(capturedGoods));
reply.appendChild(captured);
}
}
}
// TODO: REMOVE MAGIC: This should not really be necessary:
/*if (result == Unit.ATTACK_DONE_SETTLEMENT) {
Element updateElement = Message.createNewRootElement("update");
updateElement.appendChild(newTile.toXMLElement(newTile.getColony().getOwner(), updateElement.getOwnerDocument()));
ServerPlayer enemyPlayer = (ServerPlayer) defender.getOwner();
try {
enemyPlayer.getConnection().send(updateElement);
} catch (IOException e) {
logger.warning("Could not send message (2) to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}*/
| private Element attack(Connection connection, Element attackElement) {
FreeColServer freeColServer = getFreeColServer();
Game game = freeColServer.getGame();
ServerPlayer player = freeColServer.getPlayer(connection);
// Get parameters:
Unit unit = (Unit) game.getFreeColGameObject(attackElement.getAttribute("unit"));
int direction = Integer.parseInt(attackElement.getAttribute("direction"));
// Test the parameters:
if (unit == null) {
throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + attackElement.getAttribute("unit"));
}
if (unit.getTile() == null) {
throw new IllegalArgumentException("'Unit' is not on the map: " + unit.toString());
}
if (unit.getOwner() != player) {
throw new IllegalStateException("Not your unit!");
}
Tile oldTile = unit.getTile();
Tile newTile = game.getMap().getNeighbourOrNull(direction, unit.getTile());
if (newTile == null) {
throw new IllegalArgumentException("Could not find tile in direction " + direction + " from unit with ID " + attackElement.getAttribute("unit"));
}
Element dowElement = null;
Unit defender = newTile.getDefendingUnit(unit);
if (defender == null) {
throw new IllegalStateException("Nothing to attack in direction " +
direction + " from unit with ID " +
attackElement.getAttribute("unit"));
}
int result = generateAttackResult(unit, defender);
int plunderGold = -1;
if (result == Unit.ATTACK_DONE_SETTLEMENT) {
plunderGold = newTile.getSettlement().getOwner().getGold()/10; // 10% of their gold
}
// Inform the players (other then the player attacking) about the attack:
Iterator enemyPlayerIterator = game.getPlayerIterator();
while (enemyPlayerIterator.hasNext()) {
ServerPlayer enemyPlayer = (ServerPlayer) enemyPlayerIterator.next();
if (player.equals(enemyPlayer) || enemyPlayer.getConnection() == null) {
continue;
}
if (dowElement != null) {
try {
enemyPlayer.getConnection().send(dowElement);
} catch (IOException e) {
logger.warning("Could not send message to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}
Element opponentAttackElement = Message.createNewRootElement("opponentAttack");
if (unit.isVisibleTo(enemyPlayer) || defender.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("direction", Integer.toString(direction));
opponentAttackElement.setAttribute("result", Integer.toString(result));
opponentAttackElement.setAttribute("plunderGold", Integer.toString(plunderGold));
opponentAttackElement.setAttribute("unit", unit.getID());
opponentAttackElement.setAttribute("defender", defender.getID());
if (!defender.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("update", "defender");
if (!enemyPlayer.canSee(defender.getTile())) {
enemyPlayer.setExplored(defender.getTile());
opponentAttackElement.appendChild(defender.getTile().toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
}
opponentAttackElement.appendChild(defender.toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
} else if (!unit.isVisibleTo(enemyPlayer)) {
opponentAttackElement.setAttribute("update", "unit");
opponentAttackElement.appendChild(unit.toXMLElement(enemyPlayer, opponentAttackElement.getOwnerDocument()));
}
try {
enemyPlayer.getConnection().send(opponentAttackElement);
} catch (IOException e) {
logger.warning("Could not send message to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}
}
// Create the reply for the attacking player:
Element reply = Message.createNewRootElement("attackResult");
reply.setAttribute("result", Integer.toString(result));
reply.setAttribute("plunderGold", Integer.toString(plunderGold));
if (result == Unit.ATTACK_DONE_SETTLEMENT && newTile.getColony() != null) { // If a colony will been won, send an updated tile:
reply.appendChild(newTile.toXMLElement(newTile.getColony().getOwner(), reply.getOwnerDocument()));
}
if (!defender.isVisibleTo(player)) {
reply.appendChild(defender.toXMLElement(player, reply.getOwnerDocument()));
}
int[] oldGoodsCounts = new int[Goods.NUMBER_OF_TYPES];
if (unit.canCaptureGoods() && game.getGameOptions().getBoolean(GameOptions.UNIT_HIDING)) {
for (int i=0; i < oldGoodsCounts.length; i++) {
oldGoodsCounts[i] = unit.getGoodsContainer().getGoodsCount(i);
}
}
unit.attack(defender, result, plunderGold);
// Send capturedGoods if UNIT_HIDING is true
// because when it's false unit is already sent with carried goods and units
if (unit.canCaptureGoods() && game.getGameOptions().getBoolean(GameOptions.UNIT_HIDING)) {
Iterator goodsIt = unit.getGoodsContainer().getCompactGoodsIterator();
while (goodsIt.hasNext()) {
Goods newGoods = (Goods) goodsIt.next();
int capturedGoods = newGoods.getAmount() - oldGoodsCounts[newGoods.getType()];
if (capturedGoods > 0) {
Element captured = reply.getOwnerDocument().createElement("capturedGoods");
captured.setAttribute("type", Integer.toString(newGoods.getType()));
captured.setAttribute("amount", Integer.toString(capturedGoods));
reply.appendChild(captured);
}
}
}
// TODO: REMOVE MAGIC: This should not really be necessary:
/*if (result == Unit.ATTACK_DONE_SETTLEMENT) {
Element updateElement = Message.createNewRootElement("update");
updateElement.appendChild(newTile.toXMLElement(newTile.getColony().getOwner(), updateElement.getOwnerDocument()));
ServerPlayer enemyPlayer = (ServerPlayer) defender.getOwner();
try {
enemyPlayer.getConnection().send(updateElement);
} catch (IOException e) {
logger.warning("Could not send message (2) to: " +
enemyPlayer.getName() + " with connection " +
enemyPlayer.getConnection());
}
}*/
|
diff --git a/src/org/anddev/amatidev/pvb/bug/Bug.java b/src/org/anddev/amatidev/pvb/bug/Bug.java
index 5876730..9a1c998 100644
--- a/src/org/anddev/amatidev/pvb/bug/Bug.java
+++ b/src/org/anddev/amatidev/pvb/bug/Bug.java
@@ -1,150 +1,150 @@
package org.anddev.amatidev.pvb.bug;
import org.amatidev.AdEnviroment;
import org.amatidev.AdScene;
import org.anddev.amatidev.pvb.Game;
import org.anddev.amatidev.pvb.plant.Plant;
import org.anddev.amatidev.pvb.singleton.GameData;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.entity.Entity;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.PathModifier;
import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.anddev.andengine.entity.modifier.PathModifier.Path;
import org.anddev.andengine.entity.shape.IShape;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.SimplePreferences;
import org.anddev.andengine.util.modifier.IModifier;
import org.anddev.andengine.util.modifier.ease.EaseSineInOut;
import android.util.Log;
public abstract class Bug extends Entity {
protected int mLife = 3;
protected int mPoint = 10;
protected float mSpeed = 21f;
private Path mPath;
private boolean mCollide = true;
public Bug(final float y, final TextureRegion pTexture) {
Sprite shadow = new Sprite(2, 55, GameData.getInstance().mPlantShadow);
shadow.setAlpha(0.4f);
shadow.attachChild(new Sprite(0, -68, pTexture));
attachChild(shadow);
setPosition(705, y);
}
public void onAttached() {
SimplePreferences.incrementAccessCount(AdEnviroment.getInstance().getContext(), "count" + Float.toString(this.mY));
start(); // move
registerUpdateHandler(new IUpdateHandler() {
@Override
public void onUpdate(float pSecondsElapsed) {
AdEnviroment.getInstance().getEngine().runOnUpdateThread(new Runnable() {
@Override
public void run() {
Bug.this.checkAndRemove();
Bug.this.checkAndRestart();
}
});
}
@Override
public void reset() {
}
});
}
public void onDetached() {
SimplePreferences.incrementAccessCount(AdEnviroment.getInstance().getContext(), "count" + Float.toString(this.mY), -1);
GameData.getInstance().mScoring.addScore(this.mPoint);
}
private void pushDamage() {
// chiamare solo da thread safe
this.mLife--;
if (this.mLife <= 0)
this.detachSelf();
}
public int getLife() {
return this.mLife;
}
private void start() {
this.mCollide = true;
this.mPath = new Path(2).to(this.mX, this.mY).to(0, this.mY);
float duration = this.mX / this.mSpeed;
registerEntityModifier(new PathModifier(duration, this.mPath, new IEntityModifierListener() {
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
AdEnviroment.getInstance().nextScene();
}
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
}
}, EaseSineInOut.getInstance()));
}
private void stop() {
this.clearEntityModifiers();
}
private void checkAndRemove() {
// chiamare solo da thread safe
IEntity shotLayer = AdEnviroment.getInstance().getScene().getChild(AdScene.EXTRA_GAME_LAYER);
for (int i = 0; i < shotLayer.getChildCount(); i++) {
IShape body_bug = ((IShape) getFirstChild().getFirstChild());
IShape body_shot = (IShape) shotLayer.getChild(i);
if (body_bug.collidesWith(body_shot)) {
this.pushDamage();
body_shot.detachSelf();
break;
}
}
}
private void checkAndRestart() {
// chiamare solo da thread safe
for (int i = 0; i < 45; i++) {
IEntity field = AdEnviroment.getInstance().getScene().getChild(Game.GAME_LAYER).getChild(i);
if (field.getChildCount() == 1 && field.getFirstChild() instanceof Plant) {
IShape body_bug = ((IShape) getFirstChild().getFirstChild());
IShape body_plant = (IShape) field.getFirstChild().getFirstChild().getFirstChild();
- if (body_bug.collidesWith(body_plant) && this.mCollide) {
+ if (body_bug.collidesWith(body_plant) && this.mY == field.getY() && this.mCollide) {
this.mCollide = false;
try {
final Plant plant = (Plant) field.getFirstChild();
if (plant.getLife() != 0) {
stop();
registerUpdateHandler(new TimerHandler(1.5f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
Bug.this.mCollide = true;
plant.pushDamage();
Log.i("Game", "collision");
}
}));
} else
start();
} catch (Exception e) {
start();
Log.e("Game", "error");
}
}
}
}
}
}
| true | true | private void checkAndRestart() {
// chiamare solo da thread safe
for (int i = 0; i < 45; i++) {
IEntity field = AdEnviroment.getInstance().getScene().getChild(Game.GAME_LAYER).getChild(i);
if (field.getChildCount() == 1 && field.getFirstChild() instanceof Plant) {
IShape body_bug = ((IShape) getFirstChild().getFirstChild());
IShape body_plant = (IShape) field.getFirstChild().getFirstChild().getFirstChild();
if (body_bug.collidesWith(body_plant) && this.mCollide) {
this.mCollide = false;
try {
final Plant plant = (Plant) field.getFirstChild();
if (plant.getLife() != 0) {
stop();
registerUpdateHandler(new TimerHandler(1.5f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
Bug.this.mCollide = true;
plant.pushDamage();
Log.i("Game", "collision");
}
}));
} else
start();
} catch (Exception e) {
start();
Log.e("Game", "error");
}
}
}
}
}
| private void checkAndRestart() {
// chiamare solo da thread safe
for (int i = 0; i < 45; i++) {
IEntity field = AdEnviroment.getInstance().getScene().getChild(Game.GAME_LAYER).getChild(i);
if (field.getChildCount() == 1 && field.getFirstChild() instanceof Plant) {
IShape body_bug = ((IShape) getFirstChild().getFirstChild());
IShape body_plant = (IShape) field.getFirstChild().getFirstChild().getFirstChild();
if (body_bug.collidesWith(body_plant) && this.mY == field.getY() && this.mCollide) {
this.mCollide = false;
try {
final Plant plant = (Plant) field.getFirstChild();
if (plant.getLife() != 0) {
stop();
registerUpdateHandler(new TimerHandler(1.5f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
Bug.this.mCollide = true;
plant.pushDamage();
Log.i("Game", "collision");
}
}));
} else
start();
} catch (Exception e) {
start();
Log.e("Game", "error");
}
}
}
}
}
|
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java b/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java
index 48d0dc8444..536b1cfe48 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocsAndPositions.java
@@ -1,370 +1,371 @@
package org.apache.lucene.index;
/*
* 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.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
public class TestDocsAndPositions extends LuceneTestCase {
private String fieldName;
@Override
public void setUp() throws Exception {
super.setUp();
fieldName = "field" + random().nextInt();
}
/**
* Simple testcase for {@link DocsAndPositionsEnum}
*/
public void testPositionsSimple() throws IOException {
Directory directory = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), directory,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
for (int i = 0; i < 39; i++) {
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
doc.add(newField(fieldName, "1 2 3 4 5 6 7 8 9 10 "
+ "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 "
+ "1 2 3 4 5 6 7 8 9 10", customType));
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("1");
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
if (atomicReaderContext.reader().maxDoc() == 0) {
continue;
}
final int advance = docsAndPosEnum.advance(random().nextInt(atomicReaderContext.reader().maxDoc()));
do {
String msg = "Advanced to: " + advance + " current doc: "
+ docsAndPosEnum.docID(); // TODO: + " usePayloads: " + usePayload;
assertEquals(msg, 4, docsAndPosEnum.freq());
assertEquals(msg, 0, docsAndPosEnum.nextPosition());
assertEquals(msg, 4, docsAndPosEnum.freq());
assertEquals(msg, 10, docsAndPosEnum.nextPosition());
assertEquals(msg, 4, docsAndPosEnum.freq());
assertEquals(msg, 20, docsAndPosEnum.nextPosition());
assertEquals(msg, 4, docsAndPosEnum.freq());
assertEquals(msg, 30, docsAndPosEnum.nextPosition());
} while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.close();
directory.close();
}
public DocsAndPositionsEnum getDocsAndPositions(AtomicReader reader,
BytesRef bytes, Bits liveDocs) throws IOException {
return reader.termPositionsEnum(null, fieldName, bytes, false);
}
/**
* this test indexes random numbers within a range into a field and checks
* their occurrences by searching for a number from that range selected at
* random. All positions for that number are saved up front and compared to
* the enums positions.
*/
public void testRandomPositions() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
int numDocs = atLeast(47);
int max = 1051;
int term = random().nextInt(max);
Integer[][] positionsInDoc = new Integer[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
ArrayList<Integer> positions = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
int num = atLeast(131);
for (int j = 0; j < num; j++) {
int nextInt = random().nextInt(max);
builder.append(nextInt).append(" ");
if (nextInt == term) {
positions.add(Integer.valueOf(j));
}
}
if (positions.size() == 0) {
builder.append(term);
positions.add(num);
}
doc.add(newField(fieldName, builder.toString(), customType));
positionsInDoc[i] = positions.toArray(new Integer[0]);
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.reader().maxDoc();
// initially advance or do next doc
if (random().nextBoolean()) {
initDoc = docsAndPosEnum.nextDoc();
} else {
initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc));
}
// now run through the scorer and check if all positions are there...
do {
int docID = docsAndPosEnum.docID();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID];
assertEquals(pos.length, docsAndPosEnum.freq());
// number of positions read should be random - don't read all of them
// allways
final int howMany = random().nextInt(20) == 0 ? pos.length
- random().nextInt(pos.length) : pos.length;
for (int j = 0; j < howMany; j++) {
assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: "
+ docID + " base: " + atomicReaderContext.docBase
+ " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: "
+ usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition());
}
if (random().nextInt(10) == 0) { // once is a while advance
- docsAndPosEnum
- .advance(docID + 1 + random().nextInt((maxDoc - docID)));
+ if (docsAndPosEnum.advance(docID + 1 + random().nextInt((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS) {
+ break;
+ }
}
} while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.close();
dir.close();
}
public void testRandomDocs() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
int numDocs = atLeast(49);
int max = 15678;
int term = random().nextInt(max);
int[] freqInDoc = new int[numDocs];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < 199; j++) {
int nextInt = random().nextInt(max);
builder.append(nextInt).append(' ');
if (nextInt == term) {
freqInDoc[i]++;
}
}
doc.add(newField(fieldName, builder.toString(), customType));
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext context : topReaderContext.leaves()) {
int maxDoc = context.reader().maxDoc();
DocsEnum docsEnum = _TestUtil.docs(random(), context.reader(), fieldName, bytes, null, null, true);
if (findNext(freqInDoc, context.docBase, context.docBase + maxDoc) == Integer.MAX_VALUE) {
assertNull(docsEnum);
continue;
}
assertNotNull(docsEnum);
docsEnum.nextDoc();
for (int j = 0; j < maxDoc; j++) {
if (freqInDoc[context.docBase + j] != 0) {
assertEquals(j, docsEnum.docID());
assertEquals(docsEnum.freq(), freqInDoc[context.docBase +j]);
if (i % 2 == 0 && random().nextInt(10) == 0) {
int next = findNext(freqInDoc, context.docBase+j+1, context.docBase + maxDoc) - context.docBase;
int advancedTo = docsEnum.advance(next);
if (next >= maxDoc) {
assertEquals(DocIdSetIterator.NO_MORE_DOCS, advancedTo);
} else {
assertTrue("advanced to: " +advancedTo + " but should be <= " + next, next >= advancedTo);
}
} else {
docsEnum.nextDoc();
}
}
}
assertEquals("docBase: " + context.docBase + " maxDoc: " + maxDoc + " " + docsEnum.getClass(), DocIdSetIterator.NO_MORE_DOCS, docsEnum.docID());
}
}
reader.close();
dir.close();
}
private static int findNext(int[] docs, int pos, int max) {
for (int i = pos; i < max; i++) {
if( docs[i] != 0) {
return i;
}
}
return Integer.MAX_VALUE;
}
/**
* tests retrieval of positions for terms that have a large number of
* occurrences to force test of buffer refill during positions iteration.
*/
public void testLargeNumberOfPositions() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
int howMany = 1000;
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < 39; i++) {
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < howMany; j++) {
if (j % 2 == 0) {
builder.append("even ");
} else {
builder.append("odd ");
}
}
doc.add(newField(fieldName, builder.toString(), customType));
writer.addDocument(doc);
}
// now do searches
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("even");
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.reader().maxDoc();
// initially advance or do next doc
if (random().nextBoolean()) {
initDoc = docsAndPosEnum.nextDoc();
} else {
initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc));
}
String msg = "Iteration: " + i + " initDoc: " + initDoc; // TODO: + " payloads: " + usePayload;
assertEquals(howMany / 2, docsAndPosEnum.freq());
for (int j = 0; j < howMany; j += 2) {
assertEquals("position missmatch index: " + j + " with freq: "
+ docsAndPosEnum.freq() + " -- " + msg, j,
docsAndPosEnum.nextPosition());
}
}
}
reader.close();
dir.close();
}
public void testDocsEnumStart() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
Document doc = new Document();
doc.add(newStringField("foo", "bar", Field.Store.NO));
writer.addDocument(doc);
DirectoryReader reader = writer.getReader();
AtomicReader r = getOnlySegmentReader(reader);
DocsEnum disi = _TestUtil.docs(random(), r, "foo", new BytesRef("bar"), null, null, false);
int docid = disi.docID();
assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS);
assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.terms("foo").iterator(null);
assertTrue(te.seekExact(new BytesRef("bar"), true));
disi = _TestUtil.docs(random(), te, null, disi, false);
docid = disi.docID();
assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS);
assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.close();
r.close();
dir.close();
}
public void testDocsAndPositionsEnumStart() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
Document doc = new Document();
doc.add(newTextField("foo", "bar", Field.Store.NO));
writer.addDocument(doc);
DirectoryReader reader = writer.getReader();
AtomicReader r = getOnlySegmentReader(reader);
DocsAndPositionsEnum disi = r.termPositionsEnum(null, "foo", new BytesRef("bar"), false);
int docid = disi.docID();
assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS);
assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.terms("foo").iterator(null);
assertTrue(te.seekExact(new BytesRef("bar"), true));
disi = te.docsAndPositions(null, disi, false);
docid = disi.docID();
assertTrue(docid == -1 || docid == DocIdSetIterator.NO_MORE_DOCS);
assertTrue(disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.close();
r.close();
dir.close();
}
}
| true | true | public void testRandomPositions() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
int numDocs = atLeast(47);
int max = 1051;
int term = random().nextInt(max);
Integer[][] positionsInDoc = new Integer[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
ArrayList<Integer> positions = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
int num = atLeast(131);
for (int j = 0; j < num; j++) {
int nextInt = random().nextInt(max);
builder.append(nextInt).append(" ");
if (nextInt == term) {
positions.add(Integer.valueOf(j));
}
}
if (positions.size() == 0) {
builder.append(term);
positions.add(num);
}
doc.add(newField(fieldName, builder.toString(), customType));
positionsInDoc[i] = positions.toArray(new Integer[0]);
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.reader().maxDoc();
// initially advance or do next doc
if (random().nextBoolean()) {
initDoc = docsAndPosEnum.nextDoc();
} else {
initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc));
}
// now run through the scorer and check if all positions are there...
do {
int docID = docsAndPosEnum.docID();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID];
assertEquals(pos.length, docsAndPosEnum.freq());
// number of positions read should be random - don't read all of them
// allways
final int howMany = random().nextInt(20) == 0 ? pos.length
- random().nextInt(pos.length) : pos.length;
for (int j = 0; j < howMany; j++) {
assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: "
+ docID + " base: " + atomicReaderContext.docBase
+ " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: "
+ usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition());
}
if (random().nextInt(10) == 0) { // once is a while advance
docsAndPosEnum
.advance(docID + 1 + random().nextInt((maxDoc - docID)));
}
} while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.close();
dir.close();
}
| public void testRandomPositions() throws IOException {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
int numDocs = atLeast(47);
int max = 1051;
int term = random().nextInt(max);
Integer[][] positionsInDoc = new Integer[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.setOmitNorms(true);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
ArrayList<Integer> positions = new ArrayList<Integer>();
StringBuilder builder = new StringBuilder();
int num = atLeast(131);
for (int j = 0; j < num; j++) {
int nextInt = random().nextInt(max);
builder.append(nextInt).append(" ");
if (nextInt == term) {
positions.add(Integer.valueOf(j));
}
}
if (positions.size() == 0) {
builder.append(term);
positions.add(num);
}
doc.add(newField(fieldName, builder.toString(), customType));
positionsInDoc[i] = positions.toArray(new Integer[0]);
writer.addDocument(doc);
}
IndexReader reader = writer.getReader();
writer.close();
int num = atLeast(13);
for (int i = 0; i < num; i++) {
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.getTopReaderContext();
for (AtomicReaderContext atomicReaderContext : topReaderContext.leaves()) {
DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions(
atomicReaderContext.reader(), bytes, null);
assertNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.reader().maxDoc();
// initially advance or do next doc
if (random().nextBoolean()) {
initDoc = docsAndPosEnum.nextDoc();
} else {
initDoc = docsAndPosEnum.advance(random().nextInt(maxDoc));
}
// now run through the scorer and check if all positions are there...
do {
int docID = docsAndPosEnum.docID();
if (docID == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID];
assertEquals(pos.length, docsAndPosEnum.freq());
// number of positions read should be random - don't read all of them
// allways
final int howMany = random().nextInt(20) == 0 ? pos.length
- random().nextInt(pos.length) : pos.length;
for (int j = 0; j < howMany; j++) {
assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: "
+ docID + " base: " + atomicReaderContext.docBase
+ " positions: " + Arrays.toString(pos) /* TODO: + " usePayloads: "
+ usePayload*/, pos[j].intValue(), docsAndPosEnum.nextPosition());
}
if (random().nextInt(10) == 0) { // once is a while advance
if (docsAndPosEnum.advance(docID + 1 + random().nextInt((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
}
} while (docsAndPosEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.close();
dir.close();
}
|
diff --git a/src/java/com/threerings/opengl/model/config/StaticSetConfig.java b/src/java/com/threerings/opengl/model/config/StaticSetConfig.java
index c06c4e0e..2f0dbd8a 100644
--- a/src/java/com/threerings/opengl/model/config/StaticSetConfig.java
+++ b/src/java/com/threerings/opengl/model/config/StaticSetConfig.java
@@ -1,97 +1,97 @@
//
// $Id$
package com.threerings.opengl.model.config;
import java.util.TreeMap;
import java.util.TreeSet;
import com.samskivert.util.ComparableTuple;
import com.threerings.editor.Editable;
import com.threerings.expr.Scope;
import com.threerings.util.Shallow;
import com.threerings.opengl.mod.Model;
import com.threerings.opengl.mod.Static;
import com.threerings.opengl.model.config.ModelConfig.MeshSet;
import com.threerings.opengl.model.config.ModelConfig.VisibleMesh;
import com.threerings.opengl.model.tools.ModelDef;
import com.threerings.opengl.util.GlContext;
/**
* An original static set implementation.
*/
public class StaticSetConfig extends ModelConfig.Imported
{
/** The selected model. */
@Editable(editor="choice", depends={"source"})
public String model;
/** Maps top-level node names to meshes. */
@Shallow
public TreeMap<String, MeshSet> meshes;
/**
* Returns the options for the model field.
*/
public String[] getModelOptions ()
{
return (meshes == null) ?
new String[0] : meshes.keySet().toArray(new String[meshes.size()]);
}
@Override // documentation inherited
public Model.Implementation getModelImplementation (
GlContext ctx, Scope scope, Model.Implementation impl)
{
- MeshSet mset = (meshes == null) ? null : meshes.get(model);
+ MeshSet mset = (model == null || meshes == null) ? null : meshes.get(model);
if (mset == null) {
return null;
}
if (impl instanceof Static) {
((Static)impl).setConfig(mset, materialMappings);
} else {
impl = new Static(ctx, scope, mset, materialMappings);
}
return impl;
}
@Override // documentation inherited
protected VisibleMesh getParticleMesh ()
{
MeshSet mset = (meshes == null) ? null : meshes.get(model);
return (mset == null || mset.visible.length == 0) ? null : mset.visible[0];
}
@Override // documentation inherited
protected void updateFromSource (ModelDef def)
{
if (def == null) {
model = null;
meshes = null;
} else {
def.update(this);
}
}
@Override // documentation inherited
protected void getTextures (TreeSet<String> textures)
{
if (meshes != null) {
for (MeshSet set : meshes.values()) {
set.getTextures(textures);
}
}
}
@Override // documentation inherited
protected void getTextureTagPairs (TreeSet<ComparableTuple<String, String>> pairs)
{
if (meshes != null) {
for (MeshSet set : meshes.values()) {
set.getTextureTagPairs(pairs);
}
}
}
}
| true | true | public Model.Implementation getModelImplementation (
GlContext ctx, Scope scope, Model.Implementation impl)
{
MeshSet mset = (meshes == null) ? null : meshes.get(model);
if (mset == null) {
return null;
}
if (impl instanceof Static) {
((Static)impl).setConfig(mset, materialMappings);
} else {
impl = new Static(ctx, scope, mset, materialMappings);
}
return impl;
}
| public Model.Implementation getModelImplementation (
GlContext ctx, Scope scope, Model.Implementation impl)
{
MeshSet mset = (model == null || meshes == null) ? null : meshes.get(model);
if (mset == null) {
return null;
}
if (impl instanceof Static) {
((Static)impl).setConfig(mset, materialMappings);
} else {
impl = new Static(ctx, scope, mset, materialMappings);
}
return impl;
}
|
diff --git a/src/com/ModDamage/Events/Entity/ProjectileLaunch.java b/src/com/ModDamage/Events/Entity/ProjectileLaunch.java
index 755f83a..dbd9e58 100644
--- a/src/com/ModDamage/Events/Entity/ProjectileLaunch.java
+++ b/src/com/ModDamage/Events/Entity/ProjectileLaunch.java
@@ -1,45 +1,46 @@
package com.ModDamage.Events.Entity;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import com.ModDamage.MDEvent;
import com.ModDamage.ModDamage;
import com.ModDamage.EventInfo.EventData;
import com.ModDamage.EventInfo.EventInfo;
import com.ModDamage.EventInfo.SimpleEventInfo;
public class ProjectileLaunch extends MDEvent implements Listener
{
public ProjectileLaunch() { super(myInfo); }
static final EventInfo myInfo = new SimpleEventInfo(
Entity.class, "shooter", "entity",
Projectile.class, "projectile",
World.class, "world",
Boolean.class, "cancelled");
@EventHandler(priority=EventPriority.HIGHEST)
public void onProjectileLaunch(ProjectileLaunchEvent event)
{
if(!ModDamage.isEnabled) return;
Projectile projectile = (Projectile)event.getEntity();
LivingEntity shooter = projectile.getShooter();
EventData data = myInfo.makeData(
shooter,
projectile,
- projectile.getWorld());
+ projectile.getWorld(),
+ event.isCancelled());
runRoutines(data);
event.setCancelled(data.get(Boolean.class, data.start + data.objects.length - 1));
}
}
| true | true | public void onProjectileLaunch(ProjectileLaunchEvent event)
{
if(!ModDamage.isEnabled) return;
Projectile projectile = (Projectile)event.getEntity();
LivingEntity shooter = projectile.getShooter();
EventData data = myInfo.makeData(
shooter,
projectile,
projectile.getWorld());
runRoutines(data);
event.setCancelled(data.get(Boolean.class, data.start + data.objects.length - 1));
}
| public void onProjectileLaunch(ProjectileLaunchEvent event)
{
if(!ModDamage.isEnabled) return;
Projectile projectile = (Projectile)event.getEntity();
LivingEntity shooter = projectile.getShooter();
EventData data = myInfo.makeData(
shooter,
projectile,
projectile.getWorld(),
event.isCancelled());
runRoutines(data);
event.setCancelled(data.get(Boolean.class, data.start + data.objects.length - 1));
}
|
diff --git a/src/com/android/exchange/service/CalendarSyncAdapterService.java b/src/com/android/exchange/service/CalendarSyncAdapterService.java
index a6919c5d..876b1c4c 100644
--- a/src/com/android/exchange/service/CalendarSyncAdapterService.java
+++ b/src/com/android/exchange/service/CalendarSyncAdapterService.java
@@ -1,127 +1,131 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.exchange.service;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncResult;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CalendarContract.Events;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.AccountColumns;
import com.android.emailcommon.provider.EmailContent.MailboxColumns;
import com.android.emailcommon.provider.Mailbox;
import com.android.exchange.Eas;
import com.android.mail.utils.LogUtils;
public class CalendarSyncAdapterService extends AbstractSyncAdapterService {
private static final String TAG = "EASCalSyncAdaptSvc";
private static final String ACCOUNT_AND_TYPE_CALENDAR =
MailboxColumns.ACCOUNT_KEY + "=? AND " + MailboxColumns.TYPE + '=' + Mailbox.TYPE_CALENDAR;
private static final String DIRTY_IN_ACCOUNT =
Events.DIRTY + "=1 AND " + Events.ACCOUNT_NAME + "=?";
public CalendarSyncAdapterService() {
super();
}
@Override
protected AbstractThreadedSyncAdapter newSyncAdapter() {
return new SyncAdapterImpl(this);
}
private static class SyncAdapterImpl extends AbstractThreadedSyncAdapter {
public SyncAdapterImpl(Context context) {
super(context, true /* autoInitialize */);
}
@Override
public void onPerformSync(Account account, Bundle extras,
String authority, ContentProviderClient provider, SyncResult syncResult) {
CalendarSyncAdapterService.performSync(getContext(), account, extras);
}
}
/**
* Partial integration with system SyncManager; we tell our EAS ExchangeService to start a
* calendar sync when we get the signal from SyncManager.
* The missing piece at this point is integration with the push/ping mechanism in EAS; this will
* be put in place at a later time.
*/
private static void performSync(Context context, Account account, Bundle extras) {
- ContentResolver cr = context.getContentResolver();
- boolean logging = Eas.USER_LOG;
+ final ContentResolver cr = context.getContentResolver();
+ final boolean logging = Eas.USER_LOG;
if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD)) {
- Cursor c = cr.query(Events.CONTENT_URI,
+ final Cursor c = cr.query(Events.CONTENT_URI,
new String[] {Events._ID}, DIRTY_IN_ACCOUNT, new String[] {account.name}, null);
+ if (c == null) {
+ LogUtils.e(TAG, "Null changes cursor in CalendarSyncAdapterService");
+ return;
+ }
try {
if (!c.moveToFirst()) {
if (logging) {
LogUtils.d(TAG, "No changes for " + account.name);
}
return;
}
} finally {
c.close();
}
}
// Find the (EmailProvider) account associated with this email address
final Cursor accountCursor =
cr.query(com.android.emailcommon.provider.Account.CONTENT_URI,
EmailContent.ID_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?",
new String[] {account.name}, null);
if (accountCursor == null) {
LogUtils.e(TAG, "Null account cursor in CalendarSyncAdapterService");
return;
}
try {
if (accountCursor.moveToFirst()) {
final long accountId = accountCursor.getLong(0);
// Now, find the calendar mailbox associated with the account
final Cursor mailboxCursor = cr.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION,
ACCOUNT_AND_TYPE_CALENDAR, new String[] {Long.toString(accountId)}, null);
try {
if (mailboxCursor.moveToFirst()) {
if (logging) {
LogUtils.d(TAG, "Upload sync requested for " + account.name);
}
// TODO: Currently just bouncing this to Email sync; eventually streamline.
final long mailboxId = mailboxCursor.getLong(Mailbox.ID_PROJECTION_COLUMN);
// TODO: Should we be using the existing extras and just adding our bits?
final Bundle mailboxExtras = new Bundle(4);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
mailboxExtras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId);
ContentResolver.requestSync(account, EmailContent.AUTHORITY, mailboxExtras);
}
} finally {
mailboxCursor.close();
}
}
} finally {
accountCursor.close();
}
}
}
| false | true | private static void performSync(Context context, Account account, Bundle extras) {
ContentResolver cr = context.getContentResolver();
boolean logging = Eas.USER_LOG;
if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD)) {
Cursor c = cr.query(Events.CONTENT_URI,
new String[] {Events._ID}, DIRTY_IN_ACCOUNT, new String[] {account.name}, null);
try {
if (!c.moveToFirst()) {
if (logging) {
LogUtils.d(TAG, "No changes for " + account.name);
}
return;
}
} finally {
c.close();
}
}
// Find the (EmailProvider) account associated with this email address
final Cursor accountCursor =
cr.query(com.android.emailcommon.provider.Account.CONTENT_URI,
EmailContent.ID_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?",
new String[] {account.name}, null);
if (accountCursor == null) {
LogUtils.e(TAG, "Null account cursor in CalendarSyncAdapterService");
return;
}
try {
if (accountCursor.moveToFirst()) {
final long accountId = accountCursor.getLong(0);
// Now, find the calendar mailbox associated with the account
final Cursor mailboxCursor = cr.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION,
ACCOUNT_AND_TYPE_CALENDAR, new String[] {Long.toString(accountId)}, null);
try {
if (mailboxCursor.moveToFirst()) {
if (logging) {
LogUtils.d(TAG, "Upload sync requested for " + account.name);
}
// TODO: Currently just bouncing this to Email sync; eventually streamline.
final long mailboxId = mailboxCursor.getLong(Mailbox.ID_PROJECTION_COLUMN);
// TODO: Should we be using the existing extras and just adding our bits?
final Bundle mailboxExtras = new Bundle(4);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
mailboxExtras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId);
ContentResolver.requestSync(account, EmailContent.AUTHORITY, mailboxExtras);
}
} finally {
mailboxCursor.close();
}
}
} finally {
accountCursor.close();
}
}
| private static void performSync(Context context, Account account, Bundle extras) {
final ContentResolver cr = context.getContentResolver();
final boolean logging = Eas.USER_LOG;
if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD)) {
final Cursor c = cr.query(Events.CONTENT_URI,
new String[] {Events._ID}, DIRTY_IN_ACCOUNT, new String[] {account.name}, null);
if (c == null) {
LogUtils.e(TAG, "Null changes cursor in CalendarSyncAdapterService");
return;
}
try {
if (!c.moveToFirst()) {
if (logging) {
LogUtils.d(TAG, "No changes for " + account.name);
}
return;
}
} finally {
c.close();
}
}
// Find the (EmailProvider) account associated with this email address
final Cursor accountCursor =
cr.query(com.android.emailcommon.provider.Account.CONTENT_URI,
EmailContent.ID_PROJECTION, AccountColumns.EMAIL_ADDRESS + "=?",
new String[] {account.name}, null);
if (accountCursor == null) {
LogUtils.e(TAG, "Null account cursor in CalendarSyncAdapterService");
return;
}
try {
if (accountCursor.moveToFirst()) {
final long accountId = accountCursor.getLong(0);
// Now, find the calendar mailbox associated with the account
final Cursor mailboxCursor = cr.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION,
ACCOUNT_AND_TYPE_CALENDAR, new String[] {Long.toString(accountId)}, null);
try {
if (mailboxCursor.moveToFirst()) {
if (logging) {
LogUtils.d(TAG, "Upload sync requested for " + account.name);
}
// TODO: Currently just bouncing this to Email sync; eventually streamline.
final long mailboxId = mailboxCursor.getLong(Mailbox.ID_PROJECTION_COLUMN);
// TODO: Should we be using the existing extras and just adding our bits?
final Bundle mailboxExtras = new Bundle(4);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, true);
mailboxExtras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
mailboxExtras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId);
ContentResolver.requestSync(account, EmailContent.AUTHORITY, mailboxExtras);
}
} finally {
mailboxCursor.close();
}
}
} finally {
accountCursor.close();
}
}
|
diff --git a/srcj/com/sun/electric/tool/placement/PlacementFrame.java b/srcj/com/sun/electric/tool/placement/PlacementFrame.java
index 7db0cb625..262fa2861 100644
--- a/srcj/com/sun/electric/tool/placement/PlacementFrame.java
+++ b/srcj/com/sun/electric/tool/placement/PlacementFrame.java
@@ -1,1000 +1,1003 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: PlacementFrame.java
*
* Copyright (c) 2009 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.placement;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.sun.electric.database.ImmutableArcInst;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.ERectangle;
import com.sun.electric.database.geometry.Orientation;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortCharacteristic;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.Pref;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.database.variable.Variable.Key;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.placement.forceDirected1.PlacementForceDirectedTeam5;
import com.sun.electric.tool.placement.forceDirected2.PlacementForceDirectedStaged;
import com.sun.electric.tool.placement.genetic1.g1.GeneticPlacement;
import com.sun.electric.tool.placement.genetic2.PlacementGenetic;
import com.sun.electric.tool.placement.metrics.AbstractMetric;
import com.sun.electric.tool.placement.metrics.boundingbox.BBMetric;
import com.sun.electric.tool.placement.metrics.mst.MSTMetric;
import com.sun.electric.tool.placement.simulatedAnnealing1.SimulatedAnnealing;
import com.sun.electric.tool.placement.simulatedAnnealing2.PlacementSimulatedAnnealing;
import com.sun.electric.tool.util.CollectionFactory;
/**
* Class to define a framework for Placement algorithms. To make Placement
* algorithms easier to write, all Placement algorithms must extend this class.
* The Placement algorithm then defines two methods:
*
* public String getAlgorithmName() returns the name of the Placement algorithm
*
* void runPlacement(List<PlacementNode> nodesToPlace, List<PlacementNetwork>
* allNetworks, String cellName) runs the placement on the "nodesToPlace",
* calling each PlacementNode's "setPlacement()" and "setOrientation()" methods
* to establish the proper placement.
*
* To avoid the complexities of the Electric database, four shadow-classes are
* defined that describe the necessary information that Placement algorithms
* want:
*
* PlacementNode is an actual node (primitive or cell instance) that is to be
* placed. PlacementPort is the connection site on the PlacementNode. Each
* PlacementNode has a list of zero or more PlacementPort objects, and each
* PlacementPort points to its "parent" PlacementNode. PlacementNetwork
* determines which PlacementPort objects will connect together. Each
* PlacementNetwork has a list of two or more PlacementPort objects that it
* connects, and each PlacementPort has a PlacementNetwork in which it resides.
* PlacementExport describes exports in the cell. Placement algorithms do not
* usually need this information: it exists as a way to communicate the
* information internally.
*/
public abstract class PlacementFrame {
/**
* Static list of all Placement algorithms. When you create a new algorithm,
* add it to the following list.
*/
private static PlacementFrame[] placementAlgorithms = { new SimulatedAnnealing(), // team
// 2
new PlacementSimulatedAnnealing(), // team 6
new GeneticPlacement(), // team 3
new PlacementGenetic(), // team 4
new PlacementForceDirectedTeam5(), // team 5
new PlacementForceDirectedStaged(), // team 7
new PlacementMinCut(), new PlacementSimple(), new PlacementRandom() };
public static boolean USE_GUIPARAMETER = true;
protected int numOfThreads;
protected int runtime;
private boolean specialDebugFlag = false;
/**
* Method to return a list of all Placement algorithms.
*
* @return a list of all Placement algorithms.
*/
public static PlacementFrame[] getPlacementAlgorithms() {
return placementAlgorithms;
}
/**
* Method to do Placement (overridden by actual Placement algorithms).
*
* @param nodesToPlace
* a list of all nodes that are to be placed.
* @param allNetworks
* a list of all networks that connect the nodes.
* @param cellName
* the name of the cell being placed.
*/
protected void runPlacement(List<PlacementNode> nodesToPlace, List<PlacementNetwork> allNetworks, String cellName) {
}
/**
* Method to return the name of the placement algorithm (overridden by
* actual Placement algorithms).
*
* @return the name of the placement algorithm.
*/
public String getAlgorithmName() {
return "?";
}
/**
* Method to return a list of parameters for this placement algorithm.
*
* @return a list of parameters for this placement algorithm.
*/
public List<PlacementParameter> getParameters() {
return null;
}
public void setParamterValues(int threads, int runtime) {
this.numOfThreads = threads;
this.runtime = runtime;
}
/**
* Class to define a parameter for a placement algorithm.
*/
public class PlacementParameter {
public static final int TYPEINTEGER = 1;
public static final int TYPESTRING = 2;
public static final int TYPEDOUBLE = 3;
private String title;
private int type;
private Pref pref;
private int tempInt;
private String tempString;
private double tempDouble;
private boolean tempValueSet;
public PlacementParameter(String name, String title, int factory) {
this.title = title;
type = TYPEINTEGER;
tempValueSet = false;
pref = Pref.makeIntPref(getAlgorithmName() + "-" + name, Placement.getPlacementTool().prefs, factory);
}
public PlacementParameter(String name, String title, String factory) {
this.title = title;
type = TYPESTRING;
tempValueSet = false;
pref = Pref.makeStringPref(getAlgorithmName() + "-" + name, Placement.getPlacementTool().prefs, factory);
}
public PlacementParameter(String name, String title, double factory) {
this.title = title;
type = TYPEDOUBLE;
tempValueSet = false;
pref = Pref.makeDoublePref(getAlgorithmName() + "-" + name, Placement.getPlacementTool().prefs, factory);
}
public String getName() {
return title;
}
public int getType() {
return type;
}
public int getIntValue() {
return pref.getInt();
}
public String getStringValue() {
return pref.getString();
}
public double getDoubleValue() {
return pref.getDouble();
}
public void resetToFactory() {
pref.factoryReset();
}
/******************** TEMP VALUES DURING THE PREFERENCES DIALOG ********************/
public int getTempIntValue() {
return tempInt;
}
public String getTempStringValue() {
return tempString;
}
public double getTempDoubleValue() {
return tempDouble;
}
public void setTempIntValue(int i) {
tempInt = i;
tempValueSet = true;
}
public void setTempStringValue(String s) {
tempString = s;
tempValueSet = true;
}
public void setTempDoubleValue(double d) {
tempDouble = d;
tempValueSet = true;
}
public boolean hasTempValue() {
return tempValueSet;
}
public void clearTempValue() {
tempValueSet = false;
}
public void makeTempSettingReal() {
if (tempValueSet) {
switch (type) {
case TYPEINTEGER:
pref.setInt(tempInt);
break;
case TYPESTRING:
pref.setString(tempString);
break;
case TYPEDOUBLE:
pref.setDouble(tempDouble);
break;
}
}
}
}
/**
* Class to define a node that is being placed. This is a shadow class for
* the internal Electric object "NodeInst". There are minor differences
* between PlacementNode and NodeInst, for example, PlacementNode is
* presumed to be centered in the middle, with port offsets based on that
* center, whereas the NodeInst has a cell-center that may not be in the
* middle.
*/
public static class PlacementNode {
private NodeProto original;
private String nodeName;
private int techBits;
private double width, height;
private List<PlacementPort> ports;
private double xPos, yPos;
private Orientation orient;
private Map<Key, Object> addedVariables;
private Object userObject;
private boolean terminal;
public Object getUserObject() {
return userObject;
}
public void setUserObject(Object obj) {
userObject = obj;
}
/**
* Method to create a PlacementNode object.
*
* @param type
* the original Electric type of this PlacementNode.
* @param name
* the name to give the node once placed (can be null).
* @param tBits
* the technology-specific bits of this PlacementNode
* (typically 0 except for specialized Schematics
* components).
* @param wid
* the width of this PlacementNode.
* @param hei
* the height of this PlacementNode.
* @param pps
* a list of PlacementPort on the PlacementNode, indicating
* connection locations.
* @param terminal
*/
public PlacementNode(NodeProto type, String name, int tBits, double wid, double hei, List<PlacementPort> pps,
boolean terminal) {
original = type;
nodeName = name;
techBits = tBits;
width = wid;
height = hei;
ports = pps;
this.terminal = terminal;
}
/**
* Method to add variables to this PlacementNode. Variables are extra
* name/value pairs, for example a transistor width and length.
*
* @param name
* the Key of the variable to add.
* @param value
* the value of the variable to add.
*/
public void addVariable(Key name, Object value) {
if (addedVariables == null)
addedVariables = new HashMap<Key, Object>();
addedVariables.put(name, value);
}
/**
* Method to return a list of PlacementPorts on this PlacementNode.
*
* @return a list of PlacementPorts on this PlacementNode.
*/
public List<PlacementPort> getPorts() {
return ports;
}
/**
* Method to return the width of this PlacementNode.
*
* @return the width of this PlacementNode.
*/
public double getWidth() {
return width;
}
/**
* Method to return the height of this PlacementNode.
*
* @return the height of this PlacementNode.
*/
public double getHeight() {
return height;
}
/**
* Method to set the location of this PlacementNode. The Placement
* algorithm must call this method to set the final location of the
* PlacementNode.
*
* @param x
* the X-coordinate of the center of this PlacementNode.
* @param y
* the Y-coordinate of the center of this PlacementNode.
*/
public void setPlacement(double x, double y) {
xPos = x;
yPos = y;
}
/**
* Method to set the orientation (rotation and mirroring) of this
* PlacementNode. The Placement algorithm may call this method to set
* the final orientation of the PlacementNode.
*
* @param o
* the Orientation of this PlacementNode.
*/
public void setOrientation(Orientation o) {
orient = o;
for (PlacementPort plPort : ports)
plPort.computeRotatedOffset();
}
/**
* Method to return the X-coordinate of the placed location of this
* PlacementNode. This is the location that the Placement algorithm has
* established for this PlacementNode.
*
* @return the X-coordinate of the placed location of this
* PlacementNode.
*/
public double getPlacementX() {
return xPos;
}
/**
* Method to return the Y-coordinate of the placed location of this
* PlacementNode. This is the location that the Placement algorithm has
* established for this PlacementNode.
*
* @return the Y-coordinate of the placed location of this
* PlacementNode.
*/
public double getPlacementY() {
return yPos;
}
/**
* Method to return the Orientation of this PlacementNode. This is the
* Orientation that the Placement algorithm has established for this
* PlacementNode.
*
* @return the Orientation of this PlacementNode.
*/
public Orientation getPlacementOrientation() {
return orient;
}
/**
* Method to return the NodeProto of this PlacementNode.
*
* @return the NodeProto of this PlacementNode.
*/
public NodeProto getType() {
return original;
}
/**
* Method to return the technology-specific information of this
* PlacementNode.
*
* @return the technology-specific information of this PlacementNode
* (typically 0 except for specialized Schematics components).
*/
public int getTechBits() {
return techBits;
}
public String toString() {
String name = original.describe(false);
if (nodeName != null)
name += "[" + nodeName + "]";
if (techBits != 0)
name += "(" + techBits + ")";
return name;
}
/**
* @param terminal
* the terminal to set
*/
public void setTerminal(boolean terminal) {
this.terminal = terminal;
}
/**
* @return the terminal
*/
public boolean isTerminal() {
return terminal;
}
}
/**
* Class to define ports on PlacementNode objects. This is a shadow class
* for the internal Electric object "PortInst".
*/
public static class PlacementPort {
private double offX, offY;
private double rotatedOffX, rotatedOffY;
private PlacementNode plNode;
private PlacementNetwork plNet;
private PortProto proto;
/**
* Constructor to create a PlacementPort.
*
* @param x
* the X offset of this PlacementPort from the center of its
* PlacementNode.
* @param y
* the Y offset of this PlacementPort from the center of its
* PlacementNode.
* @param pp
* the Electric PortProto of this PlacementPort.
*/
public PlacementPort(double x, double y, PortProto pp) {
offX = x;
offY = y;
proto = pp;
}
/**
* Method to set the "parent" PlacementNode on which this PlacementPort
* resides.
*
* @param pn
* the PlacementNode on which this PlacementPort resides.
*/
public void setPlacementNode(PlacementNode pn) {
plNode = pn;
}
/**
* Method to return the PlacementNode on which this PlacementPort
* resides.
*
* @return the PlacementNode on which this PlacementPort resides.
*/
public PlacementNode getPlacementNode() {
return plNode;
}
/**
* Method to return the PlacementNetwork on which this PlacementPort
* resides.
*
* @param pn
* the PlacementNetwork on which this PlacementPort resides.
*/
public void setPlacementNetwork(PlacementNetwork pn) {
plNet = pn;
}
/**
* Method to return the PlacementNetwork on which this PlacementPort
* resides.
*
* @return the PlacementNetwork on which this PlacementPort resides. If
* this PlacementPort does not connect to any other
* PlacementPort, the PlacementNetwork may be null.
*/
public PlacementNetwork getPlacementNetwork() {
return plNet;
}
/**
* Method to return the Electric PortProto that this PlacementPort uses.
*
* @return the Electric PortProto that this PlacementPort uses.
*/
PortProto getPortProto() {
return proto;
}
/**
* Method to return the offset of this PlacementPort's X coordinate from
* the center of its PlacementNode. The offset is valid when no
* Orientation has been applied.
*
* @return the offset of this PlacementPort's X coordinate from the
* center of its PlacementNode.
*/
public double getOffX() {
return offX;
}
/**
* Method to return the offset of this PlacementPort's Y coordinate from
* the center of its PlacementNode. The offset is valid when no
* Orientation has been applied.
*
* @return the offset of this PlacementPort's Y coordinate from the
* center of its PlacementNode.
*/
public double getOffY() {
return offY;
}
/**
* Method to return the offset of this PlacementPort's X coordinate from
* the center of its PlacementNode. The coordinate assumes that the
* PlacementNode has been rotated by its Orientation.
*
* @return the offset of this PlacementPort's X coordinate from the
* center of its PlacementNode.
*/
public double getRotatedOffX() {
return rotatedOffX;
}
/**
* Method to return the offset of this PlacementPort's Y coordinate from
* the center of its PlacementNode. The coordinate assumes that the
* PlacementNode has been rotated by its Orientation.
*
* @return the offset of this PlacementPort's Y coordinate from the
* center of its PlacementNode.
*/
public double getRotatedOffY() {
return rotatedOffY;
}
/**
* Internal method to compute the rotated offset of this PlacementPort
* assuming that the Orientation of its PlacementNode has changed. TODO:
* why is this public? it should not be accessed!
*/
public void computeRotatedOffset() {
Orientation orient = plNode.getPlacementOrientation();
if (orient == Orientation.IDENT) {
rotatedOffX = offX;
rotatedOffY = offY;
return;
}
AffineTransform trans = orient.pureRotate();
Point2D offset = new Point2D.Double(offX, offY);
trans.transform(offset, offset);
rotatedOffX = offset.getX();
rotatedOffY = offset.getY();
}
public String toString() {
return proto.getName();
}
}
/**
* Class to define networks of PlacementPort objects. This is a shadow class
* for the internal Electric object "Network", but it is simplified for
* Placement.
*/
public static class PlacementNetwork {
private List<PlacementPort> portsOnNet;
/**
* Constructor to create this PlacementNetwork with a list of
* PlacementPort objects that it connects.
*
* @param ports
* a list of PlacementPort objects that it connects.
*/
public PlacementNetwork(List<PlacementPort> ports) {
portsOnNet = ports;
}
/**
* Method to return the list of PlacementPort objects on this
* PlacementNetwork.
*
* @return a list of PlacementPort objects on this PlacementNetwork.
*/
public List<PlacementPort> getPortsOnNet() {
return portsOnNet;
}
}
/**
* Class to define an Export that will be placed in the circuit.
*/
public static class PlacementExport {
private PlacementPort portToExport;
private String exportName;
private PortCharacteristic characteristic;
/**
* Constructor to create a PlacementExport with the information about an
* Export to be created.
*
* @param port
* the PlacementPort that is being exported.
* @param name
* the name to give the Export.
* @param chr
* the PortCharacteristic (input, output, etc.) to give the
* Export.
*/
public PlacementExport(PlacementPort port, String name, PortCharacteristic chr) {
portToExport = port;
exportName = name;
characteristic = chr;
}
PlacementPort getPort() {
return portToExport;
}
String getName() {
return exportName;
}
PortCharacteristic getCharacteristic() {
return characteristic;
}
}
/**
* Entry point to do Placement of a Cell and create a new, placed Cell.
* Gathers the requirements for Placement into a collection of shadow
* objects (PlacementNode, PlacementPort, PlacementNetwork, and
* PlacementExport). Then invokes the alternate version of "doPlacement()"
* that works from shadow objedts.
*
* @param cell
* the Cell to place. Objects in that Cell will be reorganized in
* and placed in a new Cell.
* @return the new Cell with the placement results.
*/
public Cell doPlacement(Cell cell, Placement.PlacementPreferences prefs) {
// get network information for the Cell
Netlist netList = cell.getNetlist();
if (netList == null) {
System.out
.println("Sorry, a deadlock aborted routing (network information unavailable). Please try again");
return null;
}
// convert nodes in the Cell into PlacementNode objects
NodeProto iconToPlace = null;
List<PlacementNode> nodesToPlace = CollectionFactory.createArrayList();
Map<NodeInst, Map<PortProto, PlacementPort>> convertedNodes = CollectionFactory.createHashMap();
List<PlacementExport> exportsToPlace = CollectionFactory.createArrayList();
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext();) {
NodeInst ni = it.next();
if (ni.isIconOfParent()) {
iconToPlace = ni.getProto();
continue;
}
boolean validNode = ni.isCellInstance();
if (!validNode) {
if (ni.getProto().getTechnology() != Generic.tech()) {
PrimitiveNode.Function fun = ni.getFunction();
if (fun != PrimitiveNode.Function.CONNECT && fun != PrimitiveNode.Function.CONTACT && !fun.isPin())
validNode = true;
}
if (ni.hasExports())
validNode = true;
}
if (validNode) {
// make a list of PlacementPorts on this NodeInst
NodeProto np = ni.getProto();
List<PlacementPort> pl = new ArrayList<PlacementPort>();
Map<PortProto, PlacementPort> placedPorts = new HashMap<PortProto, PlacementPort>();
if (ni.isCellInstance()) {
for (Iterator<Export> eIt = ((Cell) np).getExports(); eIt.hasNext();) {
Export e = eIt.next();
Poly poly = e.getPoly();
PlacementPort plPort = new PlacementPort(poly.getCenterX(), poly.getCenterY(), e);
pl.add(plPort);
placedPorts.put(e, plPort);
}
} else {
NodeInst niDummy = NodeInst.makeDummyInstance(np);
for (Iterator<PortInst> pIt = niDummy.getPortInsts(); pIt.hasNext();) {
PortInst pi = pIt.next();
Poly poly = pi.getPoly();
double offX = poly.getCenterX() - niDummy.getTrueCenterX();
double offY = poly.getCenterY() - niDummy.getTrueCenterY();
PlacementPort plPort = new PlacementPort(offX, offY, pi.getPortProto());
pl.add(plPort);
placedPorts.put(pi.getPortProto(), plPort);
}
}
// add to the list of PlacementExports
for (Iterator<Export> eIt = ni.getExports(); eIt.hasNext();) {
Export e = eIt.next();
PlacementPort plPort = placedPorts.get(e.getOriginalPort().getPortProto());
PlacementExport plExport = new PlacementExport(plPort, e.getName(), e.getCharacteristic());
exportsToPlace.add(plExport);
}
// make the PlacementNode for this NodeInst
String name = ni.getName();
if (ni.getNameKey().isTempname())
name = null;
PlacementNode plNode = new PlacementNode(np, name, ni.getTechSpecific(), np.getDefWidth(), np
.getDefHeight(), pl, ni.isLocked());
nodesToPlace.add(plNode);
for (PlacementPort plPort : pl)
plPort.setPlacementNode(plNode);
plNode.setOrientation(Orientation.IDENT);
convertedNodes.put(ni, placedPorts);
}
}
// gather connectivity information in a list of PlacementNetwork objects
Map<Network, PortInst[]> portInstsByNetwork = null;
if (cell.getView() != View.SCHEMATIC)
portInstsByNetwork = netList.getPortInstsByNetwork();
List<PlacementNetwork> allNetworks = new ArrayList<PlacementNetwork>();
for (Iterator<Network> it = netList.getNetworks(); it.hasNext();) {
Network net = it.next();
List<PlacementPort> portsOnNet = new ArrayList<PlacementPort>();
PortInst[] portInsts = null;
if (portInstsByNetwork != null)
portInsts = portInstsByNetwork.get(net);
else {
List<PortInst> portList = new ArrayList<PortInst>();
for (Iterator<PortInst> pIt = net.getPorts(); pIt.hasNext();)
portList.add(pIt.next());
portInsts = portList.toArray(new PortInst[] {});
}
for (int i = 0; i < portInsts.length; i++) {
PortInst pi = portInsts[i];
NodeInst ni = pi.getNodeInst();
PortProto pp = pi.getPortProto();
Map<PortProto, PlacementPort> convertedPorts = convertedNodes.get(ni);
if (convertedPorts == null)
continue;
PlacementPort plPort = convertedPorts.get(pp);
if (plPort != null)
portsOnNet.add(plPort);
}
if (portsOnNet.size() > 1) {
PlacementNetwork plNet = new PlacementNetwork(portsOnNet);
for (PlacementPort plPort : portsOnNet)
plPort.setPlacementNetwork(plNet);
allNetworks.add(plNet);
}
}
// do the placement from the shadow objects
Cell newCell = doPlacement(cell.getLibrary(), cell.noLibDescribe(), nodesToPlace, allNetworks, exportsToPlace,
iconToPlace);
return newCell;
}
/**
* Entry point for other tools that wish to describe a network to be placed.
* Creates a cell with the placed network.
*
* @param lib
* the Library in which to create the placed Cell.
* @param cellName
* the name of the Cell to create.
* @param nodesToPlace
* a List of PlacementNodes to place in the Cell.
* @param allNetworks
* a List of PlacementNetworks to connect in the Cell.
* @param exportsToPlace
* a List of PlacementExports to create in the Cell.
* @param iconToPlace
* non-null to place an instance of itself (the icon) in the
* Cell.
* @return the newly created Cell.
*/
public Cell doPlacement(Library lib, String cellName, List<PlacementNode> nodesToPlace,
List<PlacementNetwork> allNetworks, List<PlacementExport> exportsToPlace, NodeProto iconToPlace) {
long startTime = System.currentTimeMillis();
System.out.println("Running placement on cell '" + cellName + "' using the '" + getAlgorithmName()
+ "' algorithm");
// do the real work of placement
runPlacement(nodesToPlace, allNetworks, cellName);
if (Job.getDebug() && specialDebugFlag) {
AbstractMetric bmetric = new BBMetric(nodesToPlace, allNetworks);
System.out.println("### BBMetric: " + bmetric.toString());
AbstractMetric mstMetric = new MSTMetric(nodesToPlace, allNetworks);
System.out.println("### MSTMetric: " + mstMetric.toString());
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try {
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("/home/Felix Schmidt/work/" + this.getAlgorithmName() + "-" + cellName + "-"
+ this.runtime + "-" + this.numOfThreads + ".txt");
// Connect print stream to the output stream
p = new PrintStream(out);
p.println(bmetric.toString());
p.println(mstMetric.toString());
p.close();
} catch (Exception e) {
System.err.println("Error writing to file");
}
}
// create a new cell for the placement results
Cell newCell = Cell.makeInstance(lib, cellName); // newCellName
// place the nodes in the new cell
Map<PlacementNode, NodeInst> placedNodes = new HashMap<PlacementNode, NodeInst>();
for (PlacementNode plNode : nodesToPlace) {
double xPos = plNode.getPlacementX();
double yPos = plNode.getPlacementY();
Orientation orient = plNode.getPlacementOrientation();
NodeProto np = plNode.original;
if (np instanceof Cell) {
Cell placementCell = (Cell) np;
Rectangle2D bounds = placementCell.getBounds();
Point2D centerOffset = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
orient.pureRotate().transform(centerOffset, centerOffset);
xPos -= centerOffset.getX();
yPos -= centerOffset.getY();
}
NodeInst ni = NodeInst.makeInstance(np, new Point2D.Double(xPos, yPos), np.getDefWidth(),
np.getDefHeight(), newCell, orient, plNode.nodeName, plNode.techBits);
if (ni == null)
System.out.println("Placement failed to create node");
- else
+ else {
+ if(plNode.isTerminal())
+ ni.setLocked();
placedNodes.put(plNode, ni);
+ }
if (plNode.addedVariables != null) {
for (Key key : plNode.addedVariables.keySet()) {
Object value = plNode.addedVariables.get(key);
Variable var = ni.newDisplayVar(key, value);
if (key == Schematics.SCHEM_RESISTANCE) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(0, 0.5).withDispPart(
TextDescriptor.DispPos.VALUE));
} else if (key == Schematics.ATTR_WIDTH) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(0.5, -1).withRelSize(1).withDispPart(
TextDescriptor.DispPos.VALUE));
} else if (key == Schematics.ATTR_LENGTH) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(-0.5, -1).withRelSize(0.5)
.withDispPart(TextDescriptor.DispPos.VALUE));
} else {
ni.setTextDescriptor(key, var.getTextDescriptor().withDispPart(TextDescriptor.DispPos.VALUE));
}
}
}
}
// place an icon if requested
if (iconToPlace != null) {
ERectangle bounds = newCell.getBounds();
EPoint center = new EPoint(bounds.getMaxX() + iconToPlace.getDefWidth(), bounds.getMaxY()
+ iconToPlace.getDefHeight());
NodeInst.makeInstance(iconToPlace, center, iconToPlace.getDefWidth(), iconToPlace.getDefHeight(), newCell);
}
// place exports in the new cell
for (PlacementExport plExport : exportsToPlace) {
PlacementPort plPort = plExport.getPort();
String exportName = plExport.getName();
PlacementNode plNode = plPort.getPlacementNode();
NodeInst newNI = placedNodes.get(plNode);
if (newNI == null)
continue;
PortInst portToExport = newNI.findPortInstFromProto(plPort.getPortProto());
Export.newInstance(newCell, portToExport, exportName, plExport.getCharacteristic());
}
ImmutableArcInst a = Generic.tech().unrouted_arc.getDefaultInst(newCell.getEditingPreferences());
long gridExtend = a.getGridExtendOverMin();
for (PlacementNetwork plNet : allNetworks) {
PlacementPort lastPp = null;
PortInst lastPi = null;
EPoint lastPt = null;
for (PlacementPort plPort : plNet.getPortsOnNet()) {
PlacementNode plNode = plPort.getPlacementNode();
NodeInst newNi = placedNodes.get(plNode);
if (newNi != null) {
PlacementPort thisPp = plPort;
PortInst thisPi = newNi.findPortInstFromProto(thisPp.getPortProto());
EPoint thisPt = new EPoint(plNode.getPlacementX() + plPort.getRotatedOffX(), plNode.getPlacementY()
+ plPort.getRotatedOffY());
if (lastPp != null) {
// connect them
ArcInst.newInstance(newCell, Generic.tech().unrouted_arc, null, null, lastPi, thisPi, lastPt,
thisPt, gridExtend, ArcInst.DEFAULTANGLE, a.flags);
}
lastPp = thisPp;
lastPi = thisPi;
lastPt = thisPt;
}
}
}
long endTime = System.currentTimeMillis();
System.out.println("\t(took " + TextUtils.getElapsedTime(endTime - startTime) + ")");
return newCell;
}
}
| false | true | public Cell doPlacement(Library lib, String cellName, List<PlacementNode> nodesToPlace,
List<PlacementNetwork> allNetworks, List<PlacementExport> exportsToPlace, NodeProto iconToPlace) {
long startTime = System.currentTimeMillis();
System.out.println("Running placement on cell '" + cellName + "' using the '" + getAlgorithmName()
+ "' algorithm");
// do the real work of placement
runPlacement(nodesToPlace, allNetworks, cellName);
if (Job.getDebug() && specialDebugFlag) {
AbstractMetric bmetric = new BBMetric(nodesToPlace, allNetworks);
System.out.println("### BBMetric: " + bmetric.toString());
AbstractMetric mstMetric = new MSTMetric(nodesToPlace, allNetworks);
System.out.println("### MSTMetric: " + mstMetric.toString());
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try {
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("/home/Felix Schmidt/work/" + this.getAlgorithmName() + "-" + cellName + "-"
+ this.runtime + "-" + this.numOfThreads + ".txt");
// Connect print stream to the output stream
p = new PrintStream(out);
p.println(bmetric.toString());
p.println(mstMetric.toString());
p.close();
} catch (Exception e) {
System.err.println("Error writing to file");
}
}
// create a new cell for the placement results
Cell newCell = Cell.makeInstance(lib, cellName); // newCellName
// place the nodes in the new cell
Map<PlacementNode, NodeInst> placedNodes = new HashMap<PlacementNode, NodeInst>();
for (PlacementNode plNode : nodesToPlace) {
double xPos = plNode.getPlacementX();
double yPos = plNode.getPlacementY();
Orientation orient = plNode.getPlacementOrientation();
NodeProto np = plNode.original;
if (np instanceof Cell) {
Cell placementCell = (Cell) np;
Rectangle2D bounds = placementCell.getBounds();
Point2D centerOffset = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
orient.pureRotate().transform(centerOffset, centerOffset);
xPos -= centerOffset.getX();
yPos -= centerOffset.getY();
}
NodeInst ni = NodeInst.makeInstance(np, new Point2D.Double(xPos, yPos), np.getDefWidth(),
np.getDefHeight(), newCell, orient, plNode.nodeName, plNode.techBits);
if (ni == null)
System.out.println("Placement failed to create node");
else
placedNodes.put(plNode, ni);
if (plNode.addedVariables != null) {
for (Key key : plNode.addedVariables.keySet()) {
Object value = plNode.addedVariables.get(key);
Variable var = ni.newDisplayVar(key, value);
if (key == Schematics.SCHEM_RESISTANCE) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(0, 0.5).withDispPart(
TextDescriptor.DispPos.VALUE));
} else if (key == Schematics.ATTR_WIDTH) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(0.5, -1).withRelSize(1).withDispPart(
TextDescriptor.DispPos.VALUE));
} else if (key == Schematics.ATTR_LENGTH) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(-0.5, -1).withRelSize(0.5)
.withDispPart(TextDescriptor.DispPos.VALUE));
} else {
ni.setTextDescriptor(key, var.getTextDescriptor().withDispPart(TextDescriptor.DispPos.VALUE));
}
}
}
}
// place an icon if requested
if (iconToPlace != null) {
ERectangle bounds = newCell.getBounds();
EPoint center = new EPoint(bounds.getMaxX() + iconToPlace.getDefWidth(), bounds.getMaxY()
+ iconToPlace.getDefHeight());
NodeInst.makeInstance(iconToPlace, center, iconToPlace.getDefWidth(), iconToPlace.getDefHeight(), newCell);
}
// place exports in the new cell
for (PlacementExport plExport : exportsToPlace) {
PlacementPort plPort = plExport.getPort();
String exportName = plExport.getName();
PlacementNode plNode = plPort.getPlacementNode();
NodeInst newNI = placedNodes.get(plNode);
if (newNI == null)
continue;
PortInst portToExport = newNI.findPortInstFromProto(plPort.getPortProto());
Export.newInstance(newCell, portToExport, exportName, plExport.getCharacteristic());
}
ImmutableArcInst a = Generic.tech().unrouted_arc.getDefaultInst(newCell.getEditingPreferences());
long gridExtend = a.getGridExtendOverMin();
for (PlacementNetwork plNet : allNetworks) {
PlacementPort lastPp = null;
PortInst lastPi = null;
EPoint lastPt = null;
for (PlacementPort plPort : plNet.getPortsOnNet()) {
PlacementNode plNode = plPort.getPlacementNode();
NodeInst newNi = placedNodes.get(plNode);
if (newNi != null) {
PlacementPort thisPp = plPort;
PortInst thisPi = newNi.findPortInstFromProto(thisPp.getPortProto());
EPoint thisPt = new EPoint(plNode.getPlacementX() + plPort.getRotatedOffX(), plNode.getPlacementY()
+ plPort.getRotatedOffY());
if (lastPp != null) {
// connect them
ArcInst.newInstance(newCell, Generic.tech().unrouted_arc, null, null, lastPi, thisPi, lastPt,
thisPt, gridExtend, ArcInst.DEFAULTANGLE, a.flags);
}
lastPp = thisPp;
lastPi = thisPi;
lastPt = thisPt;
}
}
}
long endTime = System.currentTimeMillis();
System.out.println("\t(took " + TextUtils.getElapsedTime(endTime - startTime) + ")");
return newCell;
}
| public Cell doPlacement(Library lib, String cellName, List<PlacementNode> nodesToPlace,
List<PlacementNetwork> allNetworks, List<PlacementExport> exportsToPlace, NodeProto iconToPlace) {
long startTime = System.currentTimeMillis();
System.out.println("Running placement on cell '" + cellName + "' using the '" + getAlgorithmName()
+ "' algorithm");
// do the real work of placement
runPlacement(nodesToPlace, allNetworks, cellName);
if (Job.getDebug() && specialDebugFlag) {
AbstractMetric bmetric = new BBMetric(nodesToPlace, allNetworks);
System.out.println("### BBMetric: " + bmetric.toString());
AbstractMetric mstMetric = new MSTMetric(nodesToPlace, allNetworks);
System.out.println("### MSTMetric: " + mstMetric.toString());
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try {
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("/home/Felix Schmidt/work/" + this.getAlgorithmName() + "-" + cellName + "-"
+ this.runtime + "-" + this.numOfThreads + ".txt");
// Connect print stream to the output stream
p = new PrintStream(out);
p.println(bmetric.toString());
p.println(mstMetric.toString());
p.close();
} catch (Exception e) {
System.err.println("Error writing to file");
}
}
// create a new cell for the placement results
Cell newCell = Cell.makeInstance(lib, cellName); // newCellName
// place the nodes in the new cell
Map<PlacementNode, NodeInst> placedNodes = new HashMap<PlacementNode, NodeInst>();
for (PlacementNode plNode : nodesToPlace) {
double xPos = plNode.getPlacementX();
double yPos = plNode.getPlacementY();
Orientation orient = plNode.getPlacementOrientation();
NodeProto np = plNode.original;
if (np instanceof Cell) {
Cell placementCell = (Cell) np;
Rectangle2D bounds = placementCell.getBounds();
Point2D centerOffset = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
orient.pureRotate().transform(centerOffset, centerOffset);
xPos -= centerOffset.getX();
yPos -= centerOffset.getY();
}
NodeInst ni = NodeInst.makeInstance(np, new Point2D.Double(xPos, yPos), np.getDefWidth(),
np.getDefHeight(), newCell, orient, plNode.nodeName, plNode.techBits);
if (ni == null)
System.out.println("Placement failed to create node");
else {
if(plNode.isTerminal())
ni.setLocked();
placedNodes.put(plNode, ni);
}
if (plNode.addedVariables != null) {
for (Key key : plNode.addedVariables.keySet()) {
Object value = plNode.addedVariables.get(key);
Variable var = ni.newDisplayVar(key, value);
if (key == Schematics.SCHEM_RESISTANCE) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(0, 0.5).withDispPart(
TextDescriptor.DispPos.VALUE));
} else if (key == Schematics.ATTR_WIDTH) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(0.5, -1).withRelSize(1).withDispPart(
TextDescriptor.DispPos.VALUE));
} else if (key == Schematics.ATTR_LENGTH) {
ni.setTextDescriptor(key, var.getTextDescriptor().withOff(-0.5, -1).withRelSize(0.5)
.withDispPart(TextDescriptor.DispPos.VALUE));
} else {
ni.setTextDescriptor(key, var.getTextDescriptor().withDispPart(TextDescriptor.DispPos.VALUE));
}
}
}
}
// place an icon if requested
if (iconToPlace != null) {
ERectangle bounds = newCell.getBounds();
EPoint center = new EPoint(bounds.getMaxX() + iconToPlace.getDefWidth(), bounds.getMaxY()
+ iconToPlace.getDefHeight());
NodeInst.makeInstance(iconToPlace, center, iconToPlace.getDefWidth(), iconToPlace.getDefHeight(), newCell);
}
// place exports in the new cell
for (PlacementExport plExport : exportsToPlace) {
PlacementPort plPort = plExport.getPort();
String exportName = plExport.getName();
PlacementNode plNode = plPort.getPlacementNode();
NodeInst newNI = placedNodes.get(plNode);
if (newNI == null)
continue;
PortInst portToExport = newNI.findPortInstFromProto(plPort.getPortProto());
Export.newInstance(newCell, portToExport, exportName, plExport.getCharacteristic());
}
ImmutableArcInst a = Generic.tech().unrouted_arc.getDefaultInst(newCell.getEditingPreferences());
long gridExtend = a.getGridExtendOverMin();
for (PlacementNetwork plNet : allNetworks) {
PlacementPort lastPp = null;
PortInst lastPi = null;
EPoint lastPt = null;
for (PlacementPort plPort : plNet.getPortsOnNet()) {
PlacementNode plNode = plPort.getPlacementNode();
NodeInst newNi = placedNodes.get(plNode);
if (newNi != null) {
PlacementPort thisPp = plPort;
PortInst thisPi = newNi.findPortInstFromProto(thisPp.getPortProto());
EPoint thisPt = new EPoint(plNode.getPlacementX() + plPort.getRotatedOffX(), plNode.getPlacementY()
+ plPort.getRotatedOffY());
if (lastPp != null) {
// connect them
ArcInst.newInstance(newCell, Generic.tech().unrouted_arc, null, null, lastPi, thisPi, lastPt,
thisPt, gridExtend, ArcInst.DEFAULTANGLE, a.flags);
}
lastPp = thisPp;
lastPi = thisPi;
lastPt = thisPt;
}
}
}
long endTime = System.currentTimeMillis();
System.out.println("\t(took " + TextUtils.getElapsedTime(endTime - startTime) + ")");
return newCell;
}
|
diff --git a/xjc/src/com/sun/tools/xjc/reader/xmlschema/parser/SchemaConstraintChecker.java b/xjc/src/com/sun/tools/xjc/reader/xmlschema/parser/SchemaConstraintChecker.java
index 4a353d05..a3238b8c 100644
--- a/xjc/src/com/sun/tools/xjc/reader/xmlschema/parser/SchemaConstraintChecker.java
+++ b/xjc/src/com/sun/tools/xjc/reader/xmlschema/parser/SchemaConstraintChecker.java
@@ -1,101 +1,103 @@
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tools.xjc.reader.xmlschema.parser;
import java.io.File;
import java.io.IOException;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.SchemaFactory;
import com.sun.tools.xjc.ConsoleErrorReporter;
import com.sun.tools.xjc.ErrorReceiver;
import com.sun.tools.xjc.util.ErrorReceiverFilter;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
/**
* Checks XML Schema XML representation constraints and
* schema component constraints by using JAXP 1.3 validation framework.
* <p/>
*
* @author Kohsuke Kawaguchi ([email protected])
* @author Ryan Shoemaker ([email protected])
*/
public class SchemaConstraintChecker {
/**
* @param schemas Schema files to be checked.
* @param errorHandler detected errors will be reported to this handler.
* @return true if there was no error, false if there were errors.
*/
public static boolean check(InputSource[] schemas,
ErrorReceiver errorHandler, final EntityResolver entityResolver) {
ErrorReceiverFilter errorFilter = new ErrorReceiverFilter(errorHandler);
boolean hadErrors = false;
SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
sf.setErrorHandler(errorFilter);
if( entityResolver != null ) {
sf.setResourceResolver(new LSResourceResolver() {
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
try {
- InputSource is = entityResolver.resolveEntity(publicId, systemId);
+ // XSOM passes the namespace URI to the publicID parameter.
+ // we do the same here .
+ InputSource is = entityResolver.resolveEntity(namespaceURI, systemId);
if(is==null) return null;
return new LSInputSAXWrapper(is);
} catch (SAXException e) {
// TODO: is this sufficient?
return null;
} catch (IOException e) {
// TODO: is this sufficient?
return null;
}
}
});
}
try {
sf.newSchema(getSchemaSource(schemas));
} catch (SAXException e) {
// TODO: we haven't thrown exceptions from here before. should we just trap them and return false?
hadErrors = true;
} catch( OutOfMemoryError e) {
errorHandler.warning(null,Messages.format(Messages.WARN_UNABLE_TO_CHECK_CORRECTNESS));
}
return !(hadErrors || errorFilter.hadError());
}
/**
* convert an array of {@link InputSource InputSource} into an
* array of {@link Source Source}
*
* @param schemas array of {@link InputSource InputSource}
* @return array of {@link Source Source}
*/
private static Source[] getSchemaSource(InputSource[] schemas) {
SAXSource[] sources = new SAXSource[schemas.length];
for (int i = 0; i < schemas.length; i++)
sources[i] = new SAXSource(schemas[i]);
return sources;
}
// quick test
public static void main(String[] args) throws IOException {
InputSource[] sources = new InputSource[args.length];
for (int i = 0; i < args.length; i++)
sources[i] = new InputSource(new File(args[i]).toURL().toExternalForm());
check(sources, new ConsoleErrorReporter(), null);
}
}
| true | true | public static boolean check(InputSource[] schemas,
ErrorReceiver errorHandler, final EntityResolver entityResolver) {
ErrorReceiverFilter errorFilter = new ErrorReceiverFilter(errorHandler);
boolean hadErrors = false;
SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
sf.setErrorHandler(errorFilter);
if( entityResolver != null ) {
sf.setResourceResolver(new LSResourceResolver() {
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
try {
InputSource is = entityResolver.resolveEntity(publicId, systemId);
if(is==null) return null;
return new LSInputSAXWrapper(is);
} catch (SAXException e) {
// TODO: is this sufficient?
return null;
} catch (IOException e) {
// TODO: is this sufficient?
return null;
}
}
});
}
try {
sf.newSchema(getSchemaSource(schemas));
} catch (SAXException e) {
// TODO: we haven't thrown exceptions from here before. should we just trap them and return false?
hadErrors = true;
} catch( OutOfMemoryError e) {
errorHandler.warning(null,Messages.format(Messages.WARN_UNABLE_TO_CHECK_CORRECTNESS));
}
return !(hadErrors || errorFilter.hadError());
}
| public static boolean check(InputSource[] schemas,
ErrorReceiver errorHandler, final EntityResolver entityResolver) {
ErrorReceiverFilter errorFilter = new ErrorReceiverFilter(errorHandler);
boolean hadErrors = false;
SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
sf.setErrorHandler(errorFilter);
if( entityResolver != null ) {
sf.setResourceResolver(new LSResourceResolver() {
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
try {
// XSOM passes the namespace URI to the publicID parameter.
// we do the same here .
InputSource is = entityResolver.resolveEntity(namespaceURI, systemId);
if(is==null) return null;
return new LSInputSAXWrapper(is);
} catch (SAXException e) {
// TODO: is this sufficient?
return null;
} catch (IOException e) {
// TODO: is this sufficient?
return null;
}
}
});
}
try {
sf.newSchema(getSchemaSource(schemas));
} catch (SAXException e) {
// TODO: we haven't thrown exceptions from here before. should we just trap them and return false?
hadErrors = true;
} catch( OutOfMemoryError e) {
errorHandler.warning(null,Messages.format(Messages.WARN_UNABLE_TO_CHECK_CORRECTNESS));
}
return !(hadErrors || errorFilter.hadError());
}
|
diff --git a/javabot/src/pokerbots/packets/GameAction.java b/javabot/src/pokerbots/packets/GameAction.java
index fb89ad9..6c990fb 100644
--- a/javabot/src/pokerbots/packets/GameAction.java
+++ b/javabot/src/pokerbots/packets/GameAction.java
@@ -1,30 +1,26 @@
package pokerbots.packets;
import pokerbots.utils.HandEvaluator;
public class GameAction {
public String actionType;
public int minBet; //optional
public int maxBet; //optional
public int cardToDiscard; //optional
public GameAction(String input){
- String[] values = input.split(" ");
+ String[] values = input.split(":");
String actionType = values[0];
- System.out.println("WHAT? " + actionType);
// bet or raise
- if (values.length > 1){
- String[] bets = values[1].split(":");
- minBet = Integer.parseInt(bets[0]);
- maxBet = Integer.parseInt(bets[1]);
+ if (values.length == 3){
+ minBet = Integer.parseInt(values[1]);
+ maxBet = Integer.parseInt(values[2]);
}
//discard
- else if (actionType.contains(":")){
- String[] words = actionType.split(":");
- actionType = words[0];
- cardToDiscard = HandEvaluator.stringToCard(words[1]);
+ else if (values.length == 2){
+ cardToDiscard = HandEvaluator.stringToCard(values[1]);
}
}
}
| false | true | public GameAction(String input){
String[] values = input.split(" ");
String actionType = values[0];
System.out.println("WHAT? " + actionType);
// bet or raise
if (values.length > 1){
String[] bets = values[1].split(":");
minBet = Integer.parseInt(bets[0]);
maxBet = Integer.parseInt(bets[1]);
}
//discard
else if (actionType.contains(":")){
String[] words = actionType.split(":");
actionType = words[0];
cardToDiscard = HandEvaluator.stringToCard(words[1]);
}
}
| public GameAction(String input){
String[] values = input.split(":");
String actionType = values[0];
// bet or raise
if (values.length == 3){
minBet = Integer.parseInt(values[1]);
maxBet = Integer.parseInt(values[2]);
}
//discard
else if (values.length == 2){
cardToDiscard = HandEvaluator.stringToCard(values[1]);
}
}
|
diff --git a/src/com/owncloud/android/DisplayUtils.java b/src/com/owncloud/android/DisplayUtils.java
index 0e1b2b6..70a9672 100644
--- a/src/com/owncloud/android/DisplayUtils.java
+++ b/src/com/owncloud/android/DisplayUtils.java
@@ -1,193 +1,193 @@
/* ownCloud Android client application
* Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2012-2013 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import android.util.Log;
/**
* A helper class for some string operations.
*
* @author Bartek Przybylski
* @author David A. Velasco
*/
public class DisplayUtils {
private static String TAG = DisplayUtils.class.getSimpleName();
private static final String[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
private static HashMap<String, String> mimeType2HUmanReadable;
static {
mimeType2HUmanReadable = new HashMap<String, String>();
// images
mimeType2HUmanReadable.put("image/jpeg", "JPEG image");
mimeType2HUmanReadable.put("image/jpg", "JPEG image");
mimeType2HUmanReadable.put("image/png", "PNG image");
mimeType2HUmanReadable.put("image/bmp", "Bitmap image");
mimeType2HUmanReadable.put("image/gif", "GIF image");
mimeType2HUmanReadable.put("image/svg+xml", "JPEG image");
mimeType2HUmanReadable.put("image/tiff", "TIFF image");
// music
mimeType2HUmanReadable.put("audio/mpeg", "MP3 music file");
mimeType2HUmanReadable.put("application/ogg", "OGG music file");
}
private static final String TYPE_APPLICATION = "application";
private static final String TYPE_AUDIO = "audio";
private static final String TYPE_IMAGE = "image";
private static final String TYPE_TXT = "text";
private static final String TYPE_VIDEO = "video";
private static final String SUBTYPE_PDF = "pdf";
private static final String[] SUBTYPES_DOCUMENT = { "msword", "mspowerpoint", "msexcel",
"vnd.oasis.opendocument.presentation",
"vnd.oasis.opendocument.spreadsheet",
"vnd.oasis.opendocument.text"
};
private static Set<String> SUBTYPES_DOCUMENT_SET = new HashSet<String>(Arrays.asList(SUBTYPES_DOCUMENT));
private static final String[] SUBTYPES_COMPRESSED = {"x-tar", "x-gzip", "zip"};
private static final Set<String> SUBTYPES_COMPRESSED_SET = new HashSet<String>(Arrays.asList(SUBTYPES_COMPRESSED));
/**
* Converts the file size in bytes to human readable output.
*
* @param bytes Input file size
* @return Like something readable like "12 MB"
*/
public static String bytesToHumanReadable(long bytes) {
double result = bytes;
int attachedsuff = 0;
while (result > 1024 && attachedsuff < sizeSuffixes.length) {
result /= 1024.;
attachedsuff++;
}
result = ((int) (result * 100)) / 100.;
return result + " " + sizeSuffixes[attachedsuff];
}
/**
* Removes special HTML entities from a string
*
* @param s Input string
* @return A cleaned version of the string
*/
public static String HtmlDecode(String s) {
/*
* TODO: Perhaps we should use something more proven like:
* http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#unescapeHtml%28java.lang.String%29
*/
String ret = "";
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '%') {
ret += (char) Integer.parseInt(s.substring(i + 1, i + 3), 16);
i += 2;
} else {
ret += s.charAt(i);
}
}
return ret;
}
/**
* Converts MIME types like "image/jpg" to more end user friendly output
* like "JPG image".
*
* @param mimetype MIME type to convert
* @return A human friendly version of the MIME type
*/
public static String convertMIMEtoPrettyPrint(String mimetype) {
if (mimeType2HUmanReadable.containsKey(mimetype)) {
return mimeType2HUmanReadable.get(mimetype);
}
if (mimetype.split("/").length >= 2)
return mimetype.split("/")[1].toUpperCase() + " file";
return "Unknown type";
}
/**
* Returns the resource identifier of an image resource to use as icon associated to a
* known MIME type.
*
* @param mimetype MIME type string.
* @return Resource identifier of an image resource.
*/
public static int getResourceId(String mimetype) {
if (mimetype == null || "DIR".equals(mimetype)) {
return R.drawable.ic_menu_archive;
} else {
String [] parts = mimetype.split("/");
String type = parts[0];
- String subtype = (parts.length > 0) ? parts[1] : "";
+ String subtype = (parts.length > 1) ? parts[1] : "";
if(TYPE_TXT.equals(type)) {
return R.drawable.file_doc;
} else if(TYPE_IMAGE.equals(type)) {
return R.drawable.file_image;
} else if(TYPE_VIDEO.equals(type)) {
return R.drawable.file_movie;
} else if(TYPE_AUDIO.equals(type)) {
return R.drawable.file_sound;
} else if(TYPE_APPLICATION.equals(type)) {
if (SUBTYPE_PDF.equals(subtype)) {
return R.drawable.file_pdf;
} else if (SUBTYPES_DOCUMENT_SET.contains(subtype)) {
return R.drawable.file_doc;
} else if (SUBTYPES_COMPRESSED_SET.contains(subtype)) {
return R.drawable.file_zip;
}
}
// problems: RAR, RTF, 3GP are send as application/octet-stream from the server ; extension in the filename should be explicitly reviewed
}
// default icon
return R.drawable.file;
}
/**
* Converts Unix time to human readable format
* @param miliseconds that have passed since 01/01/1970
* @return The human readable time for the users locale
*/
public static String unixTimeToHumanReadable(long milliseconds) {
Date date = new Date(milliseconds);
return date.toLocaleString();
}
}
| true | true | public static int getResourceId(String mimetype) {
if (mimetype == null || "DIR".equals(mimetype)) {
return R.drawable.ic_menu_archive;
} else {
String [] parts = mimetype.split("/");
String type = parts[0];
String subtype = (parts.length > 0) ? parts[1] : "";
if(TYPE_TXT.equals(type)) {
return R.drawable.file_doc;
} else if(TYPE_IMAGE.equals(type)) {
return R.drawable.file_image;
} else if(TYPE_VIDEO.equals(type)) {
return R.drawable.file_movie;
} else if(TYPE_AUDIO.equals(type)) {
return R.drawable.file_sound;
} else if(TYPE_APPLICATION.equals(type)) {
if (SUBTYPE_PDF.equals(subtype)) {
return R.drawable.file_pdf;
} else if (SUBTYPES_DOCUMENT_SET.contains(subtype)) {
return R.drawable.file_doc;
} else if (SUBTYPES_COMPRESSED_SET.contains(subtype)) {
return R.drawable.file_zip;
}
}
// problems: RAR, RTF, 3GP are send as application/octet-stream from the server ; extension in the filename should be explicitly reviewed
}
// default icon
return R.drawable.file;
}
| public static int getResourceId(String mimetype) {
if (mimetype == null || "DIR".equals(mimetype)) {
return R.drawable.ic_menu_archive;
} else {
String [] parts = mimetype.split("/");
String type = parts[0];
String subtype = (parts.length > 1) ? parts[1] : "";
if(TYPE_TXT.equals(type)) {
return R.drawable.file_doc;
} else if(TYPE_IMAGE.equals(type)) {
return R.drawable.file_image;
} else if(TYPE_VIDEO.equals(type)) {
return R.drawable.file_movie;
} else if(TYPE_AUDIO.equals(type)) {
return R.drawable.file_sound;
} else if(TYPE_APPLICATION.equals(type)) {
if (SUBTYPE_PDF.equals(subtype)) {
return R.drawable.file_pdf;
} else if (SUBTYPES_DOCUMENT_SET.contains(subtype)) {
return R.drawable.file_doc;
} else if (SUBTYPES_COMPRESSED_SET.contains(subtype)) {
return R.drawable.file_zip;
}
}
// problems: RAR, RTF, 3GP are send as application/octet-stream from the server ; extension in the filename should be explicitly reviewed
}
// default icon
return R.drawable.file;
}
|
diff --git a/src/main/java/com/jin/tpdb/persistence/DAO.java b/src/main/java/com/jin/tpdb/persistence/DAO.java
index b4bdfbc..ef1fe18 100755
--- a/src/main/java/com/jin/tpdb/persistence/DAO.java
+++ b/src/main/java/com/jin/tpdb/persistence/DAO.java
@@ -1,115 +1,115 @@
package com.jin.tpdb.persistence;
import java.util.List;
import javax.persistence.*;
import javax.persistence.criteria.*;
import com.jin.tpdb.entities.*;
public class DAO {
protected static EntityManagerFactory factory;
protected EntityManager em;
public DAO() {
if(DAO.getManagerFactory() == null) {
factory = Persistence.createEntityManagerFactory("jin");
DAO.setManagerFactory(factory);
} else {
factory = DAO.getManagerFactory();
}
}
protected static void setManagerFactory(EntityManagerFactory f){
factory = f;
}
protected static EntityManagerFactory getManagerFactory() {
return factory;
}
public void open() {
try {
em = factory.createEntityManager();
em.getTransaction().begin();
} catch(Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
em.getTransaction().commit();
em.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public void save(Object o) {
em.persist(o);
}
public void rollback() {
em.getTransaction().rollback();
}
public static <T> T load(Class c, int i) {
DAO dao = new DAO();
dao.open();
T result = dao.get(c, i);
dao.close();
return result;
}
public static <T> List<T> getList(Class c) {
DAO dao = new DAO();
dao.open();
List<T> results = dao.list(c);
dao.close();
return results;
}
public <T> T get(Class c, int i) {
return (T)em.find(c, i);
}
protected <T> List<T> list(Class entity) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> query = cb.createQuery(entity);
TypedQuery<T> typedQuery = em.createQuery(
query.select(
query.from(entity)
)
);
return typedQuery.getResultList();
}
public int getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
String qs = "SELECT COUNT(ac) FROM AlbumComment ac";
- TypedQuery<Integer> query = em.createQuery(qs, Integer.class);
+ TypedQuery<Long> query = em.createQuery(qs, Long.class);
return (int)query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
public static int countAlbumComments(int id) {
DAO dao = new DAO();
dao.open();
int count = dao.getAlbumTotalComments(id);
dao.close();
return count;
}
}
| true | true | public int getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
String qs = "SELECT COUNT(ac) FROM AlbumComment ac";
TypedQuery<Integer> query = em.createQuery(qs, Integer.class);
return (int)query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
| public int getAlbumTotalComments(int id) {
/*$albums_query = "SELECT users.username, albums.album_id, albums.uploader_user_id, albums.album_name,
albums.upload_date, albums.cover, albums.description, artists.artist_name,
(SELECT COUNT( comment_id ) FROM comments WHERE comments.album_id = albums.album_id) AS total_comments
FROM albums, artists, users
WHERE artists.artist_id = albums.artist_id AND users.user_id
*/
String qs = "SELECT COUNT(ac) FROM AlbumComment ac";
TypedQuery<Long> query = em.createQuery(qs, Long.class);
return (int)query.getSingleResult();
/*Root<AlbumComment> root = cq.from(AlbumComment.class);
cq.select(qb.count(root));
Predicate predicate = qb.equal(root.get("album_id"), id);
cq.where(predicate);
return em.createQuery(cq).getSingleResult();*/
}
|
diff --git a/modules/resin/src/com/caucho/amber/type/StringType.java b/modules/resin/src/com/caucho/amber/type/StringType.java
index 7a6721c68..a5b8ea6d5 100644
--- a/modules/resin/src/com/caucho/amber/type/StringType.java
+++ b/modules/resin/src/com/caucho/amber/type/StringType.java
@@ -1,129 +1,129 @@
/*
* Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.amber.type;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.caucho.amber.manager.AmberPersistenceUnit;
import com.caucho.util.L10N;
import com.caucho.java.JavaWriter;
/**
* The type of a property.
*/
public class StringType extends Type {
private static final L10N L = new L10N(StringType.class);
private static final StringType STRING_TYPE = new StringType();
private StringType()
{
}
/**
* Returns the string type.
*/
public static StringType create()
{
return STRING_TYPE;
}
/**
* Returns the type name.
*/
public String getName()
{
return "java.lang.String";
}
/**
* Generates the type for the table.
*/
public String generateCreateColumnSQL(AmberPersistenceUnit manager, int length, int precision, int scale)
{
if (length == 0)
length = 255;
return "varchar(" + length + ")";
// return manager.getCreateColumnSQL(Types.VARCHAR, length);
}
/**
* Generates a string to load the property.
*/
public int generateLoad(JavaWriter out, String rs,
String indexVar, int index)
throws IOException
{
out.print(rs + ".getString(" + indexVar + " + " + index + ")");
return index + 1;
}
/**
* Generates a string to set the property.
*/
public void generateSet(JavaWriter out, String pstmt,
String index, String value)
throws IOException
{
- out.println("if (value == null)");
+ out.println("if (" + value + " == null)");
out.println(" " + pstmt + ".setNull(" + index + "++, java.sql.Types.OTHER);");
out.println("else");
out.println(" " + pstmt + ".setString(" + index + "++, " + value + ");");
}
/**
* Sets the value.
*/
public void setParameter(PreparedStatement pstmt, int index, Object value)
throws SQLException
{
if (value == null)
pstmt.setNull(index, java.sql.Types.OTHER);
else
pstmt.setString(index, (String) value);
}
/**
* Gets the value.
*/
public Object getObject(ResultSet rs, int index)
throws SQLException
{
return rs.getString(index);
}
}
| true | true | public void generateSet(JavaWriter out, String pstmt,
String index, String value)
throws IOException
{
out.println("if (value == null)");
out.println(" " + pstmt + ".setNull(" + index + "++, java.sql.Types.OTHER);");
out.println("else");
out.println(" " + pstmt + ".setString(" + index + "++, " + value + ");");
}
| public void generateSet(JavaWriter out, String pstmt,
String index, String value)
throws IOException
{
out.println("if (" + value + " == null)");
out.println(" " + pstmt + ".setNull(" + index + "++, java.sql.Types.OTHER);");
out.println("else");
out.println(" " + pstmt + ".setString(" + index + "++, " + value + ");");
}
|
diff --git a/src/org/jitsi/impl/neomedia/device/AudioSystem.java b/src/org/jitsi/impl/neomedia/device/AudioSystem.java
index 3efaa21a..d69167ea 100644
--- a/src/org/jitsi/impl/neomedia/device/AudioSystem.java
+++ b/src/org/jitsi/impl/neomedia/device/AudioSystem.java
@@ -1,593 +1,593 @@
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jitsi.impl.neomedia.device;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import javax.media.*;
import javax.sound.sampled.*;
import org.jitsi.impl.neomedia.jmfext.media.renderer.audio.*;
import org.jitsi.service.libjitsi.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.resources.*;
import org.jitsi.util.*;
/**
* Represents a <tt>DeviceSystem</tt> which provides support for the devices to
* capture and play back audio (media). Examples include implementations which
* integrate the native PortAudio, PulseAudio libraries.
*
* @author Lyubomir Marinov
* @author Vincent Lucas
*/
public abstract class AudioSystem
extends DeviceSystem
{
/**
* Enumerates the different types of media data flow of
* <tt>CaptureDeviceInfo2</tt>s contributed by an <tt>AudioSystem</tt>.
*
* @author Lyubomir Marinov
*/
public enum DataFlow
{
CAPTURE,
NOTIFY,
PLAYBACK
}
/**
* The constant/flag (to be) returned by {@link #getFeatures()} in order to
* indicate that the respective <tt>AudioSystem</tt> supports toggling its
* denoise functionality between on and off. The UI will look for the
* presence of the flag in order to determine whether a check box is to be
* shown to the user to enable toggling the denoise functionality.
*/
public static final int FEATURE_DENOISE = 2;
/**
* The constant/flag (to be) returned by {@link #getFeatures()} in order to
* indicate that the respective <tt>AudioSystem</tt> supports toggling its
* echo cancellation functionality between on and off. The UI will look for
* the presence of the flag in order to determine whether a check box is to
* be shown to the user to enable toggling the echo cancellation
* functionality.
*/
public static final int FEATURE_ECHO_CANCELLATION = 4;
/**
* The constant/flag (to be) returned by {@link #getFeatures()} in order to
* indicate that the respective <tt>AudioSystem</tt> differentiates between
* playback and notification audio devices. The UI, for example, will look
* for the presence of the flag in order to determine whether separate combo
* boxes are to be shown to the user to allow the configuration of the
* preferred playback and notification audio devices.
*/
public static final int FEATURE_NOTIFY_AND_PLAYBACK_DEVICES = 8;
public static final String LOCATOR_PROTOCOL_AUDIORECORD = "audiorecord";
public static final String LOCATOR_PROTOCOL_JAVASOUND = "javasound";
public static final String LOCATOR_PROTOCOL_OPENSLES = "opensles";
public static final String LOCATOR_PROTOCOL_PORTAUDIO = "portaudio";
public static final String LOCATOR_PROTOCOL_PULSEAUDIO = "pulseaudio";
/**
* The protocol of the <tt>MediaLocator</tt>s identifying
* <tt>CaptureDeviceInfo</tt>s contributed by <tt>WASAPISystem</tt>.
*/
public static final String LOCATOR_PROTOCOL_WASAPI = "wasapi";
/**
* The <tt>Logger</tt> used by this instance for logging output.
*/
private static Logger logger = Logger.getLogger(AudioSystem.class);
public static AudioSystem getAudioSystem(String locatorProtocol)
{
AudioSystem[] audioSystems = getAudioSystems();
AudioSystem audioSystemWithLocatorProtocol = null;
if (audioSystems != null)
{
for (AudioSystem audioSystem : audioSystems)
{
if (audioSystem.getLocatorProtocol().equalsIgnoreCase(
locatorProtocol))
{
audioSystemWithLocatorProtocol = audioSystem;
break;
}
}
}
return audioSystemWithLocatorProtocol;
}
public static AudioSystem[] getAudioSystems()
{
DeviceSystem[] deviceSystems
= DeviceSystem.getDeviceSystems(MediaType.AUDIO);
List<AudioSystem> audioSystems;
if (deviceSystems == null)
audioSystems = null;
else
{
audioSystems = new ArrayList<AudioSystem>(deviceSystems.length);
for (DeviceSystem deviceSystem : deviceSystems)
if (deviceSystem instanceof AudioSystem)
audioSystems.add((AudioSystem) deviceSystem);
}
return
(audioSystems == null)
? null
: audioSystems.toArray(new AudioSystem[audioSystems.size()]);
}
/**
* The list of devices detected by this <tt>AudioSystem</tt> indexed by
* their category which is among {@link #CAPTURE_INDEX},
* {@link #NOTIFY_INDEX} and {@link #PLAYBACK_INDEX}.
*/
private Devices[] devices;
protected AudioSystem(String locatorProtocol)
throws Exception
{
this(locatorProtocol, 0);
}
protected AudioSystem(String locatorProtocol, int features)
throws Exception
{
super(MediaType.AUDIO, locatorProtocol, features);
}
/**
* {@inheritDoc}
*
* Delegates to {@link #createRenderer(boolean)} with the value of the
* <tt>playback</tt> argument set to true.
*/
@Override
public Renderer createRenderer()
{
return createRenderer(true);
}
/**
* Initializes a new <tt>Renderer</tt> instance which is to either perform
* playback on or sound a notification through a device contributed by this
* system. The (default) implementation of <tt>AudioSystem</tt> ignores the
* value of the <tt>playback</tt> argument and delegates to
* {@link DeviceSystem#createRenderer()}.
*
* @param playback <tt>true</tt> if the new instance is to perform playback
* or <tt>false</tt> if the new instance is to sound a notification
* @return a new <tt>Renderer</tt> instance which is to either perform
* playback on or sound a notification through a device contributed by this
* system
*/
public Renderer createRenderer(boolean playback)
{
String className = getRendererClassName();
Renderer renderer;
if (className == null)
{
/*
* There is no point in delegating to the super's createRenderer()
* because it will not have a class to instantiate.
*/
renderer = null;
}
else
{
Class<?> clazz;
try
{
clazz = Class.forName(className);
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
clazz = null;
logger.error("Failed to get class " + className, t);
}
}
if (clazz == null)
{
/*
* There is no point in delegating to the super's
* createRenderer() because it will fail to get the class.
*/
renderer = null;
}
else if (!Renderer.class.isAssignableFrom(clazz))
{
/*
* There is no point in delegating to the super's
* createRenderer() because it will fail to cast the new
* instance to a Renderer.
*/
renderer = null;
}
else
{
boolean superCreateRenderer;
if (((getFeatures() & FEATURE_NOTIFY_AND_PLAYBACK_DEVICES) != 0)
&& AbstractAudioRenderer.class.isAssignableFrom(clazz))
{
Constructor<?> constructor = null;
try
{
constructor = clazz.getConstructor(boolean.class);
}
catch (NoSuchMethodException nsme)
{
/*
* Such a constructor is optional so the failure to get
* it will be swallowed and the super's
* createRenderer() will be invoked.
*/
}
catch (SecurityException se)
{
}
- if ((constructor != null) && constructor.isAccessible())
+ if ((constructor != null))
{
superCreateRenderer = false;
try
{
renderer
= (Renderer) constructor.newInstance(playback);
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
renderer = null;
logger.error(
"Failed to initialize a new "
+ className + " instance",
t);
}
}
if ((renderer != null) && !playback)
{
CaptureDeviceInfo device
= getSelectedDevice(DataFlow.NOTIFY);
if (device == null)
{
/*
* If there is no notification device, then no
* notification is to be sounded.
*/
renderer = null;
}
else
{
MediaLocator locator = device.getLocator();
if (locator != null)
{
((AbstractAudioRenderer<?>) renderer)
.setLocator(locator);
}
}
}
}
else
{
/*
* The super's createRenderer() will be invoked because
* either there is no non-default constructor or it is
* not meant to be invoked by the public.
*/
superCreateRenderer = true;
renderer = null;
}
}
else
{
/*
* The super's createRenderer() will be invoked because
* either this AudioSystem does not distinguish between
* playback and notify data flows or the Renderer
* implementation class in not familiar.
*/
superCreateRenderer = true;
renderer = null;
}
if (superCreateRenderer && (renderer == null))
renderer = super.createRenderer();
}
}
return renderer;
}
/**
* Obtains an audio input stream from the URL provided.
* @param uri a valid uri to a sound resource.
* @return the input stream to audio data.
* @throws IOException if an I/O exception occurs
*/
public InputStream getAudioInputStream(String uri)
throws IOException
{
ResourceManagementService resources
= LibJitsi.getResourceManagementService();
URL url
= (resources == null)
? null
: resources.getSoundURLForPath(uri);
AudioInputStream audioStream = null;
try
{
// Not found by the class loader? Perhaps it is a local file.
if (url == null)
url = new URL(uri);
audioStream
= javax.sound.sampled.AudioSystem.getAudioInputStream(url);
}
catch (MalformedURLException murle)
{
// Do nothing, the value of audioStream will remain equal to null.
}
catch (UnsupportedAudioFileException uafe)
{
logger.error("Unsupported format of audio stream " + url, uafe);
}
return audioStream;
}
/**
* Gets a <tt>CaptureDeviceInfo2</tt> which has been contributed by this
* <tt>AudioSystem</tt>, supports a specific flow of media data (i.e.
* capture, notify or playback) and is identified by a specific
* <tt>MediaLocator</tt>.
*
* @param dataFlow the flow of the media data supported by the
* <tt>CaptureDeviceInfo2</tt> to be returned
* @param locator the <tt>MediaLocator</tt> of the
* <tt>CaptureDeviceInfo2</tt> to be returned
* @return a <tt>CaptureDeviceInfo2</tt> which has been contributed by this
* instance, supports the specified <tt>dataFlow</tt> and is identified by
* the specified <tt>locator</tt>
*/
public CaptureDeviceInfo2 getDevice(DataFlow dataFlow, MediaLocator locator)
{
return devices[dataFlow.ordinal()].getDevice(locator);
}
/**
* Gets the list of devices with a specific data flow: capture, notify or
* playback.
*
* @param dataFlow the data flow of the devices to retrieve: capture, notify
* or playback
* @return the list of devices with the specified <tt>dataFlow</tt>
*/
public List<CaptureDeviceInfo2> getDevices(DataFlow dataFlow)
{
return devices[dataFlow.ordinal()].getDevices();
}
/**
* Returns the FMJ format of a specific <tt>InputStream</tt> providing audio
* media.
*
* @param audioInputStream the <tt>InputStream</tt> providing audio media to
* determine the FMJ format of
* @return the FMJ format of the specified <tt>audioInputStream</tt> or
* <tt>null</tt> if such an FMJ format could not be determined
*/
public Format getFormat(InputStream audioInputStream)
{
if ((audioInputStream instanceof AudioInputStream))
{
AudioFormat audioInputStreamFormat
= ((AudioInputStream) audioInputStream).getFormat();
return
new javax.media.format.AudioFormat(
javax.media.format.AudioFormat.LINEAR,
audioInputStreamFormat.getSampleRate(),
audioInputStreamFormat.getSampleSizeInBits(),
audioInputStreamFormat.getChannels());
}
return null;
}
/**
* Gets the selected device for a specific data flow: capture, notify or
* playback.
*
* @param dataFlow the data flow of the selected device to retrieve:
* capture, notify or playback.
* @return the selected device for the specified <tt>dataFlow</tt>
*/
public CaptureDeviceInfo2 getSelectedDevice(DataFlow dataFlow)
{
return
devices[dataFlow.ordinal()].getSelectedDevice(
getLocatorProtocol(),
getDevices(dataFlow));
}
/**
* {@inheritDoc}
*
* Because <tt>AudioSystem</tt> may support playback and notification audio
* devices apart from capture audio devices, fires more specific
* <tt>PropertyChangeEvent</tt>s than <tt>DeviceSystem</tt>
*/
@Override
protected void postInitialize()
{
try
{
try
{
postInitializeSpecificDevices(DataFlow.CAPTURE);
}
finally
{
if ((FEATURE_NOTIFY_AND_PLAYBACK_DEVICES & getFeatures()) != 0)
{
try
{
postInitializeSpecificDevices(DataFlow.NOTIFY);
}
finally
{
postInitializeSpecificDevices(DataFlow.PLAYBACK);
}
}
}
}
finally
{
super.postInitialize();
}
}
/**
* Sets the device lists after the different audio systems (PortAudio,
* PulseAudio, etc) have finished detecting their devices.
*
* @param dataFlow the data flow of the devices to perform
* post-initialization on
*/
protected void postInitializeSpecificDevices(DataFlow dataFlow)
{
// Gets all current active devices.
List<CaptureDeviceInfo2> activeDevices = getDevices(dataFlow);
// Gets the default device.
Devices devices = this.devices[dataFlow.ordinal()];
String locatorProtocol = getLocatorProtocol();
CaptureDeviceInfo2 selectedActiveDevice
= devices.getSelectedDevice(locatorProtocol, activeDevices);
// Sets the default device as selected. The function will fire a
// property change only if the device has changed from a previous
// configuration. The "set" part is important because only the fired
// property event provides a way to get the hotplugged devices working
// during a call.
devices.setDevice(locatorProtocol, selectedActiveDevice, false);
}
/**
* {@inheritDoc}
*
* Removes any capture, playback and notification devices previously
* detected by this <tt>AudioSystem</tt> and prepares it for the execution
* of its {@link DeviceSystem#doInitialize()} implementation (which detects
* all devices to be provided by this instance).
*/
@Override
protected void preInitialize()
{
super.preInitialize();
if (devices == null)
{
devices = new Devices[3];
devices[DataFlow.CAPTURE.ordinal()] = new CaptureDevices(this);
devices[DataFlow.NOTIFY.ordinal()] = new NotifyDevices(this);
devices[DataFlow.PLAYBACK.ordinal()] = new PlaybackDevices(this);
}
}
/**
* Fires a new <tt>PropertyChangeEvent</tt> to the
* <tt>PropertyChangeListener</tt>s registered with this
* <tt>PropertyChangeNotifier</tt> in order to notify about a change in the
* value of a specific property which had its old value modified to a
* specific new value. <tt>PropertyChangeNotifier</tt> does not check
* whether the specified <tt>oldValue</tt> and <tt>newValue</tt> are indeed
* different.
*
* @param property the name of the property of this
* <tt>PropertyChangeNotifier</tt> which had its value changed
* @param oldValue the value of the property with the specified name before
* the change
* @param newValue the value of the property with the specified name after
* the change
*/
public void propertyChange(
String property,
Object oldValue,
Object newValue)
{
firePropertyChange(property, oldValue, newValue);
}
/**
* Sets the list of a kind of devices: capture, notify or playback.
*
* @param captureDevices The list of a kind of devices: capture, notify or
* playback.
*/
protected void setCaptureDevices(List<CaptureDeviceInfo2> captureDevices)
{
devices[DataFlow.CAPTURE.ordinal()].setDevices(captureDevices);
}
/**
* Selects the active device.
*
* @param dataFlow the data flow of the device to set: capture, notify or
* playback
* @param device The selected active device.
* @param save Flag set to true in order to save this choice in the
* configuration. False otherwise.
*/
public void setDevice(
DataFlow dataFlow,
CaptureDeviceInfo2 device,
boolean save)
{
devices[dataFlow.ordinal()].setDevice(
getLocatorProtocol(),
device,
save);
}
/**
* Sets the list of the active devices.
*
* @param playbackDevices The list of the active devices.
*/
protected void setPlaybackDevices(List<CaptureDeviceInfo2> playbackDevices)
{
devices[DataFlow.PLAYBACK.ordinal()].setDevices(playbackDevices);
// The notify devices are the same as the playback devices.
devices[DataFlow.NOTIFY.ordinal()].setDevices(playbackDevices);
}
}
| true | true | public Renderer createRenderer(boolean playback)
{
String className = getRendererClassName();
Renderer renderer;
if (className == null)
{
/*
* There is no point in delegating to the super's createRenderer()
* because it will not have a class to instantiate.
*/
renderer = null;
}
else
{
Class<?> clazz;
try
{
clazz = Class.forName(className);
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
clazz = null;
logger.error("Failed to get class " + className, t);
}
}
if (clazz == null)
{
/*
* There is no point in delegating to the super's
* createRenderer() because it will fail to get the class.
*/
renderer = null;
}
else if (!Renderer.class.isAssignableFrom(clazz))
{
/*
* There is no point in delegating to the super's
* createRenderer() because it will fail to cast the new
* instance to a Renderer.
*/
renderer = null;
}
else
{
boolean superCreateRenderer;
if (((getFeatures() & FEATURE_NOTIFY_AND_PLAYBACK_DEVICES) != 0)
&& AbstractAudioRenderer.class.isAssignableFrom(clazz))
{
Constructor<?> constructor = null;
try
{
constructor = clazz.getConstructor(boolean.class);
}
catch (NoSuchMethodException nsme)
{
/*
* Such a constructor is optional so the failure to get
* it will be swallowed and the super's
* createRenderer() will be invoked.
*/
}
catch (SecurityException se)
{
}
if ((constructor != null) && constructor.isAccessible())
{
superCreateRenderer = false;
try
{
renderer
= (Renderer) constructor.newInstance(playback);
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
renderer = null;
logger.error(
"Failed to initialize a new "
+ className + " instance",
t);
}
}
if ((renderer != null) && !playback)
{
CaptureDeviceInfo device
= getSelectedDevice(DataFlow.NOTIFY);
if (device == null)
{
/*
* If there is no notification device, then no
* notification is to be sounded.
*/
renderer = null;
}
else
{
MediaLocator locator = device.getLocator();
if (locator != null)
{
((AbstractAudioRenderer<?>) renderer)
.setLocator(locator);
}
}
}
}
else
{
/*
* The super's createRenderer() will be invoked because
* either there is no non-default constructor or it is
* not meant to be invoked by the public.
*/
superCreateRenderer = true;
renderer = null;
}
}
else
{
/*
* The super's createRenderer() will be invoked because
* either this AudioSystem does not distinguish between
* playback and notify data flows or the Renderer
* implementation class in not familiar.
*/
superCreateRenderer = true;
renderer = null;
}
if (superCreateRenderer && (renderer == null))
renderer = super.createRenderer();
}
}
return renderer;
}
| public Renderer createRenderer(boolean playback)
{
String className = getRendererClassName();
Renderer renderer;
if (className == null)
{
/*
* There is no point in delegating to the super's createRenderer()
* because it will not have a class to instantiate.
*/
renderer = null;
}
else
{
Class<?> clazz;
try
{
clazz = Class.forName(className);
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
clazz = null;
logger.error("Failed to get class " + className, t);
}
}
if (clazz == null)
{
/*
* There is no point in delegating to the super's
* createRenderer() because it will fail to get the class.
*/
renderer = null;
}
else if (!Renderer.class.isAssignableFrom(clazz))
{
/*
* There is no point in delegating to the super's
* createRenderer() because it will fail to cast the new
* instance to a Renderer.
*/
renderer = null;
}
else
{
boolean superCreateRenderer;
if (((getFeatures() & FEATURE_NOTIFY_AND_PLAYBACK_DEVICES) != 0)
&& AbstractAudioRenderer.class.isAssignableFrom(clazz))
{
Constructor<?> constructor = null;
try
{
constructor = clazz.getConstructor(boolean.class);
}
catch (NoSuchMethodException nsme)
{
/*
* Such a constructor is optional so the failure to get
* it will be swallowed and the super's
* createRenderer() will be invoked.
*/
}
catch (SecurityException se)
{
}
if ((constructor != null))
{
superCreateRenderer = false;
try
{
renderer
= (Renderer) constructor.newInstance(playback);
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
renderer = null;
logger.error(
"Failed to initialize a new "
+ className + " instance",
t);
}
}
if ((renderer != null) && !playback)
{
CaptureDeviceInfo device
= getSelectedDevice(DataFlow.NOTIFY);
if (device == null)
{
/*
* If there is no notification device, then no
* notification is to be sounded.
*/
renderer = null;
}
else
{
MediaLocator locator = device.getLocator();
if (locator != null)
{
((AbstractAudioRenderer<?>) renderer)
.setLocator(locator);
}
}
}
}
else
{
/*
* The super's createRenderer() will be invoked because
* either there is no non-default constructor or it is
* not meant to be invoked by the public.
*/
superCreateRenderer = true;
renderer = null;
}
}
else
{
/*
* The super's createRenderer() will be invoked because
* either this AudioSystem does not distinguish between
* playback and notify data flows or the Renderer
* implementation class in not familiar.
*/
superCreateRenderer = true;
renderer = null;
}
if (superCreateRenderer && (renderer == null))
renderer = super.createRenderer();
}
}
return renderer;
}
|
diff --git a/CourierWorld/src/sim/courierworld/Hub.java b/CourierWorld/src/sim/courierworld/Hub.java
index 7687090..5527e88 100644
--- a/CourierWorld/src/sim/courierworld/Hub.java
+++ b/CourierWorld/src/sim/courierworld/Hub.java
@@ -1,174 +1,175 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sim.courierworld;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import sim.broker.Broker;
import sim.broker.BrokerWithAuction;
import sim.broker.BrokerWithoutAuction;
import sim.courier.Courier;
import sim.field.grid.Grid2D;
import sim.field.grid.SparseGrid2D;
import sim.field.network.Network;
import sim.user.User;
import sim.util.Bag;
/**
*
* @author indranil
*/
public class Hub
{
public CourierWorld state;
public List<Courier> localCouriers;// the couriers in the local substrate of this hub
public List<Broker> brokers; // the local brokers for this hub
public List<Node> localNodes; // local nodes that branch out from this hub
public Node myNode;
Hub(CourierWorld state)
{
this.state = state;
}
public void setup(int useIndex)
{
boolean isAdded = false;
int randx = 0, randy = 0;
brokers = new ArrayList<>();
brokers.add(new BrokerWithAuction());
brokers.add(new BrokerWithoutAuction());
localCouriers = new ArrayList<>();
for (int i = 0; i < state.maxNumCouriersPerHub; i++)
{
localCouriers.add(new Courier(false));
}
// first we generate an (x,y) coordinate for the hub
// ensuring that it is the correct distance away from other hubs
while (!isAdded)
{
isAdded = true;
randx = state.random.nextInt(state.grid.getWidth());
randy = state.random.nextInt(state.grid.getHeight());
Bag neighbr = new Bag();
neighbr = state.grid.getMooreNeighbors(randx, randy, state.distFromHubs, Grid2D.BOUNDED, neighbr, null, null);
if (!neighbr.isEmpty())
{
for (int i = 0; i < neighbr.numObjs; i++)
{
if (((Node) neighbr.get(i)).isHub())
{
isAdded = false;
break;
}
}
}
}
// we create a node to hold this (the network is filled only user nodes
// and hub nodes)
Node hubNode = new Node(this);
myNode = hubNode;
// add the hub to the grid and the network
state.grid.setObjectLocation(hubNode, randx, randy);
// Now we are going to create the local cliques
// specific to the hub. These nodes are user nodes
// they will eventually have couriers.
double probGenNode = 0.8;
int cours[] = new int[state.maxNumCouriersPerHub];
// indices into localCouriers
for (int i = 0; i < cours.length; i++)
{
cours[i] = i;
}
int courierCount = 0;
localNodes = new ArrayList<>();
for (int i = 0; i < state.numLocalNode; i++)
{
if (state.random.nextDouble() < probGenNode)
{
User user = new User(state.numMaxPkgs, useIndex, hubNode, state.maxPolicyVal*state.random.nextDouble());
Node userNode = new Node(user);
int nodex = -1, nodey = -1;
while (!(nodex >= 0 && nodex < state.grid.getWidth() && nodey >= 0 && nodey < state.grid.getHeight()))
{
nodex = randx + (int) ((1.0 - 2.0 * state.random.nextDouble()) * state.localCliqueSize);
nodey = randy + (int) ((1.0 - 2.0 * state.random.nextDouble()) * state.localCliqueSize);
if (!(state.grid.getObjectsAtLocation(nodex, nodey) == null))
{
nodex = -1;//to look for another location
}
}
// added local node to grid
state.grid.setObjectLocation(userNode, nodex, nodey);
- if (courierCount > state.maxNumCouriersPerHub)
+ // now add the couriers that service that user
+ if (courierCount >= state.maxNumCouriersPerHub)
{
// add random number of couriers to the userNode
int numCouriers = state.random.nextInt(state.maxNumCouriersPerNode - state.minNumCouriersPerNode) + state.minNumCouriersPerNode;
// shuffle the couriers indices
for (int j = 0; j < state.maxNumCouriersPerHub; j++)
{
int shuffle = state.random.nextInt(state.maxNumCouriersPerHub - j) + j;
cours[j] = cours[shuffle];
}
for (int j = 0; j < numCouriers; j++)
{
userNode.addCourier(localCouriers.get(cours[j]));
localCouriers.get(cours[j]).addSource(userNode);
}
} else
{
// add the couriers to the node
int numCouriers = state.random.nextInt(state.maxNumCouriersPerNode - state.minNumCouriersPerNode) + state.minNumCouriersPerNode;
int j;
for (j = 0; j < numCouriers; j++)
{
userNode.addCourier(localCouriers.get(cours[j]));
localCouriers.get(courierCount++).addSource(userNode);
if (courierCount >= state.maxNumCouriersPerHub)
{
break;
}
}
numCouriers -= j;
for (int k = 0; k < numCouriers; k++)
{
userNode.addCourier(localCouriers.get(k));
localCouriers.get(k).addSource(userNode);
}
}
localNodes.add(userNode);
useIndex++;
}
}
// Set up the couriers for the local clique
for (Courier curCour : localCouriers)
{
curCour.randInit(localNodes, state, hubNode);
}
}
}
| true | true | public void setup(int useIndex)
{
boolean isAdded = false;
int randx = 0, randy = 0;
brokers = new ArrayList<>();
brokers.add(new BrokerWithAuction());
brokers.add(new BrokerWithoutAuction());
localCouriers = new ArrayList<>();
for (int i = 0; i < state.maxNumCouriersPerHub; i++)
{
localCouriers.add(new Courier(false));
}
// first we generate an (x,y) coordinate for the hub
// ensuring that it is the correct distance away from other hubs
while (!isAdded)
{
isAdded = true;
randx = state.random.nextInt(state.grid.getWidth());
randy = state.random.nextInt(state.grid.getHeight());
Bag neighbr = new Bag();
neighbr = state.grid.getMooreNeighbors(randx, randy, state.distFromHubs, Grid2D.BOUNDED, neighbr, null, null);
if (!neighbr.isEmpty())
{
for (int i = 0; i < neighbr.numObjs; i++)
{
if (((Node) neighbr.get(i)).isHub())
{
isAdded = false;
break;
}
}
}
}
// we create a node to hold this (the network is filled only user nodes
// and hub nodes)
Node hubNode = new Node(this);
myNode = hubNode;
// add the hub to the grid and the network
state.grid.setObjectLocation(hubNode, randx, randy);
// Now we are going to create the local cliques
// specific to the hub. These nodes are user nodes
// they will eventually have couriers.
double probGenNode = 0.8;
int cours[] = new int[state.maxNumCouriersPerHub];
// indices into localCouriers
for (int i = 0; i < cours.length; i++)
{
cours[i] = i;
}
int courierCount = 0;
localNodes = new ArrayList<>();
for (int i = 0; i < state.numLocalNode; i++)
{
if (state.random.nextDouble() < probGenNode)
{
User user = new User(state.numMaxPkgs, useIndex, hubNode, state.maxPolicyVal*state.random.nextDouble());
Node userNode = new Node(user);
int nodex = -1, nodey = -1;
while (!(nodex >= 0 && nodex < state.grid.getWidth() && nodey >= 0 && nodey < state.grid.getHeight()))
{
nodex = randx + (int) ((1.0 - 2.0 * state.random.nextDouble()) * state.localCliqueSize);
nodey = randy + (int) ((1.0 - 2.0 * state.random.nextDouble()) * state.localCliqueSize);
if (!(state.grid.getObjectsAtLocation(nodex, nodey) == null))
{
nodex = -1;//to look for another location
}
}
// added local node to grid
state.grid.setObjectLocation(userNode, nodex, nodey);
if (courierCount > state.maxNumCouriersPerHub)
{
// add random number of couriers to the userNode
int numCouriers = state.random.nextInt(state.maxNumCouriersPerNode - state.minNumCouriersPerNode) + state.minNumCouriersPerNode;
// shuffle the couriers indices
for (int j = 0; j < state.maxNumCouriersPerHub; j++)
{
int shuffle = state.random.nextInt(state.maxNumCouriersPerHub - j) + j;
cours[j] = cours[shuffle];
}
for (int j = 0; j < numCouriers; j++)
{
userNode.addCourier(localCouriers.get(cours[j]));
localCouriers.get(cours[j]).addSource(userNode);
}
} else
{
// add the couriers to the node
int numCouriers = state.random.nextInt(state.maxNumCouriersPerNode - state.minNumCouriersPerNode) + state.minNumCouriersPerNode;
int j;
for (j = 0; j < numCouriers; j++)
{
userNode.addCourier(localCouriers.get(cours[j]));
localCouriers.get(courierCount++).addSource(userNode);
if (courierCount >= state.maxNumCouriersPerHub)
{
break;
}
}
numCouriers -= j;
for (int k = 0; k < numCouriers; k++)
{
userNode.addCourier(localCouriers.get(k));
localCouriers.get(k).addSource(userNode);
}
}
localNodes.add(userNode);
useIndex++;
}
}
// Set up the couriers for the local clique
for (Courier curCour : localCouriers)
{
curCour.randInit(localNodes, state, hubNode);
}
}
| public void setup(int useIndex)
{
boolean isAdded = false;
int randx = 0, randy = 0;
brokers = new ArrayList<>();
brokers.add(new BrokerWithAuction());
brokers.add(new BrokerWithoutAuction());
localCouriers = new ArrayList<>();
for (int i = 0; i < state.maxNumCouriersPerHub; i++)
{
localCouriers.add(new Courier(false));
}
// first we generate an (x,y) coordinate for the hub
// ensuring that it is the correct distance away from other hubs
while (!isAdded)
{
isAdded = true;
randx = state.random.nextInt(state.grid.getWidth());
randy = state.random.nextInt(state.grid.getHeight());
Bag neighbr = new Bag();
neighbr = state.grid.getMooreNeighbors(randx, randy, state.distFromHubs, Grid2D.BOUNDED, neighbr, null, null);
if (!neighbr.isEmpty())
{
for (int i = 0; i < neighbr.numObjs; i++)
{
if (((Node) neighbr.get(i)).isHub())
{
isAdded = false;
break;
}
}
}
}
// we create a node to hold this (the network is filled only user nodes
// and hub nodes)
Node hubNode = new Node(this);
myNode = hubNode;
// add the hub to the grid and the network
state.grid.setObjectLocation(hubNode, randx, randy);
// Now we are going to create the local cliques
// specific to the hub. These nodes are user nodes
// they will eventually have couriers.
double probGenNode = 0.8;
int cours[] = new int[state.maxNumCouriersPerHub];
// indices into localCouriers
for (int i = 0; i < cours.length; i++)
{
cours[i] = i;
}
int courierCount = 0;
localNodes = new ArrayList<>();
for (int i = 0; i < state.numLocalNode; i++)
{
if (state.random.nextDouble() < probGenNode)
{
User user = new User(state.numMaxPkgs, useIndex, hubNode, state.maxPolicyVal*state.random.nextDouble());
Node userNode = new Node(user);
int nodex = -1, nodey = -1;
while (!(nodex >= 0 && nodex < state.grid.getWidth() && nodey >= 0 && nodey < state.grid.getHeight()))
{
nodex = randx + (int) ((1.0 - 2.0 * state.random.nextDouble()) * state.localCliqueSize);
nodey = randy + (int) ((1.0 - 2.0 * state.random.nextDouble()) * state.localCliqueSize);
if (!(state.grid.getObjectsAtLocation(nodex, nodey) == null))
{
nodex = -1;//to look for another location
}
}
// added local node to grid
state.grid.setObjectLocation(userNode, nodex, nodey);
// now add the couriers that service that user
if (courierCount >= state.maxNumCouriersPerHub)
{
// add random number of couriers to the userNode
int numCouriers = state.random.nextInt(state.maxNumCouriersPerNode - state.minNumCouriersPerNode) + state.minNumCouriersPerNode;
// shuffle the couriers indices
for (int j = 0; j < state.maxNumCouriersPerHub; j++)
{
int shuffle = state.random.nextInt(state.maxNumCouriersPerHub - j) + j;
cours[j] = cours[shuffle];
}
for (int j = 0; j < numCouriers; j++)
{
userNode.addCourier(localCouriers.get(cours[j]));
localCouriers.get(cours[j]).addSource(userNode);
}
} else
{
// add the couriers to the node
int numCouriers = state.random.nextInt(state.maxNumCouriersPerNode - state.minNumCouriersPerNode) + state.minNumCouriersPerNode;
int j;
for (j = 0; j < numCouriers; j++)
{
userNode.addCourier(localCouriers.get(cours[j]));
localCouriers.get(courierCount++).addSource(userNode);
if (courierCount >= state.maxNumCouriersPerHub)
{
break;
}
}
numCouriers -= j;
for (int k = 0; k < numCouriers; k++)
{
userNode.addCourier(localCouriers.get(k));
localCouriers.get(k).addSource(userNode);
}
}
localNodes.add(userNode);
useIndex++;
}
}
// Set up the couriers for the local clique
for (Courier curCour : localCouriers)
{
curCour.randInit(localNodes, state, hubNode);
}
}
|
diff --git a/component/web/resources/src/main/java/org/exoplatform/web/application/javascript/JavascriptConfigService.java b/component/web/resources/src/main/java/org/exoplatform/web/application/javascript/JavascriptConfigService.java
index 1034e996b..34abcd512 100644
--- a/component/web/resources/src/main/java/org/exoplatform/web/application/javascript/JavascriptConfigService.java
+++ b/component/web/resources/src/main/java/org/exoplatform/web/application/javascript/JavascriptConfigService.java
@@ -1,389 +1,393 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.web.application.javascript;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.exoplatform.commons.utils.CompositeReader;
import org.exoplatform.commons.utils.PropertyManager;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.portal.resource.AbstractResourceService;
import org.exoplatform.portal.resource.compressor.ResourceCompressor;
import org.exoplatform.web.ControllerContext;
import org.exoplatform.web.controller.router.URIWriter;
import org.gatein.common.logging.Logger;
import org.gatein.common.logging.LoggerFactory;
import org.gatein.portal.controller.resource.ResourceId;
import org.gatein.portal.controller.resource.ResourceScope;
import org.gatein.portal.controller.resource.script.FetchMode;
import org.gatein.portal.controller.resource.script.Module;
import org.gatein.portal.controller.resource.script.ScriptGraph;
import org.gatein.portal.controller.resource.script.ScriptResource;
import org.gatein.wci.WebApp;
import org.gatein.wci.WebAppListener;
import org.gatein.wci.impl.DefaultServletContainerFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.picocontainer.Startable;
public class JavascriptConfigService extends AbstractResourceService implements Startable
{
/** Our logger. */
private final Logger log = LoggerFactory.getLogger(JavascriptConfigService.class);
/** The scripts. */
final ScriptGraph scripts;
/** . */
private final WebAppListener deployer;
/** . */
public static final Comparator<Module> MODULE_COMPARATOR = new Comparator<Module>()
{
public int compare(Module o1, Module o2)
{
return o1.getPriority() - o2.getPriority();
}
};
public JavascriptConfigService(ExoContainerContext context, ResourceCompressor compressor)
{
super(compressor);
//
this.scripts = new ScriptGraph();
this.deployer = new JavascriptConfigDeployer(context.getPortalContainerName(), this);
}
public Collection<String> getAvailableScripts()
{
ArrayList<String> list = new ArrayList<String>();
for (ScriptResource shared : scripts.getResources(ResourceScope.SHARED))
{
list.addAll(shared.getModulesNames());
}
return list;
}
public Collection<String> getAvailableScriptsPaths()
{
ArrayList<Module> sharedModules = new ArrayList<Module>();
for (ScriptResource shared : scripts.getResources(ResourceScope.SHARED))
{
sharedModules.addAll(shared.getModules());
}
Collections.sort(sharedModules, MODULE_COMPARATOR);
List<String> paths = new ArrayList<String>();
for (Module module : sharedModules)
{
paths.add(module.getURI());
}
return paths;
}
public Reader getScript(ResourceId id, String name, Locale locale)
{
ScriptResource script = getResource(id);
if (script != null && !"merged".equals(name))
{
return getJavascript(script, name, locale);
}
else
{
return getScript(id, locale);
}
}
public Reader getScript(ResourceId resourceId, Locale locale)
{
ScriptResource resource = getResource(resourceId);
if (resource != null)
{
List<Module> modules = new ArrayList<Module>(resource.getModules());
Collections.sort(modules, MODULE_COMPARATOR);
ArrayList<Reader> readers = new ArrayList<Reader>(modules.size() * 2);
//
StringBuilder buffer = new StringBuilder();
boolean isModule = FetchMode.ON_LOAD.equals(resource.getFetchMode());
if (isModule)
{
buffer.append("define('").append(resourceId).append("', ");
buffer.append(new JSONArray(resource.getDependencies()));
buffer.append(", function(");
for (ResourceId resId : resource.getDependencies())
{
String alias = resource.getDependencyAlias(resId);
- buffer.append(alias == null ? getResource(resId).getAlias() : alias).append(",");
+ ScriptResource dep = getResource(resId);
+ if (dep != null)
+ {
+ buffer.append(alias == null ? dep.getAlias() : alias).append(",");
+ }
}
- if (resource.getDependencies().size() > 0)
+ if (buffer.charAt(buffer.length() - 1) == ',')
{
buffer.deleteCharAt(buffer.length() - 1);
}
//
buffer.append(") { var ").append(resource.getAlias()).append(" = {};");
}
//
for (Module js : modules)
{
Reader jScript = getJavascript(resource, js.getName(), locale);
if (jScript != null)
{
if (isModule)
{
buffer.append("var tmp = function() {");
}
buffer.append("// Begin ").append(js.getName()).append("\n");
//
readers.add(new StringReader(buffer.toString()));
buffer.setLength(0);
readers.add(jScript);
//
buffer.append("// End ").append(js.getName()).append("\n");
if (isModule)
{
buffer.append("}();for(var prop in tmp){");
buffer.append(resource.getAlias()).append("[prop]=tmp[prop];").append("}");
}
}
}
if (isModule)
{
buffer.append("return ").append(resource.getAlias()).append(";});");
}
readers.add(new StringReader(buffer.toString()));
return new CompositeReader(readers);
}
else
{
return null;
}
}
public Map<String, FetchMode> resolveURLs(
ControllerContext controllerContext,
Map<ResourceId, FetchMode> ids,
boolean merge,
boolean minified,
Locale locale) throws IOException
{
Map<String, FetchMode> urls = new LinkedHashMap<String, FetchMode>();
StringBuilder buffer = new StringBuilder();
URIWriter writer = new URIWriter(buffer);
//
if (ids.size() > 0)
{
ScriptResource resource = getResource(ids.keySet().iterator().next());
//
if (resource != null)
{
FetchMode mode = resource.getFetchMode();
List<Module> modules = resource.getModules();
if (modules.size() > 0 && modules.get(0) instanceof Module.Remote)
{
urls.put(((Module.Remote)modules.get(0)).getURI(), mode);
}
else
{
controllerContext.renderURL(resource.getParameters(minified, locale), writer);
urls.put(buffer.toString(), mode);
buffer.setLength(0);
writer.reset(buffer);
}
}
}
//
return urls;
}
public Map<ScriptResource, FetchMode> resolveIds(Map<ResourceId, FetchMode> ids)
{
return scripts.resolve(ids);
}
public JSONObject getJSConfig(ControllerContext controllerContext, Locale locale) throws Exception
{
JSONObject paths = new JSONObject();
JSONObject shim = new JSONObject();
for (ScriptResource resource : getAllResources())
{
HashMap<ResourceId, FetchMode> ids = new HashMap<ResourceId, FetchMode>();
ids.put(resource.getId(), null);
Map<String, FetchMode> urlMap = resolveURLs(controllerContext, ids, !PropertyManager.isDevelopping(),
!PropertyManager.isDevelopping(), locale);
String url = urlMap.keySet().iterator().next();
//
String name = resource.getId().toString();
paths.put(name, url.substring(0, url.length() - ".js".length()));
//
List<Module> modules = resource.getModules();
if (FetchMode.IMMEDIATE.equals(resource.getFetchMode()) ||
(modules.size() > 0 && modules.get(0) instanceof Module.Remote))
{
JSONArray deps = new JSONArray(resource.getDependencies());
if (deps.length() > 0)
{
shim.put(name, new JSONObject().put("deps", deps));
}
}
}
JSONObject config = new JSONObject();
config.put("paths", paths);
config.put("shim", shim);
return config;
}
private List<ScriptResource> getAllResources()
{
List<ScriptResource> resources = new LinkedList<ScriptResource>();
for (ResourceScope scope : ResourceScope.values())
{
resources.addAll(scripts.getResources(scope));
}
return resources;
}
public ScriptResource getResource(ResourceId resource)
{
return scripts.getResource(resource);
}
//TODO: This method should be removed once there is no call to importJavascript from Groovy template
public ScriptResource getResourceIncludingModule(String moduleName)
{
//We accept repeated graph traversing for the moment
for(ScriptResource sharedRes : scripts.getResources(ResourceScope.SHARED))
{
if(sharedRes.getModule(moduleName) != null)
{
return sharedRes;
}
}
for(ScriptResource portletRes : scripts.getResources(ResourceScope.PORTLET))
{
if(portletRes.getModule(moduleName) != null)
{
return portletRes;
}
}
for(ScriptResource portalRes : scripts.getResources(ResourceScope.PORTAL))
{
if(portalRes.getModule(moduleName) != null)
{
return portalRes;
}
}
return null;
}
public boolean isModuleLoaded(CharSequence module)
{
return getAvailableScripts().contains(module.toString());
}
public boolean isJavascriptLoaded(String path)
{
for (ScriptResource shared : scripts.getResources(ResourceScope.SHARED))
{
for (Module module : shared.getModules())
{
if (module.getURI().equals(path))
{
return true;
}
}
}
return false;
}
/**
* Start service.
* Registry org.exoplatform.web.application.javascript.JavascriptDeployer,
* org.exoplatform.web.application.javascript.JavascriptRemoval into ServletContainer
* @see org.picocontainer.Startable#start()
*/
public void start()
{
log.debug("Registering JavascriptConfigService for servlet container events");
DefaultServletContainerFactory.getInstance().getServletContainer().addWebAppListener(deployer);
}
/**
* Stop service.
* Remove org.exoplatform.web.application.javascript.JavascriptDeployer,
* org.exoplatform.web.application.javascript.JavascriptRemoval from ServletContainer
* @see org.picocontainer.Startable#stop()
*/
public void stop()
{
log.debug("Unregistering JavascriptConfigService for servlet container events");
DefaultServletContainerFactory.getInstance().getServletContainer().removeWebAppListener(deployer);
}
private Reader getJavascript(ScriptResource resource, String moduleName, Locale locale)
{
Module module = resource.getModule(moduleName);
if (module instanceof Module.Local)
{
Module.Local localModule = (Module.Local)module;
final WebApp webApp = contexts.get(localModule.getContextPath());
if (webApp != null)
{
ServletContext sc = webApp.getServletContext();
return localModule.read(locale, sc, webApp.getClassLoader());
}
}
return null;
}
}
| false | true | public Reader getScript(ResourceId resourceId, Locale locale)
{
ScriptResource resource = getResource(resourceId);
if (resource != null)
{
List<Module> modules = new ArrayList<Module>(resource.getModules());
Collections.sort(modules, MODULE_COMPARATOR);
ArrayList<Reader> readers = new ArrayList<Reader>(modules.size() * 2);
//
StringBuilder buffer = new StringBuilder();
boolean isModule = FetchMode.ON_LOAD.equals(resource.getFetchMode());
if (isModule)
{
buffer.append("define('").append(resourceId).append("', ");
buffer.append(new JSONArray(resource.getDependencies()));
buffer.append(", function(");
for (ResourceId resId : resource.getDependencies())
{
String alias = resource.getDependencyAlias(resId);
buffer.append(alias == null ? getResource(resId).getAlias() : alias).append(",");
}
if (resource.getDependencies().size() > 0)
{
buffer.deleteCharAt(buffer.length() - 1);
}
//
buffer.append(") { var ").append(resource.getAlias()).append(" = {};");
}
//
for (Module js : modules)
{
Reader jScript = getJavascript(resource, js.getName(), locale);
if (jScript != null)
{
if (isModule)
{
buffer.append("var tmp = function() {");
}
buffer.append("// Begin ").append(js.getName()).append("\n");
//
readers.add(new StringReader(buffer.toString()));
buffer.setLength(0);
readers.add(jScript);
//
buffer.append("// End ").append(js.getName()).append("\n");
if (isModule)
{
buffer.append("}();for(var prop in tmp){");
buffer.append(resource.getAlias()).append("[prop]=tmp[prop];").append("}");
}
}
}
if (isModule)
{
buffer.append("return ").append(resource.getAlias()).append(";});");
}
readers.add(new StringReader(buffer.toString()));
return new CompositeReader(readers);
}
else
{
return null;
}
}
| public Reader getScript(ResourceId resourceId, Locale locale)
{
ScriptResource resource = getResource(resourceId);
if (resource != null)
{
List<Module> modules = new ArrayList<Module>(resource.getModules());
Collections.sort(modules, MODULE_COMPARATOR);
ArrayList<Reader> readers = new ArrayList<Reader>(modules.size() * 2);
//
StringBuilder buffer = new StringBuilder();
boolean isModule = FetchMode.ON_LOAD.equals(resource.getFetchMode());
if (isModule)
{
buffer.append("define('").append(resourceId).append("', ");
buffer.append(new JSONArray(resource.getDependencies()));
buffer.append(", function(");
for (ResourceId resId : resource.getDependencies())
{
String alias = resource.getDependencyAlias(resId);
ScriptResource dep = getResource(resId);
if (dep != null)
{
buffer.append(alias == null ? dep.getAlias() : alias).append(",");
}
}
if (buffer.charAt(buffer.length() - 1) == ',')
{
buffer.deleteCharAt(buffer.length() - 1);
}
//
buffer.append(") { var ").append(resource.getAlias()).append(" = {};");
}
//
for (Module js : modules)
{
Reader jScript = getJavascript(resource, js.getName(), locale);
if (jScript != null)
{
if (isModule)
{
buffer.append("var tmp = function() {");
}
buffer.append("// Begin ").append(js.getName()).append("\n");
//
readers.add(new StringReader(buffer.toString()));
buffer.setLength(0);
readers.add(jScript);
//
buffer.append("// End ").append(js.getName()).append("\n");
if (isModule)
{
buffer.append("}();for(var prop in tmp){");
buffer.append(resource.getAlias()).append("[prop]=tmp[prop];").append("}");
}
}
}
if (isModule)
{
buffer.append("return ").append(resource.getAlias()).append(";});");
}
readers.add(new StringReader(buffer.toString()));
return new CompositeReader(readers);
}
else
{
return null;
}
}
|
diff --git a/core/src/main/java/com/datasalt/pangool/solr/SolrRecordWriter.java b/core/src/main/java/com/datasalt/pangool/solr/SolrRecordWriter.java
index ce5bea9c..8561e1c3 100644
--- a/core/src/main/java/com/datasalt/pangool/solr/SolrRecordWriter.java
+++ b/core/src/main/java/com/datasalt/pangool/solr/SolrRecordWriter.java
@@ -1,541 +1,542 @@
/**
* Copyright [2012] [Datasalt Systems S.L.]
*
* 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.datasalt.pangool.solr;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Jdk14Logger;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskID;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrResourceLoader;
import com.datasalt.pangool.io.ITuple;
/**
* Instantiate a record writer that will build a Solr index.
*
* A zip file containing the solr config and additional libraries is expected to be passed via the distributed cache.
* The incoming written records are converted via the specified document converter, and written to the index in batches.
* When the job is done, the close copies the index to the destination output file system.
* <p>
* <b>This class has been copied from SOLR-1301 patch although it might be slightly different from it.</b>
* <p>
*/
public class SolrRecordWriter extends RecordWriter<ITuple, NullWritable> {
static final Log LOG = LogFactory.getLog(SolrRecordWriter.class);
public final static List<String> allowedConfigDirectories = new ArrayList<String>(Arrays.asList(new String[] {
"conf", "lib" }));
public final static Set<String> requiredConfigDirectories = new HashSet<String>();
static {
requiredConfigDirectories.add("conf");
}
/**
* Return the list of directories names that may be included in the configuration data passed to the tasks.
*
* @return an UnmodifiableList of directory names
*/
public static List<String> getAllowedConfigDirectories() {
return Collections.unmodifiableList(allowedConfigDirectories);
}
/**
* check if the passed in directory is required to be present in the configuration data set.
*
* @param directory
* The directory to check
* @return true if the directory is required.
*/
public static boolean isRequiredConfigDirectory(final String directory) {
return requiredConfigDirectories.contains(directory);
}
private TupleDocumentConverter converter;
private EmbeddedSolrServer solr;
private SolrCore core;
private FileSystem fs;
private int batchSize;
/** The path that the final index will be written to */
private Path perm;
/** The location in a local temporary directory that the index is built in. */
private Path temp;
/** The directory that the configuration zip file was unpacked into. */
private Path solrHome = null;
private static AtomicLong sequence = new AtomicLong(0);
/**
* If true, create a zip file of the completed index in the final storage location A .zip will be appended to the
* final output name if it is not already present.
*/
private boolean outputZipFile = false;
private Configuration conf;
HeartBeater heartBeater = null;
private BatchWriter batchWriter = null;
private String localSolrHome;
private String zipName;
@SuppressWarnings("rawtypes")
private static HashMap<TaskID, Reducer.Context> contextMap = new HashMap<TaskID, Reducer.Context>();
protected boolean isClosing() {
return closing;
}
protected void setClosing(boolean closing) {
this.closing = closing;
}
/** If true, writes will throw an exception */
volatile boolean closing = false;
private String getOutFileName(TaskAttemptContext context, String prefix) {
TaskID taskId = context.getTaskAttemptID().getTaskID();
int partition = taskId.getId();
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumIntegerDigits(5);
nf.setGroupingUsed(false);
StringBuilder result = new StringBuilder();
result.append(prefix);
result.append("-");
result.append(nf.format(partition));
return result.toString();
}
public SolrRecordWriter(int batchSize, boolean outputZipFile, int threadCount, int queueSize, String localSolrHome,
String zipName, TupleDocumentConverter converter, TaskAttemptContext context) {
this.localSolrHome = localSolrHome;
this.zipName = zipName;
conf = context.getConfiguration();
this.batchSize = batchSize;
setLogLevel("org.apache.solr.core", "WARN");
setLogLevel("org.apache.solr.update", "WARN");
Logger.getLogger("org.apache.solr.core").setLevel(Level.WARN);
Logger.getLogger("org.apache.solr.update").setLevel(Level.WARN);
java.util.logging.Logger.getLogger("org.apache.solr.core").setLevel(java.util.logging.Level.WARNING);
java.util.logging.Logger.getLogger("org.apache.solr.update").setLevel(java.util.logging.Level.WARNING);
setLogLevel("org.apache.solr", "WARN");
Logger.getLogger("org.apache.solr").setLevel(Level.WARN);
java.util.logging.Logger.getLogger("org.apache.solr").setLevel(java.util.logging.Level.WARNING);
heartBeater = new HeartBeater(context);
try {
heartBeater.needHeartBeat();
/** The actual file in hdfs that holds the configuration. */
this.outputZipFile = outputZipFile;
this.fs = FileSystem.get(conf);
perm = new Path(FileOutputFormat.getOutputPath(context), getOutFileName(context, "part"));
// Make a task unique name that contains the actual index output name to
// make debugging simpler
// Note: if using JVM reuse, the sequence number will not be reset for a
// new task using the jvm
temp = conf.getLocalPath("mapred.local.dir",
"solr_" + conf.get("mapred.task.id") + '.' + sequence.incrementAndGet());
if(outputZipFile && !perm.getName().endsWith(".zip")) {
perm = perm.suffix(".zip");
}
+ fs.delete(temp, true); // delete old, if any
fs.delete(perm, true); // delete old, if any
Path local = fs.startLocalOutput(perm, temp);
solrHome = findSolrConfig(conf);
// }
// Verify that the solr home has a conf and lib directory
if(solrHome == null) {
throw new IOException("Unable to find solr home setting");
}
// Setup a solr instance that we can batch writes to
LOG.info("SolrHome: " + solrHome.toUri());
String dataDir = new File(local.toString(), "data").toString();
// copy the schema to the conf dir
File confDir = new File(local.toString(), "conf");
confDir.mkdirs();
File unpackedSolrHome = new File(solrHome.toString());
FileUtils.copyDirectory(new File(unpackedSolrHome, "conf"), confDir);
Properties props = new Properties();
props.setProperty("solr.data.dir", dataDir);
props.setProperty("solr.home", solrHome.toString());
SolrResourceLoader loader = new SolrResourceLoader(solrHome.toString(), null, props);
LOG.info(String
.format(
"Constructed instance information solr.home %s (%s), instance dir %s, conf dir %s, writing index to temporary directory %s, with permdir %s",
solrHome, solrHome.toUri(), loader.getInstanceDir(), loader.getConfigDir(), dataDir, perm));
CoreContainer container = new CoreContainer(loader);
CoreDescriptor descr = new CoreDescriptor(container, "core1", solrHome.toString());
descr.setDataDir(dataDir);
descr.setCoreProperties(props);
core = container.create(descr);
container.register(core, false);
solr = new EmbeddedSolrServer(container, "core1");
batchWriter = new BatchWriter(solr, batchSize, context.getTaskAttemptID().getTaskID(), threadCount, queueSize);
this.converter = converter;
} catch(Exception e) {
throw new IllegalStateException(String.format("Failed to initialize record writer for %s, %s",
context.getJobName(), conf.get("mapred.task.id")), e);
} finally {
heartBeater.cancelHeartBeat();
}
}
public static void incrementCounter(TaskID taskId, String groupName, String counterName, long incr) {
@SuppressWarnings("rawtypes")
Reducer.Context context = contextMap.get(taskId);
if(context != null) {
context.getCounter(groupName, counterName).increment(incr);
}
}
public static void addReducerContext(@SuppressWarnings("rawtypes") Reducer.Context context) {
TaskID taskID = context.getTaskAttemptID().getTaskID();
if(contextMap.get(taskID) == null) {
contextMap.put(taskID, context);
}
}
private Path findSolrConfig(Configuration conf) throws IOException {
Path solrHome = null;
// we added these lines to make this patch work on Hadoop 0.20.2
FileSystem localFs = FileSystem.getLocal(conf);
if(FileSystem.get(conf).equals(localFs)) {
return new Path(localSolrHome);
}
// end-of-addition
Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);
if(localArchives.length == 0) {
throw new IOException(String.format("No local cache archives, where is %s", zipName));
}
for(Path unpackedDir : localArchives) {
// Only logged if debugging
if(LOG.isDebugEnabled()) {
LOG.debug(String.format("Examining unpack directory %s for %s", unpackedDir, zipName));
ProcessBuilder lsCmd = new ProcessBuilder(new String[] { "/bin/ls", "-lR", unpackedDir.toString() });
lsCmd.redirectErrorStream();
Process ls = lsCmd.start();
try {
byte[] buf = new byte[16 * 1024];
InputStream all = ls.getInputStream();
int count;
while((count = all.read(buf)) > 0) {
System.err.write(buf, 0, count);
}
} catch(IOException ignore) {
}
System.err.format("Exit value is %d%n", ls.exitValue());
}
if(unpackedDir.getName().equals(zipName)) {
solrHome = unpackedDir;
break;
}
}
return solrHome;
}
Collection<SolrInputDocument> batch = new ArrayList<SolrInputDocument>();
/**
* Write a record. This method accumulates records in to a batch, and when {@link #batchSize} items are present
* flushes it to the indexer. The writes can take a substantial amount of time, depending on {@link #batchSize}. If
* there is heavy disk contention the writes may take more than the 600 second default timeout.
*/
@Override
public void write(ITuple key, NullWritable value) throws IOException {
if(isClosing()) {
throw new IOException("Index is already closing");
}
heartBeater.needHeartBeat();
try {
try {
batch.add(converter.convert(key, value));
if(batch.size() > batchSize) {
batchWriter.queueBatch(batch);
batch.clear();
}
} catch(SolrServerException e) {
throw new IOException(e);
}
} finally {
heartBeater.cancelHeartBeat();
}
}
@Override
public void close(TaskAttemptContext context) throws IOException, InterruptedException {
if(context != null) {
heartBeater.setProgress(context);
}
try {
if(batch.size() > 0) {
batchWriter.queueBatch(batch);
batch.clear();
}
heartBeater.needHeartBeat();
batchWriter.close(context, core);
if(outputZipFile) {
context.setStatus("Writing Zip");
packZipFile(); // Written to the perm location
} else {
context.setStatus("Copying Index");
fs.completeLocalOutput(perm, temp); // copy to dfs
}
} catch(Exception e) {
if(e instanceof IOException) {
throw (IOException) e;
}
throw new IOException(e);
} finally {
heartBeater.cancelHeartBeat();
File tempFile = new File(temp.toString());
if(tempFile.exists()) {
FileUtils.forceDelete(new File(temp.toString()));
}
}
context.setStatus("Done");
}
private void packZipFile() throws IOException {
FSDataOutputStream out = null;
ZipOutputStream zos = null;
int zipCount = 0;
LOG.info("Packing zip file for " + perm);
try {
out = fs.create(perm, false);
zos = new ZipOutputStream(out);
String name = perm.getName().replaceAll(".zip$", "");
LOG.info("adding index directory" + temp);
zipCount = zipDirectory(conf, zos, name, temp.toString(), temp);
} catch(Throwable ohFoo) {
LOG.error("packZipFile exception", ohFoo);
if(ohFoo instanceof RuntimeException) {
throw (RuntimeException) ohFoo;
}
if(ohFoo instanceof IOException) {
throw (IOException) ohFoo;
}
throw new IOException(ohFoo);
} finally {
if(zos != null) {
if(zipCount == 0) { // If no entries were written, only close out, as
// the zip will throw an error
LOG.error("No entries written to zip file " + perm);
fs.delete(perm, false);
// out.close();
} else {
LOG.info(String.format("Wrote %d items to %s for %s", zipCount, perm, temp));
zos.close();
}
}
}
}
/**
* Write a file to a zip output stream, removing leading path name components from the actual file name when creating
* the zip file entry.
*
* The entry placed in the zip file is <code>baseName</code>/ <code>relativePath</code>, where
* <code>relativePath</code> is constructed by removing a leading <code>root</code> from the path for
* <code>itemToZip</code>.
*
* If <code>itemToZip</code> is an empty directory, it is ignored. If <code>itemToZip</code> is a directory, the
* contents of the directory are added recursively.
*
* @param zos
* The zip output stream
* @param baseName
* The base name to use for the file name entry in the zip file
* @param root
* The path to remove from <code>itemToZip</code> to make a relative path name
* @param itemToZip
* The path to the file to be added to the zip file
* @return the number of entries added
* @throws IOException
*/
static public int zipDirectory(final Configuration conf, final ZipOutputStream zos, final String baseName,
final String root, final Path itemToZip) throws IOException {
LOG.info(String.format("zipDirectory: %s %s %s", baseName, root, itemToZip));
LocalFileSystem localFs = FileSystem.getLocal(conf);
int count = 0;
final FileStatus itemStatus = localFs.getFileStatus(itemToZip);
if(itemStatus.isDir()) {
final FileStatus[] statai = localFs.listStatus(itemToZip);
// Add a directory entry to the zip file
final String zipDirName = relativePathForZipEntry(itemToZip.toUri().getPath(), baseName, root);
final ZipEntry dirZipEntry = new ZipEntry(zipDirName + Path.SEPARATOR_CHAR);
LOG.info(String.format("Adding directory %s to zip", zipDirName));
zos.putNextEntry(dirZipEntry);
zos.closeEntry();
count++;
if(statai == null || statai.length == 0) {
LOG.info(String.format("Skipping empty directory %s", itemToZip));
return count;
}
for(FileStatus status : statai) {
count += zipDirectory(conf, zos, baseName, root, status.getPath());
}
LOG.info(String.format("Wrote %d entries for directory %s", count, itemToZip));
return count;
}
final String inZipPath = relativePathForZipEntry(itemToZip.toUri().getPath(), baseName, root);
if(inZipPath.length() == 0) {
LOG.warn(String.format("Skipping empty zip file path for %s (%s %s)", itemToZip, root, baseName));
return 0;
}
// Take empty files in case the place holder is needed
FSDataInputStream in = null;
try {
in = localFs.open(itemToZip);
final ZipEntry ze = new ZipEntry(inZipPath);
ze.setTime(itemStatus.getModificationTime());
// Comments confuse looking at the zip file
// ze.setComment(itemToZip.toString());
zos.putNextEntry(ze);
IOUtils.copyBytes(in, zos, conf, false);
zos.closeEntry();
LOG.info(String.format("Wrote %d entries for file %s", count, itemToZip));
return 1;
} finally {
in.close();
}
}
static String relativePathForZipEntry(final String rawPath, final String baseName, final String root) {
String relativePath = rawPath.replaceFirst(Pattern.quote(root.toString()), "");
LOG.info(String.format("RawPath %s, baseName %s, root %s, first %s", rawPath, baseName, root, relativePath));
if(relativePath.startsWith(Path.SEPARATOR)) {
relativePath = relativePath.substring(1);
}
LOG.info(String.format("RawPath %s, baseName %s, root %s, post leading slash %s", rawPath, baseName, root,
relativePath));
if(relativePath.isEmpty()) {
LOG.warn(String.format("No data after root (%s) removal from raw path %s", root, rawPath));
return baseName;
}
// Construct the path that will be written to the zip file, including
// removing any leading '/' characters
String inZipPath = baseName + Path.SEPARATOR_CHAR + relativePath;
LOG.info(String.format("RawPath %s, baseName %s, root %s, inZip 1 %s", rawPath, baseName, root, inZipPath));
if(inZipPath.startsWith(Path.SEPARATOR)) {
inZipPath = inZipPath.substring(1);
}
LOG.info(String.format("RawPath %s, baseName %s, root %s, inZip 2 %s", rawPath, baseName, root, inZipPath));
return inZipPath;
}
static boolean setLogLevel(String packageName, String level) {
Log logger = LogFactory.getLog(packageName);
if(logger == null) {
return false;
}
// look for: org.apache.commons.logging.impl.SLF4JLocationAwareLog
LOG.warn("logger class:" + logger.getClass().getName());
if(logger instanceof Log4JLogger) {
process(((Log4JLogger) logger).getLogger(), level);
return true;
}
if(logger instanceof Jdk14Logger) {
process(((Jdk14Logger) logger).getLogger(), level);
return true;
}
return false;
}
public static void process(org.apache.log4j.Logger log, String level) {
if(level != null) {
log.setLevel(org.apache.log4j.Level.toLevel(level));
}
}
public static void process(java.util.logging.Logger log, String level) {
if(level != null) {
log.setLevel(java.util.logging.Level.parse(level));
}
}
}
| true | true | public SolrRecordWriter(int batchSize, boolean outputZipFile, int threadCount, int queueSize, String localSolrHome,
String zipName, TupleDocumentConverter converter, TaskAttemptContext context) {
this.localSolrHome = localSolrHome;
this.zipName = zipName;
conf = context.getConfiguration();
this.batchSize = batchSize;
setLogLevel("org.apache.solr.core", "WARN");
setLogLevel("org.apache.solr.update", "WARN");
Logger.getLogger("org.apache.solr.core").setLevel(Level.WARN);
Logger.getLogger("org.apache.solr.update").setLevel(Level.WARN);
java.util.logging.Logger.getLogger("org.apache.solr.core").setLevel(java.util.logging.Level.WARNING);
java.util.logging.Logger.getLogger("org.apache.solr.update").setLevel(java.util.logging.Level.WARNING);
setLogLevel("org.apache.solr", "WARN");
Logger.getLogger("org.apache.solr").setLevel(Level.WARN);
java.util.logging.Logger.getLogger("org.apache.solr").setLevel(java.util.logging.Level.WARNING);
heartBeater = new HeartBeater(context);
try {
heartBeater.needHeartBeat();
/** The actual file in hdfs that holds the configuration. */
this.outputZipFile = outputZipFile;
this.fs = FileSystem.get(conf);
perm = new Path(FileOutputFormat.getOutputPath(context), getOutFileName(context, "part"));
// Make a task unique name that contains the actual index output name to
// make debugging simpler
// Note: if using JVM reuse, the sequence number will not be reset for a
// new task using the jvm
temp = conf.getLocalPath("mapred.local.dir",
"solr_" + conf.get("mapred.task.id") + '.' + sequence.incrementAndGet());
if(outputZipFile && !perm.getName().endsWith(".zip")) {
perm = perm.suffix(".zip");
}
fs.delete(perm, true); // delete old, if any
Path local = fs.startLocalOutput(perm, temp);
solrHome = findSolrConfig(conf);
// }
// Verify that the solr home has a conf and lib directory
if(solrHome == null) {
throw new IOException("Unable to find solr home setting");
}
// Setup a solr instance that we can batch writes to
LOG.info("SolrHome: " + solrHome.toUri());
String dataDir = new File(local.toString(), "data").toString();
// copy the schema to the conf dir
File confDir = new File(local.toString(), "conf");
confDir.mkdirs();
File unpackedSolrHome = new File(solrHome.toString());
FileUtils.copyDirectory(new File(unpackedSolrHome, "conf"), confDir);
Properties props = new Properties();
props.setProperty("solr.data.dir", dataDir);
props.setProperty("solr.home", solrHome.toString());
SolrResourceLoader loader = new SolrResourceLoader(solrHome.toString(), null, props);
LOG.info(String
.format(
"Constructed instance information solr.home %s (%s), instance dir %s, conf dir %s, writing index to temporary directory %s, with permdir %s",
solrHome, solrHome.toUri(), loader.getInstanceDir(), loader.getConfigDir(), dataDir, perm));
CoreContainer container = new CoreContainer(loader);
CoreDescriptor descr = new CoreDescriptor(container, "core1", solrHome.toString());
descr.setDataDir(dataDir);
descr.setCoreProperties(props);
core = container.create(descr);
container.register(core, false);
solr = new EmbeddedSolrServer(container, "core1");
batchWriter = new BatchWriter(solr, batchSize, context.getTaskAttemptID().getTaskID(), threadCount, queueSize);
this.converter = converter;
} catch(Exception e) {
throw new IllegalStateException(String.format("Failed to initialize record writer for %s, %s",
context.getJobName(), conf.get("mapred.task.id")), e);
} finally {
heartBeater.cancelHeartBeat();
}
}
| public SolrRecordWriter(int batchSize, boolean outputZipFile, int threadCount, int queueSize, String localSolrHome,
String zipName, TupleDocumentConverter converter, TaskAttemptContext context) {
this.localSolrHome = localSolrHome;
this.zipName = zipName;
conf = context.getConfiguration();
this.batchSize = batchSize;
setLogLevel("org.apache.solr.core", "WARN");
setLogLevel("org.apache.solr.update", "WARN");
Logger.getLogger("org.apache.solr.core").setLevel(Level.WARN);
Logger.getLogger("org.apache.solr.update").setLevel(Level.WARN);
java.util.logging.Logger.getLogger("org.apache.solr.core").setLevel(java.util.logging.Level.WARNING);
java.util.logging.Logger.getLogger("org.apache.solr.update").setLevel(java.util.logging.Level.WARNING);
setLogLevel("org.apache.solr", "WARN");
Logger.getLogger("org.apache.solr").setLevel(Level.WARN);
java.util.logging.Logger.getLogger("org.apache.solr").setLevel(java.util.logging.Level.WARNING);
heartBeater = new HeartBeater(context);
try {
heartBeater.needHeartBeat();
/** The actual file in hdfs that holds the configuration. */
this.outputZipFile = outputZipFile;
this.fs = FileSystem.get(conf);
perm = new Path(FileOutputFormat.getOutputPath(context), getOutFileName(context, "part"));
// Make a task unique name that contains the actual index output name to
// make debugging simpler
// Note: if using JVM reuse, the sequence number will not be reset for a
// new task using the jvm
temp = conf.getLocalPath("mapred.local.dir",
"solr_" + conf.get("mapred.task.id") + '.' + sequence.incrementAndGet());
if(outputZipFile && !perm.getName().endsWith(".zip")) {
perm = perm.suffix(".zip");
}
fs.delete(temp, true); // delete old, if any
fs.delete(perm, true); // delete old, if any
Path local = fs.startLocalOutput(perm, temp);
solrHome = findSolrConfig(conf);
// }
// Verify that the solr home has a conf and lib directory
if(solrHome == null) {
throw new IOException("Unable to find solr home setting");
}
// Setup a solr instance that we can batch writes to
LOG.info("SolrHome: " + solrHome.toUri());
String dataDir = new File(local.toString(), "data").toString();
// copy the schema to the conf dir
File confDir = new File(local.toString(), "conf");
confDir.mkdirs();
File unpackedSolrHome = new File(solrHome.toString());
FileUtils.copyDirectory(new File(unpackedSolrHome, "conf"), confDir);
Properties props = new Properties();
props.setProperty("solr.data.dir", dataDir);
props.setProperty("solr.home", solrHome.toString());
SolrResourceLoader loader = new SolrResourceLoader(solrHome.toString(), null, props);
LOG.info(String
.format(
"Constructed instance information solr.home %s (%s), instance dir %s, conf dir %s, writing index to temporary directory %s, with permdir %s",
solrHome, solrHome.toUri(), loader.getInstanceDir(), loader.getConfigDir(), dataDir, perm));
CoreContainer container = new CoreContainer(loader);
CoreDescriptor descr = new CoreDescriptor(container, "core1", solrHome.toString());
descr.setDataDir(dataDir);
descr.setCoreProperties(props);
core = container.create(descr);
container.register(core, false);
solr = new EmbeddedSolrServer(container, "core1");
batchWriter = new BatchWriter(solr, batchSize, context.getTaskAttemptID().getTaskID(), threadCount, queueSize);
this.converter = converter;
} catch(Exception e) {
throw new IllegalStateException(String.format("Failed to initialize record writer for %s, %s",
context.getJobName(), conf.get("mapred.task.id")), e);
} finally {
heartBeater.cancelHeartBeat();
}
}
|
diff --git a/Superuser/src/com/koushikdutta/superuser/SettingsFragmentInternal.java b/Superuser/src/com/koushikdutta/superuser/SettingsFragmentInternal.java
index c596c8d..4f764c7 100644
--- a/Superuser/src/com/koushikdutta/superuser/SettingsFragmentInternal.java
+++ b/Superuser/src/com/koushikdutta/superuser/SettingsFragmentInternal.java
@@ -1,439 +1,439 @@
/*
* Copyright (C) 2013 Koushik Dutta (@koush)
*
* 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.koushikdutta.superuser;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import com.koushikdutta.superuser.util.Settings;
import com.koushikdutta.widgets.BetterListFragmentInternal;
import com.koushikdutta.widgets.FragmentInterfaceWrapper;
import com.koushikdutta.widgets.ListItem;
@SuppressLint("ValidFragment")
public class SettingsFragmentInternal extends BetterListFragmentInternal {
public SettingsFragmentInternal(FragmentInterfaceWrapper fragment) {
super(fragment);
}
@Override
protected int getListFragmentResource() {
return R.layout.settings;
}
ListItem pinItem;
void confirmPin(final String pin) {
final Dialog d = new Dialog(getContext());
d.setTitle(R.string.confirm_pin);
d.setContentView(new PinViewHelper((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE), null, null) {
public void onEnter(String password) {
super.onEnter(password);
if (pin.equals(password)) {
Settings.setPin(getActivity(), password);
pinItem.setSummary(Settings.isPinProtected(getActivity()) ? R.string.pin_set : R.string.pin_protection_summary);
if (password != null && password.length() > 0)
Toast.makeText(getActivity(), getString(R.string.pin_set), Toast.LENGTH_SHORT).show();
d.dismiss();
return;
}
Toast.makeText(getActivity(), getString(R.string.pin_mismatch), Toast.LENGTH_SHORT).show();
};
public void onCancel() {
super.onCancel();
d.dismiss();
};
}.getView(), new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
d.show();
}
void setPin() {
final Dialog d = new Dialog(getContext());
d.setTitle(R.string.enter_new_pin);
d.setContentView(new PinViewHelper((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE), null, null) {
public void onEnter(String password) {
super.onEnter(password);
confirmPin(password);
d.dismiss();
};
public void onCancel() {
super.onCancel();
d.dismiss();
};
}.getView());
d.show();
}
void checkPin() {
if (Settings.isPinProtected(getActivity())) {
final Dialog d = new Dialog(getContext());
d.setTitle(R.string.enter_pin);
d.setContentView(new PinViewHelper((LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE), null, null) {
public void onEnter(String password) {
super.onEnter(password);
if (Settings.checkPin(getActivity(), password)) {
super.onEnter(password);
Settings.setPin(getActivity(), null);
pinItem.setSummary(R.string.pin_protection_summary);
Toast.makeText(getActivity(), getString(R.string.pin_disabled), Toast.LENGTH_SHORT).show();
d.dismiss();
return;
}
Toast.makeText(getActivity(), getString(R.string.incorrect_pin), Toast.LENGTH_SHORT).show();
};
public void onCancel() {
super.onCancel();
d.dismiss();
};
}.getView(), new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
d.show();
}
else {
setPin();
}
}
@Override
protected void onCreate(Bundle savedInstanceState, View view) {
super.onCreate(savedInstanceState, view);
// NOTE to future koush
// dark icons use the color #f3f3f3
addItem(R.string.security, new ListItem(this, R.string.superuser_access, 0, 0) {
void update() {
switch (Settings.getSuperuserAccess()) {
case Settings.SUPERUSER_ACCESS_ADB_ONLY:
setSummary(R.string.adb_only);
break;
case Settings.SUPERUSER_ACCESS_APPS_ONLY:
setSummary(R.string.apps_only);
break;
case Settings.SUPERUSER_ACCESS_APPS_AND_ADB:
setSummary(R.string.apps_and_adb);
break;
case Settings.SUPERUSER_ACCESS_DISABLED:
- setSummary(R.string.disabled);
+ setSummary(R.string.access_disabled);
break;
default:
setSummary(R.string.apps_and_adb);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.superuser_access);
- String[] items = new String[] { getString(R.string.disabled), getString(R.string.apps_only), getString(R.string.adb_only), getString(R.string.apps_and_adb) };
+ String[] items = new String[] { getString(R.string.access_disabled), getString(R.string.apps_only), getString(R.string.adb_only), getString(R.string.apps_and_adb) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_DISABLED);
break;
case 1:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_APPS_ONLY);
break;
case 2:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_ADB_ONLY);
break;
case 3:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_APPS_AND_ADB);
break;
}
update();
}
});
builder.create().show();
}
}).setAttrDrawable(R.attr.toggleIcon);
if (Settings.getMultiuserMode(getActivity()) != Settings.MULTIUSER_MODE_NONE) {
addItem(R.string.security, new ListItem(this, R.string.multiuser_policy, 0) {
void update() {
int res = -1;
switch (Settings.getMultiuserMode(getActivity())) {
case Settings.MULTIUSER_MODE_OWNER_MANAGED:
res = R.string.multiuser_owner_managed_summary;
break;
case Settings.MULTIUSER_MODE_OWNER_ONLY:
res = R.string.multiuser_owner_only_summary;
break;
case Settings.MULTIUSER_MODE_USER:
res = R.string.multiuser_user_summary;
break;
}
if (!Helper.isAdminUser(getActivity())) {
setEnabled(false);
String s = "";
if (res != -1)
s = getString(res) + "\n";
setSummary(s + getString(R.string.multiuser_require_owner));
}
else {
if (res != -1)
setSummary(res);
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.multiuser_policy);
String[] items = new String[] { getString(R.string.multiuser_owner_only), getString(R.string.multiuser_owner_managed), getString(R.string.multiuser_user) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_OWNER_ONLY);
break;
case 1:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_OWNER_MANAGED);
break;
case 2:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_USER);
break;
}
update();
}
});
builder.create().show();
}
}).setAttrDrawable(R.attr.multiuserIcon);
}
addItem(R.string.security, new ListItem(this, R.string.declared_permission, R.string.declared_permission_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
Settings.setRequirePermission(getActivity(), getChecked());
}
})
.setAttrDrawable(R.attr.declaredPermissionsIcon)
.setCheckboxVisible(true)
.setChecked(Settings.getRequirePermission(getActivity()));
addItem(R.string.security, new ListItem(this, R.string.automatic_response, 0) {
void update() {
switch (Settings.getAutomaticResponse(getActivity())) {
case Settings.AUTOMATIC_RESPONSE_ALLOW:
setSummary(R.string.automatic_response_allow_summary);
break;
case Settings.AUTOMATIC_RESPONSE_DENY:
setSummary(R.string.automatic_response_deny_summary);
break;
case Settings.AUTOMATIC_RESPONSE_PROMPT:
setSummary(R.string.automatic_response_prompt_summary);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.automatic_response);
String[] items = new String[] { getString(R.string.prompt), getString(R.string.deny), getString(R.string.allow) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_PROMPT);
break;
case 1:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_DENY);
break;
case 2:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_ALLOW);
break;
}
update();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.automaticResponseIcon);
pinItem = addItem(R.string.security, new ListItem(this, R.string.pin_protection, Settings.isPinProtected(getActivity()) ? R.string.pin_set : R.string.pin_protection_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
checkPin();
}
})
.setAttrDrawable(R.attr.pinProtectionIcon);
addItem(R.string.security, new ListItem(this, getString(R.string.request_timeout), getString(R.string.request_timeout_summary, Settings.getRequestTimeout(getActivity()))) {
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.request_timeout);
String[] seconds = new String[3];
for (int i = 0; i < seconds.length; i++) {
seconds[i] = getString(R.string.number_seconds, (i + 1) * 10);
}
builder.setItems(seconds, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Settings.setTimeout(getActivity(), (which + 1) * 10);
setSummary(getString(R.string.request_timeout_summary, Settings.getRequestTimeout(getActivity())));
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.requestTimeoutIcon);
addItem(R.string.settings, new ListItem(this, R.string.logging, R.string.logging_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
Settings.setLogging(getActivity(), getChecked());
}
})
.setAttrDrawable(R.attr.loggingIcon)
.setCheckboxVisible(true)
.setChecked(Settings.getLogging(getActivity()));
addItem(R.string.settings, new ListItem(this, R.string.notifications, 0) {
void update() {
switch (Settings.getNotificationType(getActivity())) {
case Settings.NOTIFICATION_TYPE_NONE:
setSummary(getString(R.string.no_notification));
break;
case Settings.NOTIFICATION_TYPE_NOTIFICATION:
setSummary(getString(R.string.notifications_summary, getString(R.string.notification)));
break;
case Settings.NOTIFICATION_TYPE_TOAST:
setSummary(getString(R.string.notifications_summary, getString(R.string.toast)));
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.notifications);
String[] items = new String[] { getString(R.string.none), getString(R.string.toast), getString(R.string.notification) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_NONE);
break;
case 2:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_NOTIFICATION);
break;
case 1:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_TOAST);
break;
}
update();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.notificationsIcon);
if ("com.koushikdutta.superuser".equals(getActivity().getPackageName())) {
addItem(R.string.settings, new ListItem(this, R.string.theme, 0) {
void update() {
switch (Settings.getTheme(getActivity())) {
case Settings.THEME_DARK:
setSummary(R.string.dark);
break;
default:
setSummary(R.string.light);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.theme);
String[] items = new String[] { getString(R.string.light), getString(R.string.dark) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case Settings.THEME_DARK:
Settings.setTheme(getContext(), Settings.THEME_DARK);
break;
default:
Settings.setTheme(getContext(), Settings.THEME_LIGHT);
break;
}
update();
getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.themeIcon);
}
}
}
| false | true | protected void onCreate(Bundle savedInstanceState, View view) {
super.onCreate(savedInstanceState, view);
// NOTE to future koush
// dark icons use the color #f3f3f3
addItem(R.string.security, new ListItem(this, R.string.superuser_access, 0, 0) {
void update() {
switch (Settings.getSuperuserAccess()) {
case Settings.SUPERUSER_ACCESS_ADB_ONLY:
setSummary(R.string.adb_only);
break;
case Settings.SUPERUSER_ACCESS_APPS_ONLY:
setSummary(R.string.apps_only);
break;
case Settings.SUPERUSER_ACCESS_APPS_AND_ADB:
setSummary(R.string.apps_and_adb);
break;
case Settings.SUPERUSER_ACCESS_DISABLED:
setSummary(R.string.disabled);
break;
default:
setSummary(R.string.apps_and_adb);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.superuser_access);
String[] items = new String[] { getString(R.string.disabled), getString(R.string.apps_only), getString(R.string.adb_only), getString(R.string.apps_and_adb) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_DISABLED);
break;
case 1:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_APPS_ONLY);
break;
case 2:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_ADB_ONLY);
break;
case 3:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_APPS_AND_ADB);
break;
}
update();
}
});
builder.create().show();
}
}).setAttrDrawable(R.attr.toggleIcon);
if (Settings.getMultiuserMode(getActivity()) != Settings.MULTIUSER_MODE_NONE) {
addItem(R.string.security, new ListItem(this, R.string.multiuser_policy, 0) {
void update() {
int res = -1;
switch (Settings.getMultiuserMode(getActivity())) {
case Settings.MULTIUSER_MODE_OWNER_MANAGED:
res = R.string.multiuser_owner_managed_summary;
break;
case Settings.MULTIUSER_MODE_OWNER_ONLY:
res = R.string.multiuser_owner_only_summary;
break;
case Settings.MULTIUSER_MODE_USER:
res = R.string.multiuser_user_summary;
break;
}
if (!Helper.isAdminUser(getActivity())) {
setEnabled(false);
String s = "";
if (res != -1)
s = getString(res) + "\n";
setSummary(s + getString(R.string.multiuser_require_owner));
}
else {
if (res != -1)
setSummary(res);
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.multiuser_policy);
String[] items = new String[] { getString(R.string.multiuser_owner_only), getString(R.string.multiuser_owner_managed), getString(R.string.multiuser_user) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_OWNER_ONLY);
break;
case 1:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_OWNER_MANAGED);
break;
case 2:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_USER);
break;
}
update();
}
});
builder.create().show();
}
}).setAttrDrawable(R.attr.multiuserIcon);
}
addItem(R.string.security, new ListItem(this, R.string.declared_permission, R.string.declared_permission_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
Settings.setRequirePermission(getActivity(), getChecked());
}
})
.setAttrDrawable(R.attr.declaredPermissionsIcon)
.setCheckboxVisible(true)
.setChecked(Settings.getRequirePermission(getActivity()));
addItem(R.string.security, new ListItem(this, R.string.automatic_response, 0) {
void update() {
switch (Settings.getAutomaticResponse(getActivity())) {
case Settings.AUTOMATIC_RESPONSE_ALLOW:
setSummary(R.string.automatic_response_allow_summary);
break;
case Settings.AUTOMATIC_RESPONSE_DENY:
setSummary(R.string.automatic_response_deny_summary);
break;
case Settings.AUTOMATIC_RESPONSE_PROMPT:
setSummary(R.string.automatic_response_prompt_summary);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.automatic_response);
String[] items = new String[] { getString(R.string.prompt), getString(R.string.deny), getString(R.string.allow) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_PROMPT);
break;
case 1:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_DENY);
break;
case 2:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_ALLOW);
break;
}
update();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.automaticResponseIcon);
pinItem = addItem(R.string.security, new ListItem(this, R.string.pin_protection, Settings.isPinProtected(getActivity()) ? R.string.pin_set : R.string.pin_protection_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
checkPin();
}
})
.setAttrDrawable(R.attr.pinProtectionIcon);
addItem(R.string.security, new ListItem(this, getString(R.string.request_timeout), getString(R.string.request_timeout_summary, Settings.getRequestTimeout(getActivity()))) {
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.request_timeout);
String[] seconds = new String[3];
for (int i = 0; i < seconds.length; i++) {
seconds[i] = getString(R.string.number_seconds, (i + 1) * 10);
}
builder.setItems(seconds, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Settings.setTimeout(getActivity(), (which + 1) * 10);
setSummary(getString(R.string.request_timeout_summary, Settings.getRequestTimeout(getActivity())));
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.requestTimeoutIcon);
addItem(R.string.settings, new ListItem(this, R.string.logging, R.string.logging_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
Settings.setLogging(getActivity(), getChecked());
}
})
.setAttrDrawable(R.attr.loggingIcon)
.setCheckboxVisible(true)
.setChecked(Settings.getLogging(getActivity()));
addItem(R.string.settings, new ListItem(this, R.string.notifications, 0) {
void update() {
switch (Settings.getNotificationType(getActivity())) {
case Settings.NOTIFICATION_TYPE_NONE:
setSummary(getString(R.string.no_notification));
break;
case Settings.NOTIFICATION_TYPE_NOTIFICATION:
setSummary(getString(R.string.notifications_summary, getString(R.string.notification)));
break;
case Settings.NOTIFICATION_TYPE_TOAST:
setSummary(getString(R.string.notifications_summary, getString(R.string.toast)));
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.notifications);
String[] items = new String[] { getString(R.string.none), getString(R.string.toast), getString(R.string.notification) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_NONE);
break;
case 2:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_NOTIFICATION);
break;
case 1:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_TOAST);
break;
}
update();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.notificationsIcon);
if ("com.koushikdutta.superuser".equals(getActivity().getPackageName())) {
addItem(R.string.settings, new ListItem(this, R.string.theme, 0) {
void update() {
switch (Settings.getTheme(getActivity())) {
case Settings.THEME_DARK:
setSummary(R.string.dark);
break;
default:
setSummary(R.string.light);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.theme);
String[] items = new String[] { getString(R.string.light), getString(R.string.dark) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case Settings.THEME_DARK:
Settings.setTheme(getContext(), Settings.THEME_DARK);
break;
default:
Settings.setTheme(getContext(), Settings.THEME_LIGHT);
break;
}
update();
getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.themeIcon);
}
}
| protected void onCreate(Bundle savedInstanceState, View view) {
super.onCreate(savedInstanceState, view);
// NOTE to future koush
// dark icons use the color #f3f3f3
addItem(R.string.security, new ListItem(this, R.string.superuser_access, 0, 0) {
void update() {
switch (Settings.getSuperuserAccess()) {
case Settings.SUPERUSER_ACCESS_ADB_ONLY:
setSummary(R.string.adb_only);
break;
case Settings.SUPERUSER_ACCESS_APPS_ONLY:
setSummary(R.string.apps_only);
break;
case Settings.SUPERUSER_ACCESS_APPS_AND_ADB:
setSummary(R.string.apps_and_adb);
break;
case Settings.SUPERUSER_ACCESS_DISABLED:
setSummary(R.string.access_disabled);
break;
default:
setSummary(R.string.apps_and_adb);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.superuser_access);
String[] items = new String[] { getString(R.string.access_disabled), getString(R.string.apps_only), getString(R.string.adb_only), getString(R.string.apps_and_adb) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_DISABLED);
break;
case 1:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_APPS_ONLY);
break;
case 2:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_ADB_ONLY);
break;
case 3:
Settings.setSuperuserAccess(Settings.SUPERUSER_ACCESS_APPS_AND_ADB);
break;
}
update();
}
});
builder.create().show();
}
}).setAttrDrawable(R.attr.toggleIcon);
if (Settings.getMultiuserMode(getActivity()) != Settings.MULTIUSER_MODE_NONE) {
addItem(R.string.security, new ListItem(this, R.string.multiuser_policy, 0) {
void update() {
int res = -1;
switch (Settings.getMultiuserMode(getActivity())) {
case Settings.MULTIUSER_MODE_OWNER_MANAGED:
res = R.string.multiuser_owner_managed_summary;
break;
case Settings.MULTIUSER_MODE_OWNER_ONLY:
res = R.string.multiuser_owner_only_summary;
break;
case Settings.MULTIUSER_MODE_USER:
res = R.string.multiuser_user_summary;
break;
}
if (!Helper.isAdminUser(getActivity())) {
setEnabled(false);
String s = "";
if (res != -1)
s = getString(res) + "\n";
setSummary(s + getString(R.string.multiuser_require_owner));
}
else {
if (res != -1)
setSummary(res);
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.multiuser_policy);
String[] items = new String[] { getString(R.string.multiuser_owner_only), getString(R.string.multiuser_owner_managed), getString(R.string.multiuser_user) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_OWNER_ONLY);
break;
case 1:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_OWNER_MANAGED);
break;
case 2:
Settings.setMultiuserMode(getActivity(), Settings.MULTIUSER_MODE_USER);
break;
}
update();
}
});
builder.create().show();
}
}).setAttrDrawable(R.attr.multiuserIcon);
}
addItem(R.string.security, new ListItem(this, R.string.declared_permission, R.string.declared_permission_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
Settings.setRequirePermission(getActivity(), getChecked());
}
})
.setAttrDrawable(R.attr.declaredPermissionsIcon)
.setCheckboxVisible(true)
.setChecked(Settings.getRequirePermission(getActivity()));
addItem(R.string.security, new ListItem(this, R.string.automatic_response, 0) {
void update() {
switch (Settings.getAutomaticResponse(getActivity())) {
case Settings.AUTOMATIC_RESPONSE_ALLOW:
setSummary(R.string.automatic_response_allow_summary);
break;
case Settings.AUTOMATIC_RESPONSE_DENY:
setSummary(R.string.automatic_response_deny_summary);
break;
case Settings.AUTOMATIC_RESPONSE_PROMPT:
setSummary(R.string.automatic_response_prompt_summary);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.automatic_response);
String[] items = new String[] { getString(R.string.prompt), getString(R.string.deny), getString(R.string.allow) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_PROMPT);
break;
case 1:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_DENY);
break;
case 2:
Settings.setAutomaticResponse(getActivity(), Settings.AUTOMATIC_RESPONSE_ALLOW);
break;
}
update();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.automaticResponseIcon);
pinItem = addItem(R.string.security, new ListItem(this, R.string.pin_protection, Settings.isPinProtected(getActivity()) ? R.string.pin_set : R.string.pin_protection_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
checkPin();
}
})
.setAttrDrawable(R.attr.pinProtectionIcon);
addItem(R.string.security, new ListItem(this, getString(R.string.request_timeout), getString(R.string.request_timeout_summary, Settings.getRequestTimeout(getActivity()))) {
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.request_timeout);
String[] seconds = new String[3];
for (int i = 0; i < seconds.length; i++) {
seconds[i] = getString(R.string.number_seconds, (i + 1) * 10);
}
builder.setItems(seconds, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Settings.setTimeout(getActivity(), (which + 1) * 10);
setSummary(getString(R.string.request_timeout_summary, Settings.getRequestTimeout(getActivity())));
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.requestTimeoutIcon);
addItem(R.string.settings, new ListItem(this, R.string.logging, R.string.logging_summary) {
@Override
public void onClick(View view) {
super.onClick(view);
Settings.setLogging(getActivity(), getChecked());
}
})
.setAttrDrawable(R.attr.loggingIcon)
.setCheckboxVisible(true)
.setChecked(Settings.getLogging(getActivity()));
addItem(R.string.settings, new ListItem(this, R.string.notifications, 0) {
void update() {
switch (Settings.getNotificationType(getActivity())) {
case Settings.NOTIFICATION_TYPE_NONE:
setSummary(getString(R.string.no_notification));
break;
case Settings.NOTIFICATION_TYPE_NOTIFICATION:
setSummary(getString(R.string.notifications_summary, getString(R.string.notification)));
break;
case Settings.NOTIFICATION_TYPE_TOAST:
setSummary(getString(R.string.notifications_summary, getString(R.string.toast)));
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.notifications);
String[] items = new String[] { getString(R.string.none), getString(R.string.toast), getString(R.string.notification) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_NONE);
break;
case 2:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_NOTIFICATION);
break;
case 1:
Settings.setNotificationType(getActivity(), Settings.NOTIFICATION_TYPE_TOAST);
break;
}
update();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.notificationsIcon);
if ("com.koushikdutta.superuser".equals(getActivity().getPackageName())) {
addItem(R.string.settings, new ListItem(this, R.string.theme, 0) {
void update() {
switch (Settings.getTheme(getActivity())) {
case Settings.THEME_DARK:
setSummary(R.string.dark);
break;
default:
setSummary(R.string.light);
break;
}
}
{
update();
}
@Override
public void onClick(View view) {
super.onClick(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.theme);
String[] items = new String[] { getString(R.string.light), getString(R.string.dark) };
builder.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case Settings.THEME_DARK:
Settings.setTheme(getContext(), Settings.THEME_DARK);
break;
default:
Settings.setTheme(getContext(), Settings.THEME_LIGHT);
break;
}
update();
getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
}
});
builder.create().show();
}
})
.setAttrDrawable(R.attr.themeIcon);
}
}
|
diff --git a/src/test/java/com/eyeq/pivot4j/datasource/PooledOlapDataSourceIT.java b/src/test/java/com/eyeq/pivot4j/datasource/PooledOlapDataSourceIT.java
index 65d87cb7..027153c0 100644
--- a/src/test/java/com/eyeq/pivot4j/datasource/PooledOlapDataSourceIT.java
+++ b/src/test/java/com/eyeq/pivot4j/datasource/PooledOlapDataSourceIT.java
@@ -1,82 +1,82 @@
/*
* ====================================================================
* This software is subject to the terms of the Common Public License
* Agreement, available at the following URL:
* http://www.opensource.org/licenses/cpl.html .
* You must accept the terms of that agreement to use this software.
* ====================================================================
*/
package com.eyeq.pivot4j.datasource;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.sql.SQLException;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.junit.Test;
import org.olap4j.OlapConnection;
import com.eyeq.pivot4j.AbstractIntegrationTestCase;
import com.eyeq.pivot4j.datasource.PooledOlapDataSource;
public class PooledOlapDataSourceIT extends AbstractIntegrationTestCase {
/**
* Test method for
* {@link com.eyeq.pivot4j.datasource.AbstractOlapDataSource#getConnection()}
* .
*
* @throws SQLException
*/
@Test
public void testGetConnection() throws SQLException {
GenericObjectPool.Config config = new GenericObjectPool.Config();
config.maxActive = 3;
config.maxIdle = 3;
PooledOlapDataSource dataSource = new PooledOlapDataSource(
- getDataSource());
+ getDataSource(), config);
OlapConnection connection1 = dataSource.getConnection();
OlapConnection connection2 = dataSource.getConnection();
OlapConnection connection3 = dataSource.getConnection();
assertTrue("Invalid connection returned.", connection1.isValid(10));
assertTrue("Invalid connection returned.", connection2.isValid(10));
assertTrue("Invalid connection returned.", connection3.isValid(10));
assertFalse("Closed connection returned.", connection1.isClosed());
assertFalse("Closed connection returned.", connection2.isClosed());
assertFalse("Closed connection returned.", connection3.isClosed());
assertFalse("Should return a new Connection instance.",
connection1.unwrap(OlapConnection.class) == connection2
.unwrap(OlapConnection.class));
assertFalse("Should return a new Connection instance.",
connection2.unwrap(OlapConnection.class) == connection3
.unwrap(OlapConnection.class));
connection3.close();
assertFalse("Connection remains open.", connection3.isClosed());
OlapConnection connection4 = dataSource.getConnection();
assertTrue("Should reuse an existing connection.",
connection3.unwrap(OlapConnection.class) == connection4
.unwrap(OlapConnection.class));
assertFalse("Closed connection returned.", connection4.isClosed());
dataSource.close();
assertFalse(
"Connection remains open after data source has been closed.",
connection1.isClosed());
assertFalse(
"Connection remains open after data source has been closed.",
connection2.isClosed());
assertFalse(
"Connection remains open after data source has been closed.",
connection3.isClosed());
}
}
| true | true | public void testGetConnection() throws SQLException {
GenericObjectPool.Config config = new GenericObjectPool.Config();
config.maxActive = 3;
config.maxIdle = 3;
PooledOlapDataSource dataSource = new PooledOlapDataSource(
getDataSource());
OlapConnection connection1 = dataSource.getConnection();
OlapConnection connection2 = dataSource.getConnection();
OlapConnection connection3 = dataSource.getConnection();
assertTrue("Invalid connection returned.", connection1.isValid(10));
assertTrue("Invalid connection returned.", connection2.isValid(10));
assertTrue("Invalid connection returned.", connection3.isValid(10));
assertFalse("Closed connection returned.", connection1.isClosed());
assertFalse("Closed connection returned.", connection2.isClosed());
assertFalse("Closed connection returned.", connection3.isClosed());
assertFalse("Should return a new Connection instance.",
connection1.unwrap(OlapConnection.class) == connection2
.unwrap(OlapConnection.class));
assertFalse("Should return a new Connection instance.",
connection2.unwrap(OlapConnection.class) == connection3
.unwrap(OlapConnection.class));
connection3.close();
assertFalse("Connection remains open.", connection3.isClosed());
OlapConnection connection4 = dataSource.getConnection();
assertTrue("Should reuse an existing connection.",
connection3.unwrap(OlapConnection.class) == connection4
.unwrap(OlapConnection.class));
assertFalse("Closed connection returned.", connection4.isClosed());
dataSource.close();
assertFalse(
"Connection remains open after data source has been closed.",
connection1.isClosed());
assertFalse(
"Connection remains open after data source has been closed.",
connection2.isClosed());
assertFalse(
"Connection remains open after data source has been closed.",
connection3.isClosed());
}
| public void testGetConnection() throws SQLException {
GenericObjectPool.Config config = new GenericObjectPool.Config();
config.maxActive = 3;
config.maxIdle = 3;
PooledOlapDataSource dataSource = new PooledOlapDataSource(
getDataSource(), config);
OlapConnection connection1 = dataSource.getConnection();
OlapConnection connection2 = dataSource.getConnection();
OlapConnection connection3 = dataSource.getConnection();
assertTrue("Invalid connection returned.", connection1.isValid(10));
assertTrue("Invalid connection returned.", connection2.isValid(10));
assertTrue("Invalid connection returned.", connection3.isValid(10));
assertFalse("Closed connection returned.", connection1.isClosed());
assertFalse("Closed connection returned.", connection2.isClosed());
assertFalse("Closed connection returned.", connection3.isClosed());
assertFalse("Should return a new Connection instance.",
connection1.unwrap(OlapConnection.class) == connection2
.unwrap(OlapConnection.class));
assertFalse("Should return a new Connection instance.",
connection2.unwrap(OlapConnection.class) == connection3
.unwrap(OlapConnection.class));
connection3.close();
assertFalse("Connection remains open.", connection3.isClosed());
OlapConnection connection4 = dataSource.getConnection();
assertTrue("Should reuse an existing connection.",
connection3.unwrap(OlapConnection.class) == connection4
.unwrap(OlapConnection.class));
assertFalse("Closed connection returned.", connection4.isClosed());
dataSource.close();
assertFalse(
"Connection remains open after data source has been closed.",
connection1.isClosed());
assertFalse(
"Connection remains open after data source has been closed.",
connection2.isClosed());
assertFalse(
"Connection remains open after data source has been closed.",
connection3.isClosed());
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandr.java b/Essentials/src/com/earth2me/essentials/commands/Commandr.java
index 7d8ee481..fe2a4e5b 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandr.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandr.java
@@ -1,84 +1,84 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Console;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.IReplyTo;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandr extends EssentialsCommand
{
public Commandr()
{
super("r");
}
@Override
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
String message = getFinalArg(args, 0);
IReplyTo replyTo;
String senderName;
if (sender instanceof Player)
{
User user = ess.getUser(sender);
if (user.isAuthorized("essentials.msg.color"))
{
message = Util.replaceColor(message);
}
else
{
message = Util.stripColor(message);
}
replyTo = user;
senderName = user.getDisplayName();
}
else
{
message = Util.replaceColor(message);
replyTo = Console.getConsoleReplyTo();
senderName = Console.NAME;
}
final CommandSender target = replyTo.getReplyTo();
final String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME;
- if (target == null || ((target instanceof Player) && ((Player)target).isOnline()))
+ if (target == null || ((target instanceof Player) && !((Player)target).isOnline()))
{
throw new Exception(_("foreverAlone"));
}
sender.sendMessage(_("msgFormat", _("me"), targetName, message));
if (target instanceof Player)
{
User player = ess.getUser(target);
if (player.isIgnoredPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME))
{
return;
}
}
target.sendMessage(_("msgFormat", senderName, _("me"), message));
replyTo.setReplyTo(target);
if (target != sender)
{
if (target instanceof Player)
{
ess.getUser((Player)target).setReplyTo(sender);
}
else
{
Console.getConsoleReplyTo().setReplyTo(sender);
}
}
}
}
| true | true | public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
String message = getFinalArg(args, 0);
IReplyTo replyTo;
String senderName;
if (sender instanceof Player)
{
User user = ess.getUser(sender);
if (user.isAuthorized("essentials.msg.color"))
{
message = Util.replaceColor(message);
}
else
{
message = Util.stripColor(message);
}
replyTo = user;
senderName = user.getDisplayName();
}
else
{
message = Util.replaceColor(message);
replyTo = Console.getConsoleReplyTo();
senderName = Console.NAME;
}
final CommandSender target = replyTo.getReplyTo();
final String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME;
if (target == null || ((target instanceof Player) && ((Player)target).isOnline()))
{
throw new Exception(_("foreverAlone"));
}
sender.sendMessage(_("msgFormat", _("me"), targetName, message));
if (target instanceof Player)
{
User player = ess.getUser(target);
if (player.isIgnoredPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME))
{
return;
}
}
target.sendMessage(_("msgFormat", senderName, _("me"), message));
replyTo.setReplyTo(target);
if (target != sender)
{
if (target instanceof Player)
{
ess.getUser((Player)target).setReplyTo(sender);
}
else
{
Console.getConsoleReplyTo().setReplyTo(sender);
}
}
}
| public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 1)
{
throw new NotEnoughArgumentsException();
}
String message = getFinalArg(args, 0);
IReplyTo replyTo;
String senderName;
if (sender instanceof Player)
{
User user = ess.getUser(sender);
if (user.isAuthorized("essentials.msg.color"))
{
message = Util.replaceColor(message);
}
else
{
message = Util.stripColor(message);
}
replyTo = user;
senderName = user.getDisplayName();
}
else
{
message = Util.replaceColor(message);
replyTo = Console.getConsoleReplyTo();
senderName = Console.NAME;
}
final CommandSender target = replyTo.getReplyTo();
final String targetName = target instanceof Player ? ((Player)target).getDisplayName() : Console.NAME;
if (target == null || ((target instanceof Player) && !((Player)target).isOnline()))
{
throw new Exception(_("foreverAlone"));
}
sender.sendMessage(_("msgFormat", _("me"), targetName, message));
if (target instanceof Player)
{
User player = ess.getUser(target);
if (player.isIgnoredPlayer(sender instanceof Player ? ((Player)sender).getName() : Console.NAME))
{
return;
}
}
target.sendMessage(_("msgFormat", senderName, _("me"), message));
replyTo.setReplyTo(target);
if (target != sender)
{
if (target instanceof Player)
{
ess.getUser((Player)target).setReplyTo(sender);
}
else
{
Console.getConsoleReplyTo().setReplyTo(sender);
}
}
}
|
diff --git a/src/com/lostaris/bukkit/MineralScanner/MineralScannerPlayerListener.java b/src/com/lostaris/bukkit/MineralScanner/MineralScannerPlayerListener.java
index 487ee8b..86a04a2 100644
--- a/src/com/lostaris/bukkit/MineralScanner/MineralScannerPlayerListener.java
+++ b/src/com/lostaris/bukkit/MineralScanner/MineralScannerPlayerListener.java
@@ -1,268 +1,268 @@
package com.lostaris.bukkit.MineralScanner;
import java.util.ArrayList;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockRightClickEvent;
/**
* Handle events for all Player related events
* @author Lostaris
*/
public class MineralScannerPlayerListener extends BlockListener {
private final MineralScanner plugin;
private Player player;
public MineralScannerPlayerListener(MineralScanner instance) {
plugin = instance;
}
public void onBlockRightClick(BlockRightClickEvent event) {
player = event.getPlayer();
if (player.getItemInHand().getTypeId() != 345) {
return;
} else {
getCone();
}
}
public Block blockFacing(String dir) {
Location loc = player.getLocation();
Block facing = player.getWorld().getBlockAt((int)Math.floor(loc.getX()),
(int)Math.floor(loc.getY()), (int)Math.floor(loc.getZ())).getFace(BlockFace.valueOf(dir));
return facing;
}
public Block diagFacing(String dir1, String dir2) {
Location loc = player.getLocation();
Block facing = player.getWorld().getBlockAt((int)Math.floor(loc.getX()),
(int)Math.floor(loc.getY()), (int)Math.floor(loc.getZ())).getFace(BlockFace.valueOf(dir1 + "_" + dir2));
return facing;
}
public String direction() {
int r = (int)Math.abs((player.getLocation().getYaw() - 90.0F) % 360.0F);
String dir;
if (r < 23) {
dir = "NORTH";
} else {
if (r < 68) {
dir = "NORTH_EAST";
} else {
if (r < 113) {
dir = "EAST";
} else {
if (r < 158) {
dir = "SOUTH_EAST";
} else {
if (r < 203) {
dir = "SOUTH";
} else {
if (r < 248) {
dir = "SOUTH_WEST";
} else {
if (r < 293) {
dir = "WEST";
}
else {
if (r < 338) {
dir = "NORTH_WEST";
} else {
dir = "NORTH";
}
}
}
}
}
}
}
}
return dir;
}
public void getCone() {
int r = (int)Math.abs((player.getLocation().getYaw() - 90.0F) % 360.0F);
String dir;
if (r < 23) {
dir = "NORTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
} else {
if (r < 68) {
dir = "NORTH_EAST";
//printCone(diagonal("NORTH", "EAST"));
- isMineral(diagonal("NORTH", "EAST"));
+ isMineral(diagonal("NORTH", "WEST"));
} else {
if (r < 113) {
dir = "EAST";
//printCone(eastWest(dir));
- isMineral(eastWest(dir));
+ isMineral(eastWest("WEST"));
} else {
if (r < 158) {
dir = "SOUTH_EAST";
//printCone(diagonal("SOUTH", "EAST"));
- isMineral(diagonal("SOUTH", "EAST"));
+ isMineral(diagonal("SOUTH", "WEST"));
} else {
if (r < 203) {
dir = "SOUTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
} else {
if (r < 248) {
dir = "SOUTH_WEST";
//printCone(diagonal("SOUTH", "WEST"));
- isMineral(diagonal("SOUTH", "WEST"));
+ isMineral(diagonal("SOUTH", "EAST"));
} else {
if (r < 293) {
dir = "WEST";
//printCone(eastWest(dir));
- isMineral(eastWest(dir));
+ isMineral(eastWest("EAST"));
}
else {
if (r < 338) {
dir = "NORTH_WEST";
//printCone(diagonal("NORTH", "WEST"));
- isMineral(diagonal("NORTH", "WEST"));
+ isMineral(diagonal("NORTH", "EAST"));
} else {
dir = "NORTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
}
}
}
}
}
}
}
}
}
public ArrayList<Block> diagonal(String dir1, String dir2) {
ArrayList<Block> scanCone = new ArrayList<Block>();
String dir = dir1 + "_" + dir2;
Block feet = diagFacing(dir1, dir2);
Block head = feet.getFace(BlockFace.UP);
Block aboveHead = head.getFace(BlockFace.UP);
scanCone.add(feet);
scanCone.add(head);
scanCone.add(aboveHead);
// next row
Block feetNext = feet.getFace(BlockFace.valueOf(dir));
Block headNext = head.getFace(BlockFace.valueOf(dir));
Block aboveNext = aboveHead.getFace(BlockFace.valueOf(dir));
scanCone.add(feetNext);
scanCone.add(headNext);
scanCone.add(aboveNext);
// expand out
scanCone.add(feetNext.getFace(BlockFace.valueOf(dir1)));
scanCone.add(feetNext.getFace(BlockFace.valueOf(dir2)));
scanCone.add(headNext.getFace(BlockFace.valueOf(dir1)));
scanCone.add(headNext.getFace(BlockFace.valueOf(dir2)));
scanCone.add(aboveNext.getFace(BlockFace.valueOf(dir1)));
scanCone.add(aboveNext.getFace(BlockFace.valueOf(dir2)));
// last one
scanCone.add(headNext.getFace(BlockFace.valueOf(dir)));
return scanCone;
}
public ArrayList<Block> northSouth(String dir) {
ArrayList<Block> scanCone = new ArrayList<Block>();
Block feet = blockFacing(dir);
Block head = feet.getFace(BlockFace.UP);
Block aboveHead = head.getFace(BlockFace.UP);
scanCone.add(feet);
scanCone.add(head);
scanCone.add(aboveHead);
// next row
Block feetNext = feet.getFace(BlockFace.valueOf(dir));
Block headNext = head.getFace(BlockFace.valueOf(dir));
Block aboveNext = aboveHead.getFace(BlockFace.valueOf(dir));
scanCone.add(feetNext);
scanCone.add(headNext);
scanCone.add(aboveNext);
// expand out
scanCone.add(feetNext.getFace(BlockFace.EAST));
scanCone.add(feetNext.getFace(BlockFace.WEST));
scanCone.add(headNext.getFace(BlockFace.EAST));
scanCone.add(headNext.getFace(BlockFace.WEST));
scanCone.add(aboveNext.getFace(BlockFace.EAST));
scanCone.add(aboveNext.getFace(BlockFace.WEST));
// last row
scanCone.add(headNext.getFace(BlockFace.valueOf(dir)));
scanCone.add(headNext.getFace(BlockFace.valueOf(dir + "_WEST")));
scanCone.add(headNext.getFace(BlockFace.valueOf(dir + "_EAST")));
return scanCone;
}
public ArrayList<Block> eastWest(String dir) {
ArrayList<Block> scanCone = new ArrayList<Block>();
Block feet = blockFacing(dir);
Block head = feet.getFace(BlockFace.UP);
Block aboveHead = head.getFace(BlockFace.UP);
scanCone.add(feet);
scanCone.add(head);
scanCone.add(aboveHead);
// next row
Block feetNext = feet.getFace(BlockFace.valueOf(dir));
Block headNext = head.getFace(BlockFace.valueOf(dir));
Block aboveNext = aboveHead.getFace(BlockFace.valueOf(dir));
scanCone.add(feetNext);
scanCone.add(headNext);
scanCone.add(aboveNext);
// expand out
scanCone.add(feetNext.getFace(BlockFace.NORTH));
scanCone.add(feetNext.getFace(BlockFace.SOUTH));
scanCone.add(headNext.getFace(BlockFace.NORTH));
scanCone.add(headNext.getFace(BlockFace.SOUTH));
scanCone.add(aboveNext.getFace(BlockFace.NORTH));
scanCone.add(aboveNext.getFace(BlockFace.SOUTH));
// last row
scanCone.add(headNext.getFace(BlockFace.valueOf(dir)));
scanCone.add(headNext.getFace(BlockFace.valueOf("NORTH_" +dir)));
scanCone.add(headNext.getFace(BlockFace.valueOf("SOUTH_" + dir)));
return scanCone;
}
public void printCone(ArrayList<Block> cone) {
StringBuilder string = new StringBuilder();
for(Block i: cone) {
string.append(", " + i.getType());
}
player.sendMessage(string.toString());
}
public void isMineral(ArrayList<Block> cone) {
for(Block i: cone) {
if (i.getTypeId() == 14 || i.getTypeId() == 15 || i.getTypeId() == 16
|| i.getTypeId() == 21 || i.getTypeId() == 56 || i.getTypeId() == 73
|| i.getTypeId() == 74) {
player.sendMessage("BEEP");
return;
}
}
}
public void setPlayer(Player player) {
this.player = player;
}
public MineralScanner getPlugin() {
return plugin;
}
}
| false | true | public void getCone() {
int r = (int)Math.abs((player.getLocation().getYaw() - 90.0F) % 360.0F);
String dir;
if (r < 23) {
dir = "NORTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
} else {
if (r < 68) {
dir = "NORTH_EAST";
//printCone(diagonal("NORTH", "EAST"));
isMineral(diagonal("NORTH", "EAST"));
} else {
if (r < 113) {
dir = "EAST";
//printCone(eastWest(dir));
isMineral(eastWest(dir));
} else {
if (r < 158) {
dir = "SOUTH_EAST";
//printCone(diagonal("SOUTH", "EAST"));
isMineral(diagonal("SOUTH", "EAST"));
} else {
if (r < 203) {
dir = "SOUTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
} else {
if (r < 248) {
dir = "SOUTH_WEST";
//printCone(diagonal("SOUTH", "WEST"));
isMineral(diagonal("SOUTH", "WEST"));
} else {
if (r < 293) {
dir = "WEST";
//printCone(eastWest(dir));
isMineral(eastWest(dir));
}
else {
if (r < 338) {
dir = "NORTH_WEST";
//printCone(diagonal("NORTH", "WEST"));
isMineral(diagonal("NORTH", "WEST"));
} else {
dir = "NORTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
}
}
}
}
}
}
}
}
}
| public void getCone() {
int r = (int)Math.abs((player.getLocation().getYaw() - 90.0F) % 360.0F);
String dir;
if (r < 23) {
dir = "NORTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
} else {
if (r < 68) {
dir = "NORTH_EAST";
//printCone(diagonal("NORTH", "EAST"));
isMineral(diagonal("NORTH", "WEST"));
} else {
if (r < 113) {
dir = "EAST";
//printCone(eastWest(dir));
isMineral(eastWest("WEST"));
} else {
if (r < 158) {
dir = "SOUTH_EAST";
//printCone(diagonal("SOUTH", "EAST"));
isMineral(diagonal("SOUTH", "WEST"));
} else {
if (r < 203) {
dir = "SOUTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
} else {
if (r < 248) {
dir = "SOUTH_WEST";
//printCone(diagonal("SOUTH", "WEST"));
isMineral(diagonal("SOUTH", "EAST"));
} else {
if (r < 293) {
dir = "WEST";
//printCone(eastWest(dir));
isMineral(eastWest("EAST"));
}
else {
if (r < 338) {
dir = "NORTH_WEST";
//printCone(diagonal("NORTH", "WEST"));
isMineral(diagonal("NORTH", "EAST"));
} else {
dir = "NORTH";
//printCone(northSouth(dir));
isMineral(northSouth(dir));
}
}
}
}
}
}
}
}
}
|
diff --git a/src/main/java/com/webgearz/tb/HomeController.java b/src/main/java/com/webgearz/tb/HomeController.java
index 07359bf..f3f046b 100644
--- a/src/main/java/com/webgearz/tb/HomeController.java
+++ b/src/main/java/com/webgearz/tb/HomeController.java
@@ -1,27 +1,27 @@
package com.webgearz.tb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value="/", method=RequestMethod.GET)
public String home() {
- logger.info("Welcome home!");
+ logger.info("Welcome home! In 2012");
return "home";
}
}
| true | true | public String home() {
logger.info("Welcome home!");
return "home";
}
| public String home() {
logger.info("Welcome home! In 2012");
return "home";
}
|
diff --git a/src/main/java/hudson/maven/settings/ConfigProviderDelegate.java b/src/main/java/hudson/maven/settings/ConfigProviderDelegate.java
index 0d7bb45..a648093 100644
--- a/src/main/java/hudson/maven/settings/ConfigProviderDelegate.java
+++ b/src/main/java/hudson/maven/settings/ConfigProviderDelegate.java
@@ -1,76 +1,76 @@
/*
The MIT License
Copyright (c) 2012, Dominik Bartholdi
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 hudson.maven.settings;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
public class ConfigProviderDelegate implements ConfigProviderFacade {
private static final Logger LOGGER = Logger.getLogger(ConfigProviderDelegate.class.getName());
private final ConfigProviderFacade cpf;
public ConfigProviderDelegate() {
if (Jenkins.getInstance().getPlugin("config-file-provider") != null) {
cpf = new ConfigProviderMediator();
} else {
- LOGGER.warning("'config-file-provider' plugin installed..., administration of setting.xml will not be available!");
+ LOGGER.warning("'config-file-provider' plugin not installed..., administration of setting.xml will not be available!");
cpf = new DefaultConfigProviderFacade();
}
}
@Override
public List<SettingConfig> getAllGlobalMavenSettingsConfigs() {
return cpf.getAllGlobalMavenSettingsConfigs();
}
@Override
public List<SettingConfig> getAllMavenSettingsConfigs() {
return cpf.getAllMavenSettingsConfigs();
}
@Override
public SettingConfig findConfig(String settingsConfigId) {
return cpf.findConfig(settingsConfigId);
}
private static final class DefaultConfigProviderFacade implements ConfigProviderFacade {
@Override
public List<SettingConfig> getAllGlobalMavenSettingsConfigs() {
return Collections.emptyList();
}
@Override
public List<SettingConfig> getAllMavenSettingsConfigs() {
return Collections.emptyList();
}
@Override
public SettingConfig findConfig(String settingsConfigId) {
return null;
}
}
}
| true | true | public ConfigProviderDelegate() {
if (Jenkins.getInstance().getPlugin("config-file-provider") != null) {
cpf = new ConfigProviderMediator();
} else {
LOGGER.warning("'config-file-provider' plugin installed..., administration of setting.xml will not be available!");
cpf = new DefaultConfigProviderFacade();
}
}
| public ConfigProviderDelegate() {
if (Jenkins.getInstance().getPlugin("config-file-provider") != null) {
cpf = new ConfigProviderMediator();
} else {
LOGGER.warning("'config-file-provider' plugin not installed..., administration of setting.xml will not be available!");
cpf = new DefaultConfigProviderFacade();
}
}
|
diff --git a/src/com/android/camera/Switcher.java b/src/com/android/camera/Switcher.java
index 342f0d68..c88ddb8a 100644
--- a/src/com/android/camera/Switcher.java
+++ b/src/com/android/camera/Switcher.java
@@ -1,184 +1,184 @@
/*
* 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.camera;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
/**
* A widget which switchs between the {@code Camera} and the {@code VideoCamera}
* activities.
*/
public class Switcher extends ImageView implements View.OnTouchListener {
@SuppressWarnings("unused")
private static final String TAG = "Switcher";
/** A callback to be called when the user wants to switch activity. */
public interface OnSwitchListener {
// Returns true if the listener agrees that the switch can be changed.
public boolean onSwitchChanged(Switcher source, boolean onOff);
}
private static final int ANIMATION_SPEED = 200;
private static final long NO_ANIMATION = -1;
private boolean mSwitch = false;
private int mPosition = 0;
private long mAnimationStartTime = NO_ANIMATION;
private int mAnimationStartPosition;
private OnSwitchListener mListener;
public Switcher(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSwitch(boolean onOff) {
if (mSwitch == onOff) return;
mSwitch = onOff;
invalidate();
}
// Try to change the switch position. (The client can veto it.)
private void tryToSetSwitch(boolean onOff) {
try {
if (mSwitch == onOff) return;
if (mListener != null) {
if (!mListener.onSwitchChanged(this, onOff)) {
return;
}
}
mSwitch = onOff;
} finally {
startParkingAnimation();
}
}
public void setOnSwitchListener(OnSwitchListener listener) {
mListener = listener;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) return false;
final int available = getHeight() - getPaddingTop() - getPaddingBottom()
- getDrawable().getIntrinsicHeight();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mAnimationStartTime = NO_ANIMATION;
setPressed(true);
trackTouchEvent(event);
break;
case MotionEvent.ACTION_MOVE:
trackTouchEvent(event);
break;
case MotionEvent.ACTION_UP:
trackTouchEvent(event);
tryToSetSwitch(mPosition >= available / 2);
setPressed(false);
break;
case MotionEvent.ACTION_CANCEL:
tryToSetSwitch(mSwitch);
setPressed(false);
break;
}
return true;
}
private void startParkingAnimation() {
mAnimationStartTime = AnimationUtils.currentAnimationTimeMillis();
mAnimationStartPosition = mPosition;
}
private void trackTouchEvent(MotionEvent event) {
Drawable drawable = getDrawable();
int drawableHeight = drawable.getIntrinsicHeight();
final int height = getHeight();
final int available = height - getPaddingTop() - getPaddingBottom()
- drawableHeight;
int x = (int) event.getY();
mPosition = x - getPaddingTop() - drawableHeight / 2;
if (mPosition < 0) mPosition = 0;
if (mPosition > available) mPosition = available;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
int drawableHeight = drawable.getIntrinsicHeight();
int drawableWidth = drawable.getIntrinsicWidth();
if (drawableWidth == 0 || drawableHeight == 0) {
return; // nothing to draw (empty bounds)
}
final int available = getHeight() - getPaddingTop()
- getPaddingBottom() - drawableHeight;
if (mAnimationStartTime != NO_ANIMATION) {
long time = AnimationUtils.currentAnimationTimeMillis();
int deltaTime = (int) (time - mAnimationStartTime);
mPosition = mAnimationStartPosition +
ANIMATION_SPEED * (mSwitch ? deltaTime : -deltaTime) / 1000;
if (mPosition < 0) mPosition = 0;
if (mPosition > available) mPosition = available;
boolean done = (mPosition == (mSwitch ? available : 0));
if (!done) {
invalidate();
} else {
mAnimationStartTime = NO_ANIMATION;
}
- } else {
+ } else if (!isPressed()){
mPosition = mSwitch ? available : 0;
}
int offsetTop = getPaddingTop() + mPosition;
int offsetLeft = (getWidth()
- drawableWidth - getPaddingLeft() - getPaddingRight()) / 2;
int saveCount = canvas.getSaveCount();
canvas.save();
canvas.translate(offsetLeft, offsetTop);
drawable.draw(canvas);
canvas.restoreToCount(saveCount);
}
// Consume the touch events for the specified view.
public void addTouchView(View v) {
v.setOnTouchListener(this);
}
// This implements View.OnTouchListener so we intercept the touch events
// and pass them to ourselves.
public boolean onTouch(View v, MotionEvent event) {
onTouchEvent(event);
return true;
}
}
| true | true | protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
int drawableHeight = drawable.getIntrinsicHeight();
int drawableWidth = drawable.getIntrinsicWidth();
if (drawableWidth == 0 || drawableHeight == 0) {
return; // nothing to draw (empty bounds)
}
final int available = getHeight() - getPaddingTop()
- getPaddingBottom() - drawableHeight;
if (mAnimationStartTime != NO_ANIMATION) {
long time = AnimationUtils.currentAnimationTimeMillis();
int deltaTime = (int) (time - mAnimationStartTime);
mPosition = mAnimationStartPosition +
ANIMATION_SPEED * (mSwitch ? deltaTime : -deltaTime) / 1000;
if (mPosition < 0) mPosition = 0;
if (mPosition > available) mPosition = available;
boolean done = (mPosition == (mSwitch ? available : 0));
if (!done) {
invalidate();
} else {
mAnimationStartTime = NO_ANIMATION;
}
} else {
mPosition = mSwitch ? available : 0;
}
int offsetTop = getPaddingTop() + mPosition;
int offsetLeft = (getWidth()
- drawableWidth - getPaddingLeft() - getPaddingRight()) / 2;
int saveCount = canvas.getSaveCount();
canvas.save();
canvas.translate(offsetLeft, offsetTop);
drawable.draw(canvas);
canvas.restoreToCount(saveCount);
}
| protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
int drawableHeight = drawable.getIntrinsicHeight();
int drawableWidth = drawable.getIntrinsicWidth();
if (drawableWidth == 0 || drawableHeight == 0) {
return; // nothing to draw (empty bounds)
}
final int available = getHeight() - getPaddingTop()
- getPaddingBottom() - drawableHeight;
if (mAnimationStartTime != NO_ANIMATION) {
long time = AnimationUtils.currentAnimationTimeMillis();
int deltaTime = (int) (time - mAnimationStartTime);
mPosition = mAnimationStartPosition +
ANIMATION_SPEED * (mSwitch ? deltaTime : -deltaTime) / 1000;
if (mPosition < 0) mPosition = 0;
if (mPosition > available) mPosition = available;
boolean done = (mPosition == (mSwitch ? available : 0));
if (!done) {
invalidate();
} else {
mAnimationStartTime = NO_ANIMATION;
}
} else if (!isPressed()){
mPosition = mSwitch ? available : 0;
}
int offsetTop = getPaddingTop() + mPosition;
int offsetLeft = (getWidth()
- drawableWidth - getPaddingLeft() - getPaddingRight()) / 2;
int saveCount = canvas.getSaveCount();
canvas.save();
canvas.translate(offsetLeft, offsetTop);
drawable.draw(canvas);
canvas.restoreToCount(saveCount);
}
|
diff --git a/src/org/genyris/interp/Interpreter.java b/src/org/genyris/interp/Interpreter.java
index c42adcd..a2d47bd 100755
--- a/src/org/genyris/interp/Interpreter.java
+++ b/src/org/genyris/interp/Interpreter.java
@@ -1,171 +1,171 @@
// Copyright 2008 Peter William Birch <[email protected]>
//
// This software may be used and distributed according to the terms
// of the Genyris License, in the file "LICENSE", incorporated herein by reference.
//
package org.genyris.interp;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.genyris.classes.BuiltinClasses;
import org.genyris.core.AccessException;
import org.genyris.core.Constants;
import org.genyris.core.Exp;
import org.genyris.core.Lobject;
import org.genyris.core.Lsymbol;
import org.genyris.core.NilSymbol;
import org.genyris.core.SymbolTable;
import org.genyris.format.PrintFunction;
import org.genyris.interp.builtin.BackquoteFunction;
import org.genyris.interp.builtin.BoundFunction;
import org.genyris.interp.builtin.CarFunction;
import org.genyris.interp.builtin.CdrFunction;
import org.genyris.interp.builtin.ConditionalFunction;
import org.genyris.interp.builtin.ConsFunction;
import org.genyris.interp.builtin.DefFunction;
import org.genyris.interp.builtin.DefMacroFunction;
import org.genyris.interp.builtin.DefineClassFunction;
import org.genyris.interp.builtin.DefineFunction;
import org.genyris.interp.builtin.EqFunction;
import org.genyris.interp.builtin.EqualsFunction;
import org.genyris.interp.builtin.EvalFunction;
import org.genyris.interp.builtin.IdentityFunction;
import org.genyris.interp.builtin.LambdaFunction;
import org.genyris.interp.builtin.LambdamFunction;
import org.genyris.interp.builtin.LambdaqFunction;
import org.genyris.interp.builtin.LengthFunction;
import org.genyris.interp.builtin.ListFunction;
import org.genyris.interp.builtin.LoadFunction;
import org.genyris.interp.builtin.ObjectFunction;
import org.genyris.interp.builtin.QuoteFunction;
import org.genyris.interp.builtin.RemoveTagFunction;
import org.genyris.interp.builtin.ReplaceCarFunction;
import org.genyris.interp.builtin.ReplaceCdrFunction;
import org.genyris.interp.builtin.ReverseFunction;
import org.genyris.interp.builtin.SetFunction;
import org.genyris.interp.builtin.TagFunction;
import org.genyris.io.InStream;
import org.genyris.io.NullWriter;
import org.genyris.io.Parser;
import org.genyris.io.ReadFunction;
import org.genyris.java.JavaClassForName;
import org.genyris.load.SourceLoader;
import org.genyris.logic.AndFunction;
import org.genyris.logic.OrFunction;
import org.genyris.math.DivideFunction;
import org.genyris.math.GreaterThanFunction;
import org.genyris.math.LessThanFunction;
import org.genyris.math.MinusFunction;
import org.genyris.math.MultiplyFunction;
import org.genyris.math.PlusFunction;
import org.genyris.math.RemainderFunction;
public class Interpreter {
Environment _globalEnvironment;
SymbolTable _table;
Writer _defaultOutput;
public NilSymbol NIL;
private Lsymbol TRUE;
public Interpreter() throws GenyrisException {
NIL = new NilSymbol();
_table = new SymbolTable();
_globalEnvironment = new StandardEnvironment(this, NIL);
Lobject SYMBOL = new Lobject(_globalEnvironment);
_defaultOutput = new OutputStreamWriter(System.out);
{
// Circular references between symbols and classnames require manual bootstrap here:
_table.init(NIL);
SYMBOL.defineVariable(_table.internString(Constants.CLASSNAME), _table.internString(Constants.SYMBOL));
}
_globalEnvironment.defineVariable(NIL, NIL);
TRUE = _table.internString("true");
_globalEnvironment.defineVariable(TRUE, TRUE);
_globalEnvironment.defineVariable(_table.internString(Constants.EOF), _table.internString(Constants.EOF));
BuiltinClasses.init(_globalEnvironment);
// TODO all these constructors need to be replaced with a factory and singletons:
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDA), new LazyProcedure(_globalEnvironment, null, new LambdaFunction(this)));
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDAQ), new LazyProcedure(_globalEnvironment, null, new LambdaqFunction(this)));
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDAM), new LazyProcedure(_globalEnvironment, null, new LambdamFunction(this)));
_globalEnvironment.defineVariable(_table.internString("backquote"), new LazyProcedure(_globalEnvironment, null, new BackquoteFunction(this)));
_globalEnvironment.defineVariable(_table.internString("car"), new EagerProcedure(_globalEnvironment, null, new CarFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cdr"), new EagerProcedure(_globalEnvironment, null, new CdrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("rplaca"), new EagerProcedure(_globalEnvironment, null, new ReplaceCarFunction(this)));
_globalEnvironment.defineVariable(_table.internString("rplacd"), new EagerProcedure(_globalEnvironment, null, new ReplaceCdrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cons"), new EagerProcedure(_globalEnvironment, null, new ConsFunction(this)));
_globalEnvironment.defineVariable(_table.internString("quote"), new LazyProcedure(_globalEnvironment, null, new QuoteFunction(this)));
_globalEnvironment.defineVariable(_table.internString("set"), new EagerProcedure(_globalEnvironment, null, new SetFunction(this)));
_globalEnvironment.defineVariable(_table.internString("defvar"), new EagerProcedure(_globalEnvironment, null, new DefineFunction(this)));
_globalEnvironment.defineVariable(_table.internString("def"), new LazyProcedure(_globalEnvironment, null, new DefFunction(this)));
_globalEnvironment.defineVariable(_table.internString("defmacro"), new LazyProcedure(_globalEnvironment, null, new DefMacroFunction(this)));
_globalEnvironment.defineVariable(_table.internString("class"), new LazyProcedure(_globalEnvironment, null, new DefineClassFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cond"), new LazyProcedure(_globalEnvironment, null, new ConditionalFunction(this)));
_globalEnvironment.defineVariable(_table.internString("equal"), new EagerProcedure(_globalEnvironment, null, new EqualsFunction(this)));
_globalEnvironment.defineVariable(_table.internString("eq"), new EagerProcedure(_globalEnvironment, null, new EqFunction(this)));
_globalEnvironment.defineVariable(_table.internString("dict"), new LazyProcedure(_globalEnvironment, null, new ObjectFunction(this)));
- _globalEnvironment.defineVariable(_table.internString("eval"), new LazyProcedure(_globalEnvironment, null, new EvalFunction(this)));
+ _globalEnvironment.defineVariable(_table.internString("eval"), new EagerProcedure(_globalEnvironment, null, new EvalFunction(this)));
_globalEnvironment.defineVariable(_table.internString("the"), new EagerProcedure(_globalEnvironment, null, new IdentityFunction(this)));
_globalEnvironment.defineVariable(_table.internString("list"), new EagerProcedure(_globalEnvironment, null, new ListFunction(this)));
_globalEnvironment.defineVariable(_table.internString("reverse"), new EagerProcedure(_globalEnvironment, null, new ReverseFunction(this)));
_globalEnvironment.defineVariable(_table.internString("length"), new EagerProcedure(_globalEnvironment, null, new LengthFunction(this)));
_globalEnvironment.defineVariable(_table.internString("load"), new EagerProcedure(_globalEnvironment, null, new LoadFunction(this)));
_globalEnvironment.defineVariable(_table.internString("print"), new EagerProcedure(_globalEnvironment, null, new PrintFunction(this)));
_globalEnvironment.defineVariable(_table.internString("read"), new EagerProcedure(_globalEnvironment, null, new ReadFunction(this)));
_globalEnvironment.defineVariable(_table.internString("tag"), new EagerProcedure(_globalEnvironment, null, new TagFunction(this)));
_globalEnvironment.defineVariable(_table.internString("remove-tag"), new EagerProcedure(_globalEnvironment, null, new RemoveTagFunction(this)));
_globalEnvironment.defineVariable(_table.internString("+"), new EagerProcedure(_globalEnvironment, null, new PlusFunction(this)));
_globalEnvironment.defineVariable(_table.internString("-"), new EagerProcedure(_globalEnvironment, null, new MinusFunction(this)));
_globalEnvironment.defineVariable(_table.internString("*"), new EagerProcedure(_globalEnvironment, null, new MultiplyFunction(this)));
_globalEnvironment.defineVariable(_table.internString("/"), new EagerProcedure(_globalEnvironment, null, new DivideFunction(this)));
_globalEnvironment.defineVariable(_table.internString("%"), new EagerProcedure(_globalEnvironment, null, new RemainderFunction(this)));
_globalEnvironment.defineVariable(_table.internString(">"), new EagerProcedure(_globalEnvironment, null, new GreaterThanFunction(this)));
_globalEnvironment.defineVariable(_table.internString("<"), new EagerProcedure(_globalEnvironment, null, new LessThanFunction(this)));
_globalEnvironment.defineVariable(_table.internString("or"), new LazyProcedure(_globalEnvironment, null, new OrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("and"), new LazyProcedure(_globalEnvironment, null, new AndFunction(this)));
_globalEnvironment.defineVariable(_table.internString("bound?"), new LazyProcedure(_globalEnvironment, null, new BoundFunction(this)));
_globalEnvironment.defineVariable(_table.internString("java-class"), new EagerProcedure(_globalEnvironment, null, new JavaClassForName(this)));
}
public Exp init(boolean verbose) throws GenyrisException {
return SourceLoader.loadScriptFromClasspath(this, "org/genyris/load/boot/init.lin", verbose? _defaultOutput: (Writer)new NullWriter());
}
public Parser newParser(InStream input) {
return new Parser(_table, input);
}
public Exp evalInGlobalEnvironment(Exp expression) throws UnboundException, AccessException, GenyrisException {
return Evaluator.eval(_globalEnvironment, expression);
}
public Writer getDefaultOutputWriter() {
return _defaultOutput;
}
public Lsymbol getNil() {
return NIL;
}
public Exp getTrue() {
return TRUE;
}
public Environment getGlobalEnv() {
return _globalEnvironment;
}
public SymbolTable getSymbolTable() {
return _table;
}
}
| true | true | public Interpreter() throws GenyrisException {
NIL = new NilSymbol();
_table = new SymbolTable();
_globalEnvironment = new StandardEnvironment(this, NIL);
Lobject SYMBOL = new Lobject(_globalEnvironment);
_defaultOutput = new OutputStreamWriter(System.out);
{
// Circular references between symbols and classnames require manual bootstrap here:
_table.init(NIL);
SYMBOL.defineVariable(_table.internString(Constants.CLASSNAME), _table.internString(Constants.SYMBOL));
}
_globalEnvironment.defineVariable(NIL, NIL);
TRUE = _table.internString("true");
_globalEnvironment.defineVariable(TRUE, TRUE);
_globalEnvironment.defineVariable(_table.internString(Constants.EOF), _table.internString(Constants.EOF));
BuiltinClasses.init(_globalEnvironment);
// TODO all these constructors need to be replaced with a factory and singletons:
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDA), new LazyProcedure(_globalEnvironment, null, new LambdaFunction(this)));
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDAQ), new LazyProcedure(_globalEnvironment, null, new LambdaqFunction(this)));
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDAM), new LazyProcedure(_globalEnvironment, null, new LambdamFunction(this)));
_globalEnvironment.defineVariable(_table.internString("backquote"), new LazyProcedure(_globalEnvironment, null, new BackquoteFunction(this)));
_globalEnvironment.defineVariable(_table.internString("car"), new EagerProcedure(_globalEnvironment, null, new CarFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cdr"), new EagerProcedure(_globalEnvironment, null, new CdrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("rplaca"), new EagerProcedure(_globalEnvironment, null, new ReplaceCarFunction(this)));
_globalEnvironment.defineVariable(_table.internString("rplacd"), new EagerProcedure(_globalEnvironment, null, new ReplaceCdrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cons"), new EagerProcedure(_globalEnvironment, null, new ConsFunction(this)));
_globalEnvironment.defineVariable(_table.internString("quote"), new LazyProcedure(_globalEnvironment, null, new QuoteFunction(this)));
_globalEnvironment.defineVariable(_table.internString("set"), new EagerProcedure(_globalEnvironment, null, new SetFunction(this)));
_globalEnvironment.defineVariable(_table.internString("defvar"), new EagerProcedure(_globalEnvironment, null, new DefineFunction(this)));
_globalEnvironment.defineVariable(_table.internString("def"), new LazyProcedure(_globalEnvironment, null, new DefFunction(this)));
_globalEnvironment.defineVariable(_table.internString("defmacro"), new LazyProcedure(_globalEnvironment, null, new DefMacroFunction(this)));
_globalEnvironment.defineVariable(_table.internString("class"), new LazyProcedure(_globalEnvironment, null, new DefineClassFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cond"), new LazyProcedure(_globalEnvironment, null, new ConditionalFunction(this)));
_globalEnvironment.defineVariable(_table.internString("equal"), new EagerProcedure(_globalEnvironment, null, new EqualsFunction(this)));
_globalEnvironment.defineVariable(_table.internString("eq"), new EagerProcedure(_globalEnvironment, null, new EqFunction(this)));
_globalEnvironment.defineVariable(_table.internString("dict"), new LazyProcedure(_globalEnvironment, null, new ObjectFunction(this)));
_globalEnvironment.defineVariable(_table.internString("eval"), new LazyProcedure(_globalEnvironment, null, new EvalFunction(this)));
_globalEnvironment.defineVariable(_table.internString("the"), new EagerProcedure(_globalEnvironment, null, new IdentityFunction(this)));
_globalEnvironment.defineVariable(_table.internString("list"), new EagerProcedure(_globalEnvironment, null, new ListFunction(this)));
_globalEnvironment.defineVariable(_table.internString("reverse"), new EagerProcedure(_globalEnvironment, null, new ReverseFunction(this)));
_globalEnvironment.defineVariable(_table.internString("length"), new EagerProcedure(_globalEnvironment, null, new LengthFunction(this)));
_globalEnvironment.defineVariable(_table.internString("load"), new EagerProcedure(_globalEnvironment, null, new LoadFunction(this)));
_globalEnvironment.defineVariable(_table.internString("print"), new EagerProcedure(_globalEnvironment, null, new PrintFunction(this)));
_globalEnvironment.defineVariable(_table.internString("read"), new EagerProcedure(_globalEnvironment, null, new ReadFunction(this)));
_globalEnvironment.defineVariable(_table.internString("tag"), new EagerProcedure(_globalEnvironment, null, new TagFunction(this)));
_globalEnvironment.defineVariable(_table.internString("remove-tag"), new EagerProcedure(_globalEnvironment, null, new RemoveTagFunction(this)));
_globalEnvironment.defineVariable(_table.internString("+"), new EagerProcedure(_globalEnvironment, null, new PlusFunction(this)));
_globalEnvironment.defineVariable(_table.internString("-"), new EagerProcedure(_globalEnvironment, null, new MinusFunction(this)));
_globalEnvironment.defineVariable(_table.internString("*"), new EagerProcedure(_globalEnvironment, null, new MultiplyFunction(this)));
_globalEnvironment.defineVariable(_table.internString("/"), new EagerProcedure(_globalEnvironment, null, new DivideFunction(this)));
_globalEnvironment.defineVariable(_table.internString("%"), new EagerProcedure(_globalEnvironment, null, new RemainderFunction(this)));
_globalEnvironment.defineVariable(_table.internString(">"), new EagerProcedure(_globalEnvironment, null, new GreaterThanFunction(this)));
_globalEnvironment.defineVariable(_table.internString("<"), new EagerProcedure(_globalEnvironment, null, new LessThanFunction(this)));
_globalEnvironment.defineVariable(_table.internString("or"), new LazyProcedure(_globalEnvironment, null, new OrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("and"), new LazyProcedure(_globalEnvironment, null, new AndFunction(this)));
_globalEnvironment.defineVariable(_table.internString("bound?"), new LazyProcedure(_globalEnvironment, null, new BoundFunction(this)));
_globalEnvironment.defineVariable(_table.internString("java-class"), new EagerProcedure(_globalEnvironment, null, new JavaClassForName(this)));
}
| public Interpreter() throws GenyrisException {
NIL = new NilSymbol();
_table = new SymbolTable();
_globalEnvironment = new StandardEnvironment(this, NIL);
Lobject SYMBOL = new Lobject(_globalEnvironment);
_defaultOutput = new OutputStreamWriter(System.out);
{
// Circular references between symbols and classnames require manual bootstrap here:
_table.init(NIL);
SYMBOL.defineVariable(_table.internString(Constants.CLASSNAME), _table.internString(Constants.SYMBOL));
}
_globalEnvironment.defineVariable(NIL, NIL);
TRUE = _table.internString("true");
_globalEnvironment.defineVariable(TRUE, TRUE);
_globalEnvironment.defineVariable(_table.internString(Constants.EOF), _table.internString(Constants.EOF));
BuiltinClasses.init(_globalEnvironment);
// TODO all these constructors need to be replaced with a factory and singletons:
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDA), new LazyProcedure(_globalEnvironment, null, new LambdaFunction(this)));
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDAQ), new LazyProcedure(_globalEnvironment, null, new LambdaqFunction(this)));
_globalEnvironment.defineVariable(_table.internString(Constants.LAMBDAM), new LazyProcedure(_globalEnvironment, null, new LambdamFunction(this)));
_globalEnvironment.defineVariable(_table.internString("backquote"), new LazyProcedure(_globalEnvironment, null, new BackquoteFunction(this)));
_globalEnvironment.defineVariable(_table.internString("car"), new EagerProcedure(_globalEnvironment, null, new CarFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cdr"), new EagerProcedure(_globalEnvironment, null, new CdrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("rplaca"), new EagerProcedure(_globalEnvironment, null, new ReplaceCarFunction(this)));
_globalEnvironment.defineVariable(_table.internString("rplacd"), new EagerProcedure(_globalEnvironment, null, new ReplaceCdrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cons"), new EagerProcedure(_globalEnvironment, null, new ConsFunction(this)));
_globalEnvironment.defineVariable(_table.internString("quote"), new LazyProcedure(_globalEnvironment, null, new QuoteFunction(this)));
_globalEnvironment.defineVariable(_table.internString("set"), new EagerProcedure(_globalEnvironment, null, new SetFunction(this)));
_globalEnvironment.defineVariable(_table.internString("defvar"), new EagerProcedure(_globalEnvironment, null, new DefineFunction(this)));
_globalEnvironment.defineVariable(_table.internString("def"), new LazyProcedure(_globalEnvironment, null, new DefFunction(this)));
_globalEnvironment.defineVariable(_table.internString("defmacro"), new LazyProcedure(_globalEnvironment, null, new DefMacroFunction(this)));
_globalEnvironment.defineVariable(_table.internString("class"), new LazyProcedure(_globalEnvironment, null, new DefineClassFunction(this)));
_globalEnvironment.defineVariable(_table.internString("cond"), new LazyProcedure(_globalEnvironment, null, new ConditionalFunction(this)));
_globalEnvironment.defineVariable(_table.internString("equal"), new EagerProcedure(_globalEnvironment, null, new EqualsFunction(this)));
_globalEnvironment.defineVariable(_table.internString("eq"), new EagerProcedure(_globalEnvironment, null, new EqFunction(this)));
_globalEnvironment.defineVariable(_table.internString("dict"), new LazyProcedure(_globalEnvironment, null, new ObjectFunction(this)));
_globalEnvironment.defineVariable(_table.internString("eval"), new EagerProcedure(_globalEnvironment, null, new EvalFunction(this)));
_globalEnvironment.defineVariable(_table.internString("the"), new EagerProcedure(_globalEnvironment, null, new IdentityFunction(this)));
_globalEnvironment.defineVariable(_table.internString("list"), new EagerProcedure(_globalEnvironment, null, new ListFunction(this)));
_globalEnvironment.defineVariable(_table.internString("reverse"), new EagerProcedure(_globalEnvironment, null, new ReverseFunction(this)));
_globalEnvironment.defineVariable(_table.internString("length"), new EagerProcedure(_globalEnvironment, null, new LengthFunction(this)));
_globalEnvironment.defineVariable(_table.internString("load"), new EagerProcedure(_globalEnvironment, null, new LoadFunction(this)));
_globalEnvironment.defineVariable(_table.internString("print"), new EagerProcedure(_globalEnvironment, null, new PrintFunction(this)));
_globalEnvironment.defineVariable(_table.internString("read"), new EagerProcedure(_globalEnvironment, null, new ReadFunction(this)));
_globalEnvironment.defineVariable(_table.internString("tag"), new EagerProcedure(_globalEnvironment, null, new TagFunction(this)));
_globalEnvironment.defineVariable(_table.internString("remove-tag"), new EagerProcedure(_globalEnvironment, null, new RemoveTagFunction(this)));
_globalEnvironment.defineVariable(_table.internString("+"), new EagerProcedure(_globalEnvironment, null, new PlusFunction(this)));
_globalEnvironment.defineVariable(_table.internString("-"), new EagerProcedure(_globalEnvironment, null, new MinusFunction(this)));
_globalEnvironment.defineVariable(_table.internString("*"), new EagerProcedure(_globalEnvironment, null, new MultiplyFunction(this)));
_globalEnvironment.defineVariable(_table.internString("/"), new EagerProcedure(_globalEnvironment, null, new DivideFunction(this)));
_globalEnvironment.defineVariable(_table.internString("%"), new EagerProcedure(_globalEnvironment, null, new RemainderFunction(this)));
_globalEnvironment.defineVariable(_table.internString(">"), new EagerProcedure(_globalEnvironment, null, new GreaterThanFunction(this)));
_globalEnvironment.defineVariable(_table.internString("<"), new EagerProcedure(_globalEnvironment, null, new LessThanFunction(this)));
_globalEnvironment.defineVariable(_table.internString("or"), new LazyProcedure(_globalEnvironment, null, new OrFunction(this)));
_globalEnvironment.defineVariable(_table.internString("and"), new LazyProcedure(_globalEnvironment, null, new AndFunction(this)));
_globalEnvironment.defineVariable(_table.internString("bound?"), new LazyProcedure(_globalEnvironment, null, new BoundFunction(this)));
_globalEnvironment.defineVariable(_table.internString("java-class"), new EagerProcedure(_globalEnvironment, null, new JavaClassForName(this)));
}
|
diff --git a/src/com/android/camera/CameraSettings.java b/src/com/android/camera/CameraSettings.java
index 905c134b..748d904f 100644
--- a/src/com/android/camera/CameraSettings.java
+++ b/src/com/android/camera/CameraSettings.java
@@ -1,187 +1,193 @@
package com.android.camera;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.os.SystemProperties;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import java.util.ArrayList;
import java.util.List;
public class CameraSettings {
private static final int FIRST_REQUEST_CODE = 100;
private static final int NOT_FOUND = -1;
public static final String KEY_VERSION = "pref_version_key";
public static final String KEY_RECORD_LOCATION =
"pref_camera_recordlocation_key";
public static final String KEY_VIDEO_QUALITY =
"pref_camera_videoquality_key";
public static final String KEY_VIDEO_DURATION =
"pref_camera_video_duration_key";
public static final String KEY_PICTURE_SIZE = "pref_camera_picturesize_key";
public static final String KEY_JPEG_QUALITY = "pref_camera_jpegquality_key";
public static final String KEY_FOCUS_MODE = "pref_camera_focusmode_key";
public static final String KEY_FLASH_MODE = "pref_camera_flashmode_key";
public static final String KEY_COLOR_EFFECT = "pref_camera_coloreffect_key";
public static final String KEY_WHITE_BALANCE =
"pref_camera_whitebalance_key";
public static final String KEY_SCENE_MODE = "pref_camera_scenemode_key";
// TODO: use camera parameters API after it is finished.
public static final String VALUE_FOCUS_INFINITY = "infinity";
public static final String VALUE_FOCUS_AUTO = "auto";
public static final int CURRENT_VERSION = 1;
// max mms video duration in seconds.
public static final int MMS_VIDEO_DURATION =
SystemProperties.getInt("ro.media.enc.lprof.duration", 60);
public static final boolean DEFAULT_VIDEO_QUALITY_VALUE = true;
// MMS video length
public static final int DEFAULT_VIDEO_DURATION_VALUE = -1;
private static final String TAG = "CameraSettings";
private final Context mContext;
private final Parameters mParameters;
private final PreferenceManager mManager;
public CameraSettings(Activity activity, Parameters parameters) {
mContext = activity;
mParameters = parameters;
mManager = new PreferenceManager(activity, FIRST_REQUEST_CODE);
}
public PreferenceScreen getPreferenceScreen(int preferenceRes) {
PreferenceScreen screen = mManager.createPreferenceScreen(mContext);
mManager.inflateFromResource(mContext, preferenceRes, screen);
initPreference(screen);
return screen;
}
private void initPreference(PreferenceScreen screen) {
ListPreference videoDuration =
(ListPreference) screen.findPreference(KEY_VIDEO_DURATION);
ListPreference pictureSize =
(ListPreference) screen.findPreference(KEY_PICTURE_SIZE);
ListPreference whiteBalance =
(ListPreference) screen.findPreference(KEY_WHITE_BALANCE);
ListPreference colorEffect =
(ListPreference) screen.findPreference(KEY_COLOR_EFFECT);
ListPreference sceneMode =
(ListPreference) screen.findPreference(KEY_SCENE_MODE);
+ ListPreference flashMode =
+ (ListPreference) screen.findPreference(KEY_FLASH_MODE);
// Since the screen could be loaded from different resources, we need
// to check if the preference is available here
if (videoDuration != null) {
// Modify video duration settings.
// The first entry is for MMS video duration, and we need to fill
// in the device-dependent value (in seconds).
CharSequence[] entries = videoDuration.getEntries();
entries[0] = String.format(
entries[0].toString(), MMS_VIDEO_DURATION);
}
// Filter out unsupported settings / options
if (pictureSize != null) {
filterUnsupportedOptions(screen, pictureSize, sizeListToStringList(
mParameters.getSupportedPictureSizes()));
}
if (whiteBalance != null) {
filterUnsupportedOptions(screen,
whiteBalance, mParameters.getSupportedWhiteBalance());
}
if (colorEffect != null) {
filterUnsupportedOptions(screen,
colorEffect, mParameters.getSupportedColorEffects());
}
if (sceneMode != null) {
filterUnsupportedOptions(screen,
sceneMode, mParameters.getSupportedSceneModes());
}
+ if (flashMode != null) {
+ filterUnsupportedOptions(screen,
+ flashMode, mParameters.getSupportedFlashModes());
+ }
}
private boolean removePreference(PreferenceGroup group, Preference remove) {
if (group.removePreference(remove)) return true;
for (int i = 0; i < group.getPreferenceCount(); i++) {
final Preference child = group.getPreference(i);
if (child instanceof PreferenceGroup) {
if (removePreference((PreferenceGroup) child, remove)) {
return true;
}
}
}
return false;
}
private void filterUnsupportedOptions(PreferenceScreen screen,
ListPreference pref, List<String> supported) {
// Remove the preference if the parameter is not supported.
if (supported == null) {
removePreference(screen, pref);
return;
}
// Prepare setting entries and entry values.
CharSequence[] allEntries = pref.getEntries();
CharSequence[] allEntryValues = pref.getEntryValues();
ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
ArrayList<CharSequence> entryValues = new ArrayList<CharSequence>();
for (int i = 0, len = allEntryValues.length; i < len; i++) {
if (supported.indexOf(allEntryValues[i].toString()) != NOT_FOUND) {
entries.add(allEntries[i]);
entryValues.add(allEntryValues[i]);
}
}
// Set entries and entry values to list preference.
pref.setEntries(entries.toArray(new CharSequence[entries.size()]));
pref.setEntryValues(entryValues.toArray(
new CharSequence[entryValues.size()]));
// Set the value to the first entry if it is invalid.
String value = pref.getValue();
if (pref.findIndexOfValue(value) == NOT_FOUND) {
pref.setValueIndex(0);
}
}
private static List<String> sizeListToStringList(List<Size> sizes) {
ArrayList<String> list = new ArrayList<String>();
for (Size size : sizes) {
list.add(String.format("%dx%d", size.width, size.height));
}
return list;
}
public static void upgradePreferences(SharedPreferences pref) {
int version;
try {
version = pref.getInt(KEY_VERSION, 0);
} catch (Exception ex) {
version = 0;
}
if (version == 0) {
SharedPreferences.Editor editor = pref.edit();
// For old version, change 1 to -1 for video duration preference.
if (pref.getString(KEY_VIDEO_DURATION, "1").equals("1")) {
editor.putString(KEY_VIDEO_DURATION, "-1");
}
editor.putInt(KEY_VERSION, CURRENT_VERSION);
editor.commit();
}
}
}
| false | true | private void initPreference(PreferenceScreen screen) {
ListPreference videoDuration =
(ListPreference) screen.findPreference(KEY_VIDEO_DURATION);
ListPreference pictureSize =
(ListPreference) screen.findPreference(KEY_PICTURE_SIZE);
ListPreference whiteBalance =
(ListPreference) screen.findPreference(KEY_WHITE_BALANCE);
ListPreference colorEffect =
(ListPreference) screen.findPreference(KEY_COLOR_EFFECT);
ListPreference sceneMode =
(ListPreference) screen.findPreference(KEY_SCENE_MODE);
// Since the screen could be loaded from different resources, we need
// to check if the preference is available here
if (videoDuration != null) {
// Modify video duration settings.
// The first entry is for MMS video duration, and we need to fill
// in the device-dependent value (in seconds).
CharSequence[] entries = videoDuration.getEntries();
entries[0] = String.format(
entries[0].toString(), MMS_VIDEO_DURATION);
}
// Filter out unsupported settings / options
if (pictureSize != null) {
filterUnsupportedOptions(screen, pictureSize, sizeListToStringList(
mParameters.getSupportedPictureSizes()));
}
if (whiteBalance != null) {
filterUnsupportedOptions(screen,
whiteBalance, mParameters.getSupportedWhiteBalance());
}
if (colorEffect != null) {
filterUnsupportedOptions(screen,
colorEffect, mParameters.getSupportedColorEffects());
}
if (sceneMode != null) {
filterUnsupportedOptions(screen,
sceneMode, mParameters.getSupportedSceneModes());
}
}
| private void initPreference(PreferenceScreen screen) {
ListPreference videoDuration =
(ListPreference) screen.findPreference(KEY_VIDEO_DURATION);
ListPreference pictureSize =
(ListPreference) screen.findPreference(KEY_PICTURE_SIZE);
ListPreference whiteBalance =
(ListPreference) screen.findPreference(KEY_WHITE_BALANCE);
ListPreference colorEffect =
(ListPreference) screen.findPreference(KEY_COLOR_EFFECT);
ListPreference sceneMode =
(ListPreference) screen.findPreference(KEY_SCENE_MODE);
ListPreference flashMode =
(ListPreference) screen.findPreference(KEY_FLASH_MODE);
// Since the screen could be loaded from different resources, we need
// to check if the preference is available here
if (videoDuration != null) {
// Modify video duration settings.
// The first entry is for MMS video duration, and we need to fill
// in the device-dependent value (in seconds).
CharSequence[] entries = videoDuration.getEntries();
entries[0] = String.format(
entries[0].toString(), MMS_VIDEO_DURATION);
}
// Filter out unsupported settings / options
if (pictureSize != null) {
filterUnsupportedOptions(screen, pictureSize, sizeListToStringList(
mParameters.getSupportedPictureSizes()));
}
if (whiteBalance != null) {
filterUnsupportedOptions(screen,
whiteBalance, mParameters.getSupportedWhiteBalance());
}
if (colorEffect != null) {
filterUnsupportedOptions(screen,
colorEffect, mParameters.getSupportedColorEffects());
}
if (sceneMode != null) {
filterUnsupportedOptions(screen,
sceneMode, mParameters.getSupportedSceneModes());
}
if (flashMode != null) {
filterUnsupportedOptions(screen,
flashMode, mParameters.getSupportedFlashModes());
}
}
|
diff --git a/beam-pixel-extraction/src/test/java/org/esa/beam/pixex/output/MatchupFormatStrategyTest.java b/beam-pixel-extraction/src/test/java/org/esa/beam/pixex/output/MatchupFormatStrategyTest.java
index b1c275c58..4b7c36140 100644
--- a/beam-pixel-extraction/src/test/java/org/esa/beam/pixex/output/MatchupFormatStrategyTest.java
+++ b/beam-pixel-extraction/src/test/java/org/esa/beam/pixex/output/MatchupFormatStrategyTest.java
@@ -1,81 +1,81 @@
package org.esa.beam.pixex.output;
import org.esa.beam.framework.datamodel.GeoPos;
import org.esa.beam.measurement.Measurement;
import org.esa.beam.measurement.writer.FormatStrategy;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class MatchupFormatStrategyTest {
@Test
public void testWriteMeasurements_oneMeasurement_withNaN() throws Exception {
// preparation
final Number[] values = {12.4, Double.NaN, 1.0345, 7};
final Measurement measurement = new Measurement(14, "name", 13, 1, 1, null, new GeoPos(10, 10), values, true);
final Number[] originalValues = {13.4, Double.NaN, 2.0345, 12};
final Measurement originalMeasurement = new Measurement(14, null, -1, -1, -1, null, new GeoPos(10.1F, 10.01F),
originalValues, new String[] {"sst", "tsm", "pigs", "cows"}, true);
final FormatStrategy pixExFormat = new MatchupFormatStrategy(
new Measurement[]{originalMeasurement},
null, 1, "expression", false);
// execution
final StringWriter stringWriter = new StringWriter();
pixExFormat.writeMeasurements(new PrintWriter(stringWriter), new Measurement[]{measurement});
// verifying
final BufferedReader reader = new BufferedReader(new StringReader(stringWriter.toString()));
String originalMeasurementString = "13.4\t\t2.0345\t12";
String newMeasurementString = "\t13\t14\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t\t1.0345\t7";
assertEquals(originalMeasurementString + newMeasurementString, reader.readLine());
assertNull(reader.readLine());
}
@Test
public void testWriteTwoMeasurements() throws Exception {
final Measurement originalMeasurement1 = createMeasurement(14, new String[]{"sst", "tsm"}, "_1");
final Measurement originalMeasurement2 = createMeasurement(23, new String[]{"pigs", "cows"}, "_2");
final Number[] values = {12.4, 7};
Measurement additionalMeasurement = new Measurement(14, "name", 13, 1, 1, null, new GeoPos(10, 10), values, true);
final FormatStrategy pixExFormat = new MatchupFormatStrategy(
new Measurement[]{
originalMeasurement1,
originalMeasurement2
},
null, 1, "expression", false);
StringWriter stringWriter = new StringWriter();
pixExFormat.writeMeasurements(new PrintWriter(stringWriter), new Measurement[]{additionalMeasurement});
String originalMeasurementString = "value1_1\tvalue2_1\t\t";
- String newMeasurementString = "\t13\t14\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t7";
+ String newMeasurementString = "\t13\t14\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t7\n";
assertEquals(originalMeasurementString + newMeasurementString, stringWriter.toString());
additionalMeasurement = new Measurement(23, "name", 13, 1, 1, null, new GeoPos(10, 10), values, true);
stringWriter = new StringWriter();
pixExFormat.writeMeasurements(new PrintWriter(stringWriter), new Measurement[]{additionalMeasurement});
originalMeasurementString = "\t\tvalue1_2\tvalue2_2";
- newMeasurementString = "\t13\t23\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t7";
+ newMeasurementString = "\t13\t23\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t7\n";
assertEquals(originalMeasurementString + newMeasurementString, stringWriter.toString());
}
private static Measurement createMeasurement(int coordinateId, String[] attributeNames, String msmntIndex) {
final Object[] originalValues = {"value1" + msmntIndex, "value2" + msmntIndex};
return new Measurement(coordinateId, null, -1, -1, -1, null, new GeoPos(10.1F, 10.01F),
originalValues, attributeNames, true);
}
}
| false | true | public void testWriteTwoMeasurements() throws Exception {
final Measurement originalMeasurement1 = createMeasurement(14, new String[]{"sst", "tsm"}, "_1");
final Measurement originalMeasurement2 = createMeasurement(23, new String[]{"pigs", "cows"}, "_2");
final Number[] values = {12.4, 7};
Measurement additionalMeasurement = new Measurement(14, "name", 13, 1, 1, null, new GeoPos(10, 10), values, true);
final FormatStrategy pixExFormat = new MatchupFormatStrategy(
new Measurement[]{
originalMeasurement1,
originalMeasurement2
},
null, 1, "expression", false);
StringWriter stringWriter = new StringWriter();
pixExFormat.writeMeasurements(new PrintWriter(stringWriter), new Measurement[]{additionalMeasurement});
String originalMeasurementString = "value1_1\tvalue2_1\t\t";
String newMeasurementString = "\t13\t14\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t7";
assertEquals(originalMeasurementString + newMeasurementString, stringWriter.toString());
additionalMeasurement = new Measurement(23, "name", 13, 1, 1, null, new GeoPos(10, 10), values, true);
stringWriter = new StringWriter();
pixExFormat.writeMeasurements(new PrintWriter(stringWriter), new Measurement[]{additionalMeasurement});
originalMeasurementString = "\t\tvalue1_2\tvalue2_2";
newMeasurementString = "\t13\t23\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t7";
assertEquals(originalMeasurementString + newMeasurementString, stringWriter.toString());
}
private static Measurement createMeasurement(int coordinateId, String[] attributeNames, String msmntIndex) {
final Object[] originalValues = {"value1" + msmntIndex, "value2" + msmntIndex};
return new Measurement(coordinateId, null, -1, -1, -1, null, new GeoPos(10.1F, 10.01F),
originalValues, attributeNames, true);
}
}
| public void testWriteTwoMeasurements() throws Exception {
final Measurement originalMeasurement1 = createMeasurement(14, new String[]{"sst", "tsm"}, "_1");
final Measurement originalMeasurement2 = createMeasurement(23, new String[]{"pigs", "cows"}, "_2");
final Number[] values = {12.4, 7};
Measurement additionalMeasurement = new Measurement(14, "name", 13, 1, 1, null, new GeoPos(10, 10), values, true);
final FormatStrategy pixExFormat = new MatchupFormatStrategy(
new Measurement[]{
originalMeasurement1,
originalMeasurement2
},
null, 1, "expression", false);
StringWriter stringWriter = new StringWriter();
pixExFormat.writeMeasurements(new PrintWriter(stringWriter), new Measurement[]{additionalMeasurement});
String originalMeasurementString = "value1_1\tvalue2_1\t\t";
String newMeasurementString = "\t13\t14\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t7\n";
assertEquals(originalMeasurementString + newMeasurementString, stringWriter.toString());
additionalMeasurement = new Measurement(23, "name", 13, 1, 1, null, new GeoPos(10, 10), values, true);
stringWriter = new StringWriter();
pixExFormat.writeMeasurements(new PrintWriter(stringWriter), new Measurement[]{additionalMeasurement});
originalMeasurementString = "\t\tvalue1_2\tvalue2_2";
newMeasurementString = "\t13\t23\tname\t10.000000\t10.000000\t1.000\t1.000\t \t \t12.4\t7\n";
assertEquals(originalMeasurementString + newMeasurementString, stringWriter.toString());
}
private static Measurement createMeasurement(int coordinateId, String[] attributeNames, String msmntIndex) {
final Object[] originalValues = {"value1" + msmntIndex, "value2" + msmntIndex};
return new Measurement(coordinateId, null, -1, -1, -1, null, new GeoPos(10.1F, 10.01F),
originalValues, attributeNames, true);
}
}
|
diff --git a/src/com/dmr/ShortLC.java b/src/com/dmr/ShortLC.java
index 06757d5..3679d16 100644
--- a/src/com/dmr/ShortLC.java
+++ b/src/com/dmr/ShortLC.java
@@ -1,299 +1,299 @@
package com.dmr;
public class ShortLC {
private boolean dataReady;
private String line;
private boolean rawData[]=new boolean[69];
private boolean crcResult=false;
private int currentState=-1;
private DMRDecode TtheApp;
// Add data to the Short LC data buffer
// Type 0 if First fragment of LC
// Type 1 if Continuation fragment of LC
// Type 2 if Last fragment of LC
public void addData (boolean[] CACHbuf,int type) {
int a,b=7,rawCounter=0;
dataReady=false;
// First fragment ?
// If so reset the the counters
if (type==0) {
rawCounter=0;
// Ensure nothing else has arrived before
if (currentState!=-1) return;
// Set the current state to 0 to indicate a first fragment has arrived
currentState=0;
// Clear the display line
line="";
}
// Continuation fragments
else if (type==1) {
if (currentState==0) {
rawCounter=17;
currentState=1;
}
else if (currentState==1) {
rawCounter=34;
currentState=2;
}
else if (currentState==-1) {
rawCounter=0;
return;
}
}
// Last fragment
else if (type==2) {
// Ensure that a first fragment and two continuation fragments have arrived
if (currentState!=2) {
currentState=-1;
rawCounter=0;
return;
}
else rawCounter=51;
}
// Add the data
for (a=rawCounter;a<(rawCounter+17);a++) {
// Ignore the TACT
rawData[a]=CACHbuf[b];
b++;
}
// Has the fragment ended ?
if (type==2) {
decode();
currentState=-1;
rawCounter=0;
}
}
// Make the text string available
public String getLine() {
return line;
}
// Tell the main object if decoded data is available
public boolean isDataReady() {
return dataReady;
}
// Tell the main object if the CRC and Hamming checks are OK
public boolean isCRCgood() {
return crcResult;
}
// Clear the data ready boolean
public void clrDataReady() {
dataReady=false;
}
// Deinterleave and error check the short LC
public void decode() {
crcResult=false;
if (shortLCHamming(rawData)==true) {
boolean shortLC[]=deInterleaveShortLC(rawData);
if (shortLCcrc(shortLC)==true) {
line=decodeShortLC(shortLC);
crcResult=true;
}
}
else line="";
dataReady=true;
}
// Deinterleave a Short LC from 4 CACH bursts
private boolean[] deInterleaveShortLC (boolean raw[]) {
int a,pos;
final int sequence[]={
0,4,8,12,16,20,24,28,32,36,40,44,
1,5,9,13,17,21,25,29,33,37,41,45,
2,6,10,14,18,22,26,30,34,38,42,46};
boolean[] deinter=new boolean[36];
for (a=0;a<36;a++) {
pos=sequence[a];
deinter[a]=raw[pos];
}
return deinter;
}
// Hamming check 3 of the 4 CACH rows
private boolean shortLCHamming (boolean raw[]) {
int a,pos;
final int sequence1[]={0,4,8,12,16,20,24,28,32,36,40,44};
final int sequence2[]={1,5,9,13,17,21,25,29,33,37,41,45};
final int sequence3[]={2,6,10,14,18,22,26,30,34,38,42,46};
final int ham1[]={48,52,56,60,64};
final int ham2[]={49,53,57,61,65};
final int ham3[]={50,54,58,62,66};
boolean[] d=new boolean[12];
boolean[] p=new boolean[5];
boolean[] c=new boolean[5];
// Row 1
for (a=0;a<12;a++) {
pos=sequence1[a];
d[a]=raw[pos];
if (a<5) {
pos=ham1[a];
p[a]=raw[pos];
}
}
c[0]=d[0]^d[1]^d[2]^d[3]^d[6]^d[7]^d[9];
c[1]=d[0]^d[1]^d[2]^d[3]^d[4]^d[7]^d[8]^d[10];
c[2]=d[1]^d[2]^d[3]^d[4]^d[5]^d[8]^d[9]^d[11];
c[3]=d[0]^d[1]^d[4]^d[5]^d[7]^d[10];
c[4]=d[0]^d[1]^d[2]^d[5]^d[6]^d[8]^d[11];
for (a=0;a<5;a++) {
if (c[a]!=p[a]) return false;
}
// Row 2
for (a=0;a<12;a++) {
pos=sequence2[a];
d[a]=raw[pos];
if (a<5) {
pos=ham2[a];
p[a]=raw[pos];
}
}
c[0]=d[0]^d[1]^d[2]^d[3]^d[6]^d[7]^d[9];
c[1]=d[0]^d[1]^d[2]^d[3]^d[4]^d[7]^d[8]^d[10];
c[2]=d[1]^d[2]^d[3]^d[4]^d[5]^d[8]^d[9]^d[11];
c[3]=d[0]^d[1]^d[4]^d[5]^d[7]^d[10];
c[4]=d[0]^d[1]^d[2]^d[5]^d[6]^d[8]^d[11];
for (a=0;a<5;a++) {
if (c[a]!=p[a]) return false;
}
// Row 3
for (a=0;a<12;a++) {
pos=sequence3[a];
d[a]=raw[pos];
if (a<5) {
pos=ham3[a];
p[a]=raw[pos];
}
}
c[0]=d[0]^d[1]^d[2]^d[3]^d[6]^d[7]^d[9];
c[1]=d[0]^d[1]^d[2]^d[3]^d[4]^d[7]^d[8]^d[10];
c[2]=d[1]^d[2]^d[3]^d[4]^d[5]^d[8]^d[9]^d[11];
c[3]=d[0]^d[1]^d[4]^d[5]^d[7]^d[10];
c[4]=d[0]^d[1]^d[2]^d[5]^d[6]^d[8]^d[11];
for (a=0;a<5;a++) {
if (c[a]!=p[a]) return false;
}
// All done so must have passed
return true;
}
// Test if the short LC passes its CRC8 test
private boolean shortLCcrc (boolean dataBits[]) {
int a;
crc tCRC=new crc();
tCRC.setCrc8Value(0);
for (a=0;a<dataBits.length;a++) {
tCRC.crc8(dataBits[a]);
}
if (tCRC.getCrc8Value()==0) return true;
else return false;
}
// Decode and display the info in SHORT LC PDUs
private String decodeShortLC (boolean db[]) {
int slco,a;
StringBuilder dline=new StringBuilder(250);
// Calculate the SLCO
if (db[0]==true) slco=8;
else slco=0;
if (db[1]==true) slco=slco+4;
if (db[2]==true) slco=slco+2;
if (db[3]==true) slco++;
// Short LC Types
if (slco==0) {
dline.append("Nul_Msg");
}
else if (slco==1) {
int addr1,addr2,inf;
dline.append("Act_Updt - ");
// Slot 1
if (db[4]==true) inf=8;
else inf=0;
if (db[5]==true) inf=inf+4;
if (db[6]==true) inf=inf+2;
if (db[7]==true) inf++;
dline.append(decodeAct_Updt(inf,1));
// Hashed Address
if (inf!=0) {
if (db[12]==true) addr1=128;
else addr1=0;
if (db[13]==true) addr1=addr1+64;
if (db[14]==true) addr1=addr1+32;
if (db[15]==true) addr1=addr1+16;
if (db[16]==true) addr1=addr1+8;
if (db[17]==true) addr1=addr1+4;
if (db[18]==true) addr1=addr1+2;
if (db[19]==true) addr1++;
dline.append(" Hashed Addr "+Integer.toString(addr1));
}
dline.append(" : ");
// Slot 2
if (db[8]==true) inf=8;
else inf=0;
if (db[9]==true) inf=inf+4;
if (db[10]==true) inf=inf+2;
if (db[11]==true) inf++;
dline.append(decodeAct_Updt(inf,2));
if (inf!=0) {
// Hashed Address
if (db[20]==true) addr2=128;
else addr2=0;
if (db[21]==true) addr2=addr2+64;
if (db[22]==true) addr2=addr2+32;
if (db[23]==true) addr2=addr2+16;
if (db[24]==true) addr2=addr2+8;
if (db[25]==true) addr2=addr2+4;
if (db[26]==true) addr2=addr2+2;
if (db[27]==true) addr2++;
dline.append(" Hashed Addr "+Integer.toString(addr2));
}
}
// Capacity Plus SLCO 15
else if (slco==15) {
int lcn;
- if (db[17]==true) lcn=8;
+ if (db[16]==true) lcn=8;
else lcn=0;
- if (db[18]==true) lcn=lcn+4;
- if (db[19]==true) lcn=lcn+2;
- if (db[20]==true) lcn++;
+ if (db[17]==true) lcn=lcn+4;
+ if (db[18]==true) lcn=lcn+2;
+ if (db[19]==true) lcn++;
dline.append(" Capacity Plus Act_Updt - Rest Channel is LCN "+Integer.toString(lcn));
}
else {
dline.append("Unknown SLCO="+Integer.toString(slco)+" ");
for (a=4;a<28;a++) {
if (db[a]==true) dline.append("1");
else dline.append("0");
}
}
return dline.toString();
}
// Decode a 4 bit section of an Act_Updt
private String decodeAct_Updt (int inf,int channel) {
String l;
if (inf==0) {
l="No activity on BS time slot "+Integer.toString(channel);
if (channel==1) TtheApp.setCh1Label("Unused",TtheApp.labelQuiteColour);
else if (channel==2) TtheApp.setCh2Label("Unused",TtheApp.labelQuiteColour);
}
else if (inf==2) l="Group CSBK activity on BS time slot "+Integer.toString(channel);
else if (inf==3) l="Individual CSBK activity on BS time slot "+Integer.toString(channel);
else if (inf==8) l="Group voice activity on BS time slot "+Integer.toString(channel);
else if (inf==9) l="Individual voice activity on BS time slot "+Integer.toString(channel);
else if (inf==10) l="Individual data activity on BS time slot "+Integer.toString(channel);
else if (inf==11) l="Group data activity on BS time slot "+Integer.toString(channel);
else if (inf==12) l="Emergency group activity on BS time slot "+Integer.toString(channel);
else if (inf==13) l="Emergency individual voice activity on BS time slot "+Integer.toString(channel);
else l="Reserved";
return l;
}
public void setApp (DMRDecode theApp) {
TtheApp=theApp;
}
}
| false | true | private String decodeShortLC (boolean db[]) {
int slco,a;
StringBuilder dline=new StringBuilder(250);
// Calculate the SLCO
if (db[0]==true) slco=8;
else slco=0;
if (db[1]==true) slco=slco+4;
if (db[2]==true) slco=slco+2;
if (db[3]==true) slco++;
// Short LC Types
if (slco==0) {
dline.append("Nul_Msg");
}
else if (slco==1) {
int addr1,addr2,inf;
dline.append("Act_Updt - ");
// Slot 1
if (db[4]==true) inf=8;
else inf=0;
if (db[5]==true) inf=inf+4;
if (db[6]==true) inf=inf+2;
if (db[7]==true) inf++;
dline.append(decodeAct_Updt(inf,1));
// Hashed Address
if (inf!=0) {
if (db[12]==true) addr1=128;
else addr1=0;
if (db[13]==true) addr1=addr1+64;
if (db[14]==true) addr1=addr1+32;
if (db[15]==true) addr1=addr1+16;
if (db[16]==true) addr1=addr1+8;
if (db[17]==true) addr1=addr1+4;
if (db[18]==true) addr1=addr1+2;
if (db[19]==true) addr1++;
dline.append(" Hashed Addr "+Integer.toString(addr1));
}
dline.append(" : ");
// Slot 2
if (db[8]==true) inf=8;
else inf=0;
if (db[9]==true) inf=inf+4;
if (db[10]==true) inf=inf+2;
if (db[11]==true) inf++;
dline.append(decodeAct_Updt(inf,2));
if (inf!=0) {
// Hashed Address
if (db[20]==true) addr2=128;
else addr2=0;
if (db[21]==true) addr2=addr2+64;
if (db[22]==true) addr2=addr2+32;
if (db[23]==true) addr2=addr2+16;
if (db[24]==true) addr2=addr2+8;
if (db[25]==true) addr2=addr2+4;
if (db[26]==true) addr2=addr2+2;
if (db[27]==true) addr2++;
dline.append(" Hashed Addr "+Integer.toString(addr2));
}
}
// Capacity Plus SLCO 15
else if (slco==15) {
int lcn;
if (db[17]==true) lcn=8;
else lcn=0;
if (db[18]==true) lcn=lcn+4;
if (db[19]==true) lcn=lcn+2;
if (db[20]==true) lcn++;
dline.append(" Capacity Plus Act_Updt - Rest Channel is LCN "+Integer.toString(lcn));
}
else {
dline.append("Unknown SLCO="+Integer.toString(slco)+" ");
for (a=4;a<28;a++) {
if (db[a]==true) dline.append("1");
else dline.append("0");
}
}
return dline.toString();
}
| private String decodeShortLC (boolean db[]) {
int slco,a;
StringBuilder dline=new StringBuilder(250);
// Calculate the SLCO
if (db[0]==true) slco=8;
else slco=0;
if (db[1]==true) slco=slco+4;
if (db[2]==true) slco=slco+2;
if (db[3]==true) slco++;
// Short LC Types
if (slco==0) {
dline.append("Nul_Msg");
}
else if (slco==1) {
int addr1,addr2,inf;
dline.append("Act_Updt - ");
// Slot 1
if (db[4]==true) inf=8;
else inf=0;
if (db[5]==true) inf=inf+4;
if (db[6]==true) inf=inf+2;
if (db[7]==true) inf++;
dline.append(decodeAct_Updt(inf,1));
// Hashed Address
if (inf!=0) {
if (db[12]==true) addr1=128;
else addr1=0;
if (db[13]==true) addr1=addr1+64;
if (db[14]==true) addr1=addr1+32;
if (db[15]==true) addr1=addr1+16;
if (db[16]==true) addr1=addr1+8;
if (db[17]==true) addr1=addr1+4;
if (db[18]==true) addr1=addr1+2;
if (db[19]==true) addr1++;
dline.append(" Hashed Addr "+Integer.toString(addr1));
}
dline.append(" : ");
// Slot 2
if (db[8]==true) inf=8;
else inf=0;
if (db[9]==true) inf=inf+4;
if (db[10]==true) inf=inf+2;
if (db[11]==true) inf++;
dline.append(decodeAct_Updt(inf,2));
if (inf!=0) {
// Hashed Address
if (db[20]==true) addr2=128;
else addr2=0;
if (db[21]==true) addr2=addr2+64;
if (db[22]==true) addr2=addr2+32;
if (db[23]==true) addr2=addr2+16;
if (db[24]==true) addr2=addr2+8;
if (db[25]==true) addr2=addr2+4;
if (db[26]==true) addr2=addr2+2;
if (db[27]==true) addr2++;
dline.append(" Hashed Addr "+Integer.toString(addr2));
}
}
// Capacity Plus SLCO 15
else if (slco==15) {
int lcn;
if (db[16]==true) lcn=8;
else lcn=0;
if (db[17]==true) lcn=lcn+4;
if (db[18]==true) lcn=lcn+2;
if (db[19]==true) lcn++;
dline.append(" Capacity Plus Act_Updt - Rest Channel is LCN "+Integer.toString(lcn));
}
else {
dline.append("Unknown SLCO="+Integer.toString(slco)+" ");
for (a=4;a<28;a++) {
if (db[a]==true) dline.append("1");
else dline.append("0");
}
}
return dline.toString();
}
|
diff --git a/activemq-core/src/main/java/org/apache/activemq/usage/Usage.java b/activemq-core/src/main/java/org/apache/activemq/usage/Usage.java
index 6298f418e..8ef32e5b1 100755
--- a/activemq-core/src/main/java/org/apache/activemq/usage/Usage.java
+++ b/activemq-core/src/main/java/org/apache/activemq/usage/Usage.java
@@ -1,419 +1,419 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.activemq.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Used to keep track of how much of something is being used so that a
* productive working set usage can be controlled. Main use case is manage
* memory usage.
*
* @org.apache.xbean.XBean
* @version $Revision: 1.3 $
*/
public abstract class Usage<T extends Usage> implements Service {
private static final Log LOG = LogFactory.getLog(Usage.class);
protected final Object usageMutex = new Object();
protected int percentUsage;
protected T parent;
private UsageCapacity limiter = new DefaultUsageCapacity();
private int percentUsageMinDelta = 1;
private final List<UsageListener> listeners = new CopyOnWriteArrayList<UsageListener>();
private final boolean debug = LOG.isDebugEnabled();
private String name;
private float usagePortion = 1.0f;
private List<T> children = new CopyOnWriteArrayList<T>();
private final List<Runnable> callbacks = new LinkedList<Runnable>();
private int pollingTime = 100;
private ThreadPoolExecutor executor;
private AtomicBoolean started=new AtomicBoolean();
public Usage(T parent, String name, float portion) {
this.parent = parent;
this.usagePortion = portion;
if (parent != null) {
this.limiter.setLimit((long)(parent.getLimit() * portion));
name = parent.name + ":" + name;
}
this.name = name;
}
protected abstract long retrieveUsage();
/**
* @throws InterruptedException
*/
public void waitForSpace() throws InterruptedException {
waitForSpace(0);
}
/**
* @param timeout
* @throws InterruptedException
* @return true if space
*/
public boolean waitForSpace(long timeout) throws InterruptedException {
if (parent != null) {
if (!parent.waitForSpace(timeout)) {
return false;
}
}
synchronized (usageMutex) {
caclPercentUsage();
if (percentUsage >= 100) {
long deadline = timeout > 0 ? System.currentTimeMillis() + timeout : Long.MAX_VALUE;
long timeleft = deadline;
while (timeleft > 0) {
caclPercentUsage();
if (percentUsage >= 100) {
usageMutex.wait(pollingTime);
timeleft = deadline - System.currentTimeMillis();
} else {
break;
}
}
}
return percentUsage < 100;
}
}
public boolean isFull() {
if (parent != null && parent.isFull()) {
return true;
}
synchronized (usageMutex) {
caclPercentUsage();
return percentUsage >= 100;
}
}
public void addUsageListener(UsageListener listener) {
listeners.add(listener);
}
public void removeUsageListener(UsageListener listener) {
listeners.remove(listener);
}
public long getLimit() {
synchronized (usageMutex) {
return limiter.getLimit();
}
}
/**
* Sets the memory limit in bytes. Setting the limit in bytes will set the
* usagePortion to 0 since the UsageManager is not going to be portion based
* off the parent. When set using XBean, you can use values such as: "20
* mb", "1024 kb", or "1 gb"
*
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.MemoryPropertyEditor"
*/
public void setLimit(long limit) {
if (percentUsageMinDelta < 0) {
throw new IllegalArgumentException("percentUsageMinDelta must be greater or equal to 0");
}
synchronized (usageMutex) {
this.limiter.setLimit(limit);
this.usagePortion = 0;
}
onLimitChange();
}
protected void onLimitChange() {
// We may need to calculate the limit
if (usagePortion > 0 && parent != null) {
synchronized (usageMutex) {
this.limiter.setLimit((long)(parent.getLimit() * usagePortion));
}
}
// Reset the percent currently being used.
int percentUsage;
synchronized (usageMutex) {
percentUsage = caclPercentUsage();
}
setPercentUsage(percentUsage);
// Let the children know that the limit has changed. They may need to
// set
// their limits based on ours.
for (T child : children) {
child.onLimitChange();
}
}
public float getUsagePortion() {
synchronized (usageMutex) {
return usagePortion;
}
}
public void setUsagePortion(float usagePortion) {
synchronized (usageMutex) {
this.usagePortion = usagePortion;
}
onLimitChange();
}
/*
* Sets the minimum number of percentage points the usage has to change
* before a UsageListener event is fired by the manager.
*/
public int getPercentUsage() {
synchronized (usageMutex) {
return percentUsage;
}
}
public int getPercentUsageMinDelta() {
synchronized (usageMutex) {
return percentUsageMinDelta;
}
}
/**
* Sets the minimum number of percentage points the usage has to change
* before a UsageListener event is fired by the manager.
*
* @param percentUsageMinDelta
*/
public void setPercentUsageMinDelta(int percentUsageMinDelta) {
if (percentUsageMinDelta < 1) {
throw new IllegalArgumentException("percentUsageMinDelta must be greater than 0");
}
int percentUsage;
synchronized (usageMutex) {
this.percentUsageMinDelta = percentUsageMinDelta;
percentUsage = caclPercentUsage();
}
setPercentUsage(percentUsage);
}
public long getUsage() {
synchronized (usageMutex) {
return retrieveUsage();
}
}
protected void setPercentUsage(int value) {
synchronized (usageMutex) {
int oldValue = percentUsage;
percentUsage = value;
if (oldValue != value) {
fireEvent(oldValue, value);
}
}
}
protected int caclPercentUsage() {
if (limiter.getLimit() == 0) {
return 0;
}
return (int)((((retrieveUsage() * 100) / limiter.getLimit()) / percentUsageMinDelta) * percentUsageMinDelta);
}
private void fireEvent(final int oldPercentUsage, final int newPercentUsage) {
if (debug) {
LOG.debug("Memory usage change. from: " + oldPercentUsage + ", to: " + newPercentUsage);
}
if (started.get()) {
// Switching from being full to not being full..
if (oldPercentUsage >= 100 && newPercentUsage < 100) {
synchronized (usageMutex) {
usageMutex.notifyAll();
for (Iterator<Runnable> iter = new ArrayList<Runnable>(callbacks).iterator(); iter.hasNext();) {
Runnable callback = iter.next();
- callback.run();
+ getExecutor().execute(callback);
}
callbacks.clear();
}
}
// Let the listeners know on a separate thread
Runnable listenerNotifier = new Runnable() {
public void run() {
for (Iterator<UsageListener> iter = listeners.iterator(); iter.hasNext();) {
UsageListener l = iter.next();
l.onUsageChanged(Usage.this, oldPercentUsage, newPercentUsage);
}
}
};
getExecutor().execute(listenerNotifier);
}
}
public String getName() {
return name;
}
public String toString() {
return "Usage(" + getName() + ") percentUsage=" + percentUsage + "%, usage=" + retrieveUsage() + " limit=" + limiter.getLimit() + " percentUsageMinDelta=" + percentUsageMinDelta + "%";
}
@SuppressWarnings("unchecked")
public synchronized void start() {
if (started.compareAndSet(false, true)){
if (parent != null) {
parent.addChild(this);
}
for (T t:children) {
t.start();
}
}
}
@SuppressWarnings("unchecked")
public synchronized void stop() {
if (started.compareAndSet(true, false)){
if (parent != null) {
parent.removeChild(this);
}
if (this.executor != null){
this.executor.shutdownNow();
}
//clear down any callbacks
synchronized (usageMutex) {
usageMutex.notifyAll();
for (Iterator<Runnable> iter = new ArrayList<Runnable>(this.callbacks).iterator(); iter.hasNext();) {
Runnable callback = iter.next();
callback.run();
}
this.callbacks.clear();
}
for (T t:children) {
t.stop();
}
}
}
private void addChild(T child) {
children.add(child);
if (started.get()) {
child.start();
}
}
private void removeChild(T child) {
children.remove(child);
}
/**
* @param callback
* @return true if the UsageManager was full. The callback will only be
* called if this method returns true.
*/
public boolean notifyCallbackWhenNotFull(final Runnable callback) {
if (parent != null) {
Runnable r = new Runnable() {
public void run() {
synchronized (usageMutex) {
if (percentUsage >= 100) {
callbacks.add(callback);
} else {
callback.run();
}
}
}
};
if (parent.notifyCallbackWhenNotFull(r)) {
return true;
}
}
synchronized (usageMutex) {
if (percentUsage >= 100) {
callbacks.add(callback);
return true;
} else {
return false;
}
}
}
/**
* @return the limiter
*/
public UsageCapacity getLimiter() {
return this.limiter;
}
/**
* @param limiter the limiter to set
*/
public void setLimiter(UsageCapacity limiter) {
this.limiter = limiter;
}
/**
* @return the pollingTime
*/
public int getPollingTime() {
return this.pollingTime;
}
/**
* @param pollingTime the pollingTime to set
*/
public void setPollingTime(int pollingTime) {
this.pollingTime = pollingTime;
}
public void setName(String name) {
this.name = name;
}
public T getParent() {
return parent;
}
public void setParent(T parent) {
this.parent = parent;
}
protected synchronized Executor getExecutor() {
if (this.executor == null) {
this.executor = new ThreadPoolExecutor(1, 1, 0,
TimeUnit.NANOSECONDS,
new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, getName()
+ " Usage Thread Pool");
thread.setDaemon(true);
return thread;
}
});
}
return this.executor;
}
}
| true | true | private void fireEvent(final int oldPercentUsage, final int newPercentUsage) {
if (debug) {
LOG.debug("Memory usage change. from: " + oldPercentUsage + ", to: " + newPercentUsage);
}
if (started.get()) {
// Switching from being full to not being full..
if (oldPercentUsage >= 100 && newPercentUsage < 100) {
synchronized (usageMutex) {
usageMutex.notifyAll();
for (Iterator<Runnable> iter = new ArrayList<Runnable>(callbacks).iterator(); iter.hasNext();) {
Runnable callback = iter.next();
callback.run();
}
callbacks.clear();
}
}
// Let the listeners know on a separate thread
Runnable listenerNotifier = new Runnable() {
public void run() {
for (Iterator<UsageListener> iter = listeners.iterator(); iter.hasNext();) {
UsageListener l = iter.next();
l.onUsageChanged(Usage.this, oldPercentUsage, newPercentUsage);
}
}
};
getExecutor().execute(listenerNotifier);
}
}
| private void fireEvent(final int oldPercentUsage, final int newPercentUsage) {
if (debug) {
LOG.debug("Memory usage change. from: " + oldPercentUsage + ", to: " + newPercentUsage);
}
if (started.get()) {
// Switching from being full to not being full..
if (oldPercentUsage >= 100 && newPercentUsage < 100) {
synchronized (usageMutex) {
usageMutex.notifyAll();
for (Iterator<Runnable> iter = new ArrayList<Runnable>(callbacks).iterator(); iter.hasNext();) {
Runnable callback = iter.next();
getExecutor().execute(callback);
}
callbacks.clear();
}
}
// Let the listeners know on a separate thread
Runnable listenerNotifier = new Runnable() {
public void run() {
for (Iterator<UsageListener> iter = listeners.iterator(); iter.hasNext();) {
UsageListener l = iter.next();
l.onUsageChanged(Usage.this, oldPercentUsage, newPercentUsage);
}
}
};
getExecutor().execute(listenerNotifier);
}
}
|
diff --git a/src/main/java/pl/agh/enrollme/service/PersonService.java b/src/main/java/pl/agh/enrollme/service/PersonService.java
index 9df4987..cee015c 100644
--- a/src/main/java/pl/agh/enrollme/service/PersonService.java
+++ b/src/main/java/pl/agh/enrollme/service/PersonService.java
@@ -1,99 +1,101 @@
package pl.agh.enrollme.service;
import org.primefaces.event.RowEditEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import pl.agh.enrollme.model.Person;
import pl.agh.enrollme.repository.IPersonDAO;
import java.util.ArrayList;
import java.util.List;
@Service
public class PersonService {
private static final Logger LOGGER = LoggerFactory.getLogger(PersonService.class);
@Autowired
private IPersonDAO personDAO;
private static List<Person> cache = new ArrayList<Person>();
static {
// cache.add(new Person(0, "Jamie", "Carr"));
// cache.add(new Person(1, "Jean", "Cobbs"));
// cache.add(new Person(2, "John", "Howard"));
// cache.add(new Person(3, "John", "Mudra"));
// cache.add(new Person(4, "Julia", "Webber"));
}
public List<String> suggestNames(String text) {
List<String> results = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
results.add(text + i);
}
return results;
}
public List<Person> suggestPeople(String text) {
List<Person> results = new ArrayList<Person>();
for (Person p : cache) {
if ((p.getFirstName() + " " + p.getLastName()).toLowerCase().startsWith(text.toLowerCase())) {
results.add(p);
}
}
return results;
}
public void onEdit(RowEditEvent event) {
LOGGER.debug("Row edited");
Person editedPerson = (Person)event.getObject();
if (editedPerson != null) {
LOGGER.debug("Updating person with id " + editedPerson.getId());
personDAO.update(editedPerson);
}
}
public void setEncodedPassword(Person person, String password) {
LOGGER.debug("Jestem w setencodedpassword");
PasswordEncoder encoder = new ShaPasswordEncoder(256);
String encodedPassword = encoder.encodePassword(password, null);
person.setPassword(encodedPassword);
}
public void setBooleans(Person person, Boolean enabled, Boolean credentialsNonExpired, Boolean accountNonExpired,
Boolean accountNonLocked) {
LOGGER.debug("Jestem w setBooleans");
person.setEnabled(enabled);
person.setAccountNonExpired(accountNonExpired);
person.setAccountNonLocked(accountNonLocked);
person.setCredentialsNonExpired(credentialsNonExpired);
}
public Person getCurrentUser() {
LOGGER.debug("Entering getCurrentUser");
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
LOGGER.debug("Principal: " + principal + " retrieved");
UserDetails userDetails = null;
if(principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
LOGGER.debug("Principal casted to UserDetails: " + userDetails);
} else {
LOGGER.warn("Principal " + principal + " is not an instance of UserDetails!");
throw new SecurityException("Principal " + principal + " is not an instance of UserDetails!");
}
- return (Person) userDetails;
+ Person person = (Person) userDetails;
+ person = personDAO.getByPK(person.getId());
+ return person;
}
}
| true | true | public Person getCurrentUser() {
LOGGER.debug("Entering getCurrentUser");
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
LOGGER.debug("Principal: " + principal + " retrieved");
UserDetails userDetails = null;
if(principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
LOGGER.debug("Principal casted to UserDetails: " + userDetails);
} else {
LOGGER.warn("Principal " + principal + " is not an instance of UserDetails!");
throw new SecurityException("Principal " + principal + " is not an instance of UserDetails!");
}
return (Person) userDetails;
}
| public Person getCurrentUser() {
LOGGER.debug("Entering getCurrentUser");
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
LOGGER.debug("Principal: " + principal + " retrieved");
UserDetails userDetails = null;
if(principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
LOGGER.debug("Principal casted to UserDetails: " + userDetails);
} else {
LOGGER.warn("Principal " + principal + " is not an instance of UserDetails!");
throw new SecurityException("Principal " + principal + " is not an instance of UserDetails!");
}
Person person = (Person) userDetails;
person = personDAO.getByPK(person.getId());
return person;
}
|
diff --git a/bikeshed/src/com/google/gwt/valuestore/shared/impl/RecordJsoImpl.java b/bikeshed/src/com/google/gwt/valuestore/shared/impl/RecordJsoImpl.java
index 60af25ef8..0395a602e 100644
--- a/bikeshed/src/com/google/gwt/valuestore/shared/impl/RecordJsoImpl.java
+++ b/bikeshed/src/com/google/gwt/valuestore/shared/impl/RecordJsoImpl.java
@@ -1,186 +1,187 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.valuestore.shared.impl;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.valuestore.shared.Property;
import com.google.gwt.valuestore.shared.PropertyReference;
import com.google.gwt.valuestore.shared.Record;
import java.util.Date;
/**
* JSO implementation of {@link Record}, used to back subclasses of
* {@link RecordImpl}.
*/
public class RecordJsoImpl extends JavaScriptObject implements Record {
public static native JsArray<RecordJsoImpl> arrayFromJson(String json) /*-{
return eval(json);
}-*/;
public static RecordJsoImpl emptyCopy(RecordImpl from) {
RecordJsoImpl copy = create();
final RecordSchema<?> schema = from.getSchema();
copy.setSchema(schema);
copy.set(Record.id, from.get(Record.id));
copy.set(Record.version, from.get(Record.version));
return copy;
}
private static native RecordJsoImpl create() /*-{
return {};
}-*/;
protected RecordJsoImpl() {
}
public final native void delete(String name)/*-{
delete this[name];
}-*/;
@SuppressWarnings("unchecked")
public final <V> V get(Property<V> property) {
assert isDefined(property.getName()) : "Cannot ask for a property before setting it: "
+ property.getName();
if (Integer.class.equals(property.getType())) {
return (V) Integer.valueOf(getInt(property.getName()));
}
if (Date.class.equals(property.getType())) {
double millis = getDouble(property.getName());
if (GWT.isScript()) {
return (V) dateForDouble(millis);
} else {
// In dev mode, we're using real JRE dates
return (V) new Date((long) millis);
}
}
- return get(property.getName());
+ // Sun JDK compile fails without this cast
+ return (V) get(property.getName());
}
public final native <T> T get(String propertyName) /*-{
return this[propertyName];
}-*/;
public final String getId() {
return this.get(id);
}
public final <V> PropertyReference<V> getRef(Property<V> property) {
return new PropertyReference<V>(this, property);
}
public final native RecordSchema<?> getSchema() /*-{
return this['__key'];
}-*/;
public final String getVersion() {
return this.get(version);
}
/**
* @param name
*/
public final native boolean isDefined(String name)/*-{
return this[name] !== undefined;
}-*/;
public final boolean isEmpty() {
for (Property<?> property : getSchema().allProperties()) {
if ((property != Record.id) && (property != Record.version)
&& (isDefined(property.getName()))) {
return false;
}
}
return true;
}
public final boolean merge(RecordJsoImpl from) {
assert getSchema() == from.getSchema();
boolean changed = false;
for (Property<?> property : getSchema().allProperties()) {
if (from.isDefined(property.getName())) {
changed |= copyPropertyIfDifferent(property.getName(), from);
}
}
return changed;
}
public final <V> void set(Property<V> property, V value) {
if (value instanceof String) {
setString(property.getName(), (String) value);
return;
}
if (value instanceof Integer) {
setInt(property.getName(), (Integer) value);
return;
}
throw new UnsupportedOperationException("Can't yet set properties of type "
+ value.getClass().getName());
}
public final native void setSchema(RecordSchema<?> schema) /*-{
this['__key'] = schema;
}-*/;
/**
* Return JSON representation using org.json library.
*
* @return returned string.
*/
public final native String toJson() /*-{
var replacer = function(key, value) {
if (key == '__key') {
return;
}
return value;
}
return JSON.stringify(this, replacer);
}-*/;
private native boolean copyPropertyIfDifferent(String name, RecordJsoImpl from) /*-{
if (this[name] == from[name]) {
return false;
}
this[name] = from[name];
return true;
}-*/;
private native Date dateForDouble(double millis) /*-{
return @java.util.Date::createFrom(D)(millis);
}-*/;;
private native double getDouble(String name) /*-{
return this[name];
}-*/;
private native int getInt(String name) /*-{
return this[name];
}-*/;
private native void setInt(String name, int value) /*-{
this[name] = value;
}-*/;
private native void setString(String name, String value) /*-{
this[name] = value;
}-*/;
}
| true | true | public final <V> V get(Property<V> property) {
assert isDefined(property.getName()) : "Cannot ask for a property before setting it: "
+ property.getName();
if (Integer.class.equals(property.getType())) {
return (V) Integer.valueOf(getInt(property.getName()));
}
if (Date.class.equals(property.getType())) {
double millis = getDouble(property.getName());
if (GWT.isScript()) {
return (V) dateForDouble(millis);
} else {
// In dev mode, we're using real JRE dates
return (V) new Date((long) millis);
}
}
return get(property.getName());
}
| public final <V> V get(Property<V> property) {
assert isDefined(property.getName()) : "Cannot ask for a property before setting it: "
+ property.getName();
if (Integer.class.equals(property.getType())) {
return (V) Integer.valueOf(getInt(property.getName()));
}
if (Date.class.equals(property.getType())) {
double millis = getDouble(property.getName());
if (GWT.isScript()) {
return (V) dateForDouble(millis);
} else {
// In dev mode, we're using real JRE dates
return (V) new Date((long) millis);
}
}
// Sun JDK compile fails without this cast
return (V) get(property.getName());
}
|
diff --git a/eXoApplication/forum/webapp/src/main/java/org/exoplatform/forum/webui/popup/UIMoveForumForm.java b/eXoApplication/forum/webapp/src/main/java/org/exoplatform/forum/webui/popup/UIMoveForumForm.java
index 8f66e57bf..84aa69d6d 100644
--- a/eXoApplication/forum/webapp/src/main/java/org/exoplatform/forum/webui/popup/UIMoveForumForm.java
+++ b/eXoApplication/forum/webapp/src/main/java/org/exoplatform/forum/webui/popup/UIMoveForumForm.java
@@ -1,143 +1,144 @@
/***************************************************************************
* 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.forum.webui.popup;
import java.util.ArrayList;
import java.util.List;
import javax.jcr.ItemExistsException;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.forum.ForumUtils;
import org.exoplatform.forum.service.Category;
import org.exoplatform.forum.service.Forum;
import org.exoplatform.forum.service.ForumService;
import org.exoplatform.forum.webui.UICategory;
import org.exoplatform.forum.webui.UIForumContainer;
import org.exoplatform.forum.webui.UIForumDescription;
import org.exoplatform.forum.webui.UIForumPortlet;
import org.exoplatform.forum.webui.UITopicContainer;
import org.exoplatform.ks.common.webui.BaseEventListener;
import org.exoplatform.ks.common.webui.BaseUIForm;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIPopupComponent;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.event.Event.Phase;
/**
* Created by The eXo Platform SARL
* Author : Hung Nguyen
* [email protected]
* Aus 01, 2007 2:48:18 PM
*/
@ComponentConfig(
lifecycle = UIFormLifecycle.class,
template = "app:/templates/forum/webui/popup/UIMoveForumForm.gtmpl",
events = {
@EventConfig(listeners = UIMoveForumForm.SaveActionListener.class),
@EventConfig(listeners = UIMoveForumForm.CancelActionListener.class,phase = Phase.DECODE)
}
)
public class UIMoveForumForm extends BaseUIForm implements UIPopupComponent {
public static final String FIELD_CATEGORY_SELECTBOX = "SelectCategory";
private List<Forum> forums_;
private String categoryId_;
private String newCategoryId_;
private boolean isForumUpdate = false;
public void setListForum(List<Forum> forums, String categoryId) {
forums_ = forums;
categoryId_ = categoryId;
}
public UIMoveForumForm() throws Exception {
}
public void setForumUpdate(boolean isForumUpdate) {
this.isForumUpdate = isForumUpdate;
}
@SuppressWarnings("unused")
private List<Category> getCategories() throws Exception {
ForumService forumService = (ForumService) ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(ForumService.class);
List<Category> categorys = new ArrayList<Category>();
for (Category category : forumService.getCategories()) {
if (!category.getId().equals(categoryId_)) {
categorys.add(category);
}
}
return categorys;
}
@SuppressWarnings("unused")
private boolean getSeclectedCategory(String cactegoryId) throws Exception {
if (cactegoryId.equalsIgnoreCase(this.newCategoryId_))
return true;
else
return false;
}
public void activate() throws Exception {
}
public void deActivate() throws Exception {
}
static public class SaveActionListener extends BaseEventListener<UIMoveForumForm> {
public void onEvent(Event<UIMoveForumForm> event, UIMoveForumForm uiForm, final String categoryPath) throws Exception {
ForumService forumService = (ForumService) ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(ForumService.class);
List<Forum> forums = uiForm.forums_;
String categoryId = categoryPath.substring((categoryPath.lastIndexOf(ForumUtils.SLASH) + 1));
try {
forumService.moveForum(forums, categoryPath);
UIForumPortlet forumPortlet = uiForm.getAncestorOfType(UIForumPortlet.class);
forumPortlet.cancelAction();
if (uiForm.isForumUpdate) {
forumPortlet.updateIsRendered(ForumUtils.FORUM);
UIForumContainer uiForumContainer = forumPortlet.getChild(UIForumContainer.class);
uiForumContainer.setIsRenderChild(true);
UITopicContainer uiTopicContainer = uiForumContainer.getChild(UITopicContainer.class);
- uiForumContainer.getChild(UIForumDescription.class).setForum(forums.get(0));
- uiTopicContainer.setUpdateForum(categoryId, forums.get(0), 0);
+ Forum forum = forumService.getForum(categoryId, forums.get(0).getId());
+ uiForumContainer.getChild(UIForumDescription.class).setForum(forum);
+ uiTopicContainer.setUpdateForum(categoryId, forum, 0);
event.getRequestContext().addUIComponentToUpdateByAjax(forumPortlet);
} else {
UICategory uiCategory = forumPortlet.findFirstComponentOfType(UICategory.class);
event.getRequestContext().addUIComponentToUpdateByAjax(uiCategory);
}
} catch (ItemExistsException e) {
warning("UIImportForm.msg.ObjectIsExist");
return;
} catch (Exception e) {
warning("UIMoveForumForm.msg.forum-deleted");
return;
}
}
}
static public class CancelActionListener extends EventListener<UIMoveForumForm> {
public void execute(Event<UIMoveForumForm> event) throws Exception {
UIForumPortlet forumPortlet = event.getSource().getAncestorOfType(UIForumPortlet.class);
forumPortlet.cancelAction();
}
}
}
| true | true | public void onEvent(Event<UIMoveForumForm> event, UIMoveForumForm uiForm, final String categoryPath) throws Exception {
ForumService forumService = (ForumService) ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(ForumService.class);
List<Forum> forums = uiForm.forums_;
String categoryId = categoryPath.substring((categoryPath.lastIndexOf(ForumUtils.SLASH) + 1));
try {
forumService.moveForum(forums, categoryPath);
UIForumPortlet forumPortlet = uiForm.getAncestorOfType(UIForumPortlet.class);
forumPortlet.cancelAction();
if (uiForm.isForumUpdate) {
forumPortlet.updateIsRendered(ForumUtils.FORUM);
UIForumContainer uiForumContainer = forumPortlet.getChild(UIForumContainer.class);
uiForumContainer.setIsRenderChild(true);
UITopicContainer uiTopicContainer = uiForumContainer.getChild(UITopicContainer.class);
uiForumContainer.getChild(UIForumDescription.class).setForum(forums.get(0));
uiTopicContainer.setUpdateForum(categoryId, forums.get(0), 0);
event.getRequestContext().addUIComponentToUpdateByAjax(forumPortlet);
} else {
UICategory uiCategory = forumPortlet.findFirstComponentOfType(UICategory.class);
event.getRequestContext().addUIComponentToUpdateByAjax(uiCategory);
}
} catch (ItemExistsException e) {
warning("UIImportForm.msg.ObjectIsExist");
return;
} catch (Exception e) {
warning("UIMoveForumForm.msg.forum-deleted");
return;
}
}
| public void onEvent(Event<UIMoveForumForm> event, UIMoveForumForm uiForm, final String categoryPath) throws Exception {
ForumService forumService = (ForumService) ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(ForumService.class);
List<Forum> forums = uiForm.forums_;
String categoryId = categoryPath.substring((categoryPath.lastIndexOf(ForumUtils.SLASH) + 1));
try {
forumService.moveForum(forums, categoryPath);
UIForumPortlet forumPortlet = uiForm.getAncestorOfType(UIForumPortlet.class);
forumPortlet.cancelAction();
if (uiForm.isForumUpdate) {
forumPortlet.updateIsRendered(ForumUtils.FORUM);
UIForumContainer uiForumContainer = forumPortlet.getChild(UIForumContainer.class);
uiForumContainer.setIsRenderChild(true);
UITopicContainer uiTopicContainer = uiForumContainer.getChild(UITopicContainer.class);
Forum forum = forumService.getForum(categoryId, forums.get(0).getId());
uiForumContainer.getChild(UIForumDescription.class).setForum(forum);
uiTopicContainer.setUpdateForum(categoryId, forum, 0);
event.getRequestContext().addUIComponentToUpdateByAjax(forumPortlet);
} else {
UICategory uiCategory = forumPortlet.findFirstComponentOfType(UICategory.class);
event.getRequestContext().addUIComponentToUpdateByAjax(uiCategory);
}
} catch (ItemExistsException e) {
warning("UIImportForm.msg.ObjectIsExist");
return;
} catch (Exception e) {
warning("UIMoveForumForm.msg.forum-deleted");
return;
}
}
|
diff --git a/dev/src/main/java/org/tessell/generators/css/CssGenerator.java b/dev/src/main/java/org/tessell/generators/css/CssGenerator.java
index 0b7996c9..19f139e1 100644
--- a/dev/src/main/java/org/tessell/generators/css/CssGenerator.java
+++ b/dev/src/main/java/org/tessell/generators/css/CssGenerator.java
@@ -1,47 +1,50 @@
package org.tessell.generators.css;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import joist.sourcegen.GClass;
import joist.sourcegen.GMethod;
import org.tessell.generators.Cleanup;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.css.ast.CssProperty.Value;
/** A utility class for creating a Java interface declaration for a given CSS file. */
public class CssGenerator extends AbstractCssGenerator {
private final GClass cssInterface;
public CssGenerator(final File inputCssFile, Cleanup cleanup, final String interfaceName, final File outputDirectory) {
super(inputCssFile, outputDirectory, cleanup);
cssInterface = new GClass(interfaceName).setInterface().baseClass(CssResource.class);
}
public void run() throws IOException {
addMethods();
markAndSaveIfChanged(cssInterface);
}
private void addMethods() {
for (final Map.Entry<String, String> e : getClassNameToMethodName().entrySet()) {
final String className = e.getKey();
final String methodName = e.getValue();
+ if (className.equals("*")) {
+ continue; // skip @external *; declarations
+ }
final GMethod m = cssInterface.getMethod(methodName).returnType(String.class);
if (!methodName.equals(className)) {
m.addAnnotation("@ClassName(\"{}\")", Generator.escape(className));
}
}
for (final Map.Entry<String, Value> def : getDefs().entrySet()) {
// need stricter matching
if (def.getValue().toString().endsWith("px")) {
cssInterface.getMethod(def.getKey()).returnType(int.class);
}
}
}
}
| true | true | private void addMethods() {
for (final Map.Entry<String, String> e : getClassNameToMethodName().entrySet()) {
final String className = e.getKey();
final String methodName = e.getValue();
final GMethod m = cssInterface.getMethod(methodName).returnType(String.class);
if (!methodName.equals(className)) {
m.addAnnotation("@ClassName(\"{}\")", Generator.escape(className));
}
}
for (final Map.Entry<String, Value> def : getDefs().entrySet()) {
// need stricter matching
if (def.getValue().toString().endsWith("px")) {
cssInterface.getMethod(def.getKey()).returnType(int.class);
}
}
}
| private void addMethods() {
for (final Map.Entry<String, String> e : getClassNameToMethodName().entrySet()) {
final String className = e.getKey();
final String methodName = e.getValue();
if (className.equals("*")) {
continue; // skip @external *; declarations
}
final GMethod m = cssInterface.getMethod(methodName).returnType(String.class);
if (!methodName.equals(className)) {
m.addAnnotation("@ClassName(\"{}\")", Generator.escape(className));
}
}
for (final Map.Entry<String, Value> def : getDefs().entrySet()) {
// need stricter matching
if (def.getValue().toString().endsWith("px")) {
cssInterface.getMethod(def.getKey()).returnType(int.class);
}
}
}
|
diff --git a/com.ibm.wala.core/src/com/ibm/wala/analysis/pointers/BasicHeapGraph.java b/com.ibm.wala.core/src/com/ibm/wala/analysis/pointers/BasicHeapGraph.java
index 57dfc82cb..2894f8392 100644
--- a/com.ibm.wala.core/src/com/ibm/wala/analysis/pointers/BasicHeapGraph.java
+++ b/com.ibm.wala.core/src/com/ibm/wala/analysis/pointers/BasicHeapGraph.java
@@ -1,514 +1,514 @@
/*******************************************************************************
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.wala.analysis.pointers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import com.ibm.wala.analysis.reflection.Malleable;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CompoundIterator;
import com.ibm.wala.util.IntFunction;
import com.ibm.wala.util.IntMapIterator;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.graph.AbstractNumberedGraph;
import com.ibm.wala.util.graph.EdgeManager;
import com.ibm.wala.util.graph.NodeManager;
import com.ibm.wala.util.graph.NumberedGraph;
import com.ibm.wala.util.graph.NumberedNodeManager;
import com.ibm.wala.util.graph.impl.NumberedNodeIterator;
import com.ibm.wala.util.intset.BasicNaturalRelation;
import com.ibm.wala.util.intset.IBinaryNaturalRelation;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableMapping;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import com.ibm.wala.util.intset.SparseIntSet;
/**
* @author sfink
*/
public class BasicHeapGraph extends HeapGraph {
private final static boolean VERBOSE = false;
private final static int VERBOSE_INTERVAL = 10000;
/**
* Pointer analysis solution
*/
private final PointerAnalysis pointerAnalysis;
/**
* The backing graph
*/
private final NumberedGraph<Object> G;
/**
* governing call graph
*/
private final CallGraph callGraph;
/**
* @param P
* governing pointer analysis
* @throws NullPointerException
* if P is null
*/
public BasicHeapGraph(final PointerAnalysis P, final CallGraph callGraph) throws NullPointerException {
super(P.getHeapModel());
this.pointerAnalysis = P;
this.callGraph = callGraph;
final OrdinalSetMapping<PointerKey> pointerKeys = getPointerKeys();
final NumberedNodeManager<Object> nodeMgr = new NumberedNodeManager<Object>() {
public Iterator<Object> iterator() {
return new CompoundIterator<Object>(pointerKeys.iterator(), P.getInstanceKeyMapping().iterator());
}
public int getNumberOfNodes() {
return pointerKeys.getSize() + P.getInstanceKeyMapping().getSize();
}
public void addNode(Object n) {
Assertions.UNREACHABLE();
}
public void removeNode(Object n) {
Assertions.UNREACHABLE();
}
public int getNumber(Object N) {
if (N instanceof PointerKey) {
return pointerKeys.getMappedIndex((PointerKey) N);
} else {
if (Assertions.verifyAssertions) {
if (!(N instanceof InstanceKey)) {
Assertions.UNREACHABLE(N.getClass().toString());
}
}
int inumber = P.getInstanceKeyMapping().getMappedIndex((InstanceKey) N);
- return (inumber == -1) ? -1 : inumber + pointerKeys.getMaximumIndex();
+ return (inumber == -1) ? -1 : inumber + pointerKeys.getMaximumIndex() + 1;
}
}
public Object getNode(int number) {
if (number > pointerKeys.getMaximumIndex()) {
return P.getInstanceKeyMapping().getMappedObject(number - pointerKeys.getSize());
} else {
return pointerKeys.getMappedObject(number);
}
}
public int getMaxNumber() {
return getNumberOfNodes() - 1;
}
public boolean containsNode(Object n) {
return getNumber(n) != -1;
}
public Iterator<Object> iterateNodes(IntSet s) {
return new NumberedNodeIterator<Object>(s, this);
}
};
final IBinaryNaturalRelation pred = computePredecessors(nodeMgr);
final IntFunction<Object> toNode = new IntFunction<Object>() {
public Object apply(int i) {
return nodeMgr.getNode(i);
}
};
this.G = new AbstractNumberedGraph<Object>() {
private final EdgeManager<Object> edgeMgr = new EdgeManager<Object>() {
public Iterator<Object> getPredNodes(Object N) {
int n = nodeMgr.getNumber(N);
IntSet p = pred.getRelated(n);
if (p == null) {
return EmptyIterator.instance();
} else {
return new IntMapIterator<Object>(p.intIterator(), toNode);
}
}
public int getPredNodeCount(Object N) {
int n = nodeMgr.getNumber(N);
return pred.getRelatedCount(n);
}
public Iterator<? extends Object> getSuccNodes(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
if (succ == null) {
return EmptyIterator.instance();
}
SparseIntSet s = new MutableSparseIntSet(succ);
return new IntMapIterator<Object>(s.intIterator(), toNode);
}
public int getSuccNodeCount(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
return succ == null ? 0 : succ.length;
}
public void addEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeAllIncidentEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeIncomingEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeOutgoingEdges(Object node) {
Assertions.UNREACHABLE();
}
public boolean hasEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
return false;
}
};
@Override
protected NodeManager<Object> getNodeManager() {
return nodeMgr;
}
@Override
protected EdgeManager<Object> getEdgeManager() {
return edgeMgr;
}
};
}
private OrdinalSetMapping<PointerKey> getPointerKeys() {
MutableMapping<PointerKey> result = new MutableMapping<PointerKey>();
for (Iterator<PointerKey> it = pointerAnalysis.getPointerKeys().iterator(); it.hasNext();) {
PointerKey p = it.next();
result.add(p);
}
return result;
}
private int[] computeSuccNodeNumbers(Object N, NumberedNodeManager<Object> nodeManager) {
if (N instanceof PointerKey) {
PointerKey P = (PointerKey) N;
OrdinalSet<InstanceKey> S = pointerAnalysis.getPointsToSet(P);
int[] result = new int[S.size()];
int i = 0;
for (Iterator<InstanceKey> it = S.iterator(); it.hasNext();) {
result[i] = nodeManager.getNumber(it.next());
i++;
}
return result;
} else if (N instanceof InstanceKey) {
InstanceKey I = (InstanceKey) N;
TypeReference T = I.getConcreteType().getReference();
if (Assertions.verifyAssertions) {
if (T == null) {
Assertions._assert(T != null, "null concrete type from " + I.getClass());
}
}
if (T.isArrayType()) {
PointerKey p = getHeapModel().getPointerKeyForArrayContents(I);
if (p == null || !nodeManager.containsNode(p)) {
return null;
} else {
return new int[] { nodeManager.getNumber(p) };
}
} else if (!Malleable.isMalleable(T)) {
IClass klass = getHeapModel().getClassHierarchy().lookupClass(T);
if (Assertions.verifyAssertions) {
if (klass == null) {
Assertions._assert(klass != null, "null klass for type " + T);
}
}
MutableSparseIntSet result = new MutableSparseIntSet();
try {
for (Iterator<IField> it = klass.getAllInstanceFields().iterator(); it.hasNext();) {
IField f = it.next();
if (!f.getReference().getFieldType().isPrimitiveType()) {
PointerKey p = getHeapModel().getPointerKeyForInstanceField(I, f);
if (p != null && nodeManager.containsNode(p)) {
result.add(nodeManager.getNumber(p));
}
}
}
} catch (ClassHierarchyException e) {
// uh oh. skip it for now.
}
return result.toIntArray();
} else {
Assertions._assert(Malleable.isMalleable(T));
return null;
}
} else {
Assertions.UNREACHABLE("Unexpected type: " + N.getClass());
return null;
}
}
/**
* @return R, y \in R(x,y) if the node y is a predecessor of node x
*/
private IBinaryNaturalRelation computePredecessors(NumberedNodeManager<Object> nodeManager) {
BasicNaturalRelation R = new BasicNaturalRelation(new byte[] { BasicNaturalRelation.SIMPLE }, BasicNaturalRelation.SIMPLE);
// we split the following loops to improve temporal locality,
// particularly for locals
computePredecessorsForNonLocals(nodeManager, R);
computePredecessorsForLocals(nodeManager, R);
return R;
}
private void computePredecessorsForNonLocals(NumberedNodeManager<Object> nodeManager, BasicNaturalRelation R) {
// Note: we run this loop backwards on purpose, to avoid lots of resizing of
// bitvectors
// in the backing relation. i.e., we will add the biggest bits first.
// pretty damn tricky.
for (int i = nodeManager.getMaxNumber(); i >= 0; i--) {
if (VERBOSE) {
if (i % VERBOSE_INTERVAL == 0) {
System.err.println("Building HeapGraph: " + i);
}
}
Object n = nodeManager.getNode(i);
if (!(n instanceof LocalPointerKey)) {
int[] succ = computeSuccNodeNumbers(n, nodeManager);
if (succ != null) {
for (int z = 0; z < succ.length; z++) {
int j = succ[z];
R.add(j, i);
}
}
}
}
}
/**
* traverse locals in order, first by node, then by value number: attempt to
* improve locality
*/
private void computePredecessorsForLocals(NumberedNodeManager<Object> nodeManager, BasicNaturalRelation R) {
ArrayList<LocalPointerKey> list = new ArrayList<LocalPointerKey>();
for (Iterator<Object> it = nodeManager.iterator(); it.hasNext();) {
Object n = it.next();
if (n instanceof LocalPointerKey) {
list.add((LocalPointerKey) n);
}
}
Object[] arr = list.toArray();
Arrays.sort(arr, new LocalPointerComparator());
for (int i = 0; i < arr.length; i++) {
if (VERBOSE) {
if (i % VERBOSE_INTERVAL == 0) {
System.err.println("Building HeapGraph: " + i + " of " + arr.length);
}
}
LocalPointerKey n = (LocalPointerKey) arr[i];
int num = nodeManager.getNumber(n);
int[] succ = computeSuccNodeNumbers(n, nodeManager);
if (succ != null) {
for (int z = 0; z < succ.length; z++) {
int j = succ[z];
R.add(j, num);
}
}
}
}
/**
* sorts local pointers by node, then value number
*/
private final class LocalPointerComparator implements Comparator<Object> {
public int compare(Object arg1, Object arg2) {
LocalPointerKey o1 = (LocalPointerKey) arg1;
LocalPointerKey o2 = (LocalPointerKey) arg2;
if (o1.getNode().equals(o2.getNode())) {
return o1.getValueNumber() - o2.getValueNumber();
} else {
return callGraph.getNumber(o1.getNode()) - callGraph.getNumber(o2.getNode());
}
}
}
/*
* @see com.ibm.wala.util.graph.NumberedNodeManager#getNumber(com.ibm.wala.util.graph.Node)
*/
public int getNumber(Object N) {
return G.getNumber(N);
}
/*
* @see com.ibm.wala.util.graph.NumberedNodeManager#getNode(int)
*/
public Object getNode(int number) {
return G.getNode(number);
}
/*
* @see com.ibm.wala.util.graph.NumberedNodeManager#getMaxNumber()
*/
public int getMaxNumber() {
return G.getMaxNumber();
}
/*
* @see com.ibm.wala.util.graph.NodeManager#iterateNodes()
*/
public Iterator<Object> iterator() {
return G.iterator();
}
/*
* @see com.ibm.wala.util.graph.NodeManager#getNumberOfNodes()
*/
public int getNumberOfNodes() {
return G.getNumberOfNodes();
}
/*
* @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(com.ibm.wala.util.graph.Node)
*/
public Iterator<? extends Object> getPredNodes(Object N) {
return G.getPredNodes(N);
}
/*
* @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(com.ibm.wala.util.graph.Node)
*/
public int getPredNodeCount(Object N) {
return G.getPredNodeCount(N);
}
/*
* @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(com.ibm.wala.util.graph.Node)
*/
public Iterator<? extends Object> getSuccNodes(Object N) {
return G.getSuccNodes(N);
}
/*
* @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(com.ibm.wala.util.graph.Node)
*/
public int getSuccNodeCount(Object N) {
return G.getSuccNodeCount(N);
}
/*
* @see com.ibm.wala.util.graph.NodeManager#addNode(com.ibm.wala.util.graph.Node)
*/
public void addNode(Object n) throws UnimplementedError {
Assertions.UNREACHABLE();
}
/*
* @see com.ibm.wala.util.graph.NodeManager#remove(com.ibm.wala.util.graph.Node)
*/
public void removeNode(Object n) throws UnimplementedError {
Assertions.UNREACHABLE();
}
public void addEdge(Object from, Object to) throws UnimplementedError {
Assertions.UNREACHABLE();
}
public void removeEdge(Object from, Object to) throws UnimplementedError {
Assertions.UNREACHABLE();
}
public boolean hasEdge(Object from, Object to) throws UnimplementedError {
Assertions.UNREACHABLE();
return false;
}
public void removeAllIncidentEdges(Object node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/*
* @see com.ibm.wala.util.graph.NodeManager#containsNode(com.ibm.wala.util.graph.Node)
*/
public boolean containsNode(Object N) {
return G.containsNode(N);
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
result.append("Nodes:\n");
for (int i = 0; i <= getMaxNumber(); i++) {
Object node = getNode(i);
if (node != null) {
result.append(i).append(" ").append(node).append("\n");
}
}
result.append("Edges:\n");
for (int i = 0; i <= getMaxNumber(); i++) {
Object node = getNode(i);
if (node != null) {
result.append(i).append(" -> ");
for (Iterator it = getSuccNodes(node); it.hasNext();) {
Object s = it.next();
result.append(getNumber(s)).append(" ");
}
result.append("\n");
}
}
return result.toString();
}
public void removeIncomingEdges(Object node) throws UnimplementedError {
Assertions.UNREACHABLE();
}
public void removeOutgoingEdges(Object node) throws UnimplementedError {
Assertions.UNREACHABLE();
}
public IntSet getSuccNodeNumbers(Object node) throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
public IntSet getPredNodeNumbers(Object node) throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
}
| true | true | public BasicHeapGraph(final PointerAnalysis P, final CallGraph callGraph) throws NullPointerException {
super(P.getHeapModel());
this.pointerAnalysis = P;
this.callGraph = callGraph;
final OrdinalSetMapping<PointerKey> pointerKeys = getPointerKeys();
final NumberedNodeManager<Object> nodeMgr = new NumberedNodeManager<Object>() {
public Iterator<Object> iterator() {
return new CompoundIterator<Object>(pointerKeys.iterator(), P.getInstanceKeyMapping().iterator());
}
public int getNumberOfNodes() {
return pointerKeys.getSize() + P.getInstanceKeyMapping().getSize();
}
public void addNode(Object n) {
Assertions.UNREACHABLE();
}
public void removeNode(Object n) {
Assertions.UNREACHABLE();
}
public int getNumber(Object N) {
if (N instanceof PointerKey) {
return pointerKeys.getMappedIndex((PointerKey) N);
} else {
if (Assertions.verifyAssertions) {
if (!(N instanceof InstanceKey)) {
Assertions.UNREACHABLE(N.getClass().toString());
}
}
int inumber = P.getInstanceKeyMapping().getMappedIndex((InstanceKey) N);
return (inumber == -1) ? -1 : inumber + pointerKeys.getMaximumIndex();
}
}
public Object getNode(int number) {
if (number > pointerKeys.getMaximumIndex()) {
return P.getInstanceKeyMapping().getMappedObject(number - pointerKeys.getSize());
} else {
return pointerKeys.getMappedObject(number);
}
}
public int getMaxNumber() {
return getNumberOfNodes() - 1;
}
public boolean containsNode(Object n) {
return getNumber(n) != -1;
}
public Iterator<Object> iterateNodes(IntSet s) {
return new NumberedNodeIterator<Object>(s, this);
}
};
final IBinaryNaturalRelation pred = computePredecessors(nodeMgr);
final IntFunction<Object> toNode = new IntFunction<Object>() {
public Object apply(int i) {
return nodeMgr.getNode(i);
}
};
this.G = new AbstractNumberedGraph<Object>() {
private final EdgeManager<Object> edgeMgr = new EdgeManager<Object>() {
public Iterator<Object> getPredNodes(Object N) {
int n = nodeMgr.getNumber(N);
IntSet p = pred.getRelated(n);
if (p == null) {
return EmptyIterator.instance();
} else {
return new IntMapIterator<Object>(p.intIterator(), toNode);
}
}
public int getPredNodeCount(Object N) {
int n = nodeMgr.getNumber(N);
return pred.getRelatedCount(n);
}
public Iterator<? extends Object> getSuccNodes(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
if (succ == null) {
return EmptyIterator.instance();
}
SparseIntSet s = new MutableSparseIntSet(succ);
return new IntMapIterator<Object>(s.intIterator(), toNode);
}
public int getSuccNodeCount(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
return succ == null ? 0 : succ.length;
}
public void addEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeAllIncidentEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeIncomingEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeOutgoingEdges(Object node) {
Assertions.UNREACHABLE();
}
public boolean hasEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
return false;
}
};
@Override
protected NodeManager<Object> getNodeManager() {
return nodeMgr;
}
@Override
protected EdgeManager<Object> getEdgeManager() {
return edgeMgr;
}
};
}
| public BasicHeapGraph(final PointerAnalysis P, final CallGraph callGraph) throws NullPointerException {
super(P.getHeapModel());
this.pointerAnalysis = P;
this.callGraph = callGraph;
final OrdinalSetMapping<PointerKey> pointerKeys = getPointerKeys();
final NumberedNodeManager<Object> nodeMgr = new NumberedNodeManager<Object>() {
public Iterator<Object> iterator() {
return new CompoundIterator<Object>(pointerKeys.iterator(), P.getInstanceKeyMapping().iterator());
}
public int getNumberOfNodes() {
return pointerKeys.getSize() + P.getInstanceKeyMapping().getSize();
}
public void addNode(Object n) {
Assertions.UNREACHABLE();
}
public void removeNode(Object n) {
Assertions.UNREACHABLE();
}
public int getNumber(Object N) {
if (N instanceof PointerKey) {
return pointerKeys.getMappedIndex((PointerKey) N);
} else {
if (Assertions.verifyAssertions) {
if (!(N instanceof InstanceKey)) {
Assertions.UNREACHABLE(N.getClass().toString());
}
}
int inumber = P.getInstanceKeyMapping().getMappedIndex((InstanceKey) N);
return (inumber == -1) ? -1 : inumber + pointerKeys.getMaximumIndex() + 1;
}
}
public Object getNode(int number) {
if (number > pointerKeys.getMaximumIndex()) {
return P.getInstanceKeyMapping().getMappedObject(number - pointerKeys.getSize());
} else {
return pointerKeys.getMappedObject(number);
}
}
public int getMaxNumber() {
return getNumberOfNodes() - 1;
}
public boolean containsNode(Object n) {
return getNumber(n) != -1;
}
public Iterator<Object> iterateNodes(IntSet s) {
return new NumberedNodeIterator<Object>(s, this);
}
};
final IBinaryNaturalRelation pred = computePredecessors(nodeMgr);
final IntFunction<Object> toNode = new IntFunction<Object>() {
public Object apply(int i) {
return nodeMgr.getNode(i);
}
};
this.G = new AbstractNumberedGraph<Object>() {
private final EdgeManager<Object> edgeMgr = new EdgeManager<Object>() {
public Iterator<Object> getPredNodes(Object N) {
int n = nodeMgr.getNumber(N);
IntSet p = pred.getRelated(n);
if (p == null) {
return EmptyIterator.instance();
} else {
return new IntMapIterator<Object>(p.intIterator(), toNode);
}
}
public int getPredNodeCount(Object N) {
int n = nodeMgr.getNumber(N);
return pred.getRelatedCount(n);
}
public Iterator<? extends Object> getSuccNodes(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
if (succ == null) {
return EmptyIterator.instance();
}
SparseIntSet s = new MutableSparseIntSet(succ);
return new IntMapIterator<Object>(s.intIterator(), toNode);
}
public int getSuccNodeCount(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
return succ == null ? 0 : succ.length;
}
public void addEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
public void removeAllIncidentEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeIncomingEdges(Object node) {
Assertions.UNREACHABLE();
}
public void removeOutgoingEdges(Object node) {
Assertions.UNREACHABLE();
}
public boolean hasEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
return false;
}
};
@Override
protected NodeManager<Object> getNodeManager() {
return nodeMgr;
}
@Override
protected EdgeManager<Object> getEdgeManager() {
return edgeMgr;
}
};
}
|
diff --git a/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChatListener.java b/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChatListener.java
index 8508b97..05945f9 100644
--- a/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChatListener.java
+++ b/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChatListener.java
@@ -1,271 +1,272 @@
package me.cmastudios.plugins.WarhubModChat;
import java.util.ArrayList;
import java.util.List;
import me.cmastudios.plugins.WarhubModChat.util.Config;
import me.cmastudios.plugins.WarhubModChat.util.Message;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
public class WarhubModChatListener implements Listener {
public boolean nukerEnabled = false;
public static WarhubModChat plugin;
public WarhubModChatListener(WarhubModChat instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerChat(final PlayerChatEvent event) {
Player player = event.getPlayer();
if (plugin.mutedplrs.containsKey(player.getName())) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You are muted.");
return;
}
/*
* Anti-spam removed due to bukkit built in anti spam
*/
event.setMessage(Capslock(player, event.getMessage()));
ArrayList<Player> plrs = new ArrayList<Player>();
for (Player plr : plugin.getServer().getOnlinePlayers()) {
if (plugin.ignores.containsKey(plr))
plrs.add(plr);
}
for (Player plr : plrs) {
event.getRecipients().remove(plr);
}
if (event.getMessage().contains(ChatColor.COLOR_CHAR + "")
&& !player.hasPermission("warhub.moderator")) {
event.setMessage(event.getMessage().replaceAll(
ChatColor.COLOR_CHAR + "[0-9a-zA-Z]", ""));
}
if (plugin.channels.containsKey(event.getPlayer())) {
if (DynmapManager.getDynmapCommonAPI() != null)
DynmapManager.getDynmapCommonAPI()
.setDisableChatToWebProcessing(true);
if (plugin.channels.get(event.getPlayer()).equalsIgnoreCase("mod")) {
event.setCancelled(true);
sendToMods(Message
.colorizeText(Config.config.getString("modchat-format"))
.replace("%player", event.getPlayer().getDisplayName())
.replace("%message", event.getMessage()));
plugin.log.info("[MODCHAT] "
+ event.getPlayer().getDisplayName() + ": "
+ event.getMessage());
}
if (plugin.channels.get(event.getPlayer())
.equalsIgnoreCase("alert")) {
event.setCancelled(true);
Bukkit.getServer().broadcastMessage(
Message.colorizeText(
Config.config.getString("alert-format"))
.replace("%player",
event.getPlayer().getDisplayName())
.replace("%message", event.getMessage()));
if (DynmapManager.getDynmapCommonAPI() != null)
DynmapManager.getDynmapCommonAPI().sendBroadcastToWeb(
"Attention", event.getMessage());
}
} else {
if (DynmapManager.getDynmapCommonAPI() != null)
DynmapManager.getDynmapCommonAPI()
.setDisableChatToWebProcessing(false);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(final PlayerJoinEvent event) {
plugin.channels.remove(event.getPlayer());
plugin.ignores.remove(event.getPlayer());
/*
* Removed IP-logging due to multi-alt griefers not being much of a
* problem anymore
*/
}
@EventHandler
public void onBlockBreak(final BlockBreakEvent event) {
if (nukerEnabled) {
if (WarhubModChat.blockbreaks.get(event.getPlayer()) == null)
WarhubModChat.blockbreaks.put(event.getPlayer(), 0);
int breaks = WarhubModChat.blockbreaks.get(event.getPlayer());
breaks++;
WarhubModChat.blockbreaks.put(event.getPlayer(), breaks);
if (breaks > Config.config.getInt("blockspersecond")) {
event.setCancelled(true);
plugin.getServer().dispatchCommand(
plugin.getServer().getConsoleSender(),
"kick " + event.getPlayer().getName()
+ " Do not use nuker hacks!");
}
}
}
@EventHandler
public void onBlockPlace(final BlockPlaceEvent event) {
if (nukerEnabled) {
if (WarhubModChat.blockbreaks.get(event.getPlayer()) == null)
WarhubModChat.blockbreaks.put(event.getPlayer(), 0);
int breaks = WarhubModChat.blockbreaks.get(event.getPlayer());
breaks++;
WarhubModChat.blockbreaks.put(event.getPlayer(), breaks);
if (breaks > Config.config.getInt("blockspersecond")) {
event.getBlock().breakNaturally();
event.setCancelled(true);
plugin.getServer().dispatchCommand(
plugin.getServer().getConsoleSender(),
"kick " + event.getPlayer().getName()
+ " Do not use fastplace hacks!");
}
}
}
@EventHandler
public void onPlayerCommandPreprocess(
final PlayerCommandPreprocessEvent event) {
String command = event.getMessage();
/*
* Allow use of TooManyItems features
*/
if (command.startsWith("/toggledownfall")) {
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.weather")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
if (event.getPlayer().getWorld().hasStorm()) {
event.getPlayer().getWorld().setStorm(false);
} else {
event.getPlayer().getWorld().setStorm(true);
}
}
if (command.startsWith("/time set")) {
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.time.set")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
int ticks;
try {
ticks = Integer.parseInt(command.split(" ")[2]);
event.getPlayer().getWorld().setTime(ticks);
} catch (Exception e) {
event.getPlayer().sendMessage(e.toString());
}
}
if (command.startsWith("/give")) {
if (event.getPlayer().hasPermission("essentials.give"))
return;
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.item")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
try {
String player = command.split(" ")[1];
+ if (Config.config.getBoolean("debug")) System.out.println("'"+player+"'");
int item = Integer.parseInt(command.split(" ")[2]);
int amount = Integer.parseInt(command.split(" ")[3]);
short data = Short.parseShort(command.split(" ")[4]);
- if (event.getPlayer().getName() != player) {
+ if (event.getPlayer().getName().toLowerCase() != player.toLowerCase()) {
event.getPlayer().sendMessage(
ChatColor.RED
+ "You may only give items to yourself");
return;
}
event.getPlayer().getInventory()
.addItem(new ItemStack(item, amount, data));
} catch (Exception e) {
event.getPlayer().sendMessage(e.toString());
}
}
}
private String Capslock(Player player, String message) {
int countChars = 0;
int countCharsCaps = 0;
if (!player.hasPermission("warhub.moderator")) {
countChars = message.length();
if ((countChars > 0) && (countChars > 8)) {
for (int i = 0; i < countChars; i++) {
char c = message.charAt(i);
String ch = Character.toString(c);
if (ch.matches("[A-Z]")) {
countCharsCaps++;
}
}
if (100 / countChars * countCharsCaps >= 40) {
// Message has too many capital letters
message = message.toLowerCase();
plugin.warnings.put(player.getName(),
getWarnings(player) + 1);
if (getWarnings(player) % 50 == 0) {
plugin.getServer().dispatchCommand(
plugin.getServer().getConsoleSender(),
"kick " + player.getName()
+ " Do not type in caps!");
plugin.getServer().dispatchCommand(
plugin.getServer().getConsoleSender(),
"tempban " + player.getName() + " 20m");
} else if (getWarnings(player) % 5 == 0) {
plugin.getServer().dispatchCommand(
plugin.getServer().getConsoleSender(),
"kick " + player.getName()
+ " Do not type in caps!");
} else {
player.sendMessage(ChatColor.YELLOW
+ "Do not type in all caps ["
+ getWarnings(player) + " Violations]");
sendToMods(ChatColor.DARK_RED + "[WHChat] "
+ ChatColor.WHITE + player.getDisplayName()
+ ChatColor.YELLOW + " all caps'd ["
+ getWarnings(player) + " Violations]");
}
}
}
}
return message;
}
private int getWarnings(Player key) {
if (plugin.warnings.get(key.getName()) != null) {
return plugin.warnings.get(key.getName());
} else {
plugin.warnings.put(key.getName(), 0);
}
return 0;
}
private void sendToMods(String message) {
List<Player> sendto = new ArrayList<Player>();
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (p.hasPermission("warhub.moderator")) {
sendto.add(p);
}
}
for (Player p : sendto) {
p.sendMessage(message);
}
}
}
| false | true | public void onPlayerCommandPreprocess(
final PlayerCommandPreprocessEvent event) {
String command = event.getMessage();
/*
* Allow use of TooManyItems features
*/
if (command.startsWith("/toggledownfall")) {
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.weather")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
if (event.getPlayer().getWorld().hasStorm()) {
event.getPlayer().getWorld().setStorm(false);
} else {
event.getPlayer().getWorld().setStorm(true);
}
}
if (command.startsWith("/time set")) {
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.time.set")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
int ticks;
try {
ticks = Integer.parseInt(command.split(" ")[2]);
event.getPlayer().getWorld().setTime(ticks);
} catch (Exception e) {
event.getPlayer().sendMessage(e.toString());
}
}
if (command.startsWith("/give")) {
if (event.getPlayer().hasPermission("essentials.give"))
return;
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.item")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
try {
String player = command.split(" ")[1];
int item = Integer.parseInt(command.split(" ")[2]);
int amount = Integer.parseInt(command.split(" ")[3]);
short data = Short.parseShort(command.split(" ")[4]);
if (event.getPlayer().getName() != player) {
event.getPlayer().sendMessage(
ChatColor.RED
+ "You may only give items to yourself");
return;
}
event.getPlayer().getInventory()
.addItem(new ItemStack(item, amount, data));
} catch (Exception e) {
event.getPlayer().sendMessage(e.toString());
}
}
}
| public void onPlayerCommandPreprocess(
final PlayerCommandPreprocessEvent event) {
String command = event.getMessage();
/*
* Allow use of TooManyItems features
*/
if (command.startsWith("/toggledownfall")) {
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.weather")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
if (event.getPlayer().getWorld().hasStorm()) {
event.getPlayer().getWorld().setStorm(false);
} else {
event.getPlayer().getWorld().setStorm(true);
}
}
if (command.startsWith("/time set")) {
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.time.set")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
int ticks;
try {
ticks = Integer.parseInt(command.split(" ")[2]);
event.getPlayer().getWorld().setTime(ticks);
} catch (Exception e) {
event.getPlayer().sendMessage(e.toString());
}
}
if (command.startsWith("/give")) {
if (event.getPlayer().hasPermission("essentials.give"))
return;
event.setCancelled(true);
if (!event.getPlayer().hasPermission("essentials.item")) {
event.getPlayer().sendMessage(
ChatColor.RED + "You don't have permission.");
return;
}
try {
String player = command.split(" ")[1];
if (Config.config.getBoolean("debug")) System.out.println("'"+player+"'");
int item = Integer.parseInt(command.split(" ")[2]);
int amount = Integer.parseInt(command.split(" ")[3]);
short data = Short.parseShort(command.split(" ")[4]);
if (event.getPlayer().getName().toLowerCase() != player.toLowerCase()) {
event.getPlayer().sendMessage(
ChatColor.RED
+ "You may only give items to yourself");
return;
}
event.getPlayer().getInventory()
.addItem(new ItemStack(item, amount, data));
} catch (Exception e) {
event.getPlayer().sendMessage(e.toString());
}
}
}
|
diff --git a/TheAdventure/src/se/chalmers/kangaroo/model/iobject/RedBlueButton.java b/TheAdventure/src/se/chalmers/kangaroo/model/iobject/RedBlueButton.java
index 1a16e10..d415217 100644
--- a/TheAdventure/src/se/chalmers/kangaroo/model/iobject/RedBlueButton.java
+++ b/TheAdventure/src/se/chalmers/kangaroo/model/iobject/RedBlueButton.java
@@ -1,96 +1,97 @@
package se.chalmers.kangaroo.model.iobject;
import se.chalmers.kangaroo.constants.Constants;
import se.chalmers.kangaroo.model.GameMap;
import se.chalmers.kangaroo.model.InteractiveTile;
import se.chalmers.kangaroo.model.utils.Position;
import se.chalmers.kangaroo.utils.Sound2;
/**
*
* A class for the interactive object Red/Blue-button. If the outer part of the
* button is red, all red tiles will be visible and collidable, while all blue
* tiles are not visible and not collidable. If Kangaroo collides with the
* button, it will become blue and all the blue tiles will be visible and
* collidable instead.
*
* @author pavlov
*
*/
public class RedBlueButton implements InteractiveObject {
private GameMap gameMap;
private Position pos;
private boolean sleep;
private int id;
private Sound2 s;
public RedBlueButton(Position p, int id, GameMap gameMap) {
this.gameMap = gameMap;
this.pos = p;
this.sleep = false;
this.id = id;
this.s = Sound2.getInstance();
}
@Override
public void onCollision() {
if (!sleep) {
if (getId() % 2 == 0) {
s.playSfx("red");
} else {
s.playSfx("blue");
}
int x = gameMap.getTileWidth();
int y = gameMap.getTileHeight();
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
if (Constants.INTERACTIVE_TILES_REDBLUE.contains(" "
+ gameMap.getTile(j, i).getId() + " ")) {
((InteractiveTile) gameMap.getTile(j, i)).onTrigger();
}
InteractiveObject iobj = gameMap.getIObjectAt(j, i);
if(iobj != null)
- iobj.changeId();
+ if(Constants.IOBJECTS_IDS_REDBLUE.contains(" "+iobj.getId()+" "))
+ iobj.changeId();
}
}
sleep = true;
new Thread() {
@Override
public void run() {
try {
sleep(600);
sleep = false;
} catch (InterruptedException e) {
}
};
}.start();
}
}
@Override
public int getChangedId(int currentId) {
if (currentId % 2 == 0) {
return currentId - 1;
} else {
return currentId + 1;
}
}
@Override
public Position getPosition() {
return pos;
}
@Override
public int getId() {
return id;
}
@Override
public void changeId(){
id = id == 71 ? id + 1 : id - 1;
}
}
| true | true | public void onCollision() {
if (!sleep) {
if (getId() % 2 == 0) {
s.playSfx("red");
} else {
s.playSfx("blue");
}
int x = gameMap.getTileWidth();
int y = gameMap.getTileHeight();
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
if (Constants.INTERACTIVE_TILES_REDBLUE.contains(" "
+ gameMap.getTile(j, i).getId() + " ")) {
((InteractiveTile) gameMap.getTile(j, i)).onTrigger();
}
InteractiveObject iobj = gameMap.getIObjectAt(j, i);
if(iobj != null)
iobj.changeId();
}
}
sleep = true;
new Thread() {
@Override
public void run() {
try {
sleep(600);
sleep = false;
} catch (InterruptedException e) {
}
};
}.start();
}
}
| public void onCollision() {
if (!sleep) {
if (getId() % 2 == 0) {
s.playSfx("red");
} else {
s.playSfx("blue");
}
int x = gameMap.getTileWidth();
int y = gameMap.getTileHeight();
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
if (Constants.INTERACTIVE_TILES_REDBLUE.contains(" "
+ gameMap.getTile(j, i).getId() + " ")) {
((InteractiveTile) gameMap.getTile(j, i)).onTrigger();
}
InteractiveObject iobj = gameMap.getIObjectAt(j, i);
if(iobj != null)
if(Constants.IOBJECTS_IDS_REDBLUE.contains(" "+iobj.getId()+" "))
iobj.changeId();
}
}
sleep = true;
new Thread() {
@Override
public void run() {
try {
sleep(600);
sleep = false;
} catch (InterruptedException e) {
}
};
}.start();
}
}
|
diff --git a/src/main/ed/js/Shell.java b/src/main/ed/js/Shell.java
index 2510d07e0..2903162d7 100644
--- a/src/main/ed/js/Shell.java
+++ b/src/main/ed/js/Shell.java
@@ -1,179 +1,179 @@
// Shell.java
package ed.js;
import java.io.*;
import java.util.*;
import jline.*;
import ed.db.*;
import ed.io.*;
import ed.lang.*;
import ed.js.func.*;
import ed.js.engine.*;
import ed.appserver.*;
import ed.appserver.templates.*;
public class Shell {
static final PrintStream _originalPrintStream = System.out;
final static OutputStream _myOutputStream = new OutputStream(){
public void write( byte b[] , int off , int len ){
RuntimeException re = new RuntimeException();
re.fillInStackTrace();
re.printStackTrace();
_originalPrintStream.write( b , off , len );
}
public void write( int b ){
_originalPrintStream.write( b );
throw new RuntimeException("sad" );
}
};
public final static PrintStream _myPrintStream = new PrintStream( _myOutputStream );
public static void addNiceShellStuff( Scope s ){
s.put( "core" , CoreJS.get().getLibrary( null , null , s ) , true );
s.put( "external" , Module.getModule( "external" ).getLibrary( null , s ) , true );
s.put( "local" , new JSFileLibrary( new File( "." ) , "local" , s ) , true );
s.put( "connect" , new JSFunctionCalls2(){
public Object call( Scope s , Object name , Object ip , Object crap[] ){
return DBProvider.get( name.toString() , ip == null ? null : ip.toString() );
}
Map<String,DBJni> _dbs = new HashMap<String,DBJni>();
} , true );
s.put( "openFile" , new JSFunctionCalls1(){
public Object call( Scope s , Object fileName , Object crap[] ){
return new JSLocalFile( fileName.toString() );
}
} , true );
s.put( "exit" , new JSFunctionCalls0(){
public Object call( Scope s , Object crap[] ){
System.exit(0);
return null;
}
} , true );
s.put( "log" , ed.log.Logger.getLogger( "shell" ) ,true );
s.put( "scopeWithRoot" , new JSFunctionCalls1(){
public Object call( Scope s , Object fileName , Object crap[] ){
return s.child(new File(fileName.toString()));
}
} , true);
Djang10Converter.injectHelpers(s);
}
public static void main( String args[] )
throws Exception {
System.setProperty( "NO-SECURITY" , "true" );
Scope s = Scope.newGlobal().child( new File("." ) );
s.makeThreadLocal();
addNiceShellStuff( s );
File init = new File( System.getenv( "HOME" ) + "/.init.js" );
if ( init.exists() )
s.eval( init );
if ( args.length > 0 && args[0].equals( "-shell" ) ){
String data = StreamUtil.readFully( new FileInputStream( args[1] ) );
if ( data.startsWith( "#!" ) )
data = data.substring( data.indexOf( "\n" ) + 1);
JSFunction func = Convert.makeAnon( data );
Object jsArgs[] = new Object[ args.length - 2 ];
for ( int i=0; i<jsArgs.length; i++ )
jsArgs[i] = args[i+2];
func.call( s , jsArgs );
return;
}
boolean exit = false;
for ( String a : args ){
if ( a.equals( "-exit" ) ){
exit = true;
continue;
}
if ( a.endsWith( ".js" ) ){
File f = new File( a );
- JSFileLibrary fl = new JSFileLibrary( f.getParentFile() , "blah" , s );
+ JSFileLibrary fl = new JSFileLibrary( f.getParentFile() == null ? new File( "." ) : f.getParentFile() , "blah" , s );
try {
((JSFunction)(fl.get( f.getName().replaceAll( ".js$" , "" ) ))).call( s );
}
catch ( Exception e ){
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
return;
}
}
else {
Template t = new Template( a , StreamUtil.readFully( new FileInputStream( a ) ) , Language.find( a ) );
while ( ! t.getExtension().equals( "js" ) ){
TemplateConverter.Result r = TemplateEngine.oneConvert( t , null );
if ( r == null )
throw new RuntimeException( "can't convert : " + t.getName() );
t = r.getNewTemplate();
}
try {
s.eval( t.getContent() );
}
catch ( Exception e ){
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
return;
}
}
}
if ( exit )
return;
String line;
ConsoleReader console = new ConsoleReader();
console.setHistory( new History( new File( ".jsshell" ) ) );
boolean hasReturn[] = new boolean[1];
while ( ( line = console.readLine( "> " ) ) != null ){
line = line.trim();
if ( line.length() == 0 )
continue;
if ( line.equals( "exit" ) ){
System.out.println( "bye" );
break;
}
try {
Object res = s.eval( line , "lastline" , hasReturn );
if ( hasReturn[0] )
System.out.println( JSON.serialize( res ) );
}
catch ( Exception e ){
if ( JS.RAW_EXCPETIONS )
e.printStackTrace();
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
System.out.println();
}
}
}
}
| true | true | public static void main( String args[] )
throws Exception {
System.setProperty( "NO-SECURITY" , "true" );
Scope s = Scope.newGlobal().child( new File("." ) );
s.makeThreadLocal();
addNiceShellStuff( s );
File init = new File( System.getenv( "HOME" ) + "/.init.js" );
if ( init.exists() )
s.eval( init );
if ( args.length > 0 && args[0].equals( "-shell" ) ){
String data = StreamUtil.readFully( new FileInputStream( args[1] ) );
if ( data.startsWith( "#!" ) )
data = data.substring( data.indexOf( "\n" ) + 1);
JSFunction func = Convert.makeAnon( data );
Object jsArgs[] = new Object[ args.length - 2 ];
for ( int i=0; i<jsArgs.length; i++ )
jsArgs[i] = args[i+2];
func.call( s , jsArgs );
return;
}
boolean exit = false;
for ( String a : args ){
if ( a.equals( "-exit" ) ){
exit = true;
continue;
}
if ( a.endsWith( ".js" ) ){
File f = new File( a );
JSFileLibrary fl = new JSFileLibrary( f.getParentFile() , "blah" , s );
try {
((JSFunction)(fl.get( f.getName().replaceAll( ".js$" , "" ) ))).call( s );
}
catch ( Exception e ){
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
return;
}
}
else {
Template t = new Template( a , StreamUtil.readFully( new FileInputStream( a ) ) , Language.find( a ) );
while ( ! t.getExtension().equals( "js" ) ){
TemplateConverter.Result r = TemplateEngine.oneConvert( t , null );
if ( r == null )
throw new RuntimeException( "can't convert : " + t.getName() );
t = r.getNewTemplate();
}
try {
s.eval( t.getContent() );
}
catch ( Exception e ){
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
return;
}
}
}
if ( exit )
return;
String line;
ConsoleReader console = new ConsoleReader();
console.setHistory( new History( new File( ".jsshell" ) ) );
boolean hasReturn[] = new boolean[1];
while ( ( line = console.readLine( "> " ) ) != null ){
line = line.trim();
if ( line.length() == 0 )
continue;
if ( line.equals( "exit" ) ){
System.out.println( "bye" );
break;
}
try {
Object res = s.eval( line , "lastline" , hasReturn );
if ( hasReturn[0] )
System.out.println( JSON.serialize( res ) );
}
catch ( Exception e ){
if ( JS.RAW_EXCPETIONS )
e.printStackTrace();
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
System.out.println();
}
}
}
| public static void main( String args[] )
throws Exception {
System.setProperty( "NO-SECURITY" , "true" );
Scope s = Scope.newGlobal().child( new File("." ) );
s.makeThreadLocal();
addNiceShellStuff( s );
File init = new File( System.getenv( "HOME" ) + "/.init.js" );
if ( init.exists() )
s.eval( init );
if ( args.length > 0 && args[0].equals( "-shell" ) ){
String data = StreamUtil.readFully( new FileInputStream( args[1] ) );
if ( data.startsWith( "#!" ) )
data = data.substring( data.indexOf( "\n" ) + 1);
JSFunction func = Convert.makeAnon( data );
Object jsArgs[] = new Object[ args.length - 2 ];
for ( int i=0; i<jsArgs.length; i++ )
jsArgs[i] = args[i+2];
func.call( s , jsArgs );
return;
}
boolean exit = false;
for ( String a : args ){
if ( a.equals( "-exit" ) ){
exit = true;
continue;
}
if ( a.endsWith( ".js" ) ){
File f = new File( a );
JSFileLibrary fl = new JSFileLibrary( f.getParentFile() == null ? new File( "." ) : f.getParentFile() , "blah" , s );
try {
((JSFunction)(fl.get( f.getName().replaceAll( ".js$" , "" ) ))).call( s );
}
catch ( Exception e ){
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
return;
}
}
else {
Template t = new Template( a , StreamUtil.readFully( new FileInputStream( a ) ) , Language.find( a ) );
while ( ! t.getExtension().equals( "js" ) ){
TemplateConverter.Result r = TemplateEngine.oneConvert( t , null );
if ( r == null )
throw new RuntimeException( "can't convert : " + t.getName() );
t = r.getNewTemplate();
}
try {
s.eval( t.getContent() );
}
catch ( Exception e ){
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
return;
}
}
}
if ( exit )
return;
String line;
ConsoleReader console = new ConsoleReader();
console.setHistory( new History( new File( ".jsshell" ) ) );
boolean hasReturn[] = new boolean[1];
while ( ( line = console.readLine( "> " ) ) != null ){
line = line.trim();
if ( line.length() == 0 )
continue;
if ( line.equals( "exit" ) ){
System.out.println( "bye" );
break;
}
try {
Object res = s.eval( line , "lastline" , hasReturn );
if ( hasReturn[0] )
System.out.println( JSON.serialize( res ) );
}
catch ( Exception e ){
if ( JS.RAW_EXCPETIONS )
e.printStackTrace();
StackTraceHolder.getInstance().fix( e );
e.printStackTrace();
System.out.println();
}
}
}
|
diff --git a/App/src/main/java/org/ieeedtu/troika/fragment/RegisterFragment.java b/App/src/main/java/org/ieeedtu/troika/fragment/RegisterFragment.java
index 01c64db..9b4a783 100644
--- a/App/src/main/java/org/ieeedtu/troika/fragment/RegisterFragment.java
+++ b/App/src/main/java/org/ieeedtu/troika/fragment/RegisterFragment.java
@@ -1,256 +1,256 @@
package org.ieeedtu.troika.fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.ieeedtu.troika.R;
import org.ieeedtu.troika.utils.SubmitRegister;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link android.support.v4.app.Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link RegisterFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link RegisterFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class RegisterFragment extends Fragment {
private String registerName = new String();
private String registerEmail = new String();
private String registerPhone = new String();
private String registerTeam = new String();
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment RegisterFragment.
*/
// TODO: Rename and change types and number of parameters
public static RegisterFragment newInstance(String param1, String param2) {
RegisterFragment fragment = new RegisterFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public RegisterFragment() {
// Required empty public constructor
}
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_register, container, false);
final EditText rName, rEmail, rPhone, rTeam;
final CheckBox
bits,
bots,
brainwave,
bytes,
design_pro,
electrocution,
envision,
ether_avatar,
inspironnature,
junkyard,
mist,
radix,
spac,
technovision,
todo_en_uno,
vihaan;
rName = (EditText) rootView.findViewById(R.id.register_name);
rEmail = (EditText) rootView.findViewById(R.id.register_email);
rPhone = (EditText) rootView.findViewById(R.id.register_phone);
rTeam = (EditText) rootView.findViewById(R.id.register_teamname);
bits = (CheckBox) rootView.findViewById(R.id.register_bits_check);
bots = (CheckBox) rootView.findViewById(R.id.register_bots_check);
brainwave = (CheckBox) rootView.findViewById(R.id.register_brainwave_check);
bytes = (CheckBox) rootView.findViewById(R.id.register_bytes_check);
design_pro = (CheckBox) rootView.findViewById(R.id.register_design_pro_check);
electrocution = (CheckBox) rootView.findViewById(R.id.register_electrocution_check);
envision = (CheckBox) rootView.findViewById(R.id.register_envision_check);
ether_avatar = (CheckBox) rootView.findViewById(R.id.register_ether_avatar_check);
inspironnature = (CheckBox) rootView.findViewById(R.id.register_inspironnature_check);
junkyard = (CheckBox) rootView.findViewById(R.id.register_junkyard_check);
mist = (CheckBox) rootView.findViewById(R.id.register_mist_check);
radix = (CheckBox) rootView.findViewById(R.id.register_radix_check);
spac = (CheckBox) rootView.findViewById(R.id.register_spac_check);
technovision = (CheckBox) rootView.findViewById(R.id.register_technovision_check);
todo_en_uno = (CheckBox) rootView.findViewById(R.id.register_todo_en_uno_check);
vihaan = (CheckBox) rootView.findViewById(R.id.register_vihaan_check);
Button submit = (Button) rootView.findViewById(R.id.register_submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
registerName = rName.getText().toString();
registerEmail = rEmail.getText().toString();
registerPhone = rPhone.getText().toString();
registerTeam = rTeam.getText().toString();
if (registerName.length() < 1
|| registerEmail.length() < 1
|| registerPhone.length() < 1
|| registerTeam.length() < 1) {
Toast invalid = Toast.makeText(getActivity().getApplicationContext(), "Name, Email, Phone and Team are required", Toast.LENGTH_SHORT);
invalid.show();
return;
}
String reg_bits = String.valueOf(bits.isChecked());
String reg_bots = String.valueOf(bots.isChecked());
String reg_brainwave = String.valueOf(brainwave.isChecked());
String reg_bytes = String.valueOf(bytes.isChecked());
String reg_design_pro = String.valueOf(design_pro.isChecked());
String reg_electrocution = String.valueOf(electrocution.isChecked());
String reg_envision = String.valueOf(envision.isChecked());
String reg_ether_avatar = String.valueOf(ether_avatar.isChecked());
String reg_inspironnature = String.valueOf(inspironnature.isChecked());
String reg_junkyard = String.valueOf(junkyard.isChecked());
String reg_mist = String.valueOf(mist.isChecked());
String reg_radix = String.valueOf(radix.isChecked());
String reg_spac = String.valueOf(spac.isChecked());
String reg_technovision = String.valueOf(technovision.isChecked());
String reg_todo_en_uno = String.valueOf(todo_en_uno.isChecked());
String reg_vihaan = String.valueOf(vihaan.isChecked());
HttpClient submitClient = new DefaultHttpClient();
- HttpPost submitPost = new HttpPost("ieeedtu.com/appdata/submit-app.php");
+ HttpPost submitPost = new HttpPost("http://ieeedtu.com/appdata/submit-app.php");
List<NameValuePair> postPair = new ArrayList<NameValuePair>();
postPair.add(new BasicNameValuePair("name", registerName));
postPair.add(new BasicNameValuePair("email", registerEmail));
postPair.add(new BasicNameValuePair("phone", registerPhone));
postPair.add(new BasicNameValuePair("teamname", registerTeam));
postPair.add(new BasicNameValuePair("bits", reg_bits));
postPair.add(new BasicNameValuePair("bots", reg_bots));
postPair.add(new BasicNameValuePair("brainwave", reg_brainwave));
postPair.add(new BasicNameValuePair("bytes", reg_bytes));
postPair.add(new BasicNameValuePair("design_pro", reg_design_pro));
postPair.add(new BasicNameValuePair("electrocution", reg_electrocution));
postPair.add(new BasicNameValuePair("envision", reg_envision));
postPair.add(new BasicNameValuePair("ether_avatar", reg_ether_avatar));
postPair.add(new BasicNameValuePair("inspironnature", reg_inspironnature));
postPair.add(new BasicNameValuePair("junkyard", reg_junkyard));
postPair.add(new BasicNameValuePair("mist", reg_mist));
postPair.add(new BasicNameValuePair("radix", reg_radix));
postPair.add(new BasicNameValuePair("spac", reg_spac));
postPair.add(new BasicNameValuePair("technovision", reg_technovision));
postPair.add(new BasicNameValuePair("todo_en_uno", reg_todo_en_uno));
postPair.add(new BasicNameValuePair("vihaan", reg_vihaan));
try {
submitPost.setEntity(new UrlEncodedFormEntity(postPair));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d("TROIKA REGISTER", postPair.toString());
SubmitRegister submitRegister = new SubmitRegister(submitClient, submitPost);
submitRegister.execute();
}
});
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_register, container, false);
final EditText rName, rEmail, rPhone, rTeam;
final CheckBox
bits,
bots,
brainwave,
bytes,
design_pro,
electrocution,
envision,
ether_avatar,
inspironnature,
junkyard,
mist,
radix,
spac,
technovision,
todo_en_uno,
vihaan;
rName = (EditText) rootView.findViewById(R.id.register_name);
rEmail = (EditText) rootView.findViewById(R.id.register_email);
rPhone = (EditText) rootView.findViewById(R.id.register_phone);
rTeam = (EditText) rootView.findViewById(R.id.register_teamname);
bits = (CheckBox) rootView.findViewById(R.id.register_bits_check);
bots = (CheckBox) rootView.findViewById(R.id.register_bots_check);
brainwave = (CheckBox) rootView.findViewById(R.id.register_brainwave_check);
bytes = (CheckBox) rootView.findViewById(R.id.register_bytes_check);
design_pro = (CheckBox) rootView.findViewById(R.id.register_design_pro_check);
electrocution = (CheckBox) rootView.findViewById(R.id.register_electrocution_check);
envision = (CheckBox) rootView.findViewById(R.id.register_envision_check);
ether_avatar = (CheckBox) rootView.findViewById(R.id.register_ether_avatar_check);
inspironnature = (CheckBox) rootView.findViewById(R.id.register_inspironnature_check);
junkyard = (CheckBox) rootView.findViewById(R.id.register_junkyard_check);
mist = (CheckBox) rootView.findViewById(R.id.register_mist_check);
radix = (CheckBox) rootView.findViewById(R.id.register_radix_check);
spac = (CheckBox) rootView.findViewById(R.id.register_spac_check);
technovision = (CheckBox) rootView.findViewById(R.id.register_technovision_check);
todo_en_uno = (CheckBox) rootView.findViewById(R.id.register_todo_en_uno_check);
vihaan = (CheckBox) rootView.findViewById(R.id.register_vihaan_check);
Button submit = (Button) rootView.findViewById(R.id.register_submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
registerName = rName.getText().toString();
registerEmail = rEmail.getText().toString();
registerPhone = rPhone.getText().toString();
registerTeam = rTeam.getText().toString();
if (registerName.length() < 1
|| registerEmail.length() < 1
|| registerPhone.length() < 1
|| registerTeam.length() < 1) {
Toast invalid = Toast.makeText(getActivity().getApplicationContext(), "Name, Email, Phone and Team are required", Toast.LENGTH_SHORT);
invalid.show();
return;
}
String reg_bits = String.valueOf(bits.isChecked());
String reg_bots = String.valueOf(bots.isChecked());
String reg_brainwave = String.valueOf(brainwave.isChecked());
String reg_bytes = String.valueOf(bytes.isChecked());
String reg_design_pro = String.valueOf(design_pro.isChecked());
String reg_electrocution = String.valueOf(electrocution.isChecked());
String reg_envision = String.valueOf(envision.isChecked());
String reg_ether_avatar = String.valueOf(ether_avatar.isChecked());
String reg_inspironnature = String.valueOf(inspironnature.isChecked());
String reg_junkyard = String.valueOf(junkyard.isChecked());
String reg_mist = String.valueOf(mist.isChecked());
String reg_radix = String.valueOf(radix.isChecked());
String reg_spac = String.valueOf(spac.isChecked());
String reg_technovision = String.valueOf(technovision.isChecked());
String reg_todo_en_uno = String.valueOf(todo_en_uno.isChecked());
String reg_vihaan = String.valueOf(vihaan.isChecked());
HttpClient submitClient = new DefaultHttpClient();
HttpPost submitPost = new HttpPost("ieeedtu.com/appdata/submit-app.php");
List<NameValuePair> postPair = new ArrayList<NameValuePair>();
postPair.add(new BasicNameValuePair("name", registerName));
postPair.add(new BasicNameValuePair("email", registerEmail));
postPair.add(new BasicNameValuePair("phone", registerPhone));
postPair.add(new BasicNameValuePair("teamname", registerTeam));
postPair.add(new BasicNameValuePair("bits", reg_bits));
postPair.add(new BasicNameValuePair("bots", reg_bots));
postPair.add(new BasicNameValuePair("brainwave", reg_brainwave));
postPair.add(new BasicNameValuePair("bytes", reg_bytes));
postPair.add(new BasicNameValuePair("design_pro", reg_design_pro));
postPair.add(new BasicNameValuePair("electrocution", reg_electrocution));
postPair.add(new BasicNameValuePair("envision", reg_envision));
postPair.add(new BasicNameValuePair("ether_avatar", reg_ether_avatar));
postPair.add(new BasicNameValuePair("inspironnature", reg_inspironnature));
postPair.add(new BasicNameValuePair("junkyard", reg_junkyard));
postPair.add(new BasicNameValuePair("mist", reg_mist));
postPair.add(new BasicNameValuePair("radix", reg_radix));
postPair.add(new BasicNameValuePair("spac", reg_spac));
postPair.add(new BasicNameValuePair("technovision", reg_technovision));
postPair.add(new BasicNameValuePair("todo_en_uno", reg_todo_en_uno));
postPair.add(new BasicNameValuePair("vihaan", reg_vihaan));
try {
submitPost.setEntity(new UrlEncodedFormEntity(postPair));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d("TROIKA REGISTER", postPair.toString());
SubmitRegister submitRegister = new SubmitRegister(submitClient, submitPost);
submitRegister.execute();
}
});
return rootView;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_register, container, false);
final EditText rName, rEmail, rPhone, rTeam;
final CheckBox
bits,
bots,
brainwave,
bytes,
design_pro,
electrocution,
envision,
ether_avatar,
inspironnature,
junkyard,
mist,
radix,
spac,
technovision,
todo_en_uno,
vihaan;
rName = (EditText) rootView.findViewById(R.id.register_name);
rEmail = (EditText) rootView.findViewById(R.id.register_email);
rPhone = (EditText) rootView.findViewById(R.id.register_phone);
rTeam = (EditText) rootView.findViewById(R.id.register_teamname);
bits = (CheckBox) rootView.findViewById(R.id.register_bits_check);
bots = (CheckBox) rootView.findViewById(R.id.register_bots_check);
brainwave = (CheckBox) rootView.findViewById(R.id.register_brainwave_check);
bytes = (CheckBox) rootView.findViewById(R.id.register_bytes_check);
design_pro = (CheckBox) rootView.findViewById(R.id.register_design_pro_check);
electrocution = (CheckBox) rootView.findViewById(R.id.register_electrocution_check);
envision = (CheckBox) rootView.findViewById(R.id.register_envision_check);
ether_avatar = (CheckBox) rootView.findViewById(R.id.register_ether_avatar_check);
inspironnature = (CheckBox) rootView.findViewById(R.id.register_inspironnature_check);
junkyard = (CheckBox) rootView.findViewById(R.id.register_junkyard_check);
mist = (CheckBox) rootView.findViewById(R.id.register_mist_check);
radix = (CheckBox) rootView.findViewById(R.id.register_radix_check);
spac = (CheckBox) rootView.findViewById(R.id.register_spac_check);
technovision = (CheckBox) rootView.findViewById(R.id.register_technovision_check);
todo_en_uno = (CheckBox) rootView.findViewById(R.id.register_todo_en_uno_check);
vihaan = (CheckBox) rootView.findViewById(R.id.register_vihaan_check);
Button submit = (Button) rootView.findViewById(R.id.register_submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
registerName = rName.getText().toString();
registerEmail = rEmail.getText().toString();
registerPhone = rPhone.getText().toString();
registerTeam = rTeam.getText().toString();
if (registerName.length() < 1
|| registerEmail.length() < 1
|| registerPhone.length() < 1
|| registerTeam.length() < 1) {
Toast invalid = Toast.makeText(getActivity().getApplicationContext(), "Name, Email, Phone and Team are required", Toast.LENGTH_SHORT);
invalid.show();
return;
}
String reg_bits = String.valueOf(bits.isChecked());
String reg_bots = String.valueOf(bots.isChecked());
String reg_brainwave = String.valueOf(brainwave.isChecked());
String reg_bytes = String.valueOf(bytes.isChecked());
String reg_design_pro = String.valueOf(design_pro.isChecked());
String reg_electrocution = String.valueOf(electrocution.isChecked());
String reg_envision = String.valueOf(envision.isChecked());
String reg_ether_avatar = String.valueOf(ether_avatar.isChecked());
String reg_inspironnature = String.valueOf(inspironnature.isChecked());
String reg_junkyard = String.valueOf(junkyard.isChecked());
String reg_mist = String.valueOf(mist.isChecked());
String reg_radix = String.valueOf(radix.isChecked());
String reg_spac = String.valueOf(spac.isChecked());
String reg_technovision = String.valueOf(technovision.isChecked());
String reg_todo_en_uno = String.valueOf(todo_en_uno.isChecked());
String reg_vihaan = String.valueOf(vihaan.isChecked());
HttpClient submitClient = new DefaultHttpClient();
HttpPost submitPost = new HttpPost("http://ieeedtu.com/appdata/submit-app.php");
List<NameValuePair> postPair = new ArrayList<NameValuePair>();
postPair.add(new BasicNameValuePair("name", registerName));
postPair.add(new BasicNameValuePair("email", registerEmail));
postPair.add(new BasicNameValuePair("phone", registerPhone));
postPair.add(new BasicNameValuePair("teamname", registerTeam));
postPair.add(new BasicNameValuePair("bits", reg_bits));
postPair.add(new BasicNameValuePair("bots", reg_bots));
postPair.add(new BasicNameValuePair("brainwave", reg_brainwave));
postPair.add(new BasicNameValuePair("bytes", reg_bytes));
postPair.add(new BasicNameValuePair("design_pro", reg_design_pro));
postPair.add(new BasicNameValuePair("electrocution", reg_electrocution));
postPair.add(new BasicNameValuePair("envision", reg_envision));
postPair.add(new BasicNameValuePair("ether_avatar", reg_ether_avatar));
postPair.add(new BasicNameValuePair("inspironnature", reg_inspironnature));
postPair.add(new BasicNameValuePair("junkyard", reg_junkyard));
postPair.add(new BasicNameValuePair("mist", reg_mist));
postPair.add(new BasicNameValuePair("radix", reg_radix));
postPair.add(new BasicNameValuePair("spac", reg_spac));
postPair.add(new BasicNameValuePair("technovision", reg_technovision));
postPair.add(new BasicNameValuePair("todo_en_uno", reg_todo_en_uno));
postPair.add(new BasicNameValuePair("vihaan", reg_vihaan));
try {
submitPost.setEntity(new UrlEncodedFormEntity(postPair));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d("TROIKA REGISTER", postPair.toString());
SubmitRegister submitRegister = new SubmitRegister(submitClient, submitPost);
submitRegister.execute();
}
});
return rootView;
}
|
diff --git a/javafxdoc/src/com/sun/tools/xslhtml/XHTMLProcessingUtils.java b/javafxdoc/src/com/sun/tools/xslhtml/XHTMLProcessingUtils.java
index e0b8ca925..b2dba5d19 100644
--- a/javafxdoc/src/com/sun/tools/xslhtml/XHTMLProcessingUtils.java
+++ b/javafxdoc/src/com/sun/tools/xslhtml/XHTMLProcessingUtils.java
@@ -1,698 +1,698 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.xslhtml;
import com.sun.tools.javafx.script.JavaFXScriptEngineFactory;
import com.sun.tools.xmldoclet.Util;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import javax.swing.JComponent;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import static java.util.logging.Level.*;
/**
*
* @author [email protected]
*/
public class XHTMLProcessingUtils {
private static ResourceBundle messageRB = null;
private static Logger logger = Logger.getLogger(XHTMLProcessingUtils.class.getName());;
private static boolean SDK_THEME = true;
static {
// set verbose for initial development
logger.setLevel(ALL); //TODO: remove or set to INFO when finished
}
private static final String PARAMETER_PROFILES_ENABLED = "profiles-enabled";
private static final String PARAMETER_TARGET_PROFILE = "target-profile";
/**
* Transform XMLDoclet output to XHTML using XSLT.
*
* @param xmlInputPath the path of the XMLDoclet output to transform
* @param xsltStream the XSLT to implement the transformation, as an input stream.
* @throws java.lang.Exception
*/
public static void process(List<String> xmlInputs, InputStream xsltStream,
String sourcePath, File docsdir, Map<String,String> parameters
) throws Exception {
if (xmlInputs == null || xmlInputs.size() == 0)
throw new IllegalArgumentException("no XML input file(s)");
System.out.println(getString("transforming.to.html"));
// TODO code application logic here
//hack to get this to work on the mac
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
System.setProperty("javax.xml.parsers.SAXParserFactory",
"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
if (xsltStream == null) {
if(SDK_THEME) {
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/sdk.xsl");
} else {
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/javadoc.xsl");
}
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
pe(WARNING, "warning: ", exception);
}
public void error(SAXParseException exception) throws SAXException {
pe(SEVERE, "error: ", exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
pe(SEVERE, "fatal error", exception);
}
private void pe(Level level, String string, SAXParseException exception) {
p(level, string + " line: " + exception.getLineNumber() + " column: " +
exception.getColumnNumber() + " " + exception.getLocalizedMessage());
}
});
//File docsdir = new File("fxdocs");
if (!docsdir.exists()) {
docsdir.mkdir();
}
p(INFO, getString("copying"));
copyResource(docsdir,"empty.html");
copyResource(docsdir,"general.css");
copyResource(docsdir,"sdk.css");
- copyResource(docsdir,"core.js");
- copyResource(docsdir,"more.js");
+ copyResource(docsdir,"mootools-1.2.1-yui.js");
+ copyResource(docsdir,"sdk.js");
copyResource(docsdir,"sessvars.js");
File images = new File(docsdir,"images");
images.mkdir();
copy(XHTMLProcessingUtils.class.getResource("resources/quote-background-1.gif"), new File(images, "quote-background-1.gif"));
copyResource(images,"JFX_arrow_down.png");
copyResource(images,"JFX_arrow_right.png");
copyResource(images,"JFX_arrow_up.png");
copyResource(images,"JFX_highlight_dot.png");
p(INFO, getString("transforming"));
//File xsltFile = new File("javadoc.xsl");
//p("reading xslt exists in: " + xsltFile.exists());
Source xslt = new StreamSource(xsltStream);
TransformerFactory transFact = TransformerFactory.newInstance();
transFact.setURIResolver(new URIResolver() {
public Source resolve(String href, String base) throws TransformerException {
p(INFO, "Trying to resolve: " + href + " " + base);
URL url = XHTMLProcessingUtils.class.getResource("resources/"+href);
p(INFO, "Resolved " + href + ":" + base + " to " + url);
try {
return new StreamSource(url.openStream());
} catch (IOException ex) {
Logger.getLogger(XHTMLProcessingUtils.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
});
Transformer trans = transFact.newTransformer(xslt);
if(SDK_THEME) {
trans.setParameter("inline-classlist","true");
trans.setParameter("inline-descriptions", "true");
}
for(String key : parameters.keySet()) {
System.out.println("using key: " + key + " " + parameters.get(key));
trans.setParameter(key, parameters.get(key));
}
trans.setErrorListener(new MainErrorListener());
//build xml doc for the packages
Document packages_doc = builder.newDocument();
Element package_list_elem = packages_doc.createElement("packageList");
packages_doc.appendChild(package_list_elem);
//merge all xml files into single document
Document unified = builder.newDocument();
Element javadocElement = unified.createElement("javadoc");
unified.appendChild(javadocElement);
mergeDocuments(xmlInputs, builder, unified, javadocElement);
// print out packages list
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList packages = (NodeList) xpath.evaluate("/javadoc/package", unified, XPathConstants.NODESET);
p(INFO, MessageFormat.format(getString("creating.packages"), packages.getLength()));
// collect all package names in this array
String[] pkgNames = new String[packages.getLength()];
//for each package, generate the package itself and append to package list doc
for (int i = 0; i < packages.getLength(); i++) {
Element pkg = ((Element) packages.item(i));
String name = pkg.getAttribute("name");
Element package_elem = packages_doc.createElement("package");
package_elem.setAttribute("name", name);
package_list_elem.appendChild(package_elem);
copyDocComment(pkg,package_elem);
Element first_line = packages_doc.createElement("first-line-comment");
first_line.appendChild(packages_doc.createTextNode("first line comment"));
package_elem.appendChild(first_line);
processPackage(name, pkg, xpath, docsdir, trans, package_elem);
pkgNames[i] = name;
}
//}
//transform the package list doc
trans.setParameter("root-path", "./");
package_list_elem.setAttribute("mode", "overview-summary");
trans.transform(new DOMSource(packages_doc), new StreamResult(new File(docsdir,"index.html")));
Transformer indexTrans = transFact.newTransformer(new StreamSource(XHTMLProcessingUtils.class.getResourceAsStream("resources/master-index.xsl")));
indexTrans.setParameter("root-path", "./");
indexTrans.transform(new DOMSource(unified), new StreamResult(new File(docsdir,"master-index.html")));
// copy "doc-files" for all packages to output
Util.copyDocFiles(pkgNames, sourcePath, docsdir);
p(INFO,getString("finished"));
}
private static void mergeDocuments(List<String> xmlInputs, DocumentBuilder builder, Document unified, Element javadocElement)
throws DOMException, SAXException, XPathExpressionException, IOException {
Map<String,Element> packageMap = new HashMap<String,Element>();
for (String xmlInputPath : xmlInputs) {
File file = new File(xmlInputPath);
p(INFO, MessageFormat.format(getString("reading.doc"), file.getAbsolutePath()));
p(FINE, "exists: " + file.exists());
Document doc = builder.parse(file);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList packages = (NodeList) xpath.evaluate("/javadoc/package", doc, XPathConstants.NODESET);
p(INFO,"found " + packages.getLength()+" packages");
for (int i = 0; i < packages.getLength(); i++) {
Element copy = (Element) unified.importNode(packages.item(i), true);
String pkgName = copy.getAttribute("name");
if(!packageMap.containsKey(pkgName)) {
packageMap.put(pkgName, copy);
} else {
Element pkg = packageMap.get(pkgName);
NodeList classes = copy.getChildNodes();
//copy to a List for safety before we start moving nodes around
List<Node> classesList = new ArrayList<Node>();
for(int j=0; j<classes.getLength();j++) {
classesList.add(classes.item(j));
}
for(Node cls : classesList) {
pkg.appendChild(cls);
}
}
}
}
for(String pkgName : packageMap.keySet()) {
Element pkg = packageMap.get(pkgName);
javadocElement.appendChild(pkg);
}
}
/*//keep this around for now.
private static void p(Level INFO, Element javadocElement, String tab) {
p(INFO,javadocElement,tab,-1);
}
private static void p(Level INFO, Element javadocElement, String tab, int depth) {
if(depth ==0) return;
p(INFO,tab+"<element: " + javadocElement.getTagName() + " " + javadocElement.hashCode());
for(int i=0; i<javadocElement.getAttributes().getLength(); i++) {
Attr attr = (Attr) javadocElement.getAttributes().item(i);
p(INFO,tab+" attr: " + attr.getName() + "=" + attr.getValue());
}
for(int i=0; i<javadocElement.getChildNodes().getLength();i++) {
Node n = javadocElement.getChildNodes().item(i);
if(n instanceof Element) {
p(INFO,(Element)n,tab+" ",depth-1);
} else {
p(INFO,tab+" child = " + n.getNodeName() + " " + n.getNodeValue() + " " + n.hashCode());
}
}
p(INFO,tab+"</element: " + javadocElement.getTagName());
}
*/
// Not used
/* private static void p(Transformer trans, Document packages_doc) throws TransformerException {
trans.transform(new DOMSource(packages_doc), new StreamResult(System.out));
}*/
private static void processPackage(String packageName, Element pkg, XPath xpath, File docsdir, Transformer trans, Element package_elem) throws TransformerException, XPathExpressionException, IOException, FileNotFoundException, ParserConfigurationException {
File packageDir = new File(docsdir, packageName);
packageDir.mkdir();
//classes
NodeList classesNodeList = (NodeList) xpath.evaluate(
"*[name() = 'class' or name() = 'abstractClass' or name() = 'interface']",
pkg, XPathConstants.NODESET);
List<Element> classes = sort(classesNodeList);
p(INFO, MessageFormat.format(getString("creating.classes"), classes.size(), packageName));
Document classes_doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element class_list = classes_doc.createElement("classList");
class_list.setAttribute("packageName", packageName);
classes_doc.appendChild(class_list);
for(Element clazz : classes) {
processClass(clazz, class_list, xpath, trans, packageDir);
Element clazz_elem = (Element) package_elem.getOwnerDocument().importNode(clazz, true);
package_elem.appendChild(clazz_elem);
}
class_list.setAttribute("mode", "overview-frame");
trans.setParameter("root-path", "../");
trans.transform(new DOMSource(classes_doc), new StreamResult(new File(packageDir,"package-frame.html")));
class_list.setAttribute("mode", "overview-summary");
trans.setParameter("root-path", "../");
trans.transform(new DOMSource(classes_doc), new StreamResult(new File(packageDir,"package-summary.html")));
}
private static void processClass(Element clazz, Element class_list, XPath xpath, Transformer trans, File packageDir) throws TransformerException, IOException, XPathExpressionException {
String qualifiedName = clazz.getAttribute("qualifiedName");
String name = clazz.getAttribute("name");
String profile = (String) xpath.evaluate("docComment/tags/profile/text()", clazz, XPathConstants.STRING);
if("true".equals(trans.getParameter(PARAMETER_PROFILES_ENABLED))) {
Object target_profile = trans.getParameter(PARAMETER_TARGET_PROFILE);
if(profile != null && profile.equals(target_profile)) {
//p(INFO, "profiles match");
} else {
//p(INFO, "Profiles don't match. skipping");
return;
}
}
//add to class list
Document doc = class_list.getOwnerDocument();
Element class_elem = doc.createElement("class");
class_list.appendChild(class_elem);
class_elem.setAttribute("name", name);
class_elem.setAttribute("qualifiedName", qualifiedName);
Element first_line = doc.createElement("first-line-comment");
first_line.appendChild(doc.createTextNode("first line comment"));
class_elem.appendChild(first_line);
copyClassDoc(clazz,class_elem);
processInlineExamples(clazz, class_elem, packageDir);
File xhtmlFile = new File(packageDir, qualifiedName + ".html");
Result xhtmlResult = new StreamResult(xhtmlFile);
Source xmlSource = new DOMSource(clazz.getOwnerDocument());
trans.setParameter("target-class", qualifiedName);
trans.setParameter("root-path", "../");
trans.transform(xmlSource, xhtmlResult);
}
private static void copyClassDoc(Element clazz, Element class_elem) {
Element docComment = (Element) clazz.getElementsByTagName("docComment").item(0);
if(docComment == null) return;
NodeList firstSent = docComment.getElementsByTagName("firstSentenceTags");
if(firstSent.getLength() > 0) {
class_elem.appendChild(class_elem.getOwnerDocument().importNode(firstSent.item(0),true));
}
NodeList tags = docComment.getElementsByTagName("tags");
if(tags.getLength() > 0) {
for(int i=0; i<tags.getLength(); i++) {
Node tag = tags.item(i);
class_elem.appendChild(class_elem.getOwnerDocument().importNode(tag,true));
}
}
}
private static void copyDocComment(Element pkg, Element package_elem) {
Element docComment = getFirstChildNamed(pkg, "docComment");
if (docComment != null) {
Node copy = package_elem.getOwnerDocument().importNode(docComment, true);
package_elem.appendChild(copy);
}
}
// return the first child element of the given name, if not found return null
private static Element getFirstChildNamed(Element elem, String childName) {
NodeList children = elem.getChildNodes();
final int length = children.getLength();
for (int index = 0; index < length; index++) {
Node node = children.item(index);
if ((node instanceof Element) &&
((Element)node).getTagName().equals(childName)){
return (Element)node;
}
}
return null;
}
private static List<Element> sort(NodeList classesNodeList) {
List<Element> nodes = new ArrayList<Element>();
for(int i=0; i<classesNodeList.getLength(); i++) {
nodes.add((Element)classesNodeList.item(i));
}
Collections.sort(nodes,new Comparator<Element>() {
public int compare(Element o1, Element o2) {
return o1.getAttribute("qualifiedName").compareTo(
o2.getAttribute("qualifiedName"));
}
}
);
return nodes;
}
private static void copy(URL url, File file) throws FileNotFoundException, IOException {
p(FINE, "copying from: " + url);
p(FINE, "copying to: " + file.getAbsolutePath());
InputStream in = url.openStream();
FileOutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
while (true) {
int n = in.read(buf);
if (n < 0) {
break;
}
out.write(buf, 0, n);
}
}
private static void copyResource(File docsdir, String string) throws FileNotFoundException, IOException {
copy(XHTMLProcessingUtils.class.getResource("resources/"+string),new File(docsdir,string));
}
/* Not used
private static void copy(File infile, File outfile) throws FileNotFoundException, IOException {
FileInputStream in = new FileInputStream(infile);
FileOutputStream out = new FileOutputStream(outfile);
byte[] buf = new byte[1024];
while (true) {
int n = in.read(buf);
if (n < 0) {
break;
}
out.write(buf, 0, n);
}
}
*/
static String getString(String key) {
ResourceBundle msgRB = messageRB;
if (msgRB == null) {
try {
messageRB = msgRB =
ResourceBundle.getBundle("com.sun.tools.xslhtml.resources.xslhtml");
} catch (MissingResourceException e) {
throw new Error("Fatal: Resource for javafxdoc is missing");
}
}
return msgRB.getString(key);
}
private static void p(Level level, String string) {
if (level.intValue() >= logger.getLevel().intValue())
System.err.println(string);
}
private static void p(Level level, String string, Throwable t) {
if (level.intValue() >= logger.getLevel().intValue()) {
StringBuilder sb = new StringBuilder();
sb.append(string);
if (t != null) {
sb.append(System.getProperty("line.separator"));
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) {
}
}
System.err.println(sb.toString());
}
}
/* Not used
private static void p(String string) {
System.out.println(string);
}
*/
/**
* Command-line/debugging entry
*/
public static void main(String[] args) throws Exception {
List<String> inputs = new ArrayList<String>();
inputs.add("javadoc.xml");
process(inputs, null, ".", new File("fxdocs_test"), new HashMap<String, String>());
}
private static class MainErrorListener implements ErrorListener {
public MainErrorListener() {
}
public void warning(TransformerException exception) throws TransformerException {
p(WARNING, "warning: " + exception);
}
public void error(TransformerException exception) throws TransformerException {
Throwable thr = exception;
while (true) {
p(SEVERE, "error: " + exception.getMessageAndLocation(), thr.getCause());
if (thr.getCause() != null) {
thr = thr.getCause();
} else {
break;
}
}
}
public void fatalError(TransformerException exception) throws TransformerException {
p(SEVERE, "fatal error: " + exception.getMessageAndLocation(), exception);
}
}
private static void processInlineExamples(Element clazz, Element class_elem, File packageDir) {
NodeList examples = clazz.getElementsByTagName("example");
if(examples != null & examples.getLength() > 0) {
for(int i=0; i<examples.getLength(); i++) {
Element example = (Element) examples.item(i);
processExampleCode(example, packageDir, clazz, i, true);
}
}
NodeList highlights = clazz.getElementsByTagName("highlight");
if(highlights != null && highlights.getLength() > 0) {
for(int i=0; i<highlights.getLength(); i++) {
Element highlight = (Element) highlights.item(i);
processExampleCode(highlight, packageDir, clazz, i, false);
}
}
}
private static void processExampleCode(Element example, File packageDir, Element clazz, int i, boolean renderScreenshot) throws DOMException {
//p(INFO, MessageFormat.format(getString("processing.example"), clazz.getAttribute("name")));
//p(INFO, example.getTextContent());
try {
//String script = "import javafx.gui.*; CubicCurve { x1: 0 y1: 50 ctrlX1: 25 ctrlY1: 0 ctrlX2: 75 ctrlY2: 100 x2: 100 y2: 50 fill:Color.RED }";
String script = example.getTextContent();
StringBuffer out = new StringBuffer();
out.append("<p>the code:</p>");
out.append("<pre class='example-code'><code>");
String styledScript = highlight(script);
out.append(styledScript);
out.append("</code></pre>");
if(renderScreenshot) {
try {
File imgFile = new File(packageDir, clazz.getAttribute("name") + i + ".png");
renderScriptToImage(imgFile, script);
out.append("<p>produces:</p>");
out.append("<p>");
out.append("<img class='example-screenshot' src='" + imgFile.getName() + "'/>");
out.append("</p>");
} catch (Throwable ex) {
System.out.println("error processing code: " + clazz.getAttribute("name"));
System.out.println("error processing: " + example.getTextContent());
ex.printStackTrace();
}
}
example.setTextContent(out.toString());
} catch (Exception ex) {
System.out.println("error processing code: " + clazz.getAttribute("name"));
System.out.println("error processing: " + example.getTextContent());
ex.printStackTrace();
}
}
private static String highlight(String text) {
//String pattern = "(/\\*)";
//String replace = "<span class='comment'>/*";
//comments
text = text.replaceAll("/\\*", "<i class='comment'>/*");
text = text.replaceAll("\\*/","*/</i>");
//imports
text = text.replaceAll("(import|package)","<b>$1</b>");
//keywords
text = text.replaceAll("(var)","<b class='keyword'>$1</b>");
//attribute names
text = text.replaceAll("(\\w\\w*):","<b>$1</b>:");
//attribute values
text = text.replaceAll("(\\d+)","<span class='number-literal'>$1</span>");
text = text.replaceAll("(\".*\")","<span class='string-literal'>$1</span>");
//put inside of precode
//text = "<pre><code>"+text+"</code></pre>";
//text = "<html><head><link rel='stylesheet' href='test.css'/></head><body>"+
// text +"</body></html>";
return text;
}
@SuppressWarnings("unchecked")
private static void renderScriptToImage(File imgFile, String script) throws ScriptException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException, ClassNotFoundException {
ScriptEngineFactory factory = new JavaFXScriptEngineFactory();
ScriptEngine scrEng = factory.getScriptEngine();
PrintWriter pw = new PrintWriter(System.err);
scrEng.getContext().setErrorWriter(pw);
//p(INFO, getString("processing.example") + '\n' + script);
try {
//System.err.println("evalling: -" + script+"-");
Object ret = scrEng.eval(script);
Class fxclass = ret.getClass();
Rectangle2D bounds = null;
Method paintMethod = null;
Object drawObject = null;
try {
Method component_method = fxclass.getMethod("getJComponent");
JComponent component = (JComponent) component_method.invoke(ret);
component.validate();
component.setSize(component.getPreferredSize());
bounds = component.getBounds();
drawObject = component;
paintMethod = drawObject.getClass().getMethod("paint",Graphics.class);
} catch (NoSuchMethodException ex) {
Method method = fxclass.getMethod("impl_getFXNode");
drawObject = method.invoke(ret);
Method getBounds = drawObject.getClass().getMethod("getBounds");
bounds = (Rectangle2D) getBounds.invoke(drawObject);
paintMethod = drawObject.getClass().getMethod("render", Graphics2D.class);
}
BufferedImage img = new BufferedImage(
(int)bounds.getWidth(),
(int)bounds.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
//let the scenegraph decide if AA should be on or not
//g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
// RenderingHints.VALUE_ANTIALIAS_ON
// );
g2.setPaint(Color.WHITE);
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
g2.translate(-bounds.getX(), -bounds.getY());
paintMethod.invoke(drawObject, g2);
g2.dispose();
ImageIO.write(img, "png", imgFile);
} catch (javax.script.ScriptException ex) {
pw.println(ex.getMessage());
pw.println(" at: line = " + ex.getLineNumber() + " column = " + ex.getColumnNumber());
pw.println("file = " + ex.getFileName());
pw.println("exception = "+ ex.toString());
pw.println(ex.getMessage());
ex.printStackTrace(pw);
pw.println("cause = " + ex.getCause());
} finally {
pw.flush();
pw.close();
}
}
}
| true | true | public static void process(List<String> xmlInputs, InputStream xsltStream,
String sourcePath, File docsdir, Map<String,String> parameters
) throws Exception {
if (xmlInputs == null || xmlInputs.size() == 0)
throw new IllegalArgumentException("no XML input file(s)");
System.out.println(getString("transforming.to.html"));
// TODO code application logic here
//hack to get this to work on the mac
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
System.setProperty("javax.xml.parsers.SAXParserFactory",
"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
if (xsltStream == null) {
if(SDK_THEME) {
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/sdk.xsl");
} else {
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/javadoc.xsl");
}
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
pe(WARNING, "warning: ", exception);
}
public void error(SAXParseException exception) throws SAXException {
pe(SEVERE, "error: ", exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
pe(SEVERE, "fatal error", exception);
}
private void pe(Level level, String string, SAXParseException exception) {
p(level, string + " line: " + exception.getLineNumber() + " column: " +
exception.getColumnNumber() + " " + exception.getLocalizedMessage());
}
});
//File docsdir = new File("fxdocs");
if (!docsdir.exists()) {
docsdir.mkdir();
}
p(INFO, getString("copying"));
copyResource(docsdir,"empty.html");
copyResource(docsdir,"general.css");
copyResource(docsdir,"sdk.css");
copyResource(docsdir,"core.js");
copyResource(docsdir,"more.js");
copyResource(docsdir,"sessvars.js");
File images = new File(docsdir,"images");
images.mkdir();
copy(XHTMLProcessingUtils.class.getResource("resources/quote-background-1.gif"), new File(images, "quote-background-1.gif"));
copyResource(images,"JFX_arrow_down.png");
copyResource(images,"JFX_arrow_right.png");
copyResource(images,"JFX_arrow_up.png");
copyResource(images,"JFX_highlight_dot.png");
p(INFO, getString("transforming"));
//File xsltFile = new File("javadoc.xsl");
//p("reading xslt exists in: " + xsltFile.exists());
Source xslt = new StreamSource(xsltStream);
TransformerFactory transFact = TransformerFactory.newInstance();
transFact.setURIResolver(new URIResolver() {
public Source resolve(String href, String base) throws TransformerException {
p(INFO, "Trying to resolve: " + href + " " + base);
URL url = XHTMLProcessingUtils.class.getResource("resources/"+href);
p(INFO, "Resolved " + href + ":" + base + " to " + url);
try {
return new StreamSource(url.openStream());
} catch (IOException ex) {
Logger.getLogger(XHTMLProcessingUtils.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
});
Transformer trans = transFact.newTransformer(xslt);
if(SDK_THEME) {
trans.setParameter("inline-classlist","true");
trans.setParameter("inline-descriptions", "true");
}
for(String key : parameters.keySet()) {
System.out.println("using key: " + key + " " + parameters.get(key));
trans.setParameter(key, parameters.get(key));
}
trans.setErrorListener(new MainErrorListener());
//build xml doc for the packages
Document packages_doc = builder.newDocument();
Element package_list_elem = packages_doc.createElement("packageList");
packages_doc.appendChild(package_list_elem);
//merge all xml files into single document
Document unified = builder.newDocument();
Element javadocElement = unified.createElement("javadoc");
unified.appendChild(javadocElement);
mergeDocuments(xmlInputs, builder, unified, javadocElement);
// print out packages list
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList packages = (NodeList) xpath.evaluate("/javadoc/package", unified, XPathConstants.NODESET);
p(INFO, MessageFormat.format(getString("creating.packages"), packages.getLength()));
// collect all package names in this array
String[] pkgNames = new String[packages.getLength()];
//for each package, generate the package itself and append to package list doc
for (int i = 0; i < packages.getLength(); i++) {
Element pkg = ((Element) packages.item(i));
String name = pkg.getAttribute("name");
Element package_elem = packages_doc.createElement("package");
package_elem.setAttribute("name", name);
package_list_elem.appendChild(package_elem);
copyDocComment(pkg,package_elem);
Element first_line = packages_doc.createElement("first-line-comment");
first_line.appendChild(packages_doc.createTextNode("first line comment"));
package_elem.appendChild(first_line);
processPackage(name, pkg, xpath, docsdir, trans, package_elem);
pkgNames[i] = name;
}
//}
//transform the package list doc
trans.setParameter("root-path", "./");
package_list_elem.setAttribute("mode", "overview-summary");
trans.transform(new DOMSource(packages_doc), new StreamResult(new File(docsdir,"index.html")));
Transformer indexTrans = transFact.newTransformer(new StreamSource(XHTMLProcessingUtils.class.getResourceAsStream("resources/master-index.xsl")));
indexTrans.setParameter("root-path", "./");
indexTrans.transform(new DOMSource(unified), new StreamResult(new File(docsdir,"master-index.html")));
// copy "doc-files" for all packages to output
Util.copyDocFiles(pkgNames, sourcePath, docsdir);
p(INFO,getString("finished"));
}
| public static void process(List<String> xmlInputs, InputStream xsltStream,
String sourcePath, File docsdir, Map<String,String> parameters
) throws Exception {
if (xmlInputs == null || xmlInputs.size() == 0)
throw new IllegalArgumentException("no XML input file(s)");
System.out.println(getString("transforming.to.html"));
// TODO code application logic here
//hack to get this to work on the mac
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
System.setProperty("javax.xml.parsers.SAXParserFactory",
"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
if (xsltStream == null) {
if(SDK_THEME) {
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/sdk.xsl");
} else {
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/javadoc.xsl");
}
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
pe(WARNING, "warning: ", exception);
}
public void error(SAXParseException exception) throws SAXException {
pe(SEVERE, "error: ", exception);
}
public void fatalError(SAXParseException exception) throws SAXException {
pe(SEVERE, "fatal error", exception);
}
private void pe(Level level, String string, SAXParseException exception) {
p(level, string + " line: " + exception.getLineNumber() + " column: " +
exception.getColumnNumber() + " " + exception.getLocalizedMessage());
}
});
//File docsdir = new File("fxdocs");
if (!docsdir.exists()) {
docsdir.mkdir();
}
p(INFO, getString("copying"));
copyResource(docsdir,"empty.html");
copyResource(docsdir,"general.css");
copyResource(docsdir,"sdk.css");
copyResource(docsdir,"mootools-1.2.1-yui.js");
copyResource(docsdir,"sdk.js");
copyResource(docsdir,"sessvars.js");
File images = new File(docsdir,"images");
images.mkdir();
copy(XHTMLProcessingUtils.class.getResource("resources/quote-background-1.gif"), new File(images, "quote-background-1.gif"));
copyResource(images,"JFX_arrow_down.png");
copyResource(images,"JFX_arrow_right.png");
copyResource(images,"JFX_arrow_up.png");
copyResource(images,"JFX_highlight_dot.png");
p(INFO, getString("transforming"));
//File xsltFile = new File("javadoc.xsl");
//p("reading xslt exists in: " + xsltFile.exists());
Source xslt = new StreamSource(xsltStream);
TransformerFactory transFact = TransformerFactory.newInstance();
transFact.setURIResolver(new URIResolver() {
public Source resolve(String href, String base) throws TransformerException {
p(INFO, "Trying to resolve: " + href + " " + base);
URL url = XHTMLProcessingUtils.class.getResource("resources/"+href);
p(INFO, "Resolved " + href + ":" + base + " to " + url);
try {
return new StreamSource(url.openStream());
} catch (IOException ex) {
Logger.getLogger(XHTMLProcessingUtils.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
});
Transformer trans = transFact.newTransformer(xslt);
if(SDK_THEME) {
trans.setParameter("inline-classlist","true");
trans.setParameter("inline-descriptions", "true");
}
for(String key : parameters.keySet()) {
System.out.println("using key: " + key + " " + parameters.get(key));
trans.setParameter(key, parameters.get(key));
}
trans.setErrorListener(new MainErrorListener());
//build xml doc for the packages
Document packages_doc = builder.newDocument();
Element package_list_elem = packages_doc.createElement("packageList");
packages_doc.appendChild(package_list_elem);
//merge all xml files into single document
Document unified = builder.newDocument();
Element javadocElement = unified.createElement("javadoc");
unified.appendChild(javadocElement);
mergeDocuments(xmlInputs, builder, unified, javadocElement);
// print out packages list
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList packages = (NodeList) xpath.evaluate("/javadoc/package", unified, XPathConstants.NODESET);
p(INFO, MessageFormat.format(getString("creating.packages"), packages.getLength()));
// collect all package names in this array
String[] pkgNames = new String[packages.getLength()];
//for each package, generate the package itself and append to package list doc
for (int i = 0; i < packages.getLength(); i++) {
Element pkg = ((Element) packages.item(i));
String name = pkg.getAttribute("name");
Element package_elem = packages_doc.createElement("package");
package_elem.setAttribute("name", name);
package_list_elem.appendChild(package_elem);
copyDocComment(pkg,package_elem);
Element first_line = packages_doc.createElement("first-line-comment");
first_line.appendChild(packages_doc.createTextNode("first line comment"));
package_elem.appendChild(first_line);
processPackage(name, pkg, xpath, docsdir, trans, package_elem);
pkgNames[i] = name;
}
//}
//transform the package list doc
trans.setParameter("root-path", "./");
package_list_elem.setAttribute("mode", "overview-summary");
trans.transform(new DOMSource(packages_doc), new StreamResult(new File(docsdir,"index.html")));
Transformer indexTrans = transFact.newTransformer(new StreamSource(XHTMLProcessingUtils.class.getResourceAsStream("resources/master-index.xsl")));
indexTrans.setParameter("root-path", "./");
indexTrans.transform(new DOMSource(unified), new StreamResult(new File(docsdir,"master-index.html")));
// copy "doc-files" for all packages to output
Util.copyDocFiles(pkgNames, sourcePath, docsdir);
p(INFO,getString("finished"));
}
|
diff --git a/lenskit-data-structures/src/main/java/org/grouplens/lenskit/scored/ScoredIdListBuilder.java b/lenskit-data-structures/src/main/java/org/grouplens/lenskit/scored/ScoredIdListBuilder.java
index 3ca7876c5..011cd3616 100644
--- a/lenskit-data-structures/src/main/java/org/grouplens/lenskit/scored/ScoredIdListBuilder.java
+++ b/lenskit-data-structures/src/main/java/org/grouplens/lenskit/scored/ScoredIdListBuilder.java
@@ -1,491 +1,491 @@
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2013 Regents of the University of Minnesota and contributors
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.grouplens.lenskit.scored;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import it.unimi.dsi.fastutil.Swapper;
import it.unimi.dsi.fastutil.doubles.DoubleArrays;
import it.unimi.dsi.fastutil.ints.AbstractIntComparator;
import it.unimi.dsi.fastutil.objects.ObjectArrays;
import it.unimi.dsi.fastutil.objects.Reference2ObjectArrayMap;
import org.apache.commons.lang3.builder.Builder;
import org.grouplens.lenskit.collections.CollectionUtils;
import org.grouplens.lenskit.symbols.DoubleSymbolValue;
import org.grouplens.lenskit.symbols.Symbol;
import org.grouplens.lenskit.symbols.SymbolValue;
import org.grouplens.lenskit.symbols.TypedSymbol;
import java.lang.reflect.Array;
import java.util.*;
import static it.unimi.dsi.fastutil.Arrays.quickSort;
/**
* Builder for packed lists of scored ids. All ids in the resulting list will have the same set
* of side channels.
*
* @since 1.4
* @compat Public
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public class ScoredIdListBuilder implements Builder<PackedScoredIdList> {
// INVARIANT: all arrays (including channel arrays) have same size, which is capacity
// INVARIANT: all arrays are non-null unless finish() has been called
private long[] ids;
private double[] scores;
private boolean ignoreUnknown = false;
private int size;
private Map<Symbol,ChannelStorage> channels;
private Map<TypedSymbol<?>,TypedChannelStorage<?>> typedChannels;
public ScoredIdListBuilder() {
this(10);
}
public ScoredIdListBuilder(int cap) {
initialize(cap);
}
private void initialize(int cap) {
ids = new long[cap];
scores = new double[cap];
size = 0;
channels = new Reference2ObjectArrayMap<Symbol, ChannelStorage>();
typedChannels = new Reference2ObjectArrayMap<TypedSymbol<?>, TypedChannelStorage<?>>();
}
@Override
public PackedScoredIdList build() {
return finish(false);
}
/**
* Destructive version of {@link #build()}, re-using storage if possible. Future use of the
* builder is impossible, and all memory used by it is released.
*
* @return The scored ID list.
*/
public PackedScoredIdList finish() {
return finish(true);
}
/**
* Implementation of {@link #build()} and {@link #finish()}.
* @param tryReuse Whether we should try to reuse the builder's storage for the packed list.
* If {@code true}, the builder will be invalid after finishing and the packed
* list will use the same arrays as the builder if they are full.
* @return The packed ID list.
*/
private PackedScoredIdList finish(boolean tryReuse) {
Preconditions.checkState(ids != null, "builder has been finished");
// check if reuse is actually possible
final boolean reuse = tryReuse && size == capacity();
Map<Symbol, double[]> chans;
Map<TypedSymbol<?>, Object[]> typedChans;
if (size > 0) {
ImmutableMap.Builder<Symbol, double[]> cbld = ImmutableMap.builder();
for (ChannelStorage chan: channels.values()) {
double[] built = reuse ? chan.values : Arrays.copyOf(chan.values, size);
cbld.put(chan.symbol, built);
}
chans = cbld.build();
ImmutableMap.Builder<TypedSymbol<?>, Object[]> tcbld = ImmutableMap.builder();
for (TypedChannelStorage<?> chan: typedChannels.values()) {
Object[] built = reuse ? chan.values : Arrays.copyOf(chan.values, size);
assert chan.symbol.getType().isAssignableFrom(built.getClass().getComponentType());
tcbld.put(chan.symbol, built);
}
typedChans = tcbld.build();
} else {
chans = Collections.emptyMap();
typedChans = Collections.emptyMap();
}
long[] builtIds = reuse ? ids : Arrays.copyOf(ids, size);
double[] builtScores = reuse ? scores : Arrays.copyOf(scores, size);
if (tryReuse) {
// invalidate the builder
ids = null;
scores = null;
channels = null;
typedChannels = null;
}
return new PackedScoredIdList(builtIds, builtScores, typedChans, chans);
}
/**
* Get the current capacity of the builder.
*
* @return The number of items the builder can hold without resizing.
*/
private int capacity() {
return ids.length;
}
/**
* Get the number of items currently in the builder.
* @return The number of items in the builder.
*/
public int size() {
return size;
}
/**
* Require the builder have a particular minimum capacity, resizing if necessary.
* @param sz The required capacity.
*/
private void requireCapacity(int sz) {
if (sz > capacity()) {
int newCap = Math.max(sz, capacity() * 2);
ids = Arrays.copyOf(ids, newCap);
scores = Arrays.copyOf(scores, newCap);
for (ChannelStorage chan: channels.values()) {
chan.resize(newCap);
}
for (TypedChannelStorage<?> chan: typedChannels.values()) {
chan.resize(newCap);
}
assert capacity() == newCap;
}
}
/**
* Add a scored ID without boxing. The default value will be used for each channel.
* @param id The ID to add.
* @param score The score for the ID.
* @return The builder (for chaining).
*/
public ScoredIdListBuilder add(long id, double score) {
Preconditions.checkState(ids != null, "builder has been finished");
final int idx = size;
requireCapacity(idx + 1);
ids[idx] = id;
scores[idx] = score;
size++;
return this;
}
/**
* Add a scored ID. The ID is copied into the builder, not referenced. All side channels on
* the ID must have already been added with one of the {@code addChannel} methods.
* @param id The ID.
* @return The builder (for chaining).
*/
public ScoredIdListBuilder add(ScoredId id) {
Preconditions.checkState(ids != null, "builder has been finished");
// check whether all symbols are valid
Collection<SymbolValue<?>> chans = id.getChannels();
if (!ignoreUnknown) {
for (SymbolValue<?> chan: chans) {
TypedSymbol<?> sym = chan.getSymbol();
boolean good = sym.getType().equals(Double.class)
? channels.containsKey(sym.getRawSymbol())
: typedChannels.containsKey(sym);
if (!good) {
throw new IllegalArgumentException("channel " + sym + " not known");
}
}
}
// now we're ready to add
final int idx = size;
add(id.getId(), id.getScore());
for (SymbolValue<?> sv: chans) {
TypedSymbol<?> sym = sv.getSymbol();
if (sym.getType().equals(Double.class) && channels.containsKey(sym.getRawSymbol())) {
ChannelStorage chan = channels.get(sym.getRawSymbol());
if (sv instanceof DoubleSymbolValue) {
chan.values[idx] = ((DoubleSymbolValue) sv).getDoubleValue();
} else {
Object v = sv.getValue();
chan.values[idx] = (Double) v;
}
} else {
- TypedChannelStorage<?> chan = typedChannels.get(sv.getSymbol());
+ TypedChannelStorage chan = typedChannels.get(sv.getSymbol());
if (chan != null) {
chan.values[idx] = sv.getValue();
}
}
}
return this;
}
/**
* Add a collection of IDs. The IDs are copied into the builder, not referenced.
* @param ids The IDs to add.
* @return The builder (for chaining)
*/
public ScoredIdListBuilder addAll(Iterable<ScoredId> ids) {
Preconditions.checkState(ids != null, "builder has been finished");
if (ids instanceof Collection) {
// we know how big to expect it to be, avoid excess resizes.
requireCapacity(size + ((Collection<ScoredId>) ids).size());
}
// fast iteration is safe since add() doesn't retain the id object
for (ScoredId id: CollectionUtils.fast(ids)) {
add(id);
}
return this;
}
/**
* Add a side channel to the list builder with a default value of 0. It is an error
* to add the same symbol multiple times. All side channels that will be used must be added
* prior to calling {@link #add(ScoredId)}.
*
* @param sym The symbol to add.
* @return The builder (for chaining).
* @see #addChannel(Symbol, double)
*/
public ScoredIdListBuilder addChannel(Symbol sym) {
return addChannel(sym, 0);
}
/**
* Add a side channel to the list builder. It is an error to add the same symbol multiple times.
* All side channels that will be used must be added prior to calling {@link #add(ScoredId)}.
*
* @param sym The symbol to add.
* @param dft The default value when adding IDs that lack this channel.
* @return The builder (for chaining).
*/
public ScoredIdListBuilder addChannel(Symbol sym, double dft) {
Preconditions.checkState(ids != null, "builder has been finished");
if (channels.containsKey(sym)) {
throw new IllegalArgumentException(sym + " already in the builder");
} else {
channels.put(sym, new ChannelStorage(sym, dft));
}
return this;
}
/**
* Add multiple unboxed channels with a default value of 0.
* @param channels The channels to add.
* @return The builder (for chaining).
*/
public ScoredIdListBuilder addChannels(Iterable<Symbol> channels) {
for (Symbol sym: channels) {
addChannel(sym);
}
return this;
}
/**
* Add a side channel to the list builder. It is an error
* to add the same symbol multiple times. All side channels that will be used must be added
* prior to calling {@link #add(ScoredId)}.
*
* @param sym The symbol to add.
* @return The builder (for chaining).
* @see #addChannel(TypedSymbol, Object)
*/
public ScoredIdListBuilder addChannel(TypedSymbol<?> sym) {
return addChannel(sym, null);
}
/**
* Add a typed side channel to the list builder. It is an error to add the same symbol multiple
* times. All side channels that will be used must be added prior to calling {@link
* #add(ScoredId)}.
*
* @param sym The symbol to add.
* @param dft The default value when adding ids that lack this channel. If {@code null},
* it will be omitted from such ids.
* @return The builder (for chaining).
*/
public <T> ScoredIdListBuilder addChannel(TypedSymbol<T> sym, T dft) {
Preconditions.checkState(ids != null, "builder has been finished");
if (typedChannels.containsKey(sym)) {
throw new IllegalArgumentException(sym + " already in the builder");
} else {
typedChannels.put(sym, new TypedChannelStorage<T>(sym, dft));
}
return this;
}
/**
* Add multiple channels with a default value of {@code null}.
* @param channels The channels to add.
* @return The builder (for chaining).
*/
public ScoredIdListBuilder addTypedChannels(Iterable<? extends TypedSymbol<?>> channels) {
for (TypedSymbol<?> sym: channels) {
addChannel(sym);
}
return this;
}
/**
* Set the builder to ignore unknown channels on IDs passed to {@link #add(ScoredId)}.
* @return The builder (for chaining).
*/
public ScoredIdListBuilder ignoreUnknownChannels() {
ignoreUnknown = true;
return this;
}
/**
* Set the builder to fail on unknown channels. This is the default response to unknown
* channels.
* @return The builder (for chaining).
*/
public ScoredIdListBuilder failOnUnknownChannels() {
ignoreUnknown = false;
return this;
}
/**
* Sort the list-in-progress by the specified comparator.
* @param order The comparator.
* @return The buidler (for chaining).
*/
public ScoredIdListBuilder sort(Comparator<ScoredId> order) {
Preconditions.checkState(ids != null, "builder has been finished");
quickSort(0, size, new SortComp(order), new SortSwap());
return this;
}
/**
* Comparator for sorting the list. This comparator internally uses a packed list over the
* entire capacity of the builder to provide ids for the real comparator to use.
*/
private class SortComp extends AbstractIntComparator {
private final Comparator<ScoredId> order;
private PackedScoredIdList.IndirectScoredId id1;
private PackedScoredIdList.IndirectScoredId id2;
public SortComp(Comparator<ScoredId> o) {
order = o;
// make an internal list
Map<Symbol,double[]> chanMap = Maps.newHashMap();
for (ChannelStorage chan: channels.values()) {
chanMap.put(chan.symbol, chan.values);
}
Map<TypedSymbol<?>,Object[]> typedMap = Maps.newHashMap();
for (TypedChannelStorage<?> chan: typedChannels.values()) {
typedMap.put(chan.symbol, chan.values);
}
PackedScoredIdList list = new PackedScoredIdList(ids, scores, typedMap, chanMap);
id1 = list.getFlyweight(0);
id2 = list.getFlyweight(0);
}
@Override
public int compare(int i1, int i2) {
id1.setIndex(i1);
id2.setIndex(i2);
return order.compare(id1, id2);
}
}
/**
* Swapper for sorting the list.
*/
private class SortSwap implements Swapper {
@Override
public void swap(int i, int j) {
doSwap(ids, i, j);
doSwap(scores, i, j);
for (ChannelStorage chan: channels.values()) {
doSwap(chan.values, i, j);
}
for (TypedChannelStorage<?> chan: typedChannels.values()) {
doSwap(chan.values, i, j);
}
}
}
private static void doSwap(long[] longs, int i, int j) {
final long tmp = longs[i];
longs[i] = longs[j];
longs[j] = tmp;
}
private static void doSwap(double[] doubles, int i, int j) {
final double tmp = doubles[i];
doubles[i] = doubles[j];
doubles[j] = tmp;
}
private static <T> void doSwap(T[] objs, int i, int j) {
final T tmp = objs[i];
objs[i] = objs[j];
objs[j] = tmp;
}
/**
* Storage for a side channel.
*/
private class ChannelStorage {
private final Symbol symbol;
private final double defaultValue;
private double[] values;
public ChannelStorage(Symbol sym, double dft) {
symbol = sym;
defaultValue = dft;
values = new double[capacity()];
if (defaultValue != 0) {
DoubleArrays.fill(values, defaultValue);
}
}
void resize(int size) {
Preconditions.checkArgument(size > values.length);
int oldSize = values.length;
values = Arrays.copyOf(values, size);
if (defaultValue != 0) {
DoubleArrays.fill(values, oldSize, size, defaultValue);
}
}
}
/**
* Storage for a typed side channel.
*/
private class TypedChannelStorage<T> {
private final TypedSymbol<T> symbol;
private final T defaultValue;
private T[] values;
@SuppressWarnings("unchecked")
private TypedChannelStorage(TypedSymbol<T> sym, T dft) {
symbol = sym;
defaultValue = dft;
values = (T[]) Array.newInstance(sym.getType(), capacity());
if (defaultValue != null) {
ObjectArrays.fill(values, defaultValue);
}
}
void resize(int size) {
Preconditions.checkArgument(size > values.length);
int oldSize = values.length;
values = Arrays.copyOf(values, size);
if (defaultValue != null) {
ObjectArrays.fill(values, oldSize, size, defaultValue);
}
}
}
}
| true | true | public ScoredIdListBuilder add(ScoredId id) {
Preconditions.checkState(ids != null, "builder has been finished");
// check whether all symbols are valid
Collection<SymbolValue<?>> chans = id.getChannels();
if (!ignoreUnknown) {
for (SymbolValue<?> chan: chans) {
TypedSymbol<?> sym = chan.getSymbol();
boolean good = sym.getType().equals(Double.class)
? channels.containsKey(sym.getRawSymbol())
: typedChannels.containsKey(sym);
if (!good) {
throw new IllegalArgumentException("channel " + sym + " not known");
}
}
}
// now we're ready to add
final int idx = size;
add(id.getId(), id.getScore());
for (SymbolValue<?> sv: chans) {
TypedSymbol<?> sym = sv.getSymbol();
if (sym.getType().equals(Double.class) && channels.containsKey(sym.getRawSymbol())) {
ChannelStorage chan = channels.get(sym.getRawSymbol());
if (sv instanceof DoubleSymbolValue) {
chan.values[idx] = ((DoubleSymbolValue) sv).getDoubleValue();
} else {
Object v = sv.getValue();
chan.values[idx] = (Double) v;
}
} else {
TypedChannelStorage<?> chan = typedChannels.get(sv.getSymbol());
if (chan != null) {
chan.values[idx] = sv.getValue();
}
}
}
return this;
}
| public ScoredIdListBuilder add(ScoredId id) {
Preconditions.checkState(ids != null, "builder has been finished");
// check whether all symbols are valid
Collection<SymbolValue<?>> chans = id.getChannels();
if (!ignoreUnknown) {
for (SymbolValue<?> chan: chans) {
TypedSymbol<?> sym = chan.getSymbol();
boolean good = sym.getType().equals(Double.class)
? channels.containsKey(sym.getRawSymbol())
: typedChannels.containsKey(sym);
if (!good) {
throw new IllegalArgumentException("channel " + sym + " not known");
}
}
}
// now we're ready to add
final int idx = size;
add(id.getId(), id.getScore());
for (SymbolValue<?> sv: chans) {
TypedSymbol<?> sym = sv.getSymbol();
if (sym.getType().equals(Double.class) && channels.containsKey(sym.getRawSymbol())) {
ChannelStorage chan = channels.get(sym.getRawSymbol());
if (sv instanceof DoubleSymbolValue) {
chan.values[idx] = ((DoubleSymbolValue) sv).getDoubleValue();
} else {
Object v = sv.getValue();
chan.values[idx] = (Double) v;
}
} else {
TypedChannelStorage chan = typedChannels.get(sv.getSymbol());
if (chan != null) {
chan.values[idx] = sv.getValue();
}
}
}
return this;
}
|
diff --git a/org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5/src/org/eclipse/bpmn2/modeler/runtime/jboss/jbpm5/property/JbpmCommonEventDetailComposite.java b/org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5/src/org/eclipse/bpmn2/modeler/runtime/jboss/jbpm5/property/JbpmCommonEventDetailComposite.java
index ee7173f7..4e19b8db 100644
--- a/org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5/src/org/eclipse/bpmn2/modeler/runtime/jboss/jbpm5/property/JbpmCommonEventDetailComposite.java
+++ b/org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5/src/org/eclipse/bpmn2/modeler/runtime/jboss/jbpm5/property/JbpmCommonEventDetailComposite.java
@@ -1,101 +1,102 @@
/*******************************************************************************
* Copyright (c) 2011, 2012 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
*
* @author Bob Brodt
******************************************************************************/
package org.eclipse.bpmn2.modeler.runtime.jboss.jbpm5.property;
import java.util.List;
import org.eclipse.bpmn2.CatchEvent;
import org.eclipse.bpmn2.Event;
import org.eclipse.bpmn2.EventDefinition;
import org.eclipse.bpmn2.ThrowEvent;
import org.eclipse.bpmn2.modeler.core.merrimac.clad.AbstractBpmn2PropertySection;
import org.eclipse.bpmn2.modeler.core.merrimac.clad.AbstractDetailComposite;
import org.eclipse.bpmn2.modeler.core.merrimac.clad.AbstractListComposite;
import org.eclipse.bpmn2.modeler.ui.property.events.CommonEventDetailComposite;
import org.eclipse.bpmn2.modeler.ui.property.events.EventDefinitionsListComposite;
import org.eclipse.bpmn2.modeler.ui.property.events.EventDefinitionsListComposite.EventDefinitionsDetailComposite;
import org.eclipse.bpmn2.modeler.ui.property.tasks.DataAssociationDetailComposite.MapType;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Composite;
/**
* @author Bob Brodt
*
*/
public class JbpmCommonEventDetailComposite extends CommonEventDetailComposite {
/**
* @param parent
* @param style
*/
public JbpmCommonEventDetailComposite(Composite parent, int style) {
super(parent, style);
}
/**
* @param section
*/
public JbpmCommonEventDetailComposite(AbstractBpmn2PropertySection section) {
super(section);
}
@Override
protected AbstractListComposite bindList(final EObject object, EStructuralFeature feature, EClass listItemClass) {
if (isModelObjectEnabled(object.eClass(), feature)) {
if ("eventDefinitions".equals(feature.getName())) { //$NON-NLS-1$
eventsTable = new EventDefinitionsListComposite(this, (Event)object) {
- public AbstractDetailComposite createDetailComposite(Composite parent, Class eClass) {
+ @Override
+ public AbstractDetailComposite createDetailComposite(Class eClass, Composite parent, int style) {
EventDefinitionsDetailComposite details = new EventDefinitionsDetailComposite(parent, (Event)getBusinessObject()) {
@Override
public void createBindings(EObject be) {
super.createBindings(be);
if (object instanceof CatchEvent)
getDataAssociationComposite().setAllowedMapTypes(MapType.Property.getValue());
else
getDataAssociationComposite().setAllowedMapTypes(MapType.Property.getValue() | MapType.SingleAssignment.getValue());
}
};
return details;
}
@Override
protected EObject addListItem(EObject object, EStructuralFeature feature) {
List<EventDefinition> eventDefinitions = null;
if (event instanceof ThrowEvent)
eventDefinitions = ((ThrowEvent)event).getEventDefinitions();
else if (event instanceof CatchEvent)
eventDefinitions = ((CatchEvent)event).getEventDefinitions();
if (eventDefinitions.size()>0) {
MessageDialog.openError(getShell(), Messages.JbpmCommonEventDetailComposite_Error_Title,
Messages.JbpmCommonEventDetailComposite_Error_Message
);
return null;
}
return super.addListItem(object, feature);
}
};
eventsTable.bindList(object, feature);
eventsTable.setTitle(Messages.JbpmCommonEventDetailComposite_Title);
return eventsTable;
}
return super.bindList(object, feature, listItemClass);
}
return null;
}
}
| true | true | protected AbstractListComposite bindList(final EObject object, EStructuralFeature feature, EClass listItemClass) {
if (isModelObjectEnabled(object.eClass(), feature)) {
if ("eventDefinitions".equals(feature.getName())) { //$NON-NLS-1$
eventsTable = new EventDefinitionsListComposite(this, (Event)object) {
public AbstractDetailComposite createDetailComposite(Composite parent, Class eClass) {
EventDefinitionsDetailComposite details = new EventDefinitionsDetailComposite(parent, (Event)getBusinessObject()) {
@Override
public void createBindings(EObject be) {
super.createBindings(be);
if (object instanceof CatchEvent)
getDataAssociationComposite().setAllowedMapTypes(MapType.Property.getValue());
else
getDataAssociationComposite().setAllowedMapTypes(MapType.Property.getValue() | MapType.SingleAssignment.getValue());
}
};
return details;
}
@Override
protected EObject addListItem(EObject object, EStructuralFeature feature) {
List<EventDefinition> eventDefinitions = null;
if (event instanceof ThrowEvent)
eventDefinitions = ((ThrowEvent)event).getEventDefinitions();
else if (event instanceof CatchEvent)
eventDefinitions = ((CatchEvent)event).getEventDefinitions();
if (eventDefinitions.size()>0) {
MessageDialog.openError(getShell(), Messages.JbpmCommonEventDetailComposite_Error_Title,
Messages.JbpmCommonEventDetailComposite_Error_Message
);
return null;
}
return super.addListItem(object, feature);
}
};
eventsTable.bindList(object, feature);
eventsTable.setTitle(Messages.JbpmCommonEventDetailComposite_Title);
return eventsTable;
}
return super.bindList(object, feature, listItemClass);
}
return null;
}
| protected AbstractListComposite bindList(final EObject object, EStructuralFeature feature, EClass listItemClass) {
if (isModelObjectEnabled(object.eClass(), feature)) {
if ("eventDefinitions".equals(feature.getName())) { //$NON-NLS-1$
eventsTable = new EventDefinitionsListComposite(this, (Event)object) {
@Override
public AbstractDetailComposite createDetailComposite(Class eClass, Composite parent, int style) {
EventDefinitionsDetailComposite details = new EventDefinitionsDetailComposite(parent, (Event)getBusinessObject()) {
@Override
public void createBindings(EObject be) {
super.createBindings(be);
if (object instanceof CatchEvent)
getDataAssociationComposite().setAllowedMapTypes(MapType.Property.getValue());
else
getDataAssociationComposite().setAllowedMapTypes(MapType.Property.getValue() | MapType.SingleAssignment.getValue());
}
};
return details;
}
@Override
protected EObject addListItem(EObject object, EStructuralFeature feature) {
List<EventDefinition> eventDefinitions = null;
if (event instanceof ThrowEvent)
eventDefinitions = ((ThrowEvent)event).getEventDefinitions();
else if (event instanceof CatchEvent)
eventDefinitions = ((CatchEvent)event).getEventDefinitions();
if (eventDefinitions.size()>0) {
MessageDialog.openError(getShell(), Messages.JbpmCommonEventDetailComposite_Error_Title,
Messages.JbpmCommonEventDetailComposite_Error_Message
);
return null;
}
return super.addListItem(object, feature);
}
};
eventsTable.bindList(object, feature);
eventsTable.setTitle(Messages.JbpmCommonEventDetailComposite_Title);
return eventsTable;
}
return super.bindList(object, feature, listItemClass);
}
return null;
}
|
diff --git a/jamwiki-web/src/main/java/org/jamwiki/servlets/EditServlet.java b/jamwiki-web/src/main/java/org/jamwiki/servlets/EditServlet.java
index ce18d16b..d2452720 100644
--- a/jamwiki-web/src/main/java/org/jamwiki/servlets/EditServlet.java
+++ b/jamwiki-web/src/main/java/org/jamwiki/servlets/EditServlet.java
@@ -1,329 +1,332 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.servlets;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.jamwiki.WikiBase;
import org.jamwiki.WikiException;
import org.jamwiki.WikiMessage;
import org.jamwiki.authentication.WikiUserAuth;
import org.jamwiki.model.Role;
import org.jamwiki.model.Topic;
import org.jamwiki.model.TopicVersion;
import org.jamwiki.model.Watchlist;
import org.jamwiki.parser.ParserInput;
import org.jamwiki.parser.ParserOutput;
import org.jamwiki.parser.ParserUtil;
import org.jamwiki.utils.DiffUtil;
import org.jamwiki.utils.LinkUtil;
import org.jamwiki.utils.NamespaceHandler;
import org.jamwiki.utils.WikiLink;
import org.jamwiki.utils.WikiLogger;
import org.jamwiki.utils.WikiUtil;
import org.springframework.web.servlet.ModelAndView;
/**
* Used to process topic edits including saving an edit, preview, resolving
* conflicts and dealing with spam.
*/
public class EditServlet extends JAMWikiServlet {
private static final WikiLogger logger = WikiLogger.getLogger(EditServlet.class.getName());
protected static final String JSP_EDIT = "edit.jsp";
/**
*
*/
protected ModelAndView handleJAMWikiRequest(HttpServletRequest request, HttpServletResponse response, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
ModelAndView loginRequired = loginRequired(request, pageInfo);
if (loginRequired != null) {
return loginRequired;
}
if (isSave(request)) {
save(request, next, pageInfo);
} else {
edit(request, next, pageInfo);
}
return next;
}
/**
*
*/
private void edit(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = WikiUtil.getTopicFromRequest(request);
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
Topic topic = loadTopic(virtualWiki, topicName);
// topic name might be updated by loadTopic
topicName = topic.getName();
Integer lastTopicVersionId = retrieveLastTopicVersionId(request, topic);
next.addObject("lastTopicVersionId", lastTopicVersionId);
loadEdit(request, next, pageInfo, virtualWiki, topicName, true);
String contents = null;
if (isPreview(request)) {
preview(request, next, pageInfo);
return;
}
pageInfo.setContentJsp(JSP_EDIT);
if (!StringUtils.isBlank(request.getParameter("topicVersionId"))) {
// editing an older version
Integer topicVersionId = new Integer(request.getParameter("topicVersionId"));
TopicVersion topicVersion = WikiBase.getDataHandler().lookupTopicVersion(topicVersionId.intValue(), null);
if (topicVersion == null) {
throw new WikiException(new WikiMessage("common.exception.notopic"));
}
contents = topicVersion.getVersionContent();
if (!lastTopicVersionId.equals(topicVersionId)) {
next.addObject("topicVersionId", topicVersionId);
}
} else if (!StringUtils.isBlank(request.getParameter("section"))) {
// editing a section of a topic
int section = (new Integer(request.getParameter("section"))).intValue();
contents = ParserUtil.parseSlice(request.getContextPath(), request.getLocale(), virtualWiki, topicName, section);
} else {
// editing a full new or existing topic
contents = (topic == null) ? "" : topic.getTopicContent();
}
next.addObject("contents", contents);
}
/**
*
*/
private boolean handleSpam(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo, String topicName, String contents) throws Exception {
String result = ServletUtil.checkForSpam(request, topicName, contents);
if (result == null) {
return false;
}
WikiMessage spam = new WikiMessage("edit.exception.spam", result);
next.addObject("spam", spam);
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
next.addObject("contents", contents);
loadEdit(request, next, pageInfo, virtualWiki, topicName, false);
next.addObject("editSpam", "true");
pageInfo.setContentJsp(JSP_EDIT);
return true;
}
/**
*
*/
private boolean isPreview(HttpServletRequest request) {
return !StringUtils.isBlank(request.getParameter("preview"));
}
/**
*
*/
private boolean isSave(HttpServletRequest request) {
return !StringUtils.isBlank(request.getParameter("save"));
}
/**
*
*/
private void loadEdit(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo, String virtualWiki, String topicName, boolean useSection) throws Exception {
pageInfo.setPageTitle(new WikiMessage("edit.title", topicName));
pageInfo.setTopicName(topicName);
WikiLink wikiLink = LinkUtil.parseWikiLink(topicName);
String namespace = wikiLink.getNamespace();
if (namespace != null && namespace.equals(NamespaceHandler.NAMESPACE_CATEGORY)) {
ServletUtil.loadCategoryContent(next, virtualWiki, topicName);
}
if (request.getParameter("editComment") != null) {
next.addObject("editComment", request.getParameter("editComment"));
}
if (useSection && request.getParameter("section") != null) {
next.addObject("section", request.getParameter("section"));
}
next.addObject("minorEdit", new Boolean(request.getParameter("minorEdit") != null));
Watchlist watchlist = ServletUtil.currentWatchlist(request, virtualWiki);
if (request.getParameter("watchTopic") != null || (watchlist.containsTopic(topicName) && !isPreview(request))) {
next.addObject("watchTopic", new Boolean(true));
}
}
/**
* Initialize topic values for the topic being edited. If a topic with
* the specified name already exists then it will be initialized,
* otherwise a new topic is created.
*/
private Topic loadTopic(String virtualWiki, String topicName) throws Exception {
Topic topic = ServletUtil.initializeTopic(virtualWiki, topicName);
if (topic.getReadOnly()) {
throw new WikiException(new WikiMessage("error.readonly"));
}
return topic;
}
/**
*
*/
private ModelAndView loginRequired(HttpServletRequest request, WikiPageInfo pageInfo) throws Exception {
String topicName = WikiUtil.getTopicFromRequest(request);
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
WikiUserAuth user = ServletUtil.currentUser();
if (ServletUtil.isEditable(virtualWiki, topicName, user)) {
return null;
}
if (!user.hasRole(Role.ROLE_EDIT_EXISTING)) {
WikiMessage messageObject = new WikiMessage("login.message.edit");
return ServletUtil.viewLogin(request, pageInfo, WikiUtil.getTopicFromURI(request), messageObject);
}
if (!user.hasRole(Role.ROLE_EDIT_NEW) && WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null) == null) {
WikiMessage messageObject = new WikiMessage("login.message.editnew");
return ServletUtil.viewLogin(request, pageInfo, WikiUtil.getTopicFromURI(request), messageObject);
}
Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (topic == null) {
// this should never trigger, but better safe than sorry...
return null;
}
if (topic.getAdminOnly()) {
WikiMessage messageObject = new WikiMessage("login.message.editadmin", topicName);
return ServletUtil.viewLogin(request, pageInfo, WikiUtil.getTopicFromURI(request), messageObject);
}
if (topic.getReadOnly()) {
throw new WikiException(new WikiMessage("error.readonly"));
}
// it should be impossible to get here...
throw new WikiException(new WikiMessage("error.unknown", "Unable to determine topic editing permissions"));
}
/**
*
*/
private void preview(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = WikiUtil.getTopicFromRequest(request);
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
String contents = (String)request.getParameter("contents");
Topic previewTopic = new Topic();
previewTopic.setName(topicName);
previewTopic.setTopicContent(contents);
previewTopic.setVirtualWiki(virtualWiki);
next.addObject("editPreview", "true");
pageInfo.setContentJsp(JSP_EDIT);
next.addObject("contents", contents);
ServletUtil.viewTopic(request, next, pageInfo, null, previewTopic, false);
}
/**
*
*/
private void resolve(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = WikiUtil.getTopicFromRequest(request);
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
Topic lastTopic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
String contents1 = lastTopic.getTopicContent();
String contents2 = request.getParameter("contents");
next.addObject("lastTopicVersionId", lastTopic.getCurrentVersionId());
next.addObject("contents", contents1);
next.addObject("contentsResolve", contents2);
Vector diffs = DiffUtil.diff(contents1, contents2);
next.addObject("diffs", diffs);
loadEdit(request, next, pageInfo, virtualWiki, topicName, false);
next.addObject("editResolve", "true");
pageInfo.setContentJsp(JSP_EDIT);
}
/**
*
*/
private Integer retrieveLastTopicVersionId(HttpServletRequest request, Topic topic) throws Exception {
return (!StringUtils.isBlank(request.getParameter("lastTopicVersionId"))) ? new Integer(request.getParameter("lastTopicVersionId")) : topic.getCurrentVersionId();
}
/**
*
*/
private void save(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = WikiUtil.getTopicFromRequest(request);
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
Topic topic = loadTopic(virtualWiki, topicName);
Topic lastTopic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (lastTopic != null && !lastTopic.getCurrentVersionId().equals(retrieveLastTopicVersionId(request, topic))) {
// someone else has edited the topic more recently
resolve(request, next, pageInfo);
return;
}
String contents = request.getParameter("contents");
String sectionName = "";
if (!StringUtils.isBlank(request.getParameter("section"))) {
// load section of topic
int section = (new Integer(request.getParameter("section"))).intValue();
ParserOutput parserOutput = new ParserOutput();
contents = ParserUtil.parseSplice(parserOutput, request.getContextPath(), request.getLocale(), virtualWiki, topicName, section, contents);
sectionName = parserOutput.getSectionName();
}
if (contents == null) {
logger.warning("The topic " + topicName + " has no content");
throw new WikiException(new WikiMessage("edit.exception.nocontent", topicName));
}
- if (lastTopic != null && lastTopic.getTopicContent().equals(contents)) {
+ // strip line feeds
+ contents = StringUtils.remove(contents, '\r');
+ String lastTopicContent = (lastTopic != null) ? StringUtils.remove(lastTopic.getTopicContent(), '\r') : "";
+ if (StringUtils.equals(lastTopicContent, contents)) {
// topic hasn't changed. redirect to prevent user from refreshing and re-submitting
ServletUtil.redirect(next, virtualWiki, topic.getName());
return;
}
if (handleSpam(request, next, pageInfo, topicName, contents)) {
return;
}
// parse for signatures and other syntax that should not be saved in raw form
WikiUserAuth user = ServletUtil.currentUser();
ParserInput parserInput = new ParserInput();
parserInput.setContext(request.getContextPath());
parserInput.setLocale(request.getLocale());
parserInput.setWikiUser(user);
parserInput.setTopicName(topicName);
parserInput.setUserIpAddress(ServletUtil.getIpAddress(request));
parserInput.setVirtualWiki(virtualWiki);
ParserOutput parserOutput = ParserUtil.parseMetadata(parserInput, contents);
// parse signatures and other values that need to be updated prior to saving
contents = ParserUtil.parseMinimal(parserInput, contents);
topic.setTopicContent(contents);
if (!StringUtils.isBlank(parserOutput.getRedirect())) {
// set up a redirect
topic.setRedirectTo(parserOutput.getRedirect());
topic.setTopicType(Topic.TYPE_REDIRECT);
} else if (topic.getTopicType() == Topic.TYPE_REDIRECT) {
// no longer a redirect
topic.setRedirectTo(null);
topic.setTopicType(Topic.TYPE_ARTICLE);
}
TopicVersion topicVersion = new TopicVersion(user, ServletUtil.getIpAddress(request), request.getParameter("editComment"), contents);
if (request.getParameter("minorEdit") != null) {
topicVersion.setEditType(TopicVersion.EDIT_MINOR);
}
WikiBase.getDataHandler().writeTopic(topic, topicVersion, parserOutput.getCategories(), parserOutput.getLinks(), true, null);
// update watchlist
if (user.hasRole(Role.ROLE_USER)) {
Watchlist watchlist = ServletUtil.currentWatchlist(request, virtualWiki);
boolean watchTopic = (request.getParameter("watchTopic") != null);
if (watchlist.containsTopic(topicName) != watchTopic) {
WikiBase.getDataHandler().writeWatchlistEntry(watchlist, virtualWiki, topicName, user.getUserId(), null);
}
}
// redirect to prevent user from refreshing and re-submitting
String target = topic.getName();
if (!StringUtils.isBlank(sectionName)) {
target += "#" + sectionName;
}
ServletUtil.redirect(next, virtualWiki, target);
}
}
| true | true | private void save(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = WikiUtil.getTopicFromRequest(request);
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
Topic topic = loadTopic(virtualWiki, topicName);
Topic lastTopic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (lastTopic != null && !lastTopic.getCurrentVersionId().equals(retrieveLastTopicVersionId(request, topic))) {
// someone else has edited the topic more recently
resolve(request, next, pageInfo);
return;
}
String contents = request.getParameter("contents");
String sectionName = "";
if (!StringUtils.isBlank(request.getParameter("section"))) {
// load section of topic
int section = (new Integer(request.getParameter("section"))).intValue();
ParserOutput parserOutput = new ParserOutput();
contents = ParserUtil.parseSplice(parserOutput, request.getContextPath(), request.getLocale(), virtualWiki, topicName, section, contents);
sectionName = parserOutput.getSectionName();
}
if (contents == null) {
logger.warning("The topic " + topicName + " has no content");
throw new WikiException(new WikiMessage("edit.exception.nocontent", topicName));
}
if (lastTopic != null && lastTopic.getTopicContent().equals(contents)) {
// topic hasn't changed. redirect to prevent user from refreshing and re-submitting
ServletUtil.redirect(next, virtualWiki, topic.getName());
return;
}
if (handleSpam(request, next, pageInfo, topicName, contents)) {
return;
}
// parse for signatures and other syntax that should not be saved in raw form
WikiUserAuth user = ServletUtil.currentUser();
ParserInput parserInput = new ParserInput();
parserInput.setContext(request.getContextPath());
parserInput.setLocale(request.getLocale());
parserInput.setWikiUser(user);
parserInput.setTopicName(topicName);
parserInput.setUserIpAddress(ServletUtil.getIpAddress(request));
parserInput.setVirtualWiki(virtualWiki);
ParserOutput parserOutput = ParserUtil.parseMetadata(parserInput, contents);
// parse signatures and other values that need to be updated prior to saving
contents = ParserUtil.parseMinimal(parserInput, contents);
topic.setTopicContent(contents);
if (!StringUtils.isBlank(parserOutput.getRedirect())) {
// set up a redirect
topic.setRedirectTo(parserOutput.getRedirect());
topic.setTopicType(Topic.TYPE_REDIRECT);
} else if (topic.getTopicType() == Topic.TYPE_REDIRECT) {
// no longer a redirect
topic.setRedirectTo(null);
topic.setTopicType(Topic.TYPE_ARTICLE);
}
TopicVersion topicVersion = new TopicVersion(user, ServletUtil.getIpAddress(request), request.getParameter("editComment"), contents);
if (request.getParameter("minorEdit") != null) {
topicVersion.setEditType(TopicVersion.EDIT_MINOR);
}
WikiBase.getDataHandler().writeTopic(topic, topicVersion, parserOutput.getCategories(), parserOutput.getLinks(), true, null);
// update watchlist
if (user.hasRole(Role.ROLE_USER)) {
Watchlist watchlist = ServletUtil.currentWatchlist(request, virtualWiki);
boolean watchTopic = (request.getParameter("watchTopic") != null);
if (watchlist.containsTopic(topicName) != watchTopic) {
WikiBase.getDataHandler().writeWatchlistEntry(watchlist, virtualWiki, topicName, user.getUserId(), null);
}
}
// redirect to prevent user from refreshing and re-submitting
String target = topic.getName();
if (!StringUtils.isBlank(sectionName)) {
target += "#" + sectionName;
}
ServletUtil.redirect(next, virtualWiki, target);
}
| private void save(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String topicName = WikiUtil.getTopicFromRequest(request);
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
Topic topic = loadTopic(virtualWiki, topicName);
Topic lastTopic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
if (lastTopic != null && !lastTopic.getCurrentVersionId().equals(retrieveLastTopicVersionId(request, topic))) {
// someone else has edited the topic more recently
resolve(request, next, pageInfo);
return;
}
String contents = request.getParameter("contents");
String sectionName = "";
if (!StringUtils.isBlank(request.getParameter("section"))) {
// load section of topic
int section = (new Integer(request.getParameter("section"))).intValue();
ParserOutput parserOutput = new ParserOutput();
contents = ParserUtil.parseSplice(parserOutput, request.getContextPath(), request.getLocale(), virtualWiki, topicName, section, contents);
sectionName = parserOutput.getSectionName();
}
if (contents == null) {
logger.warning("The topic " + topicName + " has no content");
throw new WikiException(new WikiMessage("edit.exception.nocontent", topicName));
}
// strip line feeds
contents = StringUtils.remove(contents, '\r');
String lastTopicContent = (lastTopic != null) ? StringUtils.remove(lastTopic.getTopicContent(), '\r') : "";
if (StringUtils.equals(lastTopicContent, contents)) {
// topic hasn't changed. redirect to prevent user from refreshing and re-submitting
ServletUtil.redirect(next, virtualWiki, topic.getName());
return;
}
if (handleSpam(request, next, pageInfo, topicName, contents)) {
return;
}
// parse for signatures and other syntax that should not be saved in raw form
WikiUserAuth user = ServletUtil.currentUser();
ParserInput parserInput = new ParserInput();
parserInput.setContext(request.getContextPath());
parserInput.setLocale(request.getLocale());
parserInput.setWikiUser(user);
parserInput.setTopicName(topicName);
parserInput.setUserIpAddress(ServletUtil.getIpAddress(request));
parserInput.setVirtualWiki(virtualWiki);
ParserOutput parserOutput = ParserUtil.parseMetadata(parserInput, contents);
// parse signatures and other values that need to be updated prior to saving
contents = ParserUtil.parseMinimal(parserInput, contents);
topic.setTopicContent(contents);
if (!StringUtils.isBlank(parserOutput.getRedirect())) {
// set up a redirect
topic.setRedirectTo(parserOutput.getRedirect());
topic.setTopicType(Topic.TYPE_REDIRECT);
} else if (topic.getTopicType() == Topic.TYPE_REDIRECT) {
// no longer a redirect
topic.setRedirectTo(null);
topic.setTopicType(Topic.TYPE_ARTICLE);
}
TopicVersion topicVersion = new TopicVersion(user, ServletUtil.getIpAddress(request), request.getParameter("editComment"), contents);
if (request.getParameter("minorEdit") != null) {
topicVersion.setEditType(TopicVersion.EDIT_MINOR);
}
WikiBase.getDataHandler().writeTopic(topic, topicVersion, parserOutput.getCategories(), parserOutput.getLinks(), true, null);
// update watchlist
if (user.hasRole(Role.ROLE_USER)) {
Watchlist watchlist = ServletUtil.currentWatchlist(request, virtualWiki);
boolean watchTopic = (request.getParameter("watchTopic") != null);
if (watchlist.containsTopic(topicName) != watchTopic) {
WikiBase.getDataHandler().writeWatchlistEntry(watchlist, virtualWiki, topicName, user.getUserId(), null);
}
}
// redirect to prevent user from refreshing and re-submitting
String target = topic.getName();
if (!StringUtils.isBlank(sectionName)) {
target += "#" + sectionName;
}
ServletUtil.redirect(next, virtualWiki, target);
}
|
diff --git a/src/main/java/org/xenmaster/api/util/APIUtil.java b/src/main/java/org/xenmaster/api/util/APIUtil.java
index 50a8a04..4597138 100644
--- a/src/main/java/org/xenmaster/api/util/APIUtil.java
+++ b/src/main/java/org/xenmaster/api/util/APIUtil.java
@@ -1,98 +1,98 @@
/*
* APIUtil.java
* Copyright (C) 2011,2012 Wannes De Smet
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.xenmaster.api.util;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.util.Map;
import java.util.UUID;
import net.wgr.core.ReflectionUtils;
import org.apache.log4j.Logger;
import org.xenmaster.api.entity.XenApiEntity;
/**
*
* @created Dec 14, 2011
* @author double-u
*/
public class APIUtil {
public static Object deserializeToTargetType(Object value, Class type) throws Exception {
switch (type.getSimpleName().toLowerCase()) {
case "boolean":
return Boolean.parseBoolean(value.toString());
case "integer":
case "int":
return Integer.parseInt(value.toString());
case "long":
return Long.parseLong(value.toString());
case "double":
return Double.parseDouble(value.toString());
default:
if (type.isEnum()) {
String ucase = value.toString().toUpperCase();
for (Object enumType : type.getEnumConstants()) {
if (enumType.toString().toUpperCase().equals(ucase)) {
return enumType;
}
}
throw new IllegalArgumentException("Argument value does not belong to enum values of " + type.getCanonicalName());
} else if (type.isArray()) {
// FIXME : This can break all too easily
Class t = type.getComponentType();
Object[] src = (Object[]) value;
Object[] arr = (Object[]) Array.newInstance(t, src.length);
for (int i = 0; i < src.length; i++) {
arr[i] = deserializeToTargetType(src[i], t);
}
return arr;
} else if (InetAddress.class.isAssignableFrom(type)) {
return InetAddress.getByName(value.toString());
} else if (XenApiMapField.class.isAssignableFrom(type)) {
Constructor c = type.getConstructor(Map.class);
return c.newInstance((Map<String, String>) value);
} else if (XenApiEntity.class.isAssignableFrom(type)) {
Constructor c = type.getConstructor(String.class, boolean.class);
return c.newInstance(value.toString(), false);
} else if (UUID.class.isAssignableFrom(type)) {
return UUID.fromString(value.toString());
- } else if (Map.class.isAssignableFrom(value.getClass())) {
+ } else if (value != null && Map.class.isAssignableFrom(value.getClass())) {
Logger.getLogger(APIUtil.class).info("New transformer used");
Object instance = type.newInstance();
Map<String, Object> source = (Map<String, Object>) value;
for (Map.Entry<String, Object> entry : source.entrySet()) {
for (Field f : ReflectionUtils.getAllFields(type)) {
if (f.getName().equals(entry.getKey())) {
f.setAccessible(true);
f.set(instance, deserializeToTargetType(entry.getValue(), f.getType()));
break;
}
}
}
return instance;
}
break;
}
return value;
}
}
| true | true | public static Object deserializeToTargetType(Object value, Class type) throws Exception {
switch (type.getSimpleName().toLowerCase()) {
case "boolean":
return Boolean.parseBoolean(value.toString());
case "integer":
case "int":
return Integer.parseInt(value.toString());
case "long":
return Long.parseLong(value.toString());
case "double":
return Double.parseDouble(value.toString());
default:
if (type.isEnum()) {
String ucase = value.toString().toUpperCase();
for (Object enumType : type.getEnumConstants()) {
if (enumType.toString().toUpperCase().equals(ucase)) {
return enumType;
}
}
throw new IllegalArgumentException("Argument value does not belong to enum values of " + type.getCanonicalName());
} else if (type.isArray()) {
// FIXME : This can break all too easily
Class t = type.getComponentType();
Object[] src = (Object[]) value;
Object[] arr = (Object[]) Array.newInstance(t, src.length);
for (int i = 0; i < src.length; i++) {
arr[i] = deserializeToTargetType(src[i], t);
}
return arr;
} else if (InetAddress.class.isAssignableFrom(type)) {
return InetAddress.getByName(value.toString());
} else if (XenApiMapField.class.isAssignableFrom(type)) {
Constructor c = type.getConstructor(Map.class);
return c.newInstance((Map<String, String>) value);
} else if (XenApiEntity.class.isAssignableFrom(type)) {
Constructor c = type.getConstructor(String.class, boolean.class);
return c.newInstance(value.toString(), false);
} else if (UUID.class.isAssignableFrom(type)) {
return UUID.fromString(value.toString());
} else if (Map.class.isAssignableFrom(value.getClass())) {
Logger.getLogger(APIUtil.class).info("New transformer used");
Object instance = type.newInstance();
Map<String, Object> source = (Map<String, Object>) value;
for (Map.Entry<String, Object> entry : source.entrySet()) {
for (Field f : ReflectionUtils.getAllFields(type)) {
if (f.getName().equals(entry.getKey())) {
f.setAccessible(true);
f.set(instance, deserializeToTargetType(entry.getValue(), f.getType()));
break;
}
}
}
return instance;
}
break;
}
return value;
}
| public static Object deserializeToTargetType(Object value, Class type) throws Exception {
switch (type.getSimpleName().toLowerCase()) {
case "boolean":
return Boolean.parseBoolean(value.toString());
case "integer":
case "int":
return Integer.parseInt(value.toString());
case "long":
return Long.parseLong(value.toString());
case "double":
return Double.parseDouble(value.toString());
default:
if (type.isEnum()) {
String ucase = value.toString().toUpperCase();
for (Object enumType : type.getEnumConstants()) {
if (enumType.toString().toUpperCase().equals(ucase)) {
return enumType;
}
}
throw new IllegalArgumentException("Argument value does not belong to enum values of " + type.getCanonicalName());
} else if (type.isArray()) {
// FIXME : This can break all too easily
Class t = type.getComponentType();
Object[] src = (Object[]) value;
Object[] arr = (Object[]) Array.newInstance(t, src.length);
for (int i = 0; i < src.length; i++) {
arr[i] = deserializeToTargetType(src[i], t);
}
return arr;
} else if (InetAddress.class.isAssignableFrom(type)) {
return InetAddress.getByName(value.toString());
} else if (XenApiMapField.class.isAssignableFrom(type)) {
Constructor c = type.getConstructor(Map.class);
return c.newInstance((Map<String, String>) value);
} else if (XenApiEntity.class.isAssignableFrom(type)) {
Constructor c = type.getConstructor(String.class, boolean.class);
return c.newInstance(value.toString(), false);
} else if (UUID.class.isAssignableFrom(type)) {
return UUID.fromString(value.toString());
} else if (value != null && Map.class.isAssignableFrom(value.getClass())) {
Logger.getLogger(APIUtil.class).info("New transformer used");
Object instance = type.newInstance();
Map<String, Object> source = (Map<String, Object>) value;
for (Map.Entry<String, Object> entry : source.entrySet()) {
for (Field f : ReflectionUtils.getAllFields(type)) {
if (f.getName().equals(entry.getKey())) {
f.setAccessible(true);
f.set(instance, deserializeToTargetType(entry.getValue(), f.getType()));
break;
}
}
}
return instance;
}
break;
}
return value;
}
|
diff --git a/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryDaemon.java b/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryDaemon.java
index 04a267739..7e269678c 100644
--- a/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryDaemon.java
+++ b/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryDaemon.java
@@ -1,218 +1,219 @@
/**
* A CCNx repository.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This work 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 work is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package org.ccnx.ccn.impl.repo;
import java.io.File;
import java.security.InvalidParameterException;
import java.util.logging.Level;
import org.ccnx.ccn.impl.support.Daemon;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.test.BitBucketRepository;
/**
* Daemon for stand-alone repository on persistent storage in the filesystem.
*/
public class RepositoryDaemon extends Daemon {
RepositoryServer _server;
RepositoryStore _repo;
protected class RepositoryWorkerThread extends Daemon.WorkerThread {
private static final long serialVersionUID = -6093561895394961537L;
protected RepositoryWorkerThread(String daemonName) {
super(daemonName);
}
public void work() {
synchronized(this) {
boolean interrupted = false;
do {
try {
interrupted = false;
wait();
} catch (InterruptedException e) {
interrupted = true;
}
} while (interrupted);
}
}
public void initialize() {
_server.start();
}
public void finish() {
_server.shutDown();
synchronized (this) {
notifyAll(); // notifyAll ensures shutdown in interactive case when main thread is join()'ing
}
}
public boolean signal(String name) {
return _repo.diagnostic(name);
}
public Object status(String type) {
return "running";
}
}
public RepositoryDaemon() {
super();
// This is a daemon: it should not do anything in the
// constructor but everything in the initialize() method
// which will be run in the process that will finally
// execute as the daemon, rather than in the launching
// and stopping processes also.
_daemonName = "repository";
}
/**
* Parse arguments specific to the Repository
*
* Current arguments are:<p>
*
* -root <directory> sets the root of the repository (this argument is required).
*
* The following arguments are optional:<p>
* <ul>
* <li>-log <level> enable logging and set the logging level to <level>
* <li>-policy <file> use the policy file to set initial policy for the repo
* <li>-local <path> set the local name for this repository
* <li>-global <path> set the global prefix for this repository
* </ul>
*/
public void initialize(String[] args, Daemon daemon) {
Log.info("Starting " + _daemonName + "...");
Log.setLevel(Level.INFO);
try {
Log.setDefaultLevel(Level.SEVERE); // turn off all but severe errors
String repositoryRoot = null;
File policyFile = null;
String localName = null;
String globalPrefix = null;
String nameSpace = null;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-log")) {
if (args.length < i + 2) {
usage();
return;
}
try {
Level level = Level.parse(args[i + 1]);
- Log.setLevel(level);
+ Log.setLevel(level); // XXX should level mean this or just FAC_REPO?
+ Log.setLevel(Log.FAC_REPO, level);
} catch (IllegalArgumentException iae) {
usage();
return;
}
i++;
} else if (args[i].equals("-root")) {
if (args.length < i + 2)
throw new InvalidParameterException();
repositoryRoot = args[i + 1];
i++;
} else if (args[i].equals("-policy")) {
if (args.length < i + 2)
throw new InvalidParameterException();
policyFile = new File(args[i + 1]);
i++;
} else if (args[i].equals("-local")) {
if (args.length < i + 2)
throw new InvalidParameterException();
localName = args[i + 1];
i++;
} else if (args[i].equals("-global")) {
if (args.length < i + 2)
throw new InvalidParameterException();
globalPrefix = args[i + 1];
if (!globalPrefix.startsWith("/"))
globalPrefix = "/" + globalPrefix;
i++;
} else if (args[i].equals("-prefix")) {
if (args.length < i + 2)
throw new InvalidParameterException();
nameSpace = args[i + 1];
if (!nameSpace.startsWith("/"))
nameSpace = "/" + nameSpace;
i++;
} else if (args[i].equals("-bb")) {
// Following is for upper half performance testing for writes
_repo = new BitBucketRepository();
} else if(args[i].equals("-singlefile")) {
// This is a reference to an old repo type that no longer exists
System.out.println("-singlefile no longer supported");
throw new InvalidParameterException();
}
}
if (_repo == null) // default lower half
_repo = new LogStructRepoStore();
_repo.initialize(repositoryRoot, policyFile, localName, globalPrefix, nameSpace, null);
_server = new RepositoryServer(_repo);
Log.info("started repo with response name: "+_server.getResponseName());
} catch (InvalidParameterException ipe) {
usage();
} catch (Exception e) {
e.printStackTrace();
Log.logStackTrace(Level.SEVERE, e);
System.exit(1);
}
}
protected void usage() {
try {
// Without parsing args, we don't know which repo impl we will get, so show the default
// impl usage and allow for differences
String msg = "usage: " + this.getClass().getName() + " -start -root <repository_root> | -stop <pid> | -interactive | -signal <signal> <pid>" +
" [-log <level>] [-policy <policy_file>] [-local <local_name>] [-global <global_prefix>] [-bb]";
System.out.println(msg);
Log.severe(msg);
} catch (Exception e) {
e.printStackTrace();
Log.logStackTrace(Level.SEVERE, e);
}
System.exit(1);
}
protected WorkerThread createWorkerThread() {
return new RepositoryWorkerThread(daemonName());
}
/**
* Start a new repository daemon
* @param args
*/
public static void main(String[] args) {
Daemon daemon = null;
try {
daemon = new RepositoryDaemon();
runDaemon(daemon, args);
} catch (Exception e) {
System.err.println("Error attempting to start daemon.");
Log.warning("Error attempting to start daemon.");
Log.warningStackTrace(e);
}
}
}
| true | true | public void initialize(String[] args, Daemon daemon) {
Log.info("Starting " + _daemonName + "...");
Log.setLevel(Level.INFO);
try {
Log.setDefaultLevel(Level.SEVERE); // turn off all but severe errors
String repositoryRoot = null;
File policyFile = null;
String localName = null;
String globalPrefix = null;
String nameSpace = null;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-log")) {
if (args.length < i + 2) {
usage();
return;
}
try {
Level level = Level.parse(args[i + 1]);
Log.setLevel(level);
} catch (IllegalArgumentException iae) {
usage();
return;
}
i++;
} else if (args[i].equals("-root")) {
if (args.length < i + 2)
throw new InvalidParameterException();
repositoryRoot = args[i + 1];
i++;
} else if (args[i].equals("-policy")) {
if (args.length < i + 2)
throw new InvalidParameterException();
policyFile = new File(args[i + 1]);
i++;
} else if (args[i].equals("-local")) {
if (args.length < i + 2)
throw new InvalidParameterException();
localName = args[i + 1];
i++;
} else if (args[i].equals("-global")) {
if (args.length < i + 2)
throw new InvalidParameterException();
globalPrefix = args[i + 1];
if (!globalPrefix.startsWith("/"))
globalPrefix = "/" + globalPrefix;
i++;
} else if (args[i].equals("-prefix")) {
if (args.length < i + 2)
throw new InvalidParameterException();
nameSpace = args[i + 1];
if (!nameSpace.startsWith("/"))
nameSpace = "/" + nameSpace;
i++;
} else if (args[i].equals("-bb")) {
// Following is for upper half performance testing for writes
_repo = new BitBucketRepository();
} else if(args[i].equals("-singlefile")) {
// This is a reference to an old repo type that no longer exists
System.out.println("-singlefile no longer supported");
throw new InvalidParameterException();
}
}
if (_repo == null) // default lower half
_repo = new LogStructRepoStore();
_repo.initialize(repositoryRoot, policyFile, localName, globalPrefix, nameSpace, null);
_server = new RepositoryServer(_repo);
Log.info("started repo with response name: "+_server.getResponseName());
} catch (InvalidParameterException ipe) {
usage();
} catch (Exception e) {
e.printStackTrace();
Log.logStackTrace(Level.SEVERE, e);
System.exit(1);
}
}
| public void initialize(String[] args, Daemon daemon) {
Log.info("Starting " + _daemonName + "...");
Log.setLevel(Level.INFO);
try {
Log.setDefaultLevel(Level.SEVERE); // turn off all but severe errors
String repositoryRoot = null;
File policyFile = null;
String localName = null;
String globalPrefix = null;
String nameSpace = null;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-log")) {
if (args.length < i + 2) {
usage();
return;
}
try {
Level level = Level.parse(args[i + 1]);
Log.setLevel(level); // XXX should level mean this or just FAC_REPO?
Log.setLevel(Log.FAC_REPO, level);
} catch (IllegalArgumentException iae) {
usage();
return;
}
i++;
} else if (args[i].equals("-root")) {
if (args.length < i + 2)
throw new InvalidParameterException();
repositoryRoot = args[i + 1];
i++;
} else if (args[i].equals("-policy")) {
if (args.length < i + 2)
throw new InvalidParameterException();
policyFile = new File(args[i + 1]);
i++;
} else if (args[i].equals("-local")) {
if (args.length < i + 2)
throw new InvalidParameterException();
localName = args[i + 1];
i++;
} else if (args[i].equals("-global")) {
if (args.length < i + 2)
throw new InvalidParameterException();
globalPrefix = args[i + 1];
if (!globalPrefix.startsWith("/"))
globalPrefix = "/" + globalPrefix;
i++;
} else if (args[i].equals("-prefix")) {
if (args.length < i + 2)
throw new InvalidParameterException();
nameSpace = args[i + 1];
if (!nameSpace.startsWith("/"))
nameSpace = "/" + nameSpace;
i++;
} else if (args[i].equals("-bb")) {
// Following is for upper half performance testing for writes
_repo = new BitBucketRepository();
} else if(args[i].equals("-singlefile")) {
// This is a reference to an old repo type that no longer exists
System.out.println("-singlefile no longer supported");
throw new InvalidParameterException();
}
}
if (_repo == null) // default lower half
_repo = new LogStructRepoStore();
_repo.initialize(repositoryRoot, policyFile, localName, globalPrefix, nameSpace, null);
_server = new RepositoryServer(_repo);
Log.info("started repo with response name: "+_server.getResponseName());
} catch (InvalidParameterException ipe) {
usage();
} catch (Exception e) {
e.printStackTrace();
Log.logStackTrace(Level.SEVERE, e);
System.exit(1);
}
}
|
diff --git a/src/main/java/io/github/alshain01/Flags/Flags.java b/src/main/java/io/github/alshain01/Flags/Flags.java
index 22ae9b6..140b82b 100644
--- a/src/main/java/io/github/alshain01/Flags/Flags.java
+++ b/src/main/java/io/github/alshain01/Flags/Flags.java
@@ -1,400 +1,400 @@
/* Copyright 2013 Kevin Seiden. All rights reserved.
This works is licensed under the Creative Commons Attribution-NonCommercial 3.0
You are Free to:
to Share: to copy, distribute and transmit the work
to Remix: to adapt the work
Under the following conditions:
Attribution: You must attribute the work in the manner specified by the author (but not in any way that suggests that they endorse you or your use of the work).
Non-commercial: You may not use this work for commercial purposes.
With the understanding that:
Waiver: Any of the above conditions can be waived if you get permission from the copyright holder.
Public Domain: Where the work or any of its elements is in the public domain under applicable law, that status is in no way affected by the license.
Other Rights: In no way are any of the following rights affected by the license:
Your fair dealing or fair use rights, or other applicable copyright exceptions and limitations;
The author's moral rights;
Rights other persons may have either in the work itself or in how the work is used, such as publicity or privacy rights.
Notice: For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page.
http://creativecommons.org/licenses/by-nc/3.0/
*/
package io.github.alshain01.Flags;
import io.github.alshain01.Flags.Updater.UpdateResult;
import io.github.alshain01.Flags.commands.Command;
import io.github.alshain01.Flags.data.CustomYML;
import io.github.alshain01.Flags.data.DataStore;
import io.github.alshain01.Flags.data.YamlDataStore;
import io.github.alshain01.Flags.events.PlayerChangedAreaEvent;
import io.github.alshain01.Flags.importer.GPFImport;
import io.github.alshain01.Flags.metrics.MetricsManager;
import java.util.List;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredListener;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
/**
* Flags
*
* @author Alshain01
*/
public class Flags extends JavaPlugin {
protected static CustomYML messageStore;
protected static SystemType currentSystem = SystemType.WORLD;
private static DataStore dataStore;
private static Updater updater = null;
private static Economy economy = null;
private static boolean debugOn = false;
private static Registrar flagRegistrar = new Registrar();
private static boolean borderPatrol = false;
/**
* Called when this plug-in is enabled
*/
@Override
public void onEnable() {
// Create the configuration file if it doesn't exist
saveDefaultConfig();
debugOn = getConfig().getBoolean("Flags.Debug");
if (getConfig().getBoolean("Flags.Update.Check")) {
new UpdateScheduler().runTaskTimer(this, 0, 1728000);
}
borderPatrol = getConfig().getBoolean("Flags.BorderPatrol.Enable");
// Create the specific implementation of DataStore
(messageStore = new CustomYML(this, "message.yml")).saveDefaultConfig();
// TODO: Add sub-interface for SQL
dataStore = new YamlDataStore(this);
// New installation
if (!dataStore.create(this)) {
getLogger().warning("Failed to create database schema. Shutting down Flags.");
getServer().getPluginManager().disablePlugin(this);
return;
}
// Find the first available land management system
currentSystem = findSystem(getServer().getPluginManager());
getLogger().info(currentSystem == SystemType.WORLD ? "No system detected. Only world flags will be available."
: currentSystem.getDisplayName() + " detected. Enabling integrated support.");
// Check for older database and import as necessary.
if (currentSystem == SystemType.GRIEF_PREVENTION
&& !getServer().getPluginManager().isPluginEnabled("GriefPreventionFlags")) {
GPFImport.importGPF();
}
dataStore.update(this);
// Enable Vault support
setupEconomy();
// Load Mr. Clean
MrClean.enable(this);
// Load Border Patrol
if (borderPatrol) {
log("Registering for PlayerMoveEvent", true);
BorderPatrol bp = new BorderPatrol(getConfig().getInt("Flags.BorderPatrol.EventDivisor"), getConfig().getInt("Flags.BorderPatrol.TimeDivisor"));
getServer().getPluginManager().registerEvents(bp, this);
}
// Schedule tasks to perform after server is running
- new onServerEnabledTask(this.getConfig().getBoolean("Metrics.Enabled")).runTask(this);
+ new onServerEnabledTask(this.getConfig().getBoolean("Flags.Metrics.Enabled")).runTask(this);
getLogger().info("Flags Has Been Enabled.");
}
/**
* Executes the given command, returning its success
*
* @param sender
* Source of the command
* @param cmd
* Command which was executed
* @param label
* Alias of the command which was used
* @param args
* Passed command arguments
* @return true if a valid command, otherwise false
*
*/
@Override
public boolean onCommand(CommandSender sender,
org.bukkit.command.Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("flag")) {
return Command.onFlagCommand(sender, args);
}
if (cmd.getName().equalsIgnoreCase("bundle")) {
return Command.onBundleCommand(sender, args);
}
return false;
}
/**
* Called when this plug-in is disabled
*/
@Override
public void onDisable() {
// if(dataStore instanceof SQLDataStore) {
// ((SQLDataStore)dataStore).close(); }
// Static cleanup
economy = null;
dataStore = null;
updater = null;
messageStore = null;
flagRegistrar = null;
currentSystem = null;
getLogger().info("Flags Has Been Disabled.");
}
/*
* Contains event listeners required for plugin maintenance.
*/
private class FlagsListener implements Listener {
// Update listener
@EventHandler(ignoreCancelled = true)
private void onPlayerJoin(PlayerJoinEvent e) {
if (e.getPlayer().hasPermission("flags.admin.notifyupdate")) {
if(updater.getResult() == UpdateResult.UPDATE_AVAILABLE) {
e.getPlayer().sendMessage(ChatColor.DARK_PURPLE
+ "The version of Flags that this server is running is out of date. "
+ "Please consider updating to the latest version at dev.bukkit.org/bukkit-plugins/flags/.");
} else if(updater.getResult() == UpdateResult.SUCCESS) {
e.getPlayer().sendMessage("[Flags] " + ChatColor.DARK_PURPLE
+ "An update to Flags has been downloaded and will be installed when the server is reloaded.");
}
}
}
}
/*
* Tasks that must be run only after the entire sever has loaded. Runs on
* first server tick.
*/
private class onServerEnabledTask extends BukkitRunnable {
private onServerEnabledTask(boolean mcstats) {
this.mcstats = mcstats;
}
private boolean mcstats = true;
@Override
public void run() {
for (final String b : Flags.getDataStore().readBundles()) {
log("Registering Bundle Permission:" + b, true);
final Permission perm = new Permission("flags.bundle." + b,
"Grants ability to use the bundle " + b,
PermissionDefault.FALSE);
perm.addParent("flags.bundle", true);
Bukkit.getServer().getPluginManager().addPermission(perm);
}
if (!debugOn && checkAPI("1.3.2")) {
MetricsManager.StartMetrics(Bukkit.getServer().getPluginManager().getPlugin("Flags"));
}
// Check the handlers to see if anything is registered for Border
// Patrol
final RegisteredListener[] listeners = PlayerChangedAreaEvent
.getHandlerList().getRegisteredListeners();
if (borderPatrol && (listeners == null || listeners.length == 0)) {
Bukkit.getServer()
.getConsoleSender()
.sendMessage("[Flags] " + ChatColor.RED
+ "No plugins have registered for Flags' Border Patrol listener. "
+ "Please consider disabling it in config.yml to increase performance.");
}
}
}
private class UpdateScheduler extends BukkitRunnable {
@Override
public void run() {
// Update script
final String key = getConfig().getString("Flags.Update.ServerModsAPIKey");
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("Flags");
updater = (getConfig().getBoolean("Flags.Update.Download"))
? new Updater(plugin, 65024, getFile(), Updater.UpdateType.DEFAULT, key, true)
: new Updater(plugin, 65024, getFile(), Updater.UpdateType.NO_DOWNLOAD, key, false);
if (updater.getResult() == UpdateResult.UPDATE_AVAILABLE) {
Bukkit.getServer().getConsoleSender()
.sendMessage("[Flags] " + ChatColor.DARK_PURPLE
+ "The version of Flags that this server is running is out of date. "
+ "Please consider updating to the latest version at dev.bukkit.org/bukkit-plugins/flags/.");
} else if (updater.getResult() == UpdateResult.SUCCESS) {
Bukkit.getServer().getConsoleSender()
.sendMessage("[Flags] " + ChatColor.DARK_PURPLE
+ "An update to Flags has been downloaded and will be installed when the server is reloaded.");
}
getServer().getPluginManager().registerEvents(new FlagsListener(), plugin);
}
}
/**
* Checks if the provided string represents a version number that is equal
* to or lower than the current Bukkit API version.
*
* String should be formatted with 3 numbers: x.y.z
*
* @return true if the version provided is compatible
*/
public static boolean checkAPI(String version) {
final float APIVersion = Float.valueOf(Bukkit.getServer().getBukkitVersion().substring(0, 3));
final float CompareVersion = Float.valueOf(version.substring(0, 3));
final int APIBuild = Integer.valueOf(Bukkit.getServer().getBukkitVersion().substring(4, 5));
final int CompareBuild = Integer.valueOf(version.substring(4, 5));
return (APIVersion > CompareVersion
|| APIVersion == CompareVersion && APIBuild >= CompareBuild) ? true : false;
}
/**
* Sends a log message through the Flags logger.
*
* @param message
* The message
* @param debug
* Specifies if the message is a debug message
*/
public static final void log(String message, boolean debug) {
if(debug && !debugOn) {
return;
}
if (debug) {
message += "DEBUG: ";
}
Bukkit.getServer().getPluginManager().getPlugin("Flags").getLogger().info(message);
}
/**
* Sends a severe message through the Flags logger.
*
* @param message
* The message
*/
public static final void severe(String message) {
Bukkit.getServer().getPluginManager().getPlugin("Flags").getLogger().severe(message);
}
/**
* Sends a warning message through the Flags logger.
*
* @param message
* The message
*/
public static final void warn(String message) {
Bukkit.getServer().getPluginManager().getPlugin("Flags").getLogger().warning(message);
}
/**
* Sends a log message through the Flags logger.
*
* @param message
* The message
*/
public static void log(String message) {
log(message, false);
}
/**
* Gets the status of the border patrol event listener. (i.e
* PlayerChangedAreaEvent)
*
* @return The status of the border patrol listener
*/
public static boolean getBorderPatrolEnabled() {
return borderPatrol;
}
/**
* Gets the DataStore used by Flags. In most cases, plugins should not
* attempt to access this directly.
*
* @return The vault economy.
*/
public static DataStore getDataStore() {
return dataStore;
}
/**
* Gets the vault economy for this instance of Flags.
*
* @return The vault economy.
*/
public static Economy getEconomy() {
return economy;
}
/**
* Gets the registrar for this instance of Flags.
*
* @return The flag registrar.
*/
public static Registrar getRegistrar() {
return flagRegistrar;
}
/*
* Acquires the land management plugin.
*/
private SystemType findSystem(PluginManager pm) {
final List<?> pluginList = getConfig().getList("Flags.AreaPlugins");
for(Object o : pluginList) {
log("Testing Plugin: " + (String) o, true);
if (pm.isPluginEnabled((String) o)) {
log("Plugin Found: " + (String) o, true);
return SystemType.getByName((String) o);
}
}
return SystemType.WORLD;
}
/*
* Register with the Vault economy plugin.
*
* @return True if the economy was successfully configured.
*/
private static boolean setupEconomy() {
if (!Bukkit.getServer().getPluginManager().isPluginEnabled("Vault")) {
return false;
}
final RegisteredServiceProvider<Economy> economyProvider = Bukkit
.getServer().getServicesManager()
.getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
return economy != null;
}
}
| true | true | public void onEnable() {
// Create the configuration file if it doesn't exist
saveDefaultConfig();
debugOn = getConfig().getBoolean("Flags.Debug");
if (getConfig().getBoolean("Flags.Update.Check")) {
new UpdateScheduler().runTaskTimer(this, 0, 1728000);
}
borderPatrol = getConfig().getBoolean("Flags.BorderPatrol.Enable");
// Create the specific implementation of DataStore
(messageStore = new CustomYML(this, "message.yml")).saveDefaultConfig();
// TODO: Add sub-interface for SQL
dataStore = new YamlDataStore(this);
// New installation
if (!dataStore.create(this)) {
getLogger().warning("Failed to create database schema. Shutting down Flags.");
getServer().getPluginManager().disablePlugin(this);
return;
}
// Find the first available land management system
currentSystem = findSystem(getServer().getPluginManager());
getLogger().info(currentSystem == SystemType.WORLD ? "No system detected. Only world flags will be available."
: currentSystem.getDisplayName() + " detected. Enabling integrated support.");
// Check for older database and import as necessary.
if (currentSystem == SystemType.GRIEF_PREVENTION
&& !getServer().getPluginManager().isPluginEnabled("GriefPreventionFlags")) {
GPFImport.importGPF();
}
dataStore.update(this);
// Enable Vault support
setupEconomy();
// Load Mr. Clean
MrClean.enable(this);
// Load Border Patrol
if (borderPatrol) {
log("Registering for PlayerMoveEvent", true);
BorderPatrol bp = new BorderPatrol(getConfig().getInt("Flags.BorderPatrol.EventDivisor"), getConfig().getInt("Flags.BorderPatrol.TimeDivisor"));
getServer().getPluginManager().registerEvents(bp, this);
}
// Schedule tasks to perform after server is running
new onServerEnabledTask(this.getConfig().getBoolean("Metrics.Enabled")).runTask(this);
getLogger().info("Flags Has Been Enabled.");
}
| public void onEnable() {
// Create the configuration file if it doesn't exist
saveDefaultConfig();
debugOn = getConfig().getBoolean("Flags.Debug");
if (getConfig().getBoolean("Flags.Update.Check")) {
new UpdateScheduler().runTaskTimer(this, 0, 1728000);
}
borderPatrol = getConfig().getBoolean("Flags.BorderPatrol.Enable");
// Create the specific implementation of DataStore
(messageStore = new CustomYML(this, "message.yml")).saveDefaultConfig();
// TODO: Add sub-interface for SQL
dataStore = new YamlDataStore(this);
// New installation
if (!dataStore.create(this)) {
getLogger().warning("Failed to create database schema. Shutting down Flags.");
getServer().getPluginManager().disablePlugin(this);
return;
}
// Find the first available land management system
currentSystem = findSystem(getServer().getPluginManager());
getLogger().info(currentSystem == SystemType.WORLD ? "No system detected. Only world flags will be available."
: currentSystem.getDisplayName() + " detected. Enabling integrated support.");
// Check for older database and import as necessary.
if (currentSystem == SystemType.GRIEF_PREVENTION
&& !getServer().getPluginManager().isPluginEnabled("GriefPreventionFlags")) {
GPFImport.importGPF();
}
dataStore.update(this);
// Enable Vault support
setupEconomy();
// Load Mr. Clean
MrClean.enable(this);
// Load Border Patrol
if (borderPatrol) {
log("Registering for PlayerMoveEvent", true);
BorderPatrol bp = new BorderPatrol(getConfig().getInt("Flags.BorderPatrol.EventDivisor"), getConfig().getInt("Flags.BorderPatrol.TimeDivisor"));
getServer().getPluginManager().registerEvents(bp, this);
}
// Schedule tasks to perform after server is running
new onServerEnabledTask(this.getConfig().getBoolean("Flags.Metrics.Enabled")).runTask(this);
getLogger().info("Flags Has Been Enabled.");
}
|
diff --git a/bundles/org.eclipse.orion.server.search/src/org/eclipse/orion/internal/server/search/Indexer.java b/bundles/org.eclipse.orion.server.search/src/org/eclipse/orion/internal/server/search/Indexer.java
index 1521240a..a997f156 100644
--- a/bundles/org.eclipse.orion.server.search/src/org/eclipse/orion/internal/server/search/Indexer.java
+++ b/bundles/org.eclipse.orion.server.search/src/org/eclipse/orion/internal/server/search/Indexer.java
@@ -1,239 +1,237 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 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.orion.internal.server.search;
import java.io.*;
import java.util.*;
import org.apache.solr.client.solrj.*;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.eclipse.core.filesystem.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.orion.internal.server.core.IOUtilities;
import org.eclipse.orion.internal.server.servlets.Activator;
import org.eclipse.orion.internal.server.servlets.ProtocolConstants;
import org.eclipse.orion.internal.server.servlets.workspace.WebProject;
import org.eclipse.orion.internal.server.servlets.workspace.authorization.AuthorizationService;
import org.eclipse.orion.server.core.LogHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The indexer is responsible for keeping the solr/lucene index up to date.
* It currently does this by naively polling the file system on a periodic basis.
*/
public class Indexer extends Job {
/**
* The minimum delay between indexing runs
*/
private static final long DEFAULT_DELAY = 60000;//one minute
/**
* The minimum delay between indexing runs when the server is idle.
*/
private static final long IDLE_DELAY = 300000;//five minutes
private static final long MAX_SEARCH_SIZE = 300000;//don't index files larger than 300,000 bytes
//private static final List<String> IGNORED_FILE_TYPES = Arrays.asList("png", "jpg", "gif", "bmp", "pdf", "tiff", "class", "so", "zip", "jar", "tar");
private final List<String> INDEXED_FILE_TYPES;
private final SolrServer server;
public Indexer(SolrServer server) {
super("Indexing"); //$NON-NLS-1$
this.server = server;
setSystem(true);
INDEXED_FILE_TYPES = Arrays.asList("css", "js", "html", "txt", "xml", "java", "properties", "php", "htm", "project", "conf", "pl", "sh", "text", "xhtml", "mf", "manifest");
Collections.sort(INDEXED_FILE_TYPES);
}
@Override
public boolean belongsTo(Object family) {
return SearchActivator.JOB_FAMILY.equals(family);
}
/**
* Adds all files in the given directory to the provided list.
*/
private void collectFiles(IFileStore dir, List<IFileStore> files) {
try {
IFileStore[] children = dir.childStores(EFS.NONE, null);
for (IFileStore child : children) {
if (!child.getName().startsWith(".")) { //$NON-NLS-1$
IFileInfo info = child.fetchInfo();
if (info.isDirectory())
collectFiles(child, files);
else if (!skip(info))
files.add(child);
}
}
} catch (CoreException e) {
handleIndexingFailure(e);
}
}
public void ensureUpdated() {
schedule(DEFAULT_DELAY);
}
private String getContentsAsString(IFileStore file) {
StringWriter writer = new StringWriter();
try {
IOUtilities.pipe(new InputStreamReader(file.openInputStream(EFS.NONE, null)), writer, true, false);
} catch (IOException e) {
handleIndexingFailure(e);
} catch (CoreException e) {
handleIndexingFailure(e);
}
return writer.toString();
}
/**
* Helper method for handling failures that occur while indexing.
*/
private void handleIndexingFailure(Throwable t) {
LogHelper.log(new Status(IStatus.ERROR, SearchActivator.PI_SEARCH, "Error during search indexing", t)); //$NON-NLS-1$
}
private int indexProject(WebProject project, SubMonitor monitor, List<SolrInputDocument> documents) {
Logger logger = LoggerFactory.getLogger(Indexer.class);
if (logger.isDebugEnabled())
logger.debug("Indexing project id: " + project.getId() + " name: " + project.getName()); //$NON-NLS-1$ //$NON-NLS-2$
checkCanceled(monitor);
IFileStore projectStore;
try {
projectStore = project.getProjectStore();
} catch (CoreException e) {
//TODO implement indexing of remote content
handleIndexingFailure(e);
return 0;
}
//project location is always a directory
IPath projectLocation = new Path(Activator.LOCATION_FILE_SERVLET).append(project.getId()).addTrailingSeparator();
//gather all files
int projectLocationLength = projectStore.toURI().toString().length();
final List<IFileStore> toIndex = new ArrayList<IFileStore>();
collectFiles(projectStore, toIndex);
int unmodifiedCount = 0, indexedCount = 0;
//add each file to the index
List<String> users = findUsers(projectLocation);
for (IFileStore file : toIndex) {
checkCanceled(monitor);
IFileInfo fileInfo = file.fetchInfo();
if (!isModified(file, fileInfo)) {
unmodifiedCount++;
continue;
}
indexedCount++;
SolrInputDocument doc = new SolrInputDocument();
doc.addField(ProtocolConstants.KEY_ID, file.toURI().toString());
doc.addField(ProtocolConstants.KEY_NAME, fileInfo.getName());
doc.addField(ProtocolConstants.KEY_LENGTH, Long.toString(fileInfo.getLength()));
doc.addField(ProtocolConstants.KEY_DIRECTORY, Boolean.toString(fileInfo.isDirectory()));
doc.addField(ProtocolConstants.KEY_LAST_MODIFIED, Long.toString(fileInfo.getLastModified()));
//we add the server-relative location so the server can be moved without affecting the index
String projectRelativePath = file.toURI().toString().substring(projectLocationLength);
IPath fileLocation = projectLocation.append(projectRelativePath);
doc.addField(ProtocolConstants.KEY_LOCATION, fileLocation.toString());
String projectName = project.getName();
- if (projectName == null) {
- //Projects with no name have occurred but for unknown reason - see bug 366088.
- handleIndexingFailure(new RuntimeException("Failure indexing project with no name: " + project.getId())); //$NON-NLS-1$
- projectName = "Unknown Project";
- }
+ //Projects with no name are due to an old bug where project metadata was not deleted see bug 367333.
+ if (projectName == null)
+ continue;
doc.addField(ProtocolConstants.KEY_PATH, new Path(projectName).append(projectRelativePath));
doc.addField("Text", getContentsAsString(file)); //$NON-NLS-1$
if (users != null)
for (String user : users)
doc.addField(ProtocolConstants.KEY_USER_NAME, user);
try {
server.add(doc);
} catch (Exception e) {
handleIndexingFailure(e);
}
}
try {
server.commit();
} catch (Exception e) {
handleIndexingFailure(e);
}
if (logger.isDebugEnabled())
logger.debug("\tIndexed: " + indexedCount + " Unchanged: " + unmodifiedCount); //$NON-NLS-1$ //$NON-NLS-2$
return indexedCount;
}
private List<String> findUsers(IPath projectLocation) {
return AuthorizationService.findUserWithRights(projectLocation.toString());
}
private boolean skip(IFileInfo fileInfo) {
if (fileInfo.getLength() > MAX_SEARCH_SIZE)
return true;
//skip files with no extension, or known binary file type extensions
String extension = new Path(fileInfo.getName()).getFileExtension();
if (extension == null || (Collections.binarySearch(INDEXED_FILE_TYPES, extension.toLowerCase()) < 0))
return true;
return false;
}
private boolean isModified(IFileStore file, IFileInfo fileInfo) {
try {
//if there is no match, then the file last modified doesn't match last index so assume it was modified
StringBuffer qString = new StringBuffer(ProtocolConstants.KEY_ID);
qString.append(':');
qString.append(ClientUtils.escapeQueryChars(file.toURI().toString()));
qString.append(" AND "); //$NON-NLS-1$
qString.append(ProtocolConstants.KEY_LAST_MODIFIED);
qString.append(':');
qString.append(Long.toString(fileInfo.getLastModified()));
SolrQuery query = new SolrQuery(qString.toString());
query.setParam(CommonParams.FL, ProtocolConstants.KEY_ID);
QueryResponse response = server.query(query);
return response.getResults().getNumFound() == 0;
} catch (SolrServerException e) {
handleIndexingFailure(e);
//attempt to re-index
return true;
}
}
private void checkCanceled(IProgressMonitor monitor) {
if (monitor.isCanceled())
throw new OperationCanceledException();
}
@Override
protected IStatus run(IProgressMonitor monitor) {
long start = System.currentTimeMillis();
List<WebProject> projects = WebProject.allProjects();
SubMonitor progress = SubMonitor.convert(monitor, projects.size());
List<SolrInputDocument> documents = new ArrayList<SolrInputDocument>();
int indexed = 0;
for (WebProject project : projects) {
indexed += indexProject(project, progress.newChild(1), documents);
}
long duration = System.currentTimeMillis() - start;
Logger logger = LoggerFactory.getLogger(Indexer.class);
if (logger.isDebugEnabled())
logger.debug("Indexed " + projects.size() + " projects in " + duration + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
//reschedule the indexing - throttle so the job never runs more than 10% of the time
long delay = Math.max(DEFAULT_DELAY, duration * 10);
//if there was nothing to index then back off for awhile
if (indexed == 0)
delay = Math.max(delay, IDLE_DELAY);
if (logger.isDebugEnabled())
logger.debug("Rescheduling indexing in " + delay + "ms"); //$NON-NLS-1$//$NON-NLS-2$
schedule(delay);
return Status.OK_STATUS;
}
}
| true | true | private int indexProject(WebProject project, SubMonitor monitor, List<SolrInputDocument> documents) {
Logger logger = LoggerFactory.getLogger(Indexer.class);
if (logger.isDebugEnabled())
logger.debug("Indexing project id: " + project.getId() + " name: " + project.getName()); //$NON-NLS-1$ //$NON-NLS-2$
checkCanceled(monitor);
IFileStore projectStore;
try {
projectStore = project.getProjectStore();
} catch (CoreException e) {
//TODO implement indexing of remote content
handleIndexingFailure(e);
return 0;
}
//project location is always a directory
IPath projectLocation = new Path(Activator.LOCATION_FILE_SERVLET).append(project.getId()).addTrailingSeparator();
//gather all files
int projectLocationLength = projectStore.toURI().toString().length();
final List<IFileStore> toIndex = new ArrayList<IFileStore>();
collectFiles(projectStore, toIndex);
int unmodifiedCount = 0, indexedCount = 0;
//add each file to the index
List<String> users = findUsers(projectLocation);
for (IFileStore file : toIndex) {
checkCanceled(monitor);
IFileInfo fileInfo = file.fetchInfo();
if (!isModified(file, fileInfo)) {
unmodifiedCount++;
continue;
}
indexedCount++;
SolrInputDocument doc = new SolrInputDocument();
doc.addField(ProtocolConstants.KEY_ID, file.toURI().toString());
doc.addField(ProtocolConstants.KEY_NAME, fileInfo.getName());
doc.addField(ProtocolConstants.KEY_LENGTH, Long.toString(fileInfo.getLength()));
doc.addField(ProtocolConstants.KEY_DIRECTORY, Boolean.toString(fileInfo.isDirectory()));
doc.addField(ProtocolConstants.KEY_LAST_MODIFIED, Long.toString(fileInfo.getLastModified()));
//we add the server-relative location so the server can be moved without affecting the index
String projectRelativePath = file.toURI().toString().substring(projectLocationLength);
IPath fileLocation = projectLocation.append(projectRelativePath);
doc.addField(ProtocolConstants.KEY_LOCATION, fileLocation.toString());
String projectName = project.getName();
if (projectName == null) {
//Projects with no name have occurred but for unknown reason - see bug 366088.
handleIndexingFailure(new RuntimeException("Failure indexing project with no name: " + project.getId())); //$NON-NLS-1$
projectName = "Unknown Project";
}
doc.addField(ProtocolConstants.KEY_PATH, new Path(projectName).append(projectRelativePath));
doc.addField("Text", getContentsAsString(file)); //$NON-NLS-1$
if (users != null)
for (String user : users)
doc.addField(ProtocolConstants.KEY_USER_NAME, user);
try {
server.add(doc);
} catch (Exception e) {
handleIndexingFailure(e);
}
}
try {
server.commit();
} catch (Exception e) {
handleIndexingFailure(e);
}
if (logger.isDebugEnabled())
logger.debug("\tIndexed: " + indexedCount + " Unchanged: " + unmodifiedCount); //$NON-NLS-1$ //$NON-NLS-2$
return indexedCount;
}
| private int indexProject(WebProject project, SubMonitor monitor, List<SolrInputDocument> documents) {
Logger logger = LoggerFactory.getLogger(Indexer.class);
if (logger.isDebugEnabled())
logger.debug("Indexing project id: " + project.getId() + " name: " + project.getName()); //$NON-NLS-1$ //$NON-NLS-2$
checkCanceled(monitor);
IFileStore projectStore;
try {
projectStore = project.getProjectStore();
} catch (CoreException e) {
//TODO implement indexing of remote content
handleIndexingFailure(e);
return 0;
}
//project location is always a directory
IPath projectLocation = new Path(Activator.LOCATION_FILE_SERVLET).append(project.getId()).addTrailingSeparator();
//gather all files
int projectLocationLength = projectStore.toURI().toString().length();
final List<IFileStore> toIndex = new ArrayList<IFileStore>();
collectFiles(projectStore, toIndex);
int unmodifiedCount = 0, indexedCount = 0;
//add each file to the index
List<String> users = findUsers(projectLocation);
for (IFileStore file : toIndex) {
checkCanceled(monitor);
IFileInfo fileInfo = file.fetchInfo();
if (!isModified(file, fileInfo)) {
unmodifiedCount++;
continue;
}
indexedCount++;
SolrInputDocument doc = new SolrInputDocument();
doc.addField(ProtocolConstants.KEY_ID, file.toURI().toString());
doc.addField(ProtocolConstants.KEY_NAME, fileInfo.getName());
doc.addField(ProtocolConstants.KEY_LENGTH, Long.toString(fileInfo.getLength()));
doc.addField(ProtocolConstants.KEY_DIRECTORY, Boolean.toString(fileInfo.isDirectory()));
doc.addField(ProtocolConstants.KEY_LAST_MODIFIED, Long.toString(fileInfo.getLastModified()));
//we add the server-relative location so the server can be moved without affecting the index
String projectRelativePath = file.toURI().toString().substring(projectLocationLength);
IPath fileLocation = projectLocation.append(projectRelativePath);
doc.addField(ProtocolConstants.KEY_LOCATION, fileLocation.toString());
String projectName = project.getName();
//Projects with no name are due to an old bug where project metadata was not deleted see bug 367333.
if (projectName == null)
continue;
doc.addField(ProtocolConstants.KEY_PATH, new Path(projectName).append(projectRelativePath));
doc.addField("Text", getContentsAsString(file)); //$NON-NLS-1$
if (users != null)
for (String user : users)
doc.addField(ProtocolConstants.KEY_USER_NAME, user);
try {
server.add(doc);
} catch (Exception e) {
handleIndexingFailure(e);
}
}
try {
server.commit();
} catch (Exception e) {
handleIndexingFailure(e);
}
if (logger.isDebugEnabled())
logger.debug("\tIndexed: " + indexedCount + " Unchanged: " + unmodifiedCount); //$NON-NLS-1$ //$NON-NLS-2$
return indexedCount;
}
|
diff --git a/src/main/java/com/github/hoqhuuep/islandcraft/common/chat/PrivateMessage.java b/src/main/java/com/github/hoqhuuep/islandcraft/common/chat/PrivateMessage.java
index a3dea40..6d44f1b 100644
--- a/src/main/java/com/github/hoqhuuep/islandcraft/common/chat/PrivateMessage.java
+++ b/src/main/java/com/github/hoqhuuep/islandcraft/common/chat/PrivateMessage.java
@@ -1,27 +1,27 @@
package com.github.hoqhuuep.islandcraft.common.chat;
import com.github.hoqhuuep.islandcraft.common.api.ICPlayer;
/**
* @author Daniel Simmons
* @see <a
* href="https://github.com/hoqhuuep/IslandCraft/wiki/Chat#private-message">IslandCraft
* wiki</a>
*/
public final class PrivateMessage {
/**
* To be called when a player tries to send a private message.
*
* @param from
* @param to
* @param message
*/
public final void onPrivateMessage(final ICPlayer from, final ICPlayer to, final String message) {
if (null == to) {
from.message("m-error");
return;
}
+ from.message("m", from.getName(), to.getName(), message);
to.message("m", from.getName(), to.getName(), message);
- // TODO sender needs to see message too
}
}
| false | true | public final void onPrivateMessage(final ICPlayer from, final ICPlayer to, final String message) {
if (null == to) {
from.message("m-error");
return;
}
to.message("m", from.getName(), to.getName(), message);
// TODO sender needs to see message too
}
| public final void onPrivateMessage(final ICPlayer from, final ICPlayer to, final String message) {
if (null == to) {
from.message("m-error");
return;
}
from.message("m", from.getName(), to.getName(), message);
to.message("m", from.getName(), to.getName(), message);
}
|
diff --git a/maven-scm-providers/maven-scm-provider-hg/src/main/java/org/apache/maven/scm/provider/hg/command/blame/HgBlameConsumer.java b/maven-scm-providers/maven-scm-provider-hg/src/main/java/org/apache/maven/scm/provider/hg/command/blame/HgBlameConsumer.java
index ddd3f1a3..0db3f144 100644
--- a/maven-scm-providers/maven-scm-provider-hg/src/main/java/org/apache/maven/scm/provider/hg/command/blame/HgBlameConsumer.java
+++ b/maven-scm-providers/maven-scm-provider-hg/src/main/java/org/apache/maven/scm/provider/hg/command/blame/HgBlameConsumer.java
@@ -1,78 +1,76 @@
package org.apache.maven.scm.provider.hg.command.blame;
/*
* 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 org.apache.maven.scm.ScmFileStatus;
import org.apache.maven.scm.command.blame.BlameLine;
import org.apache.maven.scm.log.ScmLogger;
import org.apache.maven.scm.provider.hg.command.HgConsumer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Evgeny Mandrikov
* @author Olivier Lamy
* @since 1.4
*/
public class HgBlameConsumer
extends HgConsumer
{
private List<BlameLine> lines = new ArrayList<BlameLine>();
private static final String HG_TIMESTAMP_PATTERN = "EEE MMM dd HH:mm:ss yyyy Z";
public HgBlameConsumer( ScmLogger logger )
{
super( logger );
}
public void doConsume( ScmFileStatus status, String trimmedLine )
{
/* godin 0 Sun Jan 31 03:04:54 2010 +0300 */
String annotation;
if(trimmedLine.indexOf(": ") > -1)
{
- annotation = trimmedLine.substring(0, trimmedLine.indexOf(": ")).trim();
- }
- else
- {
- annotation = trimmedLine.substring(0, trimmedLine.lastIndexOf(":")).trim();
+ annotation = trimmedLine.substring(0, trimmedLine.indexOf(": ")).trim();
+ } else {
+ annotation = trimmedLine.substring(0, trimmedLine.lastIndexOf(":")).trim();
}
String author = annotation.substring( 0, annotation.indexOf( ' ' ) );
annotation = annotation.substring( annotation.indexOf( ' ' ) + 1 ).trim();
String revision = annotation.substring( 0, annotation.indexOf( ' ' ) );
annotation = annotation.substring( annotation.indexOf( ' ' ) + 1 ).trim();
String dateStr = annotation;
Date dateTime = parseDate( dateStr, null, HG_TIMESTAMP_PATTERN );
lines.add( new BlameLine( dateTime, revision, author ) );
}
public List<BlameLine> getLines()
{
return lines;
}
}
| true | true | public void doConsume( ScmFileStatus status, String trimmedLine )
{
/* godin 0 Sun Jan 31 03:04:54 2010 +0300 */
String annotation;
if(trimmedLine.indexOf(": ") > -1)
{
annotation = trimmedLine.substring(0, trimmedLine.indexOf(": ")).trim();
}
else
{
annotation = trimmedLine.substring(0, trimmedLine.lastIndexOf(":")).trim();
}
String author = annotation.substring( 0, annotation.indexOf( ' ' ) );
annotation = annotation.substring( annotation.indexOf( ' ' ) + 1 ).trim();
String revision = annotation.substring( 0, annotation.indexOf( ' ' ) );
annotation = annotation.substring( annotation.indexOf( ' ' ) + 1 ).trim();
String dateStr = annotation;
Date dateTime = parseDate( dateStr, null, HG_TIMESTAMP_PATTERN );
lines.add( new BlameLine( dateTime, revision, author ) );
}
| public void doConsume( ScmFileStatus status, String trimmedLine )
{
/* godin 0 Sun Jan 31 03:04:54 2010 +0300 */
String annotation;
if(trimmedLine.indexOf(": ") > -1)
{
annotation = trimmedLine.substring(0, trimmedLine.indexOf(": ")).trim();
} else {
annotation = trimmedLine.substring(0, trimmedLine.lastIndexOf(":")).trim();
}
String author = annotation.substring( 0, annotation.indexOf( ' ' ) );
annotation = annotation.substring( annotation.indexOf( ' ' ) + 1 ).trim();
String revision = annotation.substring( 0, annotation.indexOf( ' ' ) );
annotation = annotation.substring( annotation.indexOf( ' ' ) + 1 ).trim();
String dateStr = annotation;
Date dateTime = parseDate( dateStr, null, HG_TIMESTAMP_PATTERN );
lines.add( new BlameLine( dateTime, revision, author ) );
}
|
diff --git a/src/main/java/fcatools/conexpng/gui/lattice/Node.java b/src/main/java/fcatools/conexpng/gui/lattice/Node.java
index 9ab5692..9b7b7ad 100644
--- a/src/main/java/fcatools/conexpng/gui/lattice/Node.java
+++ b/src/main/java/fcatools/conexpng/gui/lattice/Node.java
@@ -1,352 +1,355 @@
package fcatools.conexpng.gui.lattice;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JPanel;
import de.tudresden.inf.tcs.fcalib.utils.ListSet;
/**
* This class implementes the nodes of the lattice graph. It is the model for
* the concepts. Each concept are represented as a node which knows his position
* , the objects and attributes as well as the labels which contained visible
* objects resp. attributes.
*
*/
public class Node extends JPanel implements LatticeGraphElement {
/**
*
*/
private static final long serialVersionUID = 4253192979583459657L;
private Set<String> objects;
private Set<String> attributes;
private int x;
private int y;
// list of nodes which are below neighbors
private List<Node> below;
private ListSet<Node> ideal;
private ListSet<Node> filter;
private boolean isIdealVisibile;
// true if this node was clicked on
private boolean clickedOn;
private Label visibleObjects;
private Label visibleAttributes;
// true, if this node and his subgraph are moveable.
private boolean moveSubgraph;
// level of the node in the graph
private int level;
// true if the node hit the viewport's borders
private boolean hitBorder;
/**
*
* @param extent
* @param intent
* @param x
* @param y
*/
public Node(Set<String> extent, Set<String> intent, int x, int y) {
this.objects = extent;
this.attributes = intent;
this.x = x;
this.y = y;
this.setBounds(x, y, 15, 15);
positionLabels();
this.below = new ArrayList<>();
}
/**
*
*/
public Node() {
this.objects = new TreeSet<>();
this.attributes = new TreeSet<>();
this.visibleObjects = new Label(new TreeSet<String>(), this);
this.visibleAttributes = new Label(new TreeSet<String>(), this);
this.ideal = new ListSet<>();
this.x = 0;
this.y = 0;
this.setBounds(x, y, 15, 15);
this.setBackground(Color.white);
this.below = new ArrayList<>();
this.filter = new ListSet<>();
}
@Override
public void paint(Graphics g) {
}
/**
*
* @return
*/
public int getX() {
return x;
}
/**
*
* @param x
*/
public void setX(int x) {
this.x = x;
this.setBounds(x, y, 15, 15);
}
/**
*
* @return
*/
public int getY() {
return y;
}
/**
*
* @param y
*/
public void setY(int y) {
this.y = y;
this.setBounds(x, y, 15, 15);
}
/**
*
* @param extent
*/
public void addObject(String extent) {
objects.add(extent);
}
/**
*
* @param set
*/
public void addAttribute(String set) {
attributes.add(set);
}
public void addBelowNode(Node n) {
below.add(n);
}
public List<Node> getBelow() {
return below;
}
/**
* Positions attribute and object labels.
*/
public void positionLabels() {
// places the object label below and the attribute
// label above the node
visibleAttributes.update(x + (int) (LatticeView.radius * 1.5), (int) (y - LatticeView.radius * 5), false);
visibleObjects.update(x + (int) (LatticeView.radius * 1.5), y + LatticeView.radius * 5, false);
}
/**
* Updated the node position
*
* @param x
* , value of which x has to be translated
* @param y
* , value of which y has to be translated
* @param first
* , true, if you what this node is the almost top node of the
* subgraph you want to move.
*/
public void update(int x, int y, boolean first) {
int updateX;
int updateY;
if (x >= 2) {
updateX = x;
} else {
hitBorder = true;
updateX = 1;
}
if (y >= 2)
updateY = y;
else {
updateY = 1;
hitBorder = true;
}
for (Node n : ideal) {
if (!n.isUpdateXPosible(x) || !n.isUpdateYPosible(y)) {
hitBorder = true;
}
}
if (!hitBorder) {
if (moveSubgraph && first) {
+ // calculate offset the node is moved, then move subgraph
+ int offsetX = (int) ((x - this.x) / LatticeView.zoomFactor);
+ int offsetY = (int) ((y - this.y) / LatticeView.zoomFactor);
for (Node n : ideal) {
- n.update(x, y, false);
+ n.update(n.x + offsetX, n.y + offsetY, false);
}
}
this.setBounds(updateX, updateY, 15, 15);
this.x = updateX;
this.y = updateY;
positionLabels();
if (getParent() != null) {
getParent().repaint();
}
}
hitBorder = false;
}
public boolean isUpdateXPosible(int x) {
if (this.x > getParent().getWidth()) {
return true;
}
if (x >= 2 && x < getParent().getWidth()) {
return true;
}
return false;
}
public boolean isUpdateYPosible(int y) {
if (this.y > getParent().getHeight()) {
return true;
}
if (y >= 2 && y < getParent().getHeight()) {
for (Node n : this.ideal) {
if (y > n.getY() - 3) {
return false;
}
}
for (Node n : this.filter) {
if (y < n.getY() + 3) {
return false;
}
}
return true;
}
return false;
}
public ListSet<Node> getIdeal() {
return ideal;
}
public void addObjects(Set<String> extent) {
objects.addAll(extent);
}
public void addAttributs(Set<String> intent) {
attributes.addAll(intent);
}
public Set<String> getObjects() {
return objects;
}
public Set<String> getAttributes() {
return attributes;
}
public void setLevel(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
public void setVisibleObject(String object) {
visibleObjects.getSet().add(object);
}
public void setVisibleObjects(Set<String> objects) {
visibleObjects.getSet().clear();
visibleObjects.getSet().addAll(objects);
}
public Set<String> getVisibleObjects() {
return this.visibleObjects.getSet();
}
public void setVisibleAttribute(String attribute) {
this.visibleAttributes.getSet().add(attribute);
}
public void setVisibleAttributes(Set<String> attributes) {
visibleAttributes.getSet().clear();
visibleAttributes.getSet().addAll(attributes);
}
public Set<String> getVisibleAttributes() {
return this.visibleAttributes.getSet();
}
public Label getObjectsLabel() {
return this.visibleObjects;
}
public Label getAttributesLabel() {
return this.visibleAttributes;
}
public void moveSubgraph(boolean b) {
this.moveSubgraph = b;
}
public void toggleIdealVisibility() {
((LatticeGraphView) getParent()).resetHighlighting();
this.isIdealVisibile = !this.isIdealVisibile;
// this node was clicked on, necessary for red highlight circle
this.setClickedOn(true);
for (Node n : ideal) {
n.setPartOfAnIdeal(isIdealVisibile);
}
if (getParent() != null) {
getParent().repaint();
}
}
/**
* Returns true if this is the node that was clicked on. Needed to highlight
* the node red.
*
* @return true if this is the node that was clicked on
*/
public boolean isClickedOn() {
return this.clickedOn;
}
/**
* Set to true if this node was clicked on. Results in a red circle around
* the node to highlight it.
*
* @param b
*/
public void setClickedOn(boolean b) {
this.clickedOn = b;
}
public boolean isPartOfAnIdeal() {
return this.isIdealVisibile;
}
public void setPartOfAnIdeal(boolean b) {
this.isIdealVisibile = b;
}
public ListSet<Node> getFilter() {
return this.filter;
}
}
| false | true | public void update(int x, int y, boolean first) {
int updateX;
int updateY;
if (x >= 2) {
updateX = x;
} else {
hitBorder = true;
updateX = 1;
}
if (y >= 2)
updateY = y;
else {
updateY = 1;
hitBorder = true;
}
for (Node n : ideal) {
if (!n.isUpdateXPosible(x) || !n.isUpdateYPosible(y)) {
hitBorder = true;
}
}
if (!hitBorder) {
if (moveSubgraph && first) {
for (Node n : ideal) {
n.update(x, y, false);
}
}
this.setBounds(updateX, updateY, 15, 15);
this.x = updateX;
this.y = updateY;
positionLabels();
if (getParent() != null) {
getParent().repaint();
}
}
hitBorder = false;
}
| public void update(int x, int y, boolean first) {
int updateX;
int updateY;
if (x >= 2) {
updateX = x;
} else {
hitBorder = true;
updateX = 1;
}
if (y >= 2)
updateY = y;
else {
updateY = 1;
hitBorder = true;
}
for (Node n : ideal) {
if (!n.isUpdateXPosible(x) || !n.isUpdateYPosible(y)) {
hitBorder = true;
}
}
if (!hitBorder) {
if (moveSubgraph && first) {
// calculate offset the node is moved, then move subgraph
int offsetX = (int) ((x - this.x) / LatticeView.zoomFactor);
int offsetY = (int) ((y - this.y) / LatticeView.zoomFactor);
for (Node n : ideal) {
n.update(n.x + offsetX, n.y + offsetY, false);
}
}
this.setBounds(updateX, updateY, 15, 15);
this.x = updateX;
this.y = updateY;
positionLabels();
if (getParent() != null) {
getParent().repaint();
}
}
hitBorder = false;
}
|
diff --git a/src/biz/bokhorst/xprivacy/XTelephonyManager.java b/src/biz/bokhorst/xprivacy/XTelephonyManager.java
index 6f6bab29..7d528de6 100644
--- a/src/biz/bokhorst/xprivacy/XTelephonyManager.java
+++ b/src/biz/bokhorst/xprivacy/XTelephonyManager.java
@@ -1,269 +1,269 @@
package biz.bokhorst.xprivacy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import android.os.Binder;
import android.telephony.CellLocation;
import android.telephony.NeighboringCellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.CellInfo;
import android.telephony.TelephonyManager;
import android.util.Log;
import de.robv.android.xposed.XC_MethodHook.MethodHookParam;
public class XTelephonyManager extends XHook {
private Methods mMethod;
private String mClassName;
private static final Map<PhoneStateListener, XPhoneStateListener> mListener = new WeakHashMap<PhoneStateListener, XPhoneStateListener>();
private XTelephonyManager(Methods method, String restrictionName, String className) {
super(restrictionName, method.name(), null);
mMethod = method;
mClassName = className;
}
private XTelephonyManager(Methods method, String restrictionName, String className, int sdk) {
super(restrictionName, method.name(), null, sdk);
mMethod = method;
mClassName = className;
}
public String getClassName() {
return mClassName;
}
// public void disableLocationUpdates()
// public void enableLocationUpdates()
// public List<CellInfo> getAllCellInfo()
// public CellLocation getCellLocation()
// public String getDeviceId()
// public String getGroupIdLevel1()
// public String getIsimDomain()
// public String getIsimImpi()
// public String[] getIsimImpu()
// public String getLine1AlphaTag()
// public String getLine1Number()
// public String getMsisdn()
// public List<NeighboringCellInfo> getNeighboringCellInfo()
// public String getNetworkCountryIso()
// public String getNetworkOperator()
// public String getNetworkOperatorName()
// public int getNetworkType()
// public int getPhoneType()
// public String getSimCountryIso()
// public String getSimOperator()
// public String getSimOperatorName()
// public static int getPhoneType(int networkMode)
// public String getSimSerialNumber()
// public String getSubscriberId()
// public String getVoiceMailAlphaTag()
// public String getVoiceMailNumber()
// public void listen(PhoneStateListener listener, int events)
// frameworks/base/telephony/java/android/telephony/TelephonyManager.java
// http://developer.android.com/reference/android/telephony/TelephonyManager.html
// @formatter:off
private enum Methods {
disableLocationUpdates, enableLocationUpdates,
getAllCellInfo, getCellLocation,
getDeviceId, getGroupIdLevel1,
getIsimDomain, getIsimImpi, getIsimImpu,
getLine1AlphaTag, getLine1Number, getMsisdn,
getNeighboringCellInfo,
getNetworkCountryIso, getNetworkOperator, getNetworkOperatorName,
getNetworkType, getPhoneType,
getSimCountryIso, getSimOperator, getSimOperatorName, getSimSerialNumber,
getSubscriberId,
getVoiceMailAlphaTag, getVoiceMailNumber,
listen
};
// @formatter:on
public static List<XHook> getInstances(Object instance) {
String className = instance.getClass().getName();
List<XHook> listHook = new ArrayList<XHook>();
- listHook.add(new XTelephonyManager(Methods.disableLocationUpdates, PrivacyManager.cLocation, className));
- listHook.add(new XTelephonyManager(Methods.enableLocationUpdates, null, className, 10));
+ listHook.add(new XTelephonyManager(Methods.disableLocationUpdates, null, className, 10));
+ listHook.add(new XTelephonyManager(Methods.enableLocationUpdates, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getAllCellInfo, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getCellLocation, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getDeviceId, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getGroupIdLevel1, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimDomain, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimImpi, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimImpu, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getLine1AlphaTag, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getLine1Number, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getMsisdn, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNeighboringCellInfo, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getSimSerialNumber, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSubscriberId, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getVoiceMailAlphaTag, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getVoiceMailNumber, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.listen, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.listen, PrivacyManager.cPhone, className));
// No permissions required
listHook.add(new XTelephonyManager(Methods.getNetworkCountryIso, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkOperator, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkOperatorName, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkType, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getPhoneType, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimCountryIso, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimOperator, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimOperatorName, PrivacyManager.cPhone, className));
return listHook;
}
@Override
protected void before(MethodHookParam param) throws Throwable {
if (mMethod == Methods.listen) {
if (param.args.length > 1) {
PhoneStateListener listener = (PhoneStateListener) param.args[0];
int event = (Integer) param.args[1];
if (listener != null)
if (event == PhoneStateListener.LISTEN_NONE) {
// Remove
synchronized (mListener) {
XPhoneStateListener xlistener = mListener.get(listener);
if (xlistener != null) {
param.args[0] = xlistener;
mListener.remove(listener);
}
}
} else if (isRestricted(param))
try {
// Replace
XPhoneStateListener xListener = new XPhoneStateListener(listener);
synchronized (mListener) {
mListener.put(listener, xListener);
Util.log(this, Log.INFO, "Added count=" + mListener.size());
}
param.args[0] = xListener;
} catch (Throwable ignored) {
// Some implementations require a looper
// which is not according to the documentation
// and stock source code
}
}
} else if (mMethod == Methods.enableLocationUpdates) {
if (isRestricted(param))
param.setResult(null);
} else if (mMethod == Methods.disableLocationUpdates)
if (isRestricted(param, PrivacyManager.cLocation, "enableLocationUpdates"))
param.setResult(null);
}
@Override
protected void after(MethodHookParam param) throws Throwable {
if (mMethod != Methods.listen && mMethod != Methods.disableLocationUpdates
&& mMethod != Methods.enableLocationUpdates)
if (mMethod == Methods.getAllCellInfo) {
if (param.getResult() != null && isRestricted(param))
param.setResult(new ArrayList<CellInfo>());
} else if (mMethod == Methods.getCellLocation) {
if (param.getResult() != null && isRestricted(param))
param.setResult(CellLocation.getEmpty());
} else if (mMethod == Methods.getIsimImpu) {
if (param.getResult() != null && isRestricted(param))
param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), mMethod.name()));
} else if (mMethod == Methods.getNeighboringCellInfo) {
if (param.getResult() != null && isRestricted(param))
param.setResult(new ArrayList<NeighboringCellInfo>());
} else if (mMethod == Methods.getNetworkType) {
if (isRestricted(param))
param.setResult(TelephonyManager.NETWORK_TYPE_UNKNOWN);
} else if (mMethod == Methods.getPhoneType) {
if (isRestricted(param))
param.setResult(TelephonyManager.PHONE_TYPE_GSM); // IMEI
} else {
if (param.getResult() != null && isRestricted(param))
param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), mMethod.name()));
}
}
private class XPhoneStateListener extends PhoneStateListener {
private PhoneStateListener mListener;
public XPhoneStateListener(PhoneStateListener listener) {
mListener = listener;
}
@Override
public void onCallForwardingIndicatorChanged(boolean cfi) {
mListener.onCallForwardingIndicatorChanged(cfi);
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
mListener.onCallStateChanged(state,
(String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "PhoneNumber"));
}
@Override
public void onCellInfoChanged(List<CellInfo> cellInfo) {
mListener.onCellInfoChanged(new ArrayList<CellInfo>());
}
@Override
public void onCellLocationChanged(CellLocation location) {
mListener.onCellLocationChanged(CellLocation.getEmpty());
}
@Override
public void onDataActivity(int direction) {
mListener.onDataActivity(direction);
}
@Override
public void onDataConnectionStateChanged(int state) {
mListener.onDataConnectionStateChanged(state);
}
@Override
public void onDataConnectionStateChanged(int state, int networkType) {
mListener.onDataConnectionStateChanged(state, networkType);
}
@Override
public void onMessageWaitingIndicatorChanged(boolean mwi) {
mListener.onMessageWaitingIndicatorChanged(mwi);
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
mListener.onServiceStateChanged(serviceState);
}
@Override
@SuppressWarnings("deprecation")
public void onSignalStrengthChanged(int asu) {
mListener.onSignalStrengthChanged(asu);
}
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
mListener.onSignalStrengthsChanged(signalStrength);
}
}
}
| true | true | public static List<XHook> getInstances(Object instance) {
String className = instance.getClass().getName();
List<XHook> listHook = new ArrayList<XHook>();
listHook.add(new XTelephonyManager(Methods.disableLocationUpdates, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.enableLocationUpdates, null, className, 10));
listHook.add(new XTelephonyManager(Methods.getAllCellInfo, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getCellLocation, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getDeviceId, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getGroupIdLevel1, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimDomain, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimImpi, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimImpu, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getLine1AlphaTag, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getLine1Number, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getMsisdn, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNeighboringCellInfo, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getSimSerialNumber, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSubscriberId, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getVoiceMailAlphaTag, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getVoiceMailNumber, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.listen, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.listen, PrivacyManager.cPhone, className));
// No permissions required
listHook.add(new XTelephonyManager(Methods.getNetworkCountryIso, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkOperator, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkOperatorName, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkType, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getPhoneType, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimCountryIso, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimOperator, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimOperatorName, PrivacyManager.cPhone, className));
return listHook;
}
| public static List<XHook> getInstances(Object instance) {
String className = instance.getClass().getName();
List<XHook> listHook = new ArrayList<XHook>();
listHook.add(new XTelephonyManager(Methods.disableLocationUpdates, null, className, 10));
listHook.add(new XTelephonyManager(Methods.enableLocationUpdates, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getAllCellInfo, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getCellLocation, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getDeviceId, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getGroupIdLevel1, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimDomain, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimImpi, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getIsimImpu, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getLine1AlphaTag, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getLine1Number, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getMsisdn, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNeighboringCellInfo, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.getSimSerialNumber, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSubscriberId, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getVoiceMailAlphaTag, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getVoiceMailNumber, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.listen, PrivacyManager.cLocation, className));
listHook.add(new XTelephonyManager(Methods.listen, PrivacyManager.cPhone, className));
// No permissions required
listHook.add(new XTelephonyManager(Methods.getNetworkCountryIso, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkOperator, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkOperatorName, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getNetworkType, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getPhoneType, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimCountryIso, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimOperator, PrivacyManager.cPhone, className));
listHook.add(new XTelephonyManager(Methods.getSimOperatorName, PrivacyManager.cPhone, className));
return listHook;
}
|
diff --git a/common/src/main/java/cz/incad/kramerius/processes/impl/LRProcessDefinitionManagerImpl.java b/common/src/main/java/cz/incad/kramerius/processes/impl/LRProcessDefinitionManagerImpl.java
index c64fb9c02..b51f9196f 100644
--- a/common/src/main/java/cz/incad/kramerius/processes/impl/LRProcessDefinitionManagerImpl.java
+++ b/common/src/main/java/cz/incad/kramerius/processes/impl/LRProcessDefinitionManagerImpl.java
@@ -1,147 +1,148 @@
package cz.incad.kramerius.processes.impl;
import static cz.incad.kramerius.utils.IOUtils.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import cz.incad.kramerius.Constants;
import cz.incad.kramerius.processes.LRProcess;
import cz.incad.kramerius.processes.LRProcessDefinition;
import cz.incad.kramerius.processes.DefinitionManager;
import cz.incad.kramerius.processes.LRProcessManager;
import cz.incad.kramerius.utils.IOUtils;
import cz.incad.kramerius.utils.conf.KConfiguration;
public class LRProcessDefinitionManagerImpl implements DefinitionManager {
public static final java.util.logging.Logger LOGGER = java.util.logging.Logger
.getLogger(LRProcessDefinitionManagerImpl.class.getName());
private KConfiguration configuration;
private LRProcessManager processManager;
private String realLibsDir = null;
private String configurationFile;
@Inject
public LRProcessDefinitionManagerImpl(KConfiguration configuration,
LRProcessManager processManager,
@Named("LIBS")String defaultLibsdir//,
/*String configFile*/) {
super();
this.configuration = configuration;
this.processManager = processManager;
this.realLibsDir = defaultLibsdir;
this.load();
}
private HashMap<String, LRProcessDefinition> definitions = new HashMap<String, LRProcessDefinition>();
@Override
public LRProcessDefinition getLongRunningProcessDefinition(String id) {
return definitions.get(id);
}
@Override
public void load() {
try {
File defaultWorkDir = new File(DEFAULT_LP_WORKDIR);
if (!defaultWorkDir.exists()) {
boolean created = defaultWorkDir.mkdirs();
if (!created) throw new RuntimeException("cannot create directory '"+defaultWorkDir+"'");
}
File conFile = new File(CONFIGURATION_FILE);
if (!conFile.exists()) {
StringTemplateGroup grp = new StringTemplateGroup("m");
StringTemplate template = grp.getInstanceOf("cz/incad/kramerius/processes/res/lp");
template.setAttribute("user_home", System.getProperties().getProperty("user.home"));
template.setAttribute("default_lp_work_dir", DEFAULT_LP_WORKDIR);
String string = template.toString();
- conFile.createNewFile();
+ boolean created = conFile.createNewFile();
+ if (!created) throw new RuntimeException("cannot create conFile '"+conFile.getAbsolutePath()+"'");
FileOutputStream fos = new FileOutputStream(conFile);
try {
IOUtils.copyStreams(new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8"))), fos);
} finally {
fos.close();
}
}
LOGGER.info("Loading file from '"+CONFIGURATION_FILE+"'");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document parsed = builder.parse(CONFIGURATION_FILE);
NodeList childNodes = parsed.getDocumentElement().getChildNodes();
for (int i = 0,ll=childNodes.getLength(); i < ll; i++) {
Node item = childNodes.item(i);
if (item.getNodeType() == Node.ELEMENT_NODE) {
LRProcessDefinitionImpl def = new LRProcessDefinitionImpl(this.processManager, this.configuration);
def.loadFromXml((Element) item);
this.definitions.put(def.getId(), def);
}
}
} catch (ParserConfigurationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (SAXException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
@Override
public List<LRProcessDefinition> getLongRunningProcessDefinitions() {
return new ArrayList<LRProcessDefinition>(definitions.values());
}
public KConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(KConfiguration configuration) {
this.configuration = configuration;
}
public LRProcessManager getProcessManager() {
return processManager;
}
public void setProcessManager(LRProcessManager processManager) {
this.processManager = processManager;
}
public static void main(String[] args) {
//LRProcessDefinitionManagerImpl impl = new LRProcessDefinitionManagerImpl(KConfiguration.getKConfiguration(), null);
}
}
| true | true | public void load() {
try {
File defaultWorkDir = new File(DEFAULT_LP_WORKDIR);
if (!defaultWorkDir.exists()) {
boolean created = defaultWorkDir.mkdirs();
if (!created) throw new RuntimeException("cannot create directory '"+defaultWorkDir+"'");
}
File conFile = new File(CONFIGURATION_FILE);
if (!conFile.exists()) {
StringTemplateGroup grp = new StringTemplateGroup("m");
StringTemplate template = grp.getInstanceOf("cz/incad/kramerius/processes/res/lp");
template.setAttribute("user_home", System.getProperties().getProperty("user.home"));
template.setAttribute("default_lp_work_dir", DEFAULT_LP_WORKDIR);
String string = template.toString();
conFile.createNewFile();
FileOutputStream fos = new FileOutputStream(conFile);
try {
IOUtils.copyStreams(new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8"))), fos);
} finally {
fos.close();
}
}
LOGGER.info("Loading file from '"+CONFIGURATION_FILE+"'");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document parsed = builder.parse(CONFIGURATION_FILE);
NodeList childNodes = parsed.getDocumentElement().getChildNodes();
for (int i = 0,ll=childNodes.getLength(); i < ll; i++) {
Node item = childNodes.item(i);
if (item.getNodeType() == Node.ELEMENT_NODE) {
LRProcessDefinitionImpl def = new LRProcessDefinitionImpl(this.processManager, this.configuration);
def.loadFromXml((Element) item);
this.definitions.put(def.getId(), def);
}
}
} catch (ParserConfigurationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (SAXException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
| public void load() {
try {
File defaultWorkDir = new File(DEFAULT_LP_WORKDIR);
if (!defaultWorkDir.exists()) {
boolean created = defaultWorkDir.mkdirs();
if (!created) throw new RuntimeException("cannot create directory '"+defaultWorkDir+"'");
}
File conFile = new File(CONFIGURATION_FILE);
if (!conFile.exists()) {
StringTemplateGroup grp = new StringTemplateGroup("m");
StringTemplate template = grp.getInstanceOf("cz/incad/kramerius/processes/res/lp");
template.setAttribute("user_home", System.getProperties().getProperty("user.home"));
template.setAttribute("default_lp_work_dir", DEFAULT_LP_WORKDIR);
String string = template.toString();
boolean created = conFile.createNewFile();
if (!created) throw new RuntimeException("cannot create conFile '"+conFile.getAbsolutePath()+"'");
FileOutputStream fos = new FileOutputStream(conFile);
try {
IOUtils.copyStreams(new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8"))), fos);
} finally {
fos.close();
}
}
LOGGER.info("Loading file from '"+CONFIGURATION_FILE+"'");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document parsed = builder.parse(CONFIGURATION_FILE);
NodeList childNodes = parsed.getDocumentElement().getChildNodes();
for (int i = 0,ll=childNodes.getLength(); i < ll; i++) {
Node item = childNodes.item(i);
if (item.getNodeType() == Node.ELEMENT_NODE) {
LRProcessDefinitionImpl def = new LRProcessDefinitionImpl(this.processManager, this.configuration);
def.loadFromXml((Element) item);
this.definitions.put(def.getId(), def);
}
}
} catch (ParserConfigurationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (SAXException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
|
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/BoxingDeclarationVisitor.java b/src/com/redhat/ceylon/compiler/java/codegen/BoxingDeclarationVisitor.java
index d24a98c36..520e8212d 100644
--- a/src/com/redhat/ceylon/compiler/java/codegen/BoxingDeclarationVisitor.java
+++ b/src/com/redhat/ceylon/compiler/java/codegen/BoxingDeclarationVisitor.java
@@ -1,275 +1,283 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.codegen;
import java.util.List;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AnyAttribute;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AnyClass;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AnyMethod;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeArgument;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeSetterDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.FunctionArgument;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Variable;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
public abstract class BoxingDeclarationVisitor extends Visitor {
protected abstract boolean isCeylonBasicType(ProducedType type);
protected abstract boolean isNothing(ProducedType type);
protected abstract boolean isObject(ProducedType type);
@Override
public void visit(FunctionArgument that) {
super.visit(that);
boxMethod(that.getDeclarationModel());
}
@Override
public void visit(AnyMethod that) {
super.visit(that);
boxMethod(that.getDeclarationModel());
rawTypedDeclaration(that.getDeclarationModel());
}
private void rawTypedDeclaration(TypedDeclaration decl) {
// deal with invalid input
if(decl == null)
return;
ProducedType type = decl.getType();
if(type != null){
if(containsRaw(type))
type.setRaw(true);
}
}
private boolean containsRaw(ProducedType type) {
for(ProducedType typeArg : type.getTypeArguments().values()){
TypeDeclaration typeDeclaration = typeArg.getDeclaration();
if(typeDeclaration instanceof UnionType){
UnionType ut = (UnionType) typeDeclaration;
List<ProducedType> caseTypes = ut.getCaseTypes();
// special case for optional types
if(caseTypes.size() == 2
&& (isNothing(caseTypes.get(0))
|| isNothing(caseTypes.get(1))))
return false;
return true;
}
if(typeDeclaration instanceof IntersectionType){
IntersectionType ut = (IntersectionType) typeDeclaration;
List<ProducedType> satisfiedTypes = ut.getSatisfiedTypes();
// special case for non-optional types
if(satisfiedTypes.size() == 2
&& (isObject(satisfiedTypes.get(0))
|| isObject(satisfiedTypes.get(1))))
return false;
return true;
}
if(containsRaw(typeArg))
return true;
}
return false;
}
private void boxMethod(Method method) {
// deal with invalid input
if(method == null)
return;
Declaration refined = CodegenUtil.getTopmostRefinedDeclaration(method);
// deal with invalid input
if(refined == null
|| (!(refined instanceof Method)))
return;
Method refinedMethod = (Method)refined;
List<ParameterList> methodParameterLists = method.getParameterLists();
List<ParameterList> refinedParameterLists = refinedMethod.getParameterLists();
// A Callable, which never have primitive parameters
setBoxingState(method, refinedMethod);
// deal with invalid input
if(methodParameterLists.isEmpty()
|| refinedParameterLists.isEmpty())
return;
boxAndRawParameterLists(methodParameterLists, refinedParameterLists);
}
private void boxAndRawParameterLists(List<ParameterList> paramLists, List<ParameterList> refinedParamLists) {
if (paramLists.size() != refinedParamLists.size()) {
throw new RuntimeException();
}
for (int ii = 0; ii < paramLists.size(); ii++) {
ParameterList paramList = paramLists.get(ii);
ParameterList refinedParamList = refinedParamLists.get(ii);
if (paramList.getParameters().size() !=
refinedParamList.getParameters().size()) {
throw new RuntimeException();
}
for (int jj = 0; jj < paramList.getParameters().size(); jj++) {
Parameter param = paramList.getParameters().get(jj);
Parameter refinedParam = refinedParamList.getParameters().get(jj);
if (param instanceof Functional && refinedParam instanceof Functional) {
boxAndRawParameterLists(((Functional)param).getParameterLists(),
((Functional)refinedParam).getParameterLists());
}
setBoxingState(param, refinedParam);
// also mark params as raw if needed
rawTypedDeclaration(param);
}
}
}
@Override
public void visit(AnyClass that) {
super.visit(that);
Class klass = that.getDeclarationModel();
// deal with invalid input
if(klass == null)
return;
List<ParameterList> parameterLists = klass.getParameterLists();
// deal with invalid input
if(parameterLists.isEmpty())
return;
List<ParameterList> refinedParameterLists;
// If this is an alias we're bound by the aliased type's parameters, not by ours
// For ex:
// - class AliasedType<T>(T x){}
// - class Alias(Integer x) = AliasedType<Integer>;
// where Alias's x parameter is not really unboxed
if(klass.isAlias())
refinedParameterLists = klass.getExtendedTypeDeclaration().getParameterLists();
else
refinedParameterLists = parameterLists;
boxAndRawParameterLists(parameterLists, refinedParameterLists);
}
private void setBoxingState(TypedDeclaration declaration, TypedDeclaration refinedDeclaration) {
ProducedType type = declaration.getType();
if(type == null){
// an error must have already been reported
return;
}
// inherit underlying type constraints
if(refinedDeclaration != declaration && type.getUnderlyingType() == null)
type.setUnderlyingType(refinedDeclaration.getType().getUnderlyingType());
// abort if our boxing state has already been set
if(declaration.getUnboxed() != null)
return;
// functional parameter return values are always boxed
if(declaration instanceof FunctionalParameter){
declaration.setUnboxed(false);
return;
}
if(refinedDeclaration != declaration){
// make sure refined declarations have already been set
if(refinedDeclaration.getUnboxed() == null)
setBoxingState(refinedDeclaration, refinedDeclaration);
// inherit
declaration.setUnboxed(refinedDeclaration.getUnboxed());
- }else if((isCeylonBasicType(type) || Decl.isUnboxedVoid(declaration))
+ } else if (declaration instanceof Method
+ && CodegenUtil.isVoid(declaration.getType())
+ && Strategy.useBoxedVoid((Method)declaration)
+ && !(refinedDeclaration.getTypeDeclaration() instanceof TypeParameter)
+ && !(refinedDeclaration.getContainer() instanceof FunctionalParameter)
+ && !(refinedDeclaration instanceof Functional && Decl.isMpl((Functional)refinedDeclaration))){
+ declaration.setUnboxed(false);
+ } else if((isCeylonBasicType(type) || Decl.isUnboxedVoid(declaration))
&& !(refinedDeclaration.getTypeDeclaration() instanceof TypeParameter)
&& !(refinedDeclaration.getContainer() instanceof FunctionalParameter)
&& !(refinedDeclaration instanceof Functional && Decl.isMpl((Functional)refinedDeclaration))){
declaration.setUnboxed(true);
- }else
+ } else {
declaration.setUnboxed(false);
+ }
}
private void boxAttribute(TypedDeclaration declaration) {
// deal with invalid input
if(declaration == null)
return;
TypedDeclaration refinedDeclaration = (TypedDeclaration)CodegenUtil.getTopmostRefinedDeclaration(declaration);
// deal with invalid input
if(refinedDeclaration == null)
return;
setBoxingState(declaration, refinedDeclaration);
}
@Override
public void visit(AnyAttribute that) {
super.visit(that);
TypedDeclaration declaration = that.getDeclarationModel();
boxAttribute(declaration);
rawTypedDeclaration(declaration);
}
@Override
public void visit(AttributeDeclaration that) {
if(that.getSpecifierOrInitializerExpression() != null
&& that.getDeclarationModel() != null
&& that.getType() instanceof Tree.ValueModifier
&& that.getDeclarationModel().getType() == that.getSpecifierOrInitializerExpression().getExpression().getTypeModel()){
that.getDeclarationModel().setType(that.getDeclarationModel().getType().withoutUnderlyingType());
}
super.visit(that);
}
@Override
public void visit(AttributeArgument that) {
super.visit(that);
boxAttribute(that.getDeclarationModel());
}
@Override
public void visit(AttributeSetterDefinition that) {
super.visit(that);
Setter declarationModel = that.getDeclarationModel();
// deal with invalid input
if(declarationModel == null)
return;
TypedDeclaration declaration = declarationModel.getParameter();
boxAttribute(declaration);
}
@Override
public void visit(Variable that) {
super.visit(that);
TypedDeclaration declaration = that.getDeclarationModel();
// deal with invalid input
if(declaration == null)
return;
setBoxingState(declaration, declaration);
}
}
| false | true | private void setBoxingState(TypedDeclaration declaration, TypedDeclaration refinedDeclaration) {
ProducedType type = declaration.getType();
if(type == null){
// an error must have already been reported
return;
}
// inherit underlying type constraints
if(refinedDeclaration != declaration && type.getUnderlyingType() == null)
type.setUnderlyingType(refinedDeclaration.getType().getUnderlyingType());
// abort if our boxing state has already been set
if(declaration.getUnboxed() != null)
return;
// functional parameter return values are always boxed
if(declaration instanceof FunctionalParameter){
declaration.setUnboxed(false);
return;
}
if(refinedDeclaration != declaration){
// make sure refined declarations have already been set
if(refinedDeclaration.getUnboxed() == null)
setBoxingState(refinedDeclaration, refinedDeclaration);
// inherit
declaration.setUnboxed(refinedDeclaration.getUnboxed());
}else if((isCeylonBasicType(type) || Decl.isUnboxedVoid(declaration))
&& !(refinedDeclaration.getTypeDeclaration() instanceof TypeParameter)
&& !(refinedDeclaration.getContainer() instanceof FunctionalParameter)
&& !(refinedDeclaration instanceof Functional && Decl.isMpl((Functional)refinedDeclaration))){
declaration.setUnboxed(true);
}else
declaration.setUnboxed(false);
}
| private void setBoxingState(TypedDeclaration declaration, TypedDeclaration refinedDeclaration) {
ProducedType type = declaration.getType();
if(type == null){
// an error must have already been reported
return;
}
// inherit underlying type constraints
if(refinedDeclaration != declaration && type.getUnderlyingType() == null)
type.setUnderlyingType(refinedDeclaration.getType().getUnderlyingType());
// abort if our boxing state has already been set
if(declaration.getUnboxed() != null)
return;
// functional parameter return values are always boxed
if(declaration instanceof FunctionalParameter){
declaration.setUnboxed(false);
return;
}
if(refinedDeclaration != declaration){
// make sure refined declarations have already been set
if(refinedDeclaration.getUnboxed() == null)
setBoxingState(refinedDeclaration, refinedDeclaration);
// inherit
declaration.setUnboxed(refinedDeclaration.getUnboxed());
} else if (declaration instanceof Method
&& CodegenUtil.isVoid(declaration.getType())
&& Strategy.useBoxedVoid((Method)declaration)
&& !(refinedDeclaration.getTypeDeclaration() instanceof TypeParameter)
&& !(refinedDeclaration.getContainer() instanceof FunctionalParameter)
&& !(refinedDeclaration instanceof Functional && Decl.isMpl((Functional)refinedDeclaration))){
declaration.setUnboxed(false);
} else if((isCeylonBasicType(type) || Decl.isUnboxedVoid(declaration))
&& !(refinedDeclaration.getTypeDeclaration() instanceof TypeParameter)
&& !(refinedDeclaration.getContainer() instanceof FunctionalParameter)
&& !(refinedDeclaration instanceof Functional && Decl.isMpl((Functional)refinedDeclaration))){
declaration.setUnboxed(true);
} else {
declaration.setUnboxed(false);
}
}
|
diff --git a/src/main/java/de/uniba/wiai/dsg/betsy/virtual/host/engines/VirtualActiveBpelEngine.java b/src/main/java/de/uniba/wiai/dsg/betsy/virtual/host/engines/VirtualActiveBpelEngine.java
index dbe4ec26..0bf955b6 100644
--- a/src/main/java/de/uniba/wiai/dsg/betsy/virtual/host/engines/VirtualActiveBpelEngine.java
+++ b/src/main/java/de/uniba/wiai/dsg/betsy/virtual/host/engines/VirtualActiveBpelEngine.java
@@ -1,100 +1,102 @@
package de.uniba.wiai.dsg.betsy.virtual.host.engines;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import betsy.data.Process;
import betsy.data.engines.activeBpel.ActiveBpelEngine;
import de.uniba.wiai.dsg.betsy.Configuration;
import de.uniba.wiai.dsg.betsy.virtual.host.VirtualBoxController;
import de.uniba.wiai.dsg.betsy.virtual.host.VirtualEngine;
import de.uniba.wiai.dsg.betsy.virtual.host.VirtualEnginePackageBuilder;
import de.uniba.wiai.dsg.betsy.virtual.host.utils.ServiceAddress;
public class VirtualActiveBpelEngine extends VirtualEngine {
private final ActiveBpelEngine defaultEngine;
private final Configuration config = Configuration.getInstance();
public VirtualActiveBpelEngine(VirtualBoxController vbc) {
super(vbc);
this.defaultEngine = new ActiveBpelEngine();
this.defaultEngine.setPackageBuilder(new VirtualEnginePackageBuilder());
}
@Override
public String getName() {
return "active_bpel_v";
}
@Override
public List<ServiceAddress> getVerifiableServiceAddresses() {
List<ServiceAddress> saList = new LinkedList<>();
saList.add(new ServiceAddress(
- "http://localhost:8080/active-bpel/services", "Running"));
+ "http://localhost:8080/active-bpel/services"));
+ saList.add(new ServiceAddress("http://localhost:8080/BpelAdmin/",
+ "Running"));
return saList;
}
@Override
public Set<Integer> getRequiredPorts() {
Set<Integer> portList = new HashSet<>();
portList.add(8080);
return portList;
}
@Override
public Integer getEndpointPort() {
return 8080;
}
@Override
public String getEndpointPath(Process process) {
return "/active-bpel/services/"
+ process.getBpelFileNameWithoutExtension()
+ "TestInterfaceService";
}
@Override
public void buildArchives(Process process) {
// use default engine's operations
defaultEngine.buildArchives(process);
}
@Override
public String getXsltPath() {
return "src/main/xslt/" + defaultEngine.getName();
}
@Override
public void onPostDeployment() {
// not required. deploy is in sync and does not return before engine is
// deployed
}
@Override
public void onPostDeployment(Process process) {
// not required. deploy is in sync and does not return before process is
// deployed
}
@Override
public String getVMDeploymentDir() {
return config.getValueAsString(
"virtualisation.engines.active-bpel_v.deploymentDir",
"/usr/share/tomcat5.5/bpr");
}
@Override
public String getVMLogfileDir() {
return config.getValueAsString(
"virtualisation.engines.active-bpel_v.logfileDir",
"/usr/share/tomcat5.5/logs");
}
@Override
public String getTargetPackageExtension() {
return "bpr";
}
}
| true | true | public List<ServiceAddress> getVerifiableServiceAddresses() {
List<ServiceAddress> saList = new LinkedList<>();
saList.add(new ServiceAddress(
"http://localhost:8080/active-bpel/services", "Running"));
return saList;
}
| public List<ServiceAddress> getVerifiableServiceAddresses() {
List<ServiceAddress> saList = new LinkedList<>();
saList.add(new ServiceAddress(
"http://localhost:8080/active-bpel/services"));
saList.add(new ServiceAddress("http://localhost:8080/BpelAdmin/",
"Running"));
return saList;
}
|
diff --git a/web/src/main/java/org/openmrs/web/dwr/DWRPatientService.java b/web/src/main/java/org/openmrs/web/dwr/DWRPatientService.java
index d9277521..fc32ff02 100644
--- a/web/src/main/java/org/openmrs/web/dwr/DWRPatientService.java
+++ b/web/src/main/java/org/openmrs/web/dwr/DWRPatientService.java
@@ -1,802 +1,802 @@
/**
* 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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.GlobalProperty;
import org.openmrs.Location;
import org.openmrs.Patient;
import org.openmrs.PatientIdentifier;
import org.openmrs.PatientIdentifierType;
import org.openmrs.PersonAddress;
import org.openmrs.activelist.Allergy;
import org.openmrs.activelist.AllergySeverity;
import org.openmrs.activelist.AllergyType;
import org.openmrs.activelist.Problem;
import org.openmrs.activelist.ProblemModifier;
import org.openmrs.api.APIAuthenticationException;
import org.openmrs.api.APIException;
import org.openmrs.api.ConceptService;
import org.openmrs.api.DuplicateIdentifierException;
import org.openmrs.api.GlobalPropertyListener;
import org.openmrs.api.IdentifierNotUniqueException;
import org.openmrs.api.InsufficientIdentifiersException;
import org.openmrs.api.InvalidCheckDigitException;
import org.openmrs.api.InvalidIdentifierFormatException;
import org.openmrs.api.LocationService;
import org.openmrs.api.PatientIdentifierException;
import org.openmrs.api.PatientService;
import org.openmrs.api.context.Context;
import org.openmrs.patient.IdentifierValidator;
import org.openmrs.patient.UnallowedIdentifierException;
import org.openmrs.util.OpenmrsConstants;
/**
* DWR patient methods. The methods in here are used in the webapp to get data from the database via
* javascript calls.
*
* @see PatientService
*/
public class DWRPatientService implements GlobalPropertyListener {
private static final Log log = LogFactory.getLog(DWRPatientService.class);
private static Integer maximumResults;
/**
* Search on the <code>searchValue</code>. If a number is in the search string, do an identifier
* search. Else, do a name search
*
* @param searchValue string to be looked for
* @param includeVoided true/false whether or not to included voided patients
* @return Collection<Object> of PatientListItem or String
* @should return only patient list items with nonnumeric search
* @should return string warning if invalid patient identifier
* @should not return string warning if searching with valid identifier
* @should include string in results if doing extra decapitated search
* @should not return duplicate patient list items if doing decapitated search
* @should not do decapitated search if numbers are in the search string
* @should get results for patients that have edited themselves
* @should logged in user should load their own patient object
*/
public Collection<Object> findPatients(String searchValue, boolean includeVoided) {
return findBatchOfPatients(searchValue, includeVoided, null, null);
}
/**
* Search on the <code>searchValue</code>. If a number is in the search string, do an identifier
* search. Else, do a name search
*
* @see PatientService#getPatients(String, String, List, boolean, int, Integer)
* @param searchValue string to be looked for
* @param includeVoided true/false whether or not to included voided patients
* @param start The starting index for the results to return
* @param length The number of results of return
* @return Collection<Object> of PatientListItem or String
* @since 1.8
*/
@SuppressWarnings("unchecked")
public Collection<Object> findBatchOfPatients(String searchValue, boolean includeVoided, Integer start, Integer length) {
if (maximumResults == null)
maximumResults = getMaximumSearchResults();
if (length != null && length > maximumResults)
length = maximumResults;
// the list to return
List<Object> patientList = new Vector<Object>();
PatientService ps = Context.getPatientService();
Collection<Patient> patients;
try {
patients = ps.getPatients(searchValue, start, length);
}
catch (APIAuthenticationException e) {
patientList.add(Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage());
return patientList;
}
patientList = new Vector<Object>(patients.size());
for (Patient p : patients)
patientList.add(new PatientListItem(p));
// if the length wasn't limited to less than 3 or this is the second ajax call
// and only 2 results found and a number was not in the
// search, then do a decapitated search: trim each word
// down to the first three characters and search again
if ((length == null || length > 2) && patients.size() < 3 && !searchValue.matches(".*\\d+.*")) {
String[] names = searchValue.split(" ");
String newSearch = "";
for (String name : names) {
if (name.length() > 3)
name = name.substring(0, 4);
newSearch += " " + name;
}
newSearch = newSearch.trim();
if (!newSearch.equals(searchValue)) {
Collection<Patient> newPatients = ps.getPatients(newSearch, start, length);
patients = CollectionUtils.union(newPatients, patients); // get unique hits
//reconstruct the results list
if (newPatients.size() > 0) {
patientList = new Vector<Object>(patients.size());
//patientList.add("Minimal patients returned. Results for <b>" + newSearch + "</b>");
for (Patient p : newPatients) {
PatientListItem pi = new PatientListItem(p);
patientList.add(pi);
}
}
}
}
//no results found and a number was in the search --
//should check whether the check digit is correct.
else if (patients.size() == 0 && searchValue.matches(".*\\d+.*")) {
//Looks through all the patient identifier validators to see if this type of identifier
//is supported for any of them. If it isn't, then no need to warn about a bad check
//digit. If it does match, then if any of the validators validates the check digit
//successfully, then the user is notified that the identifier has been entered correctly.
//Otherwise, the user is notified that the identifier was entered incorrectly.
Collection<IdentifierValidator> pivs = ps.getAllIdentifierValidators();
boolean shouldWarnUser = true;
boolean validCheckDigit = false;
boolean identifierMatchesValidationScheme = false;
for (IdentifierValidator piv : pivs) {
try {
if (piv.isValid(searchValue)) {
shouldWarnUser = false;
validCheckDigit = true;
}
identifierMatchesValidationScheme = true;
}
catch (UnallowedIdentifierException e) {}
}
if (identifierMatchesValidationScheme) {
if (shouldWarnUser)
patientList
.add("<p style=\"color:red; font-size:big;\"><b>WARNING: Identifier has been typed incorrectly! Please double check the identifier.</b></p>");
else if (validCheckDigit)
patientList
.add("<p style=\"color:green; font-size:big;\"><b>This identifier has been entered correctly, but still no patients have been found.</b></p>");
}
}
return patientList;
}
/**
* Returns a map of results with the values as count of matches and a partial list of the
* matching patients (depending on values of start and length parameters) while the keys are are
* 'count' and 'objectList' respectively, if the length parameter is not specified, then all
* matches will be returned from the start index if specified.
*
* @param searchValue patient name or identifier
* @param start the beginning index
* @param length the number of matching patients to return
* @param getMatchCount Specifies if the count of matches should be included in the returned map
* @return a map of results
* @throws APIException
* @since 1.8
*/
@SuppressWarnings("unchecked")
public Map<String, Object> findCountAndPatients(String searchValue, Integer start, Integer length, boolean getMatchCount)
throws APIException {
//Map to return
Map<String, Object> resultsMap = new HashMap<String, Object>();
Collection<Object> objectList = new Vector<Object>();
try {
PatientService ps = Context.getPatientService();
int patientCount = 0;
//if this is the first call
if (getMatchCount) {
patientCount += ps.getCountOfPatients(searchValue);
// if only 2 results found and a number was not in the
// search, then do a decapitated search: trim each word
// down to the first three characters and search again
if ((length == null || length > 2) && patientCount < 3 && !searchValue.matches(".*\\d+.*")) {
String[] names = searchValue.split(" ");
String newSearch = "";
for (String name : names) {
if (name.length() > 3)
name = name.substring(0, 4);
newSearch += " " + name;
}
newSearch = newSearch.trim();
if (!newSearch.equals(searchValue)) {
//since we already know that the list is small, it doesn't hurt to load the hits
//so that we can remove them from the list of the new search results and get the
//accurate count of matches
Collection<Patient> patients = ps.getPatients(searchValue);
newSearch = newSearch.trim();
Collection<Patient> newPatients = ps.getPatients(newSearch);
newPatients = CollectionUtils.union(newPatients, patients);
//Re-compute the count of all the unique patient hits
patientCount = newPatients.size();
if (newPatients.size() > 0) {
resultsMap.put("notification", Context.getMessageSourceService().getMessage(
"Patient.warning.minimalSearchResults", new Object[] { newSearch }, Context.getLocale()));
}
}
}
//no results found and a number was in the search --
//should check whether the check digit is correct.
else if (patientCount == 0 && searchValue.matches(".*\\d+.*")) {
//Looks through all the patient identifier validators to see if this type of identifier
//is supported for any of them. If it isn't, then no need to warn about a bad check
//digit. If it does match, then if any of the validators validates the check digit
//successfully, then the user is notified that the identifier has been entered correctly.
//Otherwise, the user is notified that the identifier was entered incorrectly.
Collection<IdentifierValidator> pivs = ps.getAllIdentifierValidators();
boolean shouldWarnUser = true;
boolean validCheckDigit = false;
boolean identifierMatchesValidationScheme = false;
for (IdentifierValidator piv : pivs) {
try {
if (piv.isValid(searchValue)) {
shouldWarnUser = false;
validCheckDigit = true;
}
identifierMatchesValidationScheme = true;
}
catch (UnallowedIdentifierException e) {}
}
if (identifierMatchesValidationScheme) {
if (shouldWarnUser)
resultsMap.put("notification", "<b>"
+ Context.getMessageSourceService().getMessage("Patient.warning.inValidIdentifier")
+ "<b/>");
else if (validCheckDigit)
resultsMap.put("notification", "<b style=\"color:green;\">"
+ Context.getMessageSourceService().getMessage("Patient.message.validIdentifier")
+ "<b/>");
}
} else {
//ensure that count never exceeds this value because the API's service layer would never
//return more than it since it is limited in the DAO layer
if (maximumResults == null)
maximumResults = getMaximumSearchResults();
if (length != null && length > maximumResults)
length = maximumResults;
if (patientCount > maximumResults) {
patientCount = maximumResults;
if (log.isDebugEnabled())
log.debug("Limitng the size of matching patients to " + maximumResults);
}
}
}
//if we have any matches or this isn't the first ajax call when the caller
//requests for the count
if (patientCount > 0 || !getMatchCount)
objectList = findBatchOfPatients(searchValue, false, start, length);
resultsMap.put("count", patientCount);
resultsMap.put("objectList", objectList);
}
catch (Exception e) {
log.error("Error while searching for patients", e);
objectList.clear();
objectList.add(Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage());
resultsMap.put("count", 0);
resultsMap.put("objectList", objectList);
}
return resultsMap;
}
/**
* Convenience method for dwr/javascript to convert a patient id into a Patient object (or at
* least into data about the patient)
*
* @param patientId the {@link Patient#getPatientId()} to match on
* @return a truncated Patient object in the form of a PatientListItem
*/
public PatientListItem getPatient(Integer patientId) {
PatientService ps = Context.getPatientService();
Patient p = ps.getPatient(patientId);
PatientListItem pli = new PatientListItem(p);
if (p != null && p.getAddresses() != null && p.getAddresses().size() > 0) {
PersonAddress pa = (PersonAddress) p.getAddresses().toArray()[0];
pli.setAddress1(pa.getAddress1());
pli.setAddress2(pa.getAddress2());
}
return pli;
}
/**
* find all patients with duplicate attributes (searchOn)
*
* @param searchOn
* @return list of patientListItems
*/
public Vector<Object> findDuplicatePatients(String[] searchOn) {
Vector<Object> patientList = new Vector<Object>();
try {
List<String> options = new Vector<String>(searchOn.length);
for (String s : searchOn)
options.add(s);
List<Patient> patients = Context.getPatientService().getDuplicatePatientsByAttributes(options);
if (patients.size() > 200)
patients.subList(0, 200);
for (Patient p : patients)
patientList.add(new PatientListItem(p));
}
catch (Exception e) {
log.error(e);
patientList.add("Error while attempting to find duplicate patients - " + e.getMessage());
}
return patientList;
}
/**
* Auto generated method comment
*
* @param patientId
* @param identifierType
* @param identifier
* @param identifierLocationId
* @return
*/
public String addIdentifier(Integer patientId, String identifierType, String identifier, Integer identifierLocationId) {
String ret = "";
if (identifier == null || identifier.length() == 0)
return "PatientIdentifier.error.general";
PatientService ps = Context.getPatientService();
LocationService ls = Context.getLocationService();
Patient p = ps.getPatient(patientId);
PatientIdentifierType idType = ps.getPatientIdentifierTypeByName(identifierType);
//ps.updatePatientIdentifier(pi);
Location location = ls.getLocation(identifierLocationId);
log.debug("idType=" + identifierType + "->" + idType + " , location=" + identifierLocationId + "->" + location
+ " identifier=" + identifier);
PatientIdentifier id = new PatientIdentifier();
id.setIdentifierType(idType);
id.setIdentifier(identifier);
id.setLocation(location);
// in case we are editing, check to see if there is already an ID of this type and location
for (PatientIdentifier previousId : p.getActiveIdentifiers()) {
if (previousId.getIdentifierType().equals(idType) && previousId.getLocation().equals(location)) {
log.debug("Found equivalent ID: [" + idType + "][" + location + "][" + previousId.getIdentifier()
+ "], about to remove");
p.removeIdentifier(previousId);
} else {
if (!previousId.getIdentifierType().equals(idType))
log.debug("Previous ID id type does not match: [" + previousId.getIdentifierType().getName() + "]["
+ previousId.getIdentifier() + "]");
if (!previousId.getLocation().equals(location)) {
log.debug("Previous ID location is: " + previousId.getLocation());
log.debug("New location is: " + location);
}
}
}
p.addIdentifier(id);
try {
ps.savePatient(p);
}
catch (InvalidIdentifierFormatException iife) {
log.error(iife);
ret = "PatientIdentifier.error.formatInvalid";
}
catch (InvalidCheckDigitException icde) {
log.error(icde);
ret = "PatientIdentifier.error.checkDigit";
}
catch (IdentifierNotUniqueException inue) {
log.error(inue);
ret = "PatientIdentifier.error.notUnique";
}
catch (DuplicateIdentifierException die) {
log.error(die);
ret = "PatientIdentifier.error.duplicate";
}
catch (InsufficientIdentifiersException iie) {
log.error(iie);
ret = "PatientIdentifier.error.insufficientIdentifiers";
}
catch (PatientIdentifierException pie) {
log.error(pie);
ret = "PatientIdentifier.error.general";
}
return ret;
}
/**
* Auto generated method comment
*
* @param patientId
* @param reasonForExitId
* @param dateOfExit
* @param causeOfDeath
* @param otherReason
* @return
*/
public String exitPatientFromCare(Integer patientId, Integer exitReasonId, String exitDateStr,
Integer causeOfDeathConceptId, String otherReason) {
log.debug("Entering exitfromcare with [" + patientId + "] [" + exitReasonId + "] [" + exitDateStr + "]");
String ret = "";
PatientService ps = Context.getPatientService();
ConceptService cs = Context.getConceptService();
Patient patient = null;
try {
patient = ps.getPatient(patientId);
}
catch (Exception e) {
patient = null;
}
if (patient == null) {
ret = "Unable to find valid patient with the supplied identification information - cannot exit patient from care";
}
// Get the exit reason concept (if possible)
Concept exitReasonConcept = null;
try {
exitReasonConcept = cs.getConcept(exitReasonId);
}
catch (Exception e) {
exitReasonConcept = null;
}
// Exit reason error handling
if (exitReasonConcept == null) {
ret = "Unable to locate reason for exit in dictionary - cannot exit patient from care";
}
// Parse the exit date
Date exitDate = null;
if (exitDateStr != null) {
SimpleDateFormat sdf = Context.getDateFormat();
try {
exitDate = sdf.parse(exitDateStr);
}
catch (ParseException e) {
exitDate = null;
}
}
// Exit date error handling
if (exitDate == null) {
ret = "Invalid date supplied - cannot exit patient from care without a valid date.";
}
// If all data is provided as expected
if (patient != null && exitReasonConcept != null && exitDate != null) {
// need to check first if this is death or not
String patientDiedConceptId = Context.getAdministrationService().getGlobalProperty("concept.patientDied");
Concept patientDiedConcept = null;
if (patientDiedConceptId != null) {
patientDiedConcept = cs.getConcept(patientDiedConceptId);
}
// If there is a concept for death in the dictionary
if (patientDiedConcept != null) {
// If the exist reason == patient died
if (exitReasonConcept.equals(patientDiedConcept)) {
Concept causeOfDeathConcept = null;
try {
causeOfDeathConcept = cs.getConcept(causeOfDeathConceptId);
}
catch (Exception e) {
causeOfDeathConcept = null;
}
// Cause of death concept exists
if (causeOfDeathConcept != null) {
try {
ps.processDeath(patient, exitDate, causeOfDeathConcept, otherReason);
}
catch (Exception e) {
- log.debug("Caught error", e);
- ret = "Internal error while trying to process patient death - unable to proceed.";
+ log.warn("Caught error", e);
+ ret = "Internal error while trying to process patient death - unable to proceed. Cause: " + e.getMessage();
}
}
// cause of death concept does not exist
else {
ret = "Unable to locate cause of death in dictionary - cannot proceed";
}
}
// Otherwise, we process this as an exit
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
- log.debug("Caught error", e);
- ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time.";
+ log.warn("Caught error", e);
+ ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: " + e.getMessage();
}
}
}
// If the system does not recognize death as a concept, then we exit from care
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
- log.debug("Caught error", e);
- ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time.";
+ log.warn("Caught error", e);
+ ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: " + e.getMessage();
}
}
log.debug("Exited from care, it seems");
}
return ret;
}
/**
* Auto generated method comment
*
* @param patientId
* @param locationId
* @return
*/
public String changeHealthCenter(Integer patientId, Integer locationId) {
log.warn("Deprecated method in 'DWRPatientService.changeHealthCenter'");
String ret = "";
/*
if ( patientId != null && locationId != null ) {
Patient patient = Context.getPatientService().getPatient(patientId);
Location location = Context.getEncounterService().getLocation(locationId);
if ( patient != null && location != null ) {
patient.setHealthCenter(location);
Context.getPatientService().updatePatient(patient);
}
}
*/
return ret;
}
/**
* Creates an Allergy Item
*
* @param patientId
* @param allergenId
* @param type
* @param pStartDate
* @param severity
* @param reactionId
*/
public void createAllergy(Integer patientId, Integer allergenId, String type, String pStartDate, String severity,
Integer reactionId) {
Date startDate = parseDate(pStartDate);
Patient patient = Context.getPatientService().getPatient(patientId);
Concept allergyConcept = Context.getConceptService().getConcept(allergenId);
Concept reactionConcept = (reactionId == null) ? null : Context.getConceptService().getConcept(reactionId);
AllergySeverity allergySeverity = StringUtils.isBlank(severity) ? null : AllergySeverity.valueOf(severity);
AllergyType allergyType = StringUtils.isBlank(type) ? null : AllergyType.valueOf(type);
Allergy allergy = new Allergy(patient, allergyConcept, startDate, allergyType, reactionConcept, allergySeverity);
Context.getPatientService().saveAllergy(allergy);
}
/**
* Save an Allergy
*
* @param activeListItemId
* @param allergenId Concept ID
* @param type
* @param pStartDate
* @param severity
* @param reactionId
*/
public void saveAllergy(Integer activeListItemId, Integer allergenId, String type, String pStartDate, String severity,
Integer reactionId) {
//get the allergy
Allergy allergy = Context.getPatientService().getAllergy(activeListItemId);
allergy.setAllergen(Context.getConceptService().getConcept(allergenId));
allergy.setAllergyType(type);
allergy.setStartDate(parseDate(pStartDate));
allergy.setSeverity(severity);
allergy.setReaction((reactionId == null) ? null : Context.getConceptService().getConcept(reactionId));
Context.getPatientService().saveAllergy(allergy);
}
/**
* Resolve an allergy
*
* @param activeListId
* @param resolved
* @param reason
* @param pEndDate
*/
public void removeAllergy(Integer activeListId, String reason) {
Allergy allergy = Context.getPatientService().getAllergy(activeListId);
Context.getPatientService().removeAllergy(allergy, reason);
}
/**
* Voids the Allergy
*
* @param activeListId
* @param reason
*/
public void voidAllergy(Integer activeListId, String reason) {
Allergy allergy = Context.getPatientService().getAllergy(activeListId);
if (reason == null) {
reason = "Error - user entered incorrect data from UI";
}
Context.getPatientService().voidAllergy(allergy, reason);
}
/**
* Creates a Problem Item
*
* @param patientId
* @param problemId
* @param status
* @param pStartDate
* @param comments
*/
public void createProblem(Integer patientId, Integer problemId, String status, String pStartDate, String comments) {
Patient patient = Context.getPatientService().getPatient(patientId);
Concept problemConcept = Context.getConceptService().getConcept(problemId);
ProblemModifier modifier = StringUtils.isBlank(status) ? null : ProblemModifier.valueOf(status);
Problem problem = new Problem(patient, problemConcept, parseDate(pStartDate), modifier, comments, null);
Context.getPatientService().saveProblem(problem);
}
/**
* Saves the Problem
*
* @param activeListId
* @param problemId
* @param status
* @param pStartDate
* @param comments
*/
public void saveProblem(Integer activeListId, Integer problemId, String status, String pStartDate, String comments) {
//get the allergy
Problem problem = Context.getPatientService().getProblem(activeListId);
problem.setProblem(Context.getConceptService().getConcept(problemId));
problem.setModifier(status);
problem.setStartDate(parseDate(pStartDate));
problem.setComments(comments);
Context.getPatientService().saveProblem(problem);
}
/**
* Remove a problem, sets the end date
*
* @param activeListId
* @param resolved
* @param reason
* @param pEndDate
*/
public void removeProblem(Integer activeListId, String reason, String pEndDate) {
Problem problem = Context.getPatientService().getProblem(activeListId);
problem.setEndDate(parseDate(pEndDate));
Context.getPatientService().removeProblem(problem, reason);
}
/**
* Voids the Problem
*
* @param activeListId
* @param reason
*/
public void voidProblem(Integer activeListId, String reason) {
Problem problem = Context.getPatientService().getProblem(activeListId);
if (reason == null) {
reason = "Error - user entered incorrect data from UI";
}
Context.getPatientService().voidProblem(problem, reason);
}
/**
* Simple utility method to parse the date object into the correct, local format
*
* @param date
* @return
*/
private Date parseDate(String date) {
if (date != null) {
SimpleDateFormat sdf = Context.getDateFormat();
try {
return sdf.parse(date);
}
catch (ParseException e) {}
}
return null;
}
@Override
public boolean supportsPropertyName(String propertyName) {
return propertyName.equals(OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS);
}
@Override
public void globalPropertyChanged(GlobalProperty newValue) {
try {
maximumResults = Integer.valueOf(newValue.getPropertyValue());
}
catch (NumberFormatException e) {
maximumResults = OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE;
}
}
@Override
public void globalPropertyDeleted(String propertyName) {
maximumResults = OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE;
}
/**
* Fetch the max results value from the global properties table
*
* @return Integer value for the person search max results global property
*/
private static Integer getMaximumSearchResults() {
try {
return Integer.valueOf(Context.getAdministrationService().getGlobalProperty(
OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS,
String.valueOf(OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE)));
}
catch (Exception e) {
log.warn("Unable to convert the global property " + OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS
+ "to a valid integer. Returning the default "
+ OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE);
}
return OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE;
}
}
| false | true | public String exitPatientFromCare(Integer patientId, Integer exitReasonId, String exitDateStr,
Integer causeOfDeathConceptId, String otherReason) {
log.debug("Entering exitfromcare with [" + patientId + "] [" + exitReasonId + "] [" + exitDateStr + "]");
String ret = "";
PatientService ps = Context.getPatientService();
ConceptService cs = Context.getConceptService();
Patient patient = null;
try {
patient = ps.getPatient(patientId);
}
catch (Exception e) {
patient = null;
}
if (patient == null) {
ret = "Unable to find valid patient with the supplied identification information - cannot exit patient from care";
}
// Get the exit reason concept (if possible)
Concept exitReasonConcept = null;
try {
exitReasonConcept = cs.getConcept(exitReasonId);
}
catch (Exception e) {
exitReasonConcept = null;
}
// Exit reason error handling
if (exitReasonConcept == null) {
ret = "Unable to locate reason for exit in dictionary - cannot exit patient from care";
}
// Parse the exit date
Date exitDate = null;
if (exitDateStr != null) {
SimpleDateFormat sdf = Context.getDateFormat();
try {
exitDate = sdf.parse(exitDateStr);
}
catch (ParseException e) {
exitDate = null;
}
}
// Exit date error handling
if (exitDate == null) {
ret = "Invalid date supplied - cannot exit patient from care without a valid date.";
}
// If all data is provided as expected
if (patient != null && exitReasonConcept != null && exitDate != null) {
// need to check first if this is death or not
String patientDiedConceptId = Context.getAdministrationService().getGlobalProperty("concept.patientDied");
Concept patientDiedConcept = null;
if (patientDiedConceptId != null) {
patientDiedConcept = cs.getConcept(patientDiedConceptId);
}
// If there is a concept for death in the dictionary
if (patientDiedConcept != null) {
// If the exist reason == patient died
if (exitReasonConcept.equals(patientDiedConcept)) {
Concept causeOfDeathConcept = null;
try {
causeOfDeathConcept = cs.getConcept(causeOfDeathConceptId);
}
catch (Exception e) {
causeOfDeathConcept = null;
}
// Cause of death concept exists
if (causeOfDeathConcept != null) {
try {
ps.processDeath(patient, exitDate, causeOfDeathConcept, otherReason);
}
catch (Exception e) {
log.debug("Caught error", e);
ret = "Internal error while trying to process patient death - unable to proceed.";
}
}
// cause of death concept does not exist
else {
ret = "Unable to locate cause of death in dictionary - cannot proceed";
}
}
// Otherwise, we process this as an exit
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.debug("Caught error", e);
ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time.";
}
}
}
// If the system does not recognize death as a concept, then we exit from care
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.debug("Caught error", e);
ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time.";
}
}
log.debug("Exited from care, it seems");
}
return ret;
}
| public String exitPatientFromCare(Integer patientId, Integer exitReasonId, String exitDateStr,
Integer causeOfDeathConceptId, String otherReason) {
log.debug("Entering exitfromcare with [" + patientId + "] [" + exitReasonId + "] [" + exitDateStr + "]");
String ret = "";
PatientService ps = Context.getPatientService();
ConceptService cs = Context.getConceptService();
Patient patient = null;
try {
patient = ps.getPatient(patientId);
}
catch (Exception e) {
patient = null;
}
if (patient == null) {
ret = "Unable to find valid patient with the supplied identification information - cannot exit patient from care";
}
// Get the exit reason concept (if possible)
Concept exitReasonConcept = null;
try {
exitReasonConcept = cs.getConcept(exitReasonId);
}
catch (Exception e) {
exitReasonConcept = null;
}
// Exit reason error handling
if (exitReasonConcept == null) {
ret = "Unable to locate reason for exit in dictionary - cannot exit patient from care";
}
// Parse the exit date
Date exitDate = null;
if (exitDateStr != null) {
SimpleDateFormat sdf = Context.getDateFormat();
try {
exitDate = sdf.parse(exitDateStr);
}
catch (ParseException e) {
exitDate = null;
}
}
// Exit date error handling
if (exitDate == null) {
ret = "Invalid date supplied - cannot exit patient from care without a valid date.";
}
// If all data is provided as expected
if (patient != null && exitReasonConcept != null && exitDate != null) {
// need to check first if this is death or not
String patientDiedConceptId = Context.getAdministrationService().getGlobalProperty("concept.patientDied");
Concept patientDiedConcept = null;
if (patientDiedConceptId != null) {
patientDiedConcept = cs.getConcept(patientDiedConceptId);
}
// If there is a concept for death in the dictionary
if (patientDiedConcept != null) {
// If the exist reason == patient died
if (exitReasonConcept.equals(patientDiedConcept)) {
Concept causeOfDeathConcept = null;
try {
causeOfDeathConcept = cs.getConcept(causeOfDeathConceptId);
}
catch (Exception e) {
causeOfDeathConcept = null;
}
// Cause of death concept exists
if (causeOfDeathConcept != null) {
try {
ps.processDeath(patient, exitDate, causeOfDeathConcept, otherReason);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to process patient death - unable to proceed. Cause: " + e.getMessage();
}
}
// cause of death concept does not exist
else {
ret = "Unable to locate cause of death in dictionary - cannot proceed";
}
}
// Otherwise, we process this as an exit
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: " + e.getMessage();
}
}
}
// If the system does not recognize death as a concept, then we exit from care
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: " + e.getMessage();
}
}
log.debug("Exited from care, it seems");
}
return ret;
}
|
diff --git a/src/com/android/calendar/agenda/AgendaWindowAdapter.java b/src/com/android/calendar/agenda/AgendaWindowAdapter.java
index ac30998a..8ac14eb3 100644
--- a/src/com/android/calendar/agenda/AgendaWindowAdapter.java
+++ b/src/com/android/calendar/agenda/AgendaWindowAdapter.java
@@ -1,1349 +1,1352 @@
/*
* 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.calendar.agenda;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Instances;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.GridLayout;
import android.widget.TextView;
import com.android.calendar.CalendarController;
import com.android.calendar.CalendarController.EventType;
import com.android.calendar.CalendarController.ViewType;
import com.android.calendar.R;
import com.android.calendar.StickyHeaderListView;
import com.android.calendar.Utils;
import java.util.Formatter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;
import java.util.concurrent.ConcurrentLinkedQueue;
/*
Bugs Bugs Bugs:
- At rotation and launch time, the initial position is not set properly. This code is calling
listview.setSelection() in 2 rapid secessions but it dropped or didn't process the first one.
- Scroll using trackball isn't repositioning properly after a new adapter is added.
- Track ball clicks at the header/footer doesn't work.
- Potential ping pong effect if the prefetch window is big and data is limited
- Add index in calendar provider
ToDo ToDo ToDo:
Get design of header and footer from designer
Make scrolling smoother.
Test for correctness
Loading speed
Check for leaks and excessive allocations
*/
public class AgendaWindowAdapter extends BaseAdapter
implements StickyHeaderListView.HeaderIndexer, StickyHeaderListView.HeaderHeightListener{
static final boolean BASICLOG = false;
static final boolean DEBUGLOG = false;
private static final String TAG = "AgendaWindowAdapter";
private static final String AGENDA_SORT_ORDER =
CalendarContract.Instances.START_DAY + " ASC, " +
CalendarContract.Instances.BEGIN + " ASC, " +
CalendarContract.Events.TITLE + " ASC";
public static final int INDEX_INSTANCE_ID = 0;
public static final int INDEX_TITLE = 1;
public static final int INDEX_EVENT_LOCATION = 2;
public static final int INDEX_ALL_DAY = 3;
public static final int INDEX_HAS_ALARM = 4;
public static final int INDEX_COLOR = 5;
public static final int INDEX_RRULE = 6;
public static final int INDEX_BEGIN = 7;
public static final int INDEX_END = 8;
public static final int INDEX_EVENT_ID = 9;
public static final int INDEX_START_DAY = 10;
public static final int INDEX_END_DAY = 11;
public static final int INDEX_SELF_ATTENDEE_STATUS = 12;
public static final int INDEX_ORGANIZER = 13;
public static final int INDEX_OWNER_ACCOUNT = 14;
public static final int INDEX_CAN_ORGANIZER_RESPOND= 15;
public static final int INDEX_TIME_ZONE = 16;
private static final String[] PROJECTION = new String[] {
Instances._ID, // 0
Instances.TITLE, // 1
Instances.EVENT_LOCATION, // 2
Instances.ALL_DAY, // 3
Instances.HAS_ALARM, // 4
Instances.DISPLAY_COLOR, // 5
Instances.RRULE, // 6
Instances.BEGIN, // 7
Instances.END, // 8
Instances.EVENT_ID, // 9
Instances.START_DAY, // 10 Julian start day
Instances.END_DAY, // 11 Julian end day
Instances.SELF_ATTENDEE_STATUS, // 12
Instances.ORGANIZER, // 13
Instances.OWNER_ACCOUNT, // 14
Instances.CAN_ORGANIZER_RESPOND, // 15
Instances.EVENT_TIMEZONE, // 16
};
// Listview may have a bug where the index/position is not consistent when there's a header.
// position == positionInListView - OFF_BY_ONE_BUG
// TODO Need to look into this.
private static final int OFF_BY_ONE_BUG = 1;
private static final int MAX_NUM_OF_ADAPTERS = 5;
private static final int IDEAL_NUM_OF_EVENTS = 50;
private static final int MIN_QUERY_DURATION = 7; // days
private static final int MAX_QUERY_DURATION = 60; // days
private static final int PREFETCH_BOUNDARY = 1;
/** Times to auto-expand/retry query after getting no data */
private static final int RETRIES_ON_NO_DATA = 1;
private final Context mContext;
private final Resources mResources;
private final QueryHandler mQueryHandler;
private final AgendaListView mAgendaListView;
/** The sum of the rows in all the adapters */
private int mRowCount;
/** The number of times we have queried and gotten no results back */
private int mEmptyCursorCount;
/** Cached value of the last used adapter */
private DayAdapterInfo mLastUsedInfo;
private final LinkedList<DayAdapterInfo> mAdapterInfos =
new LinkedList<DayAdapterInfo>();
private final ConcurrentLinkedQueue<QuerySpec> mQueryQueue =
new ConcurrentLinkedQueue<QuerySpec>();
private final TextView mHeaderView;
private final TextView mFooterView;
private boolean mDoneSettingUpHeaderFooter = false;
private final boolean mIsTabletConfig;
boolean mCleanQueryInitiated = false;
private int mStickyHeaderSize = 44; // Initial size big enough for it to work
/**
* When the user scrolled to the top, a query will be made for older events
* and this will be incremented. Don't make more requests if
* mOlderRequests > mOlderRequestsProcessed.
*/
private int mOlderRequests;
/** Number of "older" query that has been processed. */
private int mOlderRequestsProcessed;
/**
* When the user scrolled to the bottom, a query will be made for newer
* events and this will be incremented. Don't make more requests if
* mNewerRequests > mNewerRequestsProcessed.
*/
private int mNewerRequests;
/** Number of "newer" query that has been processed. */
private int mNewerRequestsProcessed;
// Note: Formatter is not thread safe. Fine for now as it is only used by the main thread.
private final Formatter mFormatter;
private final StringBuilder mStringBuilder;
private String mTimeZone;
// defines if to pop-up the current event when the agenda is first shown
private final boolean mShowEventOnStart;
private final Runnable mTZUpdater = new Runnable() {
@Override
public void run() {
mTimeZone = Utils.getTimeZone(mContext, this);
notifyDataSetChanged();
}
};
private boolean mShuttingDown;
private boolean mHideDeclined;
// Used to stop a fling motion if the ListView is set to a specific position
int mListViewScrollState = OnScrollListener.SCROLL_STATE_IDLE;
/** The current search query, or null if none */
private String mSearchQuery;
private long mSelectedInstanceId = -1;
private final int mSelectedItemBackgroundColor;
private final int mSelectedItemTextColor;
private final float mItemRightMargin;
// Types of Query
private static final int QUERY_TYPE_OLDER = 0; // Query for older events
private static final int QUERY_TYPE_NEWER = 1; // Query for newer events
private static final int QUERY_TYPE_CLEAN = 2; // Delete everything and query around a date
private static class QuerySpec {
long queryStartMillis;
Time goToTime;
int start;
int end;
String searchQuery;
int queryType;
long id;
public QuerySpec(int queryType) {
this.queryType = queryType;
id = -1;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + end;
result = prime * result + (int) (queryStartMillis ^ (queryStartMillis >>> 32));
result = prime * result + queryType;
result = prime * result + start;
if (searchQuery != null) {
result = prime * result + searchQuery.hashCode();
}
if (goToTime != null) {
long goToTimeMillis = goToTime.toMillis(false);
result = prime * result + (int) (goToTimeMillis ^ (goToTimeMillis >>> 32));
}
result = prime * result + (int)id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
QuerySpec other = (QuerySpec) obj;
if (end != other.end || queryStartMillis != other.queryStartMillis
|| queryType != other.queryType || start != other.start
|| Utils.equals(searchQuery, other.searchQuery) || id != other.id) {
return false;
}
if (goToTime != null) {
if (goToTime.toMillis(false) != other.goToTime.toMillis(false)) {
return false;
}
} else {
if (other.goToTime != null) {
return false;
}
}
return true;
}
}
static class EventInfo {
long begin;
long end;
long id;
int startDay;
boolean allDay;
}
static class DayAdapterInfo {
Cursor cursor;
AgendaByDayAdapter dayAdapter;
int start; // start day of the cursor's coverage
int end; // end day of the cursor's coverage
int offset; // offset in position in the list view
int size; // dayAdapter.getCount()
public DayAdapterInfo(Context context) {
dayAdapter = new AgendaByDayAdapter(context);
}
@Override
public String toString() {
// Static class, so the time in this toString will not reflect the
// home tz settings. This should only affect debugging.
Time time = new Time();
StringBuilder sb = new StringBuilder();
time.setJulianDay(start);
time.normalize(false);
sb.append("Start:").append(time.toString());
time.setJulianDay(end);
time.normalize(false);
sb.append(" End:").append(time.toString());
sb.append(" Offset:").append(offset);
sb.append(" Size:").append(size);
return sb.toString();
}
}
public AgendaWindowAdapter(Context context,
AgendaListView agendaListView, boolean showEventOnStart) {
mContext = context;
mResources = context.getResources();
mSelectedItemBackgroundColor = mResources
.getColor(R.color.agenda_selected_background_color);
mSelectedItemTextColor = mResources.getColor(R.color.agenda_selected_text_color);
mItemRightMargin = mResources.getDimension(R.dimen.agenda_item_right_margin);
mIsTabletConfig = Utils.getConfigBool(mContext, R.bool.tablet_config);
mTimeZone = Utils.getTimeZone(context, mTZUpdater);
mAgendaListView = agendaListView;
mQueryHandler = new QueryHandler(context.getContentResolver());
mStringBuilder = new StringBuilder(50);
mFormatter = new Formatter(mStringBuilder, Locale.getDefault());
mShowEventOnStart = showEventOnStart;
// Implies there is no sticky header
if (!mShowEventOnStart) {
mStickyHeaderSize = 0;
}
mSearchQuery = null;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mHeaderView = (TextView)inflater.inflate(R.layout.agenda_header_footer, null);
mFooterView = (TextView)inflater.inflate(R.layout.agenda_header_footer, null);
mHeaderView.setText(R.string.loading);
mAgendaListView.addHeaderView(mHeaderView);
}
// Method in Adapter
@Override
public int getViewTypeCount() {
return AgendaByDayAdapter.TYPE_LAST;
}
// Method in BaseAdapter
@Override
public boolean areAllItemsEnabled() {
return false;
}
// Method in Adapter
@Override
public int getItemViewType(int position) {
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
return info.dayAdapter.getItemViewType(position - info.offset);
} else {
return -1;
}
}
// Method in BaseAdapter
@Override
public boolean isEnabled(int position) {
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
return info.dayAdapter.isEnabled(position - info.offset);
} else {
return false;
}
}
// Abstract Method in BaseAdapter
public int getCount() {
return mRowCount;
}
// Abstract Method in BaseAdapter
public Object getItem(int position) {
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
return info.dayAdapter.getItem(position - info.offset);
} else {
return null;
}
}
// Method in BaseAdapter
@Override
public boolean hasStableIds() {
return true;
}
// Abstract Method in BaseAdapter
@Override
public long getItemId(int position) {
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
int curPos = info.dayAdapter.getCursorPosition(position - info.offset);
if (curPos == Integer.MIN_VALUE) {
return -1;
}
// Regular event
if (curPos >= 0) {
info.cursor.moveToPosition(curPos);
return info.cursor.getLong(AgendaWindowAdapter.INDEX_EVENT_ID) << 20 +
info.cursor.getLong(AgendaWindowAdapter.INDEX_BEGIN);
}
// Day Header
return info.dayAdapter.findJulianDayFromPosition(position);
} else {
return -1;
}
}
// Abstract Method in BaseAdapter
public View getView(int position, View convertView, ViewGroup parent) {
if (position >= (mRowCount - PREFETCH_BOUNDARY)
&& mNewerRequests <= mNewerRequestsProcessed) {
if (DEBUGLOG) Log.e(TAG, "queryForNewerEvents: ");
mNewerRequests++;
queueQuery(new QuerySpec(QUERY_TYPE_NEWER));
}
if (position < PREFETCH_BOUNDARY
&& mOlderRequests <= mOlderRequestsProcessed) {
if (DEBUGLOG) Log.e(TAG, "queryForOlderEvents: ");
mOlderRequests++;
queueQuery(new QuerySpec(QUERY_TYPE_OLDER));
}
final View v;
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
int offset = position - info.offset;
v = info.dayAdapter.getView(offset, convertView,
parent);
// Turn on the past/present separator if the view is a day header
// and it is the first day with events after yesterday.
if (info.dayAdapter.isDayHeaderView(offset)) {
View simpleDivider = v.findViewById(R.id.top_divider_simple);
View pastPresentDivider = v.findViewById(R.id.top_divider_past_present);
if (info.dayAdapter.isFirstDayAfterYesterday(offset)) {
if (simpleDivider != null && pastPresentDivider != null) {
simpleDivider.setVisibility(View.GONE);
pastPresentDivider.setVisibility(View.VISIBLE);
}
} else if (simpleDivider != null && pastPresentDivider != null) {
simpleDivider.setVisibility(View.VISIBLE);
pastPresentDivider.setVisibility(View.GONE);
}
}
} else {
// TODO
Log.e(TAG, "BUG: getAdapterInfoByPosition returned null!!! " + position);
TextView tv = new TextView(mContext);
tv.setText("Bug! " + position);
v = tv;
}
// If this is not a tablet config don't do selection highlighting
if (!mIsTabletConfig) {
return v;
}
// Show selected marker if this is item is selected
boolean selected = false;
Object yy = v.getTag();
if (yy instanceof AgendaAdapter.ViewHolder) {
AgendaAdapter.ViewHolder vh = (AgendaAdapter.ViewHolder) yy;
selected = mSelectedInstanceId == vh.instanceId;
vh.selectedMarker.setVisibility((selected && mShowEventOnStart) ?
View.VISIBLE : View.GONE);
if (mShowEventOnStart) {
GridLayout.LayoutParams lp =
(GridLayout.LayoutParams)vh.textContainer.getLayoutParams();
if (selected) {
mSelectedVH = vh;
v.setBackgroundColor(mSelectedItemBackgroundColor);
vh.title.setTextColor(mSelectedItemTextColor);
vh.when.setTextColor(mSelectedItemTextColor);
vh.where.setTextColor(mSelectedItemTextColor);
lp.setMargins(0, 0, 0, 0);
vh.textContainer.setLayoutParams(lp);
} else {
lp.setMargins(0, 0, (int)mItemRightMargin, 0);
vh.textContainer.setLayoutParams(lp);
}
}
}
if (DEBUGLOG) {
Log.e(TAG, "getView " + position + " = " + getViewTitle(v));
}
return v;
}
private AgendaAdapter.ViewHolder mSelectedVH = null;
private int findEventPositionNearestTime(Time time, long id) {
DayAdapterInfo info = getAdapterInfoByTime(time);
int pos = -1;
if (info != null) {
pos = info.offset + info.dayAdapter.findEventPositionNearestTime(time, id);
}
if (DEBUGLOG) Log.e(TAG, "findEventPositionNearestTime " + time + " id:" + id + " =" + pos);
return pos;
}
protected DayAdapterInfo getAdapterInfoByPosition(int position) {
synchronized (mAdapterInfos) {
if (mLastUsedInfo != null && mLastUsedInfo.offset <= position
&& position < (mLastUsedInfo.offset + mLastUsedInfo.size)) {
return mLastUsedInfo;
}
for (DayAdapterInfo info : mAdapterInfos) {
if (info.offset <= position
&& position < (info.offset + info.size)) {
mLastUsedInfo = info;
return info;
}
}
}
return null;
}
private DayAdapterInfo getAdapterInfoByTime(Time time) {
if (DEBUGLOG) Log.e(TAG, "getAdapterInfoByTime " + time.toString());
Time tmpTime = new Time(time);
long timeInMillis = tmpTime.normalize(true);
int day = Time.getJulianDay(timeInMillis, tmpTime.gmtoff);
synchronized (mAdapterInfos) {
for (DayAdapterInfo info : mAdapterInfos) {
if (info.start <= day && day <= info.end) {
return info;
}
}
}
return null;
}
public EventInfo getEventByPosition(final int positionInListView) {
return getEventByPosition(positionInListView, true);
}
/**
* Return the event info for a given position in the adapter
* @param positionInListView
* @param returnEventStartDay If true, return actual event startday. Otherwise
* return agenda date-header date as the startDay.
* The two will differ for multi-day events after the first day.
* @return
*/
public EventInfo getEventByPosition(final int positionInListView,
boolean returnEventStartDay) {
if (DEBUGLOG) Log.e(TAG, "getEventByPosition " + positionInListView);
if (positionInListView < 0) {
return null;
}
final int positionInAdapter = positionInListView - OFF_BY_ONE_BUG;
DayAdapterInfo info = getAdapterInfoByPosition(positionInAdapter);
if (info == null) {
return null;
}
int cursorPosition = info.dayAdapter.getCursorPosition(positionInAdapter - info.offset);
if (cursorPosition == Integer.MIN_VALUE) {
return null;
}
boolean isDayHeader = false;
if (cursorPosition < 0) {
cursorPosition = -cursorPosition;
isDayHeader = true;
}
if (cursorPosition < info.cursor.getCount()) {
EventInfo ei = buildEventInfoFromCursor(info.cursor, cursorPosition, isDayHeader);
if (!returnEventStartDay && !isDayHeader) {
ei.startDay = info.dayAdapter.findJulianDayFromPosition(positionInAdapter -
info.offset);
}
return ei;
}
return null;
}
private EventInfo buildEventInfoFromCursor(final Cursor cursor, int cursorPosition,
boolean isDayHeader) {
if (cursorPosition == -1) {
cursor.moveToFirst();
} else {
cursor.moveToPosition(cursorPosition);
}
EventInfo event = new EventInfo();
event.begin = cursor.getLong(AgendaWindowAdapter.INDEX_BEGIN);
event.end = cursor.getLong(AgendaWindowAdapter.INDEX_END);
event.startDay = cursor.getInt(AgendaWindowAdapter.INDEX_START_DAY);
event.allDay = cursor.getInt(AgendaWindowAdapter.INDEX_ALL_DAY) != 0;
if (event.allDay) { // UTC
Time time = new Time(mTimeZone);
time.setJulianDay(Time.getJulianDay(event.begin, 0));
event.begin = time.toMillis(false /* use isDst */);
} else if (isDayHeader) { // Trim to midnight.
Time time = new Time(mTimeZone);
time.set(event.begin);
time.hour = 0;
time.minute = 0;
time.second = 0;
event.begin = time.toMillis(false /* use isDst */);
}
if (!isDayHeader) {
if (event.allDay) {
Time time = new Time(mTimeZone);
time.setJulianDay(Time.getJulianDay(event.end, 0));
event.end = time.toMillis(false /* use isDst */);
} else {
event.end = cursor.getLong(AgendaWindowAdapter.INDEX_END);
}
event.id = cursor.getLong(AgendaWindowAdapter.INDEX_EVENT_ID);
}
return event;
}
public void refresh(Time goToTime, long id, String searchQuery, boolean forced,
boolean refreshEventInfo) {
if (searchQuery != null) {
mSearchQuery = searchQuery;
}
if (DEBUGLOG) {
Log.e(TAG, this + ": refresh " + goToTime.toString() + " id " + id
+ ((searchQuery != null) ? searchQuery : "")
+ (forced ? " forced" : " not forced")
+ (refreshEventInfo ? " refresh event info" : ""));
}
int startDay = Time.getJulianDay(goToTime.toMillis(false), goToTime.gmtoff);
if (!forced && isInRange(startDay, startDay)) {
// No need to re-query
if (!mAgendaListView.isEventVisible(goToTime, id)) {
int gotoPosition = findEventPositionNearestTime(goToTime, id);
if (gotoPosition > 0) {
mAgendaListView.setSelectionFromTop(gotoPosition +
OFF_BY_ONE_BUG, mStickyHeaderSize);
if (mListViewScrollState == OnScrollListener.SCROLL_STATE_FLING) {
mAgendaListView.smoothScrollBy(0, 0);
}
if (refreshEventInfo) {
long newInstanceId = findInstanceIdFromPosition(gotoPosition);
if (newInstanceId != getSelectedInstanceId()) {
setSelectedInstanceId(newInstanceId);
new Handler().post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
Cursor tempCursor = getCursorByPosition(gotoPosition);
if (tempCursor != null) {
int tempCursorPosition = getCursorPositionByPosition(gotoPosition);
EventInfo event =
buildEventInfoFromCursor(tempCursor, tempCursorPosition,
false);
CalendarController.getInstance(mContext)
.sendEventRelatedEventWithExtra(this, EventType.VIEW_EVENT,
event.id, event.begin, event.end, 0,
0, CalendarController.EventInfo.buildViewExtraLong(
Attendees.ATTENDEE_STATUS_NONE,
event.allDay), -1);
}
}
}
}
Time actualTime = new Time(mTimeZone);
actualTime.set(goToTime);
CalendarController.getInstance(mContext).sendEvent(this, EventType.UPDATE_TITLE,
actualTime, actualTime, -1, ViewType.CURRENT);
}
return;
}
// If AllInOneActivity is sending a second GOTO event(in OnResume), ignore it.
if (!mCleanQueryInitiated || searchQuery != null) {
// Query for a total of MIN_QUERY_DURATION days
int endDay = startDay + MIN_QUERY_DURATION;
mSelectedInstanceId = -1;
mCleanQueryInitiated = true;
queueQuery(startDay, endDay, goToTime, searchQuery, QUERY_TYPE_CLEAN, id);
// Pre-fetch more data to overcome a race condition in AgendaListView.shiftSelection
// Queuing more data with the goToTime set to the selected time skips the call to
// shiftSelection on refresh.
mOlderRequests++;
queueQuery(0, 0, goToTime, searchQuery, QUERY_TYPE_OLDER, id);
mNewerRequests++;
queueQuery(0, 0, goToTime, searchQuery, QUERY_TYPE_NEWER, id);
}
}
public void close() {
mShuttingDown = true;
pruneAdapterInfo(QUERY_TYPE_CLEAN);
if (mQueryHandler != null) {
mQueryHandler.cancelOperation(0);
}
}
private DayAdapterInfo pruneAdapterInfo(int queryType) {
synchronized (mAdapterInfos) {
DayAdapterInfo recycleMe = null;
if (!mAdapterInfos.isEmpty()) {
if (mAdapterInfos.size() >= MAX_NUM_OF_ADAPTERS) {
if (queryType == QUERY_TYPE_NEWER) {
recycleMe = mAdapterInfos.removeFirst();
} else if (queryType == QUERY_TYPE_OLDER) {
recycleMe = mAdapterInfos.removeLast();
// Keep the size only if the oldest items are removed.
recycleMe.size = 0;
}
if (recycleMe != null) {
if (recycleMe.cursor != null) {
recycleMe.cursor.close();
}
return recycleMe;
}
}
if (mRowCount == 0 || queryType == QUERY_TYPE_CLEAN) {
mRowCount = 0;
int deletedRows = 0;
DayAdapterInfo info;
do {
info = mAdapterInfos.poll();
if (info != null) {
// TODO the following causes ANR's. Do this in a thread.
info.cursor.close();
deletedRows += info.size;
recycleMe = info;
}
} while (info != null);
if (recycleMe != null) {
recycleMe.cursor = null;
recycleMe.size = deletedRows;
}
}
}
return recycleMe;
}
}
private String buildQuerySelection() {
// Respect the preference to show/hide declined events
if (mHideDeclined) {
return Calendars.VISIBLE + "=1 AND "
+ Instances.SELF_ATTENDEE_STATUS + "!="
+ Attendees.ATTENDEE_STATUS_DECLINED;
} else {
return Calendars.VISIBLE + "=1";
}
}
private Uri buildQueryUri(int start, int end, String searchQuery) {
Uri rootUri = searchQuery == null ?
Instances.CONTENT_BY_DAY_URI :
Instances.CONTENT_SEARCH_BY_DAY_URI;
Uri.Builder builder = rootUri.buildUpon();
ContentUris.appendId(builder, start);
ContentUris.appendId(builder, end);
if (searchQuery != null) {
builder.appendPath(searchQuery);
}
return builder.build();
}
private boolean isInRange(int start, int end) {
synchronized (mAdapterInfos) {
if (mAdapterInfos.isEmpty()) {
return false;
}
return mAdapterInfos.getFirst().start <= start && end <= mAdapterInfos.getLast().end;
}
}
private int calculateQueryDuration(int start, int end) {
int queryDuration = MAX_QUERY_DURATION;
if (mRowCount != 0) {
queryDuration = IDEAL_NUM_OF_EVENTS * (end - start + 1) / mRowCount;
}
if (queryDuration > MAX_QUERY_DURATION) {
queryDuration = MAX_QUERY_DURATION;
} else if (queryDuration < MIN_QUERY_DURATION) {
queryDuration = MIN_QUERY_DURATION;
}
return queryDuration;
}
private boolean queueQuery(int start, int end, Time goToTime,
String searchQuery, int queryType, long id) {
QuerySpec queryData = new QuerySpec(queryType);
queryData.goToTime = goToTime;
queryData.start = start;
queryData.end = end;
queryData.searchQuery = searchQuery;
queryData.id = id;
return queueQuery(queryData);
}
private boolean queueQuery(QuerySpec queryData) {
queryData.searchQuery = mSearchQuery;
Boolean queuedQuery;
synchronized (mQueryQueue) {
queuedQuery = false;
Boolean doQueryNow = mQueryQueue.isEmpty();
mQueryQueue.add(queryData);
queuedQuery = true;
if (doQueryNow) {
doQuery(queryData);
}
}
return queuedQuery;
}
private void doQuery(QuerySpec queryData) {
if (!mAdapterInfos.isEmpty()) {
int start = mAdapterInfos.getFirst().start;
int end = mAdapterInfos.getLast().end;
int queryDuration = calculateQueryDuration(start, end);
switch(queryData.queryType) {
case QUERY_TYPE_OLDER:
queryData.end = start - 1;
queryData.start = queryData.end - queryDuration;
break;
case QUERY_TYPE_NEWER:
queryData.start = end + 1;
queryData.end = queryData.start + queryDuration;
break;
}
// By "compacting" cursors, this fixes the disco/ping-pong problem
// b/5311977
if (mRowCount < 20 && queryData.queryType != QUERY_TYPE_CLEAN) {
if (DEBUGLOG) {
Log.e(TAG, "Compacting cursor: mRowCount=" + mRowCount
+ " totalStart:" + start
+ " totalEnd:" + end
+ " query.start:" + queryData.start
+ " query.end:" + queryData.end);
}
queryData.queryType = QUERY_TYPE_CLEAN;
if (queryData.start > start) {
queryData.start = start;
}
if (queryData.end < end) {
queryData.end = end;
}
}
}
if (BASICLOG) {
Time time = new Time(mTimeZone);
time.setJulianDay(queryData.start);
Time time2 = new Time(mTimeZone);
time2.setJulianDay(queryData.end);
Log.v(TAG, "startQuery: " + time.toString() + " to "
+ time2.toString() + " then go to " + queryData.goToTime);
}
mQueryHandler.cancelOperation(0);
if (BASICLOG) queryData.queryStartMillis = System.nanoTime();
Uri queryUri = buildQueryUri(
queryData.start, queryData.end, queryData.searchQuery);
mQueryHandler.startQuery(0, queryData, queryUri,
PROJECTION, buildQuerySelection(), null,
AGENDA_SORT_ORDER);
}
private String formatDateString(int julianDay) {
Time time = new Time(mTimeZone);
time.setJulianDay(julianDay);
long millis = time.toMillis(false);
mStringBuilder.setLength(0);
return DateUtils.formatDateRange(mContext, mFormatter, millis, millis,
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_MONTH, mTimeZone).toString();
}
private void updateHeaderFooter(final int start, final int end) {
mHeaderView.setText(mContext.getString(R.string.show_older_events,
formatDateString(start)));
mFooterView.setText(mContext.getString(R.string.show_newer_events,
formatDateString(end)));
}
private class QueryHandler extends AsyncQueryHandler {
public QueryHandler(ContentResolver cr) {
super(cr);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
QuerySpec data = (QuerySpec)cookie;
if (BASICLOG) {
long queryEndMillis = System.nanoTime();
Log.e(TAG, "Query time(ms): "
+ (queryEndMillis - data.queryStartMillis) / 1000000
+ " Count: " + cursor.getCount());
}
if (data.queryType == QUERY_TYPE_CLEAN) {
mCleanQueryInitiated = false;
}
if (mShuttingDown) {
cursor.close();
return;
}
// Notify Listview of changes and update position
int cursorSize = cursor.getCount();
if (cursorSize > 0 || mAdapterInfos.isEmpty() || data.queryType == QUERY_TYPE_CLEAN) {
final int listPositionOffset = processNewCursor(data, cursor);
int newPosition = -1;
if (data.goToTime == null) { // Typical Scrolling type query
notifyDataSetChanged();
if (listPositionOffset != 0) {
mAgendaListView.shiftSelection(listPositionOffset);
}
} else { // refresh() called. Go to the designated position
final Time goToTime = data.goToTime;
notifyDataSetChanged();
newPosition = findEventPositionNearestTime(goToTime, data.id);
if (newPosition >= 0) {
if (mListViewScrollState == OnScrollListener.SCROLL_STATE_FLING) {
mAgendaListView.smoothScrollBy(0, 0);
}
mAgendaListView.setSelectionFromTop(newPosition + OFF_BY_ONE_BUG,
mStickyHeaderSize);
Time actualTime = new Time(mTimeZone);
actualTime.set(goToTime);
CalendarController.getInstance(mContext).sendEvent(this,
EventType.UPDATE_TITLE, actualTime, actualTime, -1,
ViewType.CURRENT);
}
if (DEBUGLOG) {
Log.e(TAG, "Setting listview to " +
"findEventPositionNearestTime: " + (newPosition + OFF_BY_ONE_BUG));
}
}
// Make sure we change the selected instance Id only on a clean query and we
// do not have one set already
if (mSelectedInstanceId == -1 && newPosition != -1 &&
data.queryType == QUERY_TYPE_CLEAN) {
if (data.id != -1 || data.goToTime != null) {
mSelectedInstanceId = findInstanceIdFromPosition(newPosition);
}
}
// size == 1 means a fresh query. Possibly after the data changed.
// Let's check whether mSelectedInstanceId is still valid.
if (mAdapterInfos.size() == 1 && mSelectedInstanceId != -1) {
boolean found = false;
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
if (mSelectedInstanceId == cursor
.getLong(AgendaWindowAdapter.INDEX_INSTANCE_ID)) {
found = true;
break;
}
};
if (!found) {
mSelectedInstanceId = -1;
}
}
// Show the requested event
if (mShowEventOnStart && data.queryType == QUERY_TYPE_CLEAN) {
Cursor tempCursor = null;
int tempCursorPosition = -1;
// If no valid event is selected , just pick the first one
if (mSelectedInstanceId == -1) {
if (cursor.moveToFirst()) {
mSelectedInstanceId = cursor
.getLong(AgendaWindowAdapter.INDEX_INSTANCE_ID);
// Set up a dummy view holder so we have the right all day
// info when the view is created.
// TODO determine the full set of what might be useful to
// know about the selected view and fill it in.
mSelectedVH = new AgendaAdapter.ViewHolder();
mSelectedVH.allDay =
cursor.getInt(AgendaWindowAdapter.INDEX_ALL_DAY) != 0;
tempCursor = cursor;
}
} else if (newPosition != -1) {
tempCursor = getCursorByPosition(newPosition);
tempCursorPosition = getCursorPositionByPosition(newPosition);
}
if (tempCursor != null) {
EventInfo event = buildEventInfoFromCursor(tempCursor, tempCursorPosition,
false);
CalendarController.getInstance(mContext).sendEventRelatedEventWithExtra(
this, EventType.VIEW_EVENT, event.id, event.begin,
event.end, 0, 0, CalendarController.EventInfo.buildViewExtraLong(
Attendees.ATTENDEE_STATUS_NONE, event.allDay), -1);
}
}
} else {
cursor.close();
}
// Update header and footer
if (!mDoneSettingUpHeaderFooter) {
OnClickListener headerFooterOnClickListener = new OnClickListener() {
public void onClick(View v) {
if (v == mHeaderView) {
queueQuery(new QuerySpec(QUERY_TYPE_OLDER));
} else {
queueQuery(new QuerySpec(QUERY_TYPE_NEWER));
}
}};
mHeaderView.setOnClickListener(headerFooterOnClickListener);
mFooterView.setOnClickListener(headerFooterOnClickListener);
mAgendaListView.addFooterView(mFooterView);
mDoneSettingUpHeaderFooter = true;
}
synchronized (mQueryQueue) {
int totalAgendaRangeStart = -1;
int totalAgendaRangeEnd = -1;
if (cursorSize != 0) {
// Remove the query that just completed
QuerySpec x = mQueryQueue.poll();
if (BASICLOG && !x.equals(data)) {
Log.e(TAG, "onQueryComplete - cookie != head of queue");
}
mEmptyCursorCount = 0;
if (data.queryType == QUERY_TYPE_NEWER) {
mNewerRequestsProcessed++;
} else if (data.queryType == QUERY_TYPE_OLDER) {
mOlderRequestsProcessed++;
}
totalAgendaRangeStart = mAdapterInfos.getFirst().start;
totalAgendaRangeEnd = mAdapterInfos.getLast().end;
} else { // CursorSize == 0
QuerySpec querySpec = mQueryQueue.peek();
// Update Adapter Info with new start and end date range
if (!mAdapterInfos.isEmpty()) {
DayAdapterInfo first = mAdapterInfos.getFirst();
DayAdapterInfo last = mAdapterInfos.getLast();
if (first.start - 1 <= querySpec.end && querySpec.start < first.start) {
first.start = querySpec.start;
}
if (querySpec.start <= last.end + 1 && last.end < querySpec.end) {
last.end = querySpec.end;
}
totalAgendaRangeStart = first.start;
totalAgendaRangeEnd = last.end;
} else {
totalAgendaRangeStart = querySpec.start;
totalAgendaRangeEnd = querySpec.end;
}
// Update query specification with expanded search range
// and maybe rerun query
switch (querySpec.queryType) {
case QUERY_TYPE_OLDER:
totalAgendaRangeStart = querySpec.start;
querySpec.start -= MAX_QUERY_DURATION;
break;
case QUERY_TYPE_NEWER:
totalAgendaRangeEnd = querySpec.end;
querySpec.end += MAX_QUERY_DURATION;
break;
case QUERY_TYPE_CLEAN:
totalAgendaRangeStart = querySpec.start;
totalAgendaRangeEnd = querySpec.end;
querySpec.start -= MAX_QUERY_DURATION / 2;
querySpec.end += MAX_QUERY_DURATION / 2;
break;
}
if (++mEmptyCursorCount > RETRIES_ON_NO_DATA) {
// Nothing in the cursor again. Dropping query
mQueryQueue.poll();
}
}
updateHeaderFooter(totalAgendaRangeStart, totalAgendaRangeEnd);
// Go over the events and mark the first day after yesterday
// that has events in it
+ // If the range of adapters doesn't include yesterday, skip marking it since it will
+ // mark the first day in the adapters.
synchronized (mAdapterInfos) {
DayAdapterInfo info = mAdapterInfos.getFirst();
- if (info != null) {
- Time time = new Time(mTimeZone);
- long now = System.currentTimeMillis();
- time.set(now);
- int JulianToday = Time.getJulianDay(now, time.gmtoff);
+ Time time = new Time(mTimeZone);
+ long now = System.currentTimeMillis();
+ time.set(now);
+ int JulianToday = Time.getJulianDay(now, time.gmtoff);
+ if (info != null && JulianToday >= info.start && JulianToday
+ <= mAdapterInfos.getLast().end) {
Iterator<DayAdapterInfo> iter = mAdapterInfos.iterator();
boolean foundDay = false;
while (iter.hasNext() && !foundDay) {
info = iter.next();
for (int i = 0; i < info.size; i++) {
if (info.dayAdapter.findJulianDayFromPosition(i) >= JulianToday) {
info.dayAdapter.setAsFirstDayAfterYesterday(i);
foundDay = true;
break;
}
}
}
}
}
// Fire off the next query if any
Iterator<QuerySpec> it = mQueryQueue.iterator();
while (it.hasNext()) {
QuerySpec queryData = it.next();
if (queryData.queryType == QUERY_TYPE_CLEAN
|| !isInRange(queryData.start, queryData.end)) {
// Query accepted
if (DEBUGLOG) Log.e(TAG, "Query accepted. QueueSize:" + mQueryQueue.size());
doQuery(queryData);
break;
} else {
// Query rejected
it.remove();
if (DEBUGLOG) Log.e(TAG, "Query rejected. QueueSize:" + mQueryQueue.size());
}
}
}
if (BASICLOG) {
for (DayAdapterInfo info3 : mAdapterInfos) {
Log.e(TAG, "> " + info3.toString());
}
}
}
/*
* Update the adapter info array with a the new cursor. Close out old
* cursors as needed.
*
* @return number of rows removed from the beginning
*/
private int processNewCursor(QuerySpec data, Cursor cursor) {
synchronized (mAdapterInfos) {
// Remove adapter info's from adapterInfos as needed
DayAdapterInfo info = pruneAdapterInfo(data.queryType);
int listPositionOffset = 0;
if (info == null) {
info = new DayAdapterInfo(mContext);
} else {
if (DEBUGLOG)
Log.e(TAG, "processNewCursor listPositionOffsetA="
+ -info.size);
listPositionOffset = -info.size;
}
// Setup adapter info
info.start = data.start;
info.end = data.end;
info.cursor = cursor;
info.dayAdapter.changeCursor(info);
info.size = info.dayAdapter.getCount();
// Insert into adapterInfos
if (mAdapterInfos.isEmpty()
|| data.end <= mAdapterInfos.getFirst().start) {
mAdapterInfos.addFirst(info);
listPositionOffset += info.size;
} else if (BASICLOG && data.start < mAdapterInfos.getLast().end) {
mAdapterInfos.addLast(info);
for (DayAdapterInfo info2 : mAdapterInfos) {
Log.e("========== BUG ==", info2.toString());
}
} else {
mAdapterInfos.addLast(info);
}
// Update offsets in adapterInfos
mRowCount = 0;
for (DayAdapterInfo info3 : mAdapterInfos) {
info3.offset = mRowCount;
mRowCount += info3.size;
}
mLastUsedInfo = null;
return listPositionOffset;
}
}
}
static String getViewTitle(View x) {
String title = "";
if (x != null) {
Object yy = x.getTag();
if (yy instanceof AgendaAdapter.ViewHolder) {
TextView tv = ((AgendaAdapter.ViewHolder) yy).title;
if (tv != null) {
title = (String) tv.getText();
}
} else if (yy != null) {
TextView dateView = ((AgendaByDayAdapter.ViewHolder) yy).dateView;
if (dateView != null) {
title = (String) dateView.getText();
}
}
}
return title;
}
public void onResume() {
mTZUpdater.run();
}
public void setHideDeclinedEvents(boolean hideDeclined) {
mHideDeclined = hideDeclined;
}
public void setSelectedView(View v) {
if (v != null) {
Object vh = v.getTag();
if (vh instanceof AgendaAdapter.ViewHolder) {
mSelectedVH = (AgendaAdapter.ViewHolder) vh;
if (mSelectedInstanceId != mSelectedVH.instanceId) {
mSelectedInstanceId = mSelectedVH.instanceId;
notifyDataSetChanged();
}
}
}
}
public AgendaAdapter.ViewHolder getSelectedViewHolder() {
return mSelectedVH;
}
public long getSelectedInstanceId() {
return mSelectedInstanceId;
}
public void setSelectedInstanceId(long selectedInstanceId) {
mSelectedInstanceId = selectedInstanceId;
mSelectedVH = null;
}
private long findInstanceIdFromPosition(int position) {
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
return info.dayAdapter.getInstanceId(position - info.offset);
}
return -1;
}
private Cursor getCursorByPosition(int position) {
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
return info.cursor;
}
return null;
}
private int getCursorPositionByPosition(int position) {
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
return info.dayAdapter.getCursorPosition(position - info.offset);
}
return -1;
}
// Implementation of HeaderIndexer interface for StickyHeeaderListView
// Returns the location of the day header of a specific event specified in the position
// in the adapter
@Override
public int getHeaderPositionFromItemPosition(int position) {
// For phone configuration, return -1 so there will be no sticky header
if (!mIsTabletConfig) {
return -1;
}
DayAdapterInfo info = getAdapterInfoByPosition(position);
if (info != null) {
int pos = info.dayAdapter.getHeaderPosition(position - info.offset);
return (pos != -1)?(pos + info.offset):-1;
}
return -1;
}
// Returns the number of events for a specific day header
@Override
public int getHeaderItemsNumber(int headerPosition) {
if (headerPosition < 0 || !mIsTabletConfig) {
return -1;
}
DayAdapterInfo info = getAdapterInfoByPosition(headerPosition);
if (info != null) {
return info.dayAdapter.getHeaderItemsCount(headerPosition - info.offset);
}
return -1;
}
@Override
public void OnHeaderHeightChanged(int height) {
mStickyHeaderSize = height;
}
public int getStickyHeaderHeight() {
return mStickyHeaderSize;
}
public void setScrollState(int state) {
mListViewScrollState = state;
}
}
| false | true | protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
QuerySpec data = (QuerySpec)cookie;
if (BASICLOG) {
long queryEndMillis = System.nanoTime();
Log.e(TAG, "Query time(ms): "
+ (queryEndMillis - data.queryStartMillis) / 1000000
+ " Count: " + cursor.getCount());
}
if (data.queryType == QUERY_TYPE_CLEAN) {
mCleanQueryInitiated = false;
}
if (mShuttingDown) {
cursor.close();
return;
}
// Notify Listview of changes and update position
int cursorSize = cursor.getCount();
if (cursorSize > 0 || mAdapterInfos.isEmpty() || data.queryType == QUERY_TYPE_CLEAN) {
final int listPositionOffset = processNewCursor(data, cursor);
int newPosition = -1;
if (data.goToTime == null) { // Typical Scrolling type query
notifyDataSetChanged();
if (listPositionOffset != 0) {
mAgendaListView.shiftSelection(listPositionOffset);
}
} else { // refresh() called. Go to the designated position
final Time goToTime = data.goToTime;
notifyDataSetChanged();
newPosition = findEventPositionNearestTime(goToTime, data.id);
if (newPosition >= 0) {
if (mListViewScrollState == OnScrollListener.SCROLL_STATE_FLING) {
mAgendaListView.smoothScrollBy(0, 0);
}
mAgendaListView.setSelectionFromTop(newPosition + OFF_BY_ONE_BUG,
mStickyHeaderSize);
Time actualTime = new Time(mTimeZone);
actualTime.set(goToTime);
CalendarController.getInstance(mContext).sendEvent(this,
EventType.UPDATE_TITLE, actualTime, actualTime, -1,
ViewType.CURRENT);
}
if (DEBUGLOG) {
Log.e(TAG, "Setting listview to " +
"findEventPositionNearestTime: " + (newPosition + OFF_BY_ONE_BUG));
}
}
// Make sure we change the selected instance Id only on a clean query and we
// do not have one set already
if (mSelectedInstanceId == -1 && newPosition != -1 &&
data.queryType == QUERY_TYPE_CLEAN) {
if (data.id != -1 || data.goToTime != null) {
mSelectedInstanceId = findInstanceIdFromPosition(newPosition);
}
}
// size == 1 means a fresh query. Possibly after the data changed.
// Let's check whether mSelectedInstanceId is still valid.
if (mAdapterInfos.size() == 1 && mSelectedInstanceId != -1) {
boolean found = false;
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
if (mSelectedInstanceId == cursor
.getLong(AgendaWindowAdapter.INDEX_INSTANCE_ID)) {
found = true;
break;
}
};
if (!found) {
mSelectedInstanceId = -1;
}
}
// Show the requested event
if (mShowEventOnStart && data.queryType == QUERY_TYPE_CLEAN) {
Cursor tempCursor = null;
int tempCursorPosition = -1;
// If no valid event is selected , just pick the first one
if (mSelectedInstanceId == -1) {
if (cursor.moveToFirst()) {
mSelectedInstanceId = cursor
.getLong(AgendaWindowAdapter.INDEX_INSTANCE_ID);
// Set up a dummy view holder so we have the right all day
// info when the view is created.
// TODO determine the full set of what might be useful to
// know about the selected view and fill it in.
mSelectedVH = new AgendaAdapter.ViewHolder();
mSelectedVH.allDay =
cursor.getInt(AgendaWindowAdapter.INDEX_ALL_DAY) != 0;
tempCursor = cursor;
}
} else if (newPosition != -1) {
tempCursor = getCursorByPosition(newPosition);
tempCursorPosition = getCursorPositionByPosition(newPosition);
}
if (tempCursor != null) {
EventInfo event = buildEventInfoFromCursor(tempCursor, tempCursorPosition,
false);
CalendarController.getInstance(mContext).sendEventRelatedEventWithExtra(
this, EventType.VIEW_EVENT, event.id, event.begin,
event.end, 0, 0, CalendarController.EventInfo.buildViewExtraLong(
Attendees.ATTENDEE_STATUS_NONE, event.allDay), -1);
}
}
} else {
cursor.close();
}
// Update header and footer
if (!mDoneSettingUpHeaderFooter) {
OnClickListener headerFooterOnClickListener = new OnClickListener() {
public void onClick(View v) {
if (v == mHeaderView) {
queueQuery(new QuerySpec(QUERY_TYPE_OLDER));
} else {
queueQuery(new QuerySpec(QUERY_TYPE_NEWER));
}
}};
mHeaderView.setOnClickListener(headerFooterOnClickListener);
mFooterView.setOnClickListener(headerFooterOnClickListener);
mAgendaListView.addFooterView(mFooterView);
mDoneSettingUpHeaderFooter = true;
}
synchronized (mQueryQueue) {
int totalAgendaRangeStart = -1;
int totalAgendaRangeEnd = -1;
if (cursorSize != 0) {
// Remove the query that just completed
QuerySpec x = mQueryQueue.poll();
if (BASICLOG && !x.equals(data)) {
Log.e(TAG, "onQueryComplete - cookie != head of queue");
}
mEmptyCursorCount = 0;
if (data.queryType == QUERY_TYPE_NEWER) {
mNewerRequestsProcessed++;
} else if (data.queryType == QUERY_TYPE_OLDER) {
mOlderRequestsProcessed++;
}
totalAgendaRangeStart = mAdapterInfos.getFirst().start;
totalAgendaRangeEnd = mAdapterInfos.getLast().end;
} else { // CursorSize == 0
QuerySpec querySpec = mQueryQueue.peek();
// Update Adapter Info with new start and end date range
if (!mAdapterInfos.isEmpty()) {
DayAdapterInfo first = mAdapterInfos.getFirst();
DayAdapterInfo last = mAdapterInfos.getLast();
if (first.start - 1 <= querySpec.end && querySpec.start < first.start) {
first.start = querySpec.start;
}
if (querySpec.start <= last.end + 1 && last.end < querySpec.end) {
last.end = querySpec.end;
}
totalAgendaRangeStart = first.start;
totalAgendaRangeEnd = last.end;
} else {
totalAgendaRangeStart = querySpec.start;
totalAgendaRangeEnd = querySpec.end;
}
// Update query specification with expanded search range
// and maybe rerun query
switch (querySpec.queryType) {
case QUERY_TYPE_OLDER:
totalAgendaRangeStart = querySpec.start;
querySpec.start -= MAX_QUERY_DURATION;
break;
case QUERY_TYPE_NEWER:
totalAgendaRangeEnd = querySpec.end;
querySpec.end += MAX_QUERY_DURATION;
break;
case QUERY_TYPE_CLEAN:
totalAgendaRangeStart = querySpec.start;
totalAgendaRangeEnd = querySpec.end;
querySpec.start -= MAX_QUERY_DURATION / 2;
querySpec.end += MAX_QUERY_DURATION / 2;
break;
}
if (++mEmptyCursorCount > RETRIES_ON_NO_DATA) {
// Nothing in the cursor again. Dropping query
mQueryQueue.poll();
}
}
updateHeaderFooter(totalAgendaRangeStart, totalAgendaRangeEnd);
// Go over the events and mark the first day after yesterday
// that has events in it
synchronized (mAdapterInfos) {
DayAdapterInfo info = mAdapterInfos.getFirst();
if (info != null) {
Time time = new Time(mTimeZone);
long now = System.currentTimeMillis();
time.set(now);
int JulianToday = Time.getJulianDay(now, time.gmtoff);
Iterator<DayAdapterInfo> iter = mAdapterInfos.iterator();
boolean foundDay = false;
while (iter.hasNext() && !foundDay) {
info = iter.next();
for (int i = 0; i < info.size; i++) {
if (info.dayAdapter.findJulianDayFromPosition(i) >= JulianToday) {
info.dayAdapter.setAsFirstDayAfterYesterday(i);
foundDay = true;
break;
}
}
}
}
}
// Fire off the next query if any
Iterator<QuerySpec> it = mQueryQueue.iterator();
while (it.hasNext()) {
QuerySpec queryData = it.next();
if (queryData.queryType == QUERY_TYPE_CLEAN
|| !isInRange(queryData.start, queryData.end)) {
// Query accepted
if (DEBUGLOG) Log.e(TAG, "Query accepted. QueueSize:" + mQueryQueue.size());
doQuery(queryData);
break;
} else {
// Query rejected
it.remove();
if (DEBUGLOG) Log.e(TAG, "Query rejected. QueueSize:" + mQueryQueue.size());
}
}
}
if (BASICLOG) {
for (DayAdapterInfo info3 : mAdapterInfos) {
Log.e(TAG, "> " + info3.toString());
}
}
}
| protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
QuerySpec data = (QuerySpec)cookie;
if (BASICLOG) {
long queryEndMillis = System.nanoTime();
Log.e(TAG, "Query time(ms): "
+ (queryEndMillis - data.queryStartMillis) / 1000000
+ " Count: " + cursor.getCount());
}
if (data.queryType == QUERY_TYPE_CLEAN) {
mCleanQueryInitiated = false;
}
if (mShuttingDown) {
cursor.close();
return;
}
// Notify Listview of changes and update position
int cursorSize = cursor.getCount();
if (cursorSize > 0 || mAdapterInfos.isEmpty() || data.queryType == QUERY_TYPE_CLEAN) {
final int listPositionOffset = processNewCursor(data, cursor);
int newPosition = -1;
if (data.goToTime == null) { // Typical Scrolling type query
notifyDataSetChanged();
if (listPositionOffset != 0) {
mAgendaListView.shiftSelection(listPositionOffset);
}
} else { // refresh() called. Go to the designated position
final Time goToTime = data.goToTime;
notifyDataSetChanged();
newPosition = findEventPositionNearestTime(goToTime, data.id);
if (newPosition >= 0) {
if (mListViewScrollState == OnScrollListener.SCROLL_STATE_FLING) {
mAgendaListView.smoothScrollBy(0, 0);
}
mAgendaListView.setSelectionFromTop(newPosition + OFF_BY_ONE_BUG,
mStickyHeaderSize);
Time actualTime = new Time(mTimeZone);
actualTime.set(goToTime);
CalendarController.getInstance(mContext).sendEvent(this,
EventType.UPDATE_TITLE, actualTime, actualTime, -1,
ViewType.CURRENT);
}
if (DEBUGLOG) {
Log.e(TAG, "Setting listview to " +
"findEventPositionNearestTime: " + (newPosition + OFF_BY_ONE_BUG));
}
}
// Make sure we change the selected instance Id only on a clean query and we
// do not have one set already
if (mSelectedInstanceId == -1 && newPosition != -1 &&
data.queryType == QUERY_TYPE_CLEAN) {
if (data.id != -1 || data.goToTime != null) {
mSelectedInstanceId = findInstanceIdFromPosition(newPosition);
}
}
// size == 1 means a fresh query. Possibly after the data changed.
// Let's check whether mSelectedInstanceId is still valid.
if (mAdapterInfos.size() == 1 && mSelectedInstanceId != -1) {
boolean found = false;
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
if (mSelectedInstanceId == cursor
.getLong(AgendaWindowAdapter.INDEX_INSTANCE_ID)) {
found = true;
break;
}
};
if (!found) {
mSelectedInstanceId = -1;
}
}
// Show the requested event
if (mShowEventOnStart && data.queryType == QUERY_TYPE_CLEAN) {
Cursor tempCursor = null;
int tempCursorPosition = -1;
// If no valid event is selected , just pick the first one
if (mSelectedInstanceId == -1) {
if (cursor.moveToFirst()) {
mSelectedInstanceId = cursor
.getLong(AgendaWindowAdapter.INDEX_INSTANCE_ID);
// Set up a dummy view holder so we have the right all day
// info when the view is created.
// TODO determine the full set of what might be useful to
// know about the selected view and fill it in.
mSelectedVH = new AgendaAdapter.ViewHolder();
mSelectedVH.allDay =
cursor.getInt(AgendaWindowAdapter.INDEX_ALL_DAY) != 0;
tempCursor = cursor;
}
} else if (newPosition != -1) {
tempCursor = getCursorByPosition(newPosition);
tempCursorPosition = getCursorPositionByPosition(newPosition);
}
if (tempCursor != null) {
EventInfo event = buildEventInfoFromCursor(tempCursor, tempCursorPosition,
false);
CalendarController.getInstance(mContext).sendEventRelatedEventWithExtra(
this, EventType.VIEW_EVENT, event.id, event.begin,
event.end, 0, 0, CalendarController.EventInfo.buildViewExtraLong(
Attendees.ATTENDEE_STATUS_NONE, event.allDay), -1);
}
}
} else {
cursor.close();
}
// Update header and footer
if (!mDoneSettingUpHeaderFooter) {
OnClickListener headerFooterOnClickListener = new OnClickListener() {
public void onClick(View v) {
if (v == mHeaderView) {
queueQuery(new QuerySpec(QUERY_TYPE_OLDER));
} else {
queueQuery(new QuerySpec(QUERY_TYPE_NEWER));
}
}};
mHeaderView.setOnClickListener(headerFooterOnClickListener);
mFooterView.setOnClickListener(headerFooterOnClickListener);
mAgendaListView.addFooterView(mFooterView);
mDoneSettingUpHeaderFooter = true;
}
synchronized (mQueryQueue) {
int totalAgendaRangeStart = -1;
int totalAgendaRangeEnd = -1;
if (cursorSize != 0) {
// Remove the query that just completed
QuerySpec x = mQueryQueue.poll();
if (BASICLOG && !x.equals(data)) {
Log.e(TAG, "onQueryComplete - cookie != head of queue");
}
mEmptyCursorCount = 0;
if (data.queryType == QUERY_TYPE_NEWER) {
mNewerRequestsProcessed++;
} else if (data.queryType == QUERY_TYPE_OLDER) {
mOlderRequestsProcessed++;
}
totalAgendaRangeStart = mAdapterInfos.getFirst().start;
totalAgendaRangeEnd = mAdapterInfos.getLast().end;
} else { // CursorSize == 0
QuerySpec querySpec = mQueryQueue.peek();
// Update Adapter Info with new start and end date range
if (!mAdapterInfos.isEmpty()) {
DayAdapterInfo first = mAdapterInfos.getFirst();
DayAdapterInfo last = mAdapterInfos.getLast();
if (first.start - 1 <= querySpec.end && querySpec.start < first.start) {
first.start = querySpec.start;
}
if (querySpec.start <= last.end + 1 && last.end < querySpec.end) {
last.end = querySpec.end;
}
totalAgendaRangeStart = first.start;
totalAgendaRangeEnd = last.end;
} else {
totalAgendaRangeStart = querySpec.start;
totalAgendaRangeEnd = querySpec.end;
}
// Update query specification with expanded search range
// and maybe rerun query
switch (querySpec.queryType) {
case QUERY_TYPE_OLDER:
totalAgendaRangeStart = querySpec.start;
querySpec.start -= MAX_QUERY_DURATION;
break;
case QUERY_TYPE_NEWER:
totalAgendaRangeEnd = querySpec.end;
querySpec.end += MAX_QUERY_DURATION;
break;
case QUERY_TYPE_CLEAN:
totalAgendaRangeStart = querySpec.start;
totalAgendaRangeEnd = querySpec.end;
querySpec.start -= MAX_QUERY_DURATION / 2;
querySpec.end += MAX_QUERY_DURATION / 2;
break;
}
if (++mEmptyCursorCount > RETRIES_ON_NO_DATA) {
// Nothing in the cursor again. Dropping query
mQueryQueue.poll();
}
}
updateHeaderFooter(totalAgendaRangeStart, totalAgendaRangeEnd);
// Go over the events and mark the first day after yesterday
// that has events in it
// If the range of adapters doesn't include yesterday, skip marking it since it will
// mark the first day in the adapters.
synchronized (mAdapterInfos) {
DayAdapterInfo info = mAdapterInfos.getFirst();
Time time = new Time(mTimeZone);
long now = System.currentTimeMillis();
time.set(now);
int JulianToday = Time.getJulianDay(now, time.gmtoff);
if (info != null && JulianToday >= info.start && JulianToday
<= mAdapterInfos.getLast().end) {
Iterator<DayAdapterInfo> iter = mAdapterInfos.iterator();
boolean foundDay = false;
while (iter.hasNext() && !foundDay) {
info = iter.next();
for (int i = 0; i < info.size; i++) {
if (info.dayAdapter.findJulianDayFromPosition(i) >= JulianToday) {
info.dayAdapter.setAsFirstDayAfterYesterday(i);
foundDay = true;
break;
}
}
}
}
}
// Fire off the next query if any
Iterator<QuerySpec> it = mQueryQueue.iterator();
while (it.hasNext()) {
QuerySpec queryData = it.next();
if (queryData.queryType == QUERY_TYPE_CLEAN
|| !isInRange(queryData.start, queryData.end)) {
// Query accepted
if (DEBUGLOG) Log.e(TAG, "Query accepted. QueueSize:" + mQueryQueue.size());
doQuery(queryData);
break;
} else {
// Query rejected
it.remove();
if (DEBUGLOG) Log.e(TAG, "Query rejected. QueueSize:" + mQueryQueue.size());
}
}
}
if (BASICLOG) {
for (DayAdapterInfo info3 : mAdapterInfos) {
Log.e(TAG, "> " + info3.toString());
}
}
}
|
diff --git a/Admin/Matrix.java b/Admin/Matrix.java
index 5e6f6768..5f2cde85 100644
--- a/Admin/Matrix.java
+++ b/Admin/Matrix.java
@@ -1,277 +1,279 @@
import java.util.Vector;
import java.util.List;
import java.util.Iterator;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.IOException;
// JDOM classes used for document representation
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Attribute;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
/**
* Converts the matrix.xml file to a matrix.texi file, suitable for
* being included from gettext's nls.texi.
*
* @author Bruno Haible
*/
public class Matrix {
public static class PoFile {
String domain;
String team;
int percentage;
public PoFile (String domain, String team, int percentage) {
this.domain = domain;
this.team = team;
this.percentage = percentage;
}
}
public static class Data {
List /* of String */ domains = new Vector();
List /* of String */ teams = new Vector();
List /* of PoFile */ po_files = new Vector();
}
public static final int FALSE = 0;
public static final int TRUE = 1;
public static final int EXTERNAL = 2;
public static void spaces (PrintWriter stream, int n) {
for (int i = n; i > 0; i--)
stream.print(' ');
}
public static void main (String[] args) {
Data data = new Data();
SAXBuilder builder = new SAXBuilder(/*true*/); // "true" turns on validation
Document doc;
try {
doc = builder.build(new File("matrix.xml"));
} catch (JDOMException e) {
e.printStackTrace();
doc = null;
System.exit(1);
}
Element po_inventory = doc.getRootElement();
{
Element domains = po_inventory.getChild("domains");
Iterator i = domains.getChildren("domain").iterator();
while (i.hasNext()) {
Element domain = (Element)i.next();
data.domains.add(domain.getAttribute("name").getValue());
}
}
{
Element teams = po_inventory.getChild("teams");
Iterator i = teams.getChildren("team").iterator();
while (i.hasNext()) {
Element team = (Element)i.next();
data.teams.add(team.getAttribute("name").getValue());
}
}
{
Element po_files = po_inventory.getChild("PoFiles");
Iterator i = po_files.getChildren("po").iterator();
while (i.hasNext()) {
Element po = (Element)i.next();
String value = po.getText();
data.po_files.add(
new PoFile(
po.getAttribute("domain").getValue(),
po.getAttribute("team").getValue(),
value.equals("") ? -1 : Integer.parseInt(value)));
}
}
// Special treatment of clisp. The percentages are incorrect.
data.domains.add("clisp");
if (!data.teams.contains("en"))
data.teams.add("en");
data.po_files.add(new PoFile("clisp","en",100));
data.po_files.add(new PoFile("clisp","de",99));
data.po_files.add(new PoFile("clisp","fr",99));
data.po_files.add(new PoFile("clisp","es",90));
data.po_files.add(new PoFile("clisp","nl",90));
try {
FileWriter f = new FileWriter("matrix.texi");
BufferedWriter bf = new BufferedWriter(f);
PrintWriter stream = new PrintWriter(bf);
String[] domains = (String[])data.domains.toArray(new String[0]);
Arrays.sort(domains);
String[] teams = (String[])data.teams.toArray(new String[0]);
Arrays.sort(teams);
int ndomains = domains.length;
int nteams = teams.length;
int[][] matrix = new int[ndomains][];
for (int d = 0; d < ndomains; d++)
matrix[d] = new int[nteams];
int[] total_per_domain = new int[ndomains];
int[] total_per_team = new int[nteams];
int total = 0;
{
Iterator i = data.po_files.iterator();
while (i.hasNext()) {
PoFile po = (PoFile)i.next();
if (po.percentage >= 50) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0)
throw new Error("didn't find team \""+po.team+"\"");
matrix[d][t] = TRUE;
total_per_domain[d]++;
total_per_team[t]++;
total++;
} else if (po.percentage < 0) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
- if (t < 0)
- throw new Error("didn't find team \""+po.team+"\"");
+ if (t < 0) {
+ System.err.println(po.domain+": didn't find team \""+po.team+"\"");
+ continue;
+ }
matrix[d][t] = EXTERNAL;
}
}
}
// Split into separate tables, to keep 80 column width.
int ngroups;
int[][] groups;
if (true) {
ngroups = 3;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/3+1 };
groups[1] = new int[] { nteams/3+1, (2*nteams)/3+1 };
groups[2] = new int[] { (2*nteams)/3+1, nteams };
} else if (true) {
ngroups = 2;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/2+1 };
groups[1] = new int[] { nteams/2+1, nteams };
} else {
ngroups = 1;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams };
}
stream.println("@example");
for (int group = 0; group < ngroups; group++) {
if (group > 0)
stream.println();
stream.println("@group");
if (group == 0)
stream.print("Ready PO files ");
else
stream.print(" ");
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
for (int d = 0; d < ndomains; d++) {
stream.print(domains[d]);
spaces(stream,16 - domains[d].length());
stream.print('|');
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
if (matrix[d][t] == TRUE) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("[]");
spaces(stream,(i+1)/2);
} else if (matrix[d][t] == EXTERNAL) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("()");
spaces(stream,(i+1)/2);
} else {
spaces(stream,teams[t].length());
}
}
stream.print(' ');
stream.print('|');
if (group == ngroups-1) {
stream.print(' ');
String s = Integer.toString(total_per_domain[d]);
spaces(stream,2-s.length());
stream.print(s);
}
stream.println();
}
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
if (group == ngroups-1) {
String s = Integer.toString(nteams);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" teams ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
if (group == ngroups-1) {
String s = Integer.toString(ndomains);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" domains ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
String s = Integer.toString(total_per_team[t]);
int i = teams[t].length()-2;
spaces(stream,i/2 + (2-s.length()));
stream.print(s);
spaces(stream,(i+1)/2);
}
if (group == ngroups-1) {
stream.print(' ');
stream.print(' ');
String s = Integer.toString(total);
spaces(stream,3-s.length());
stream.print(s);
}
stream.println();
stream.println("@end group");
}
stream.println("@end example");
stream.close();
bf.close();
f.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
| true | true | public static void main (String[] args) {
Data data = new Data();
SAXBuilder builder = new SAXBuilder(/*true*/); // "true" turns on validation
Document doc;
try {
doc = builder.build(new File("matrix.xml"));
} catch (JDOMException e) {
e.printStackTrace();
doc = null;
System.exit(1);
}
Element po_inventory = doc.getRootElement();
{
Element domains = po_inventory.getChild("domains");
Iterator i = domains.getChildren("domain").iterator();
while (i.hasNext()) {
Element domain = (Element)i.next();
data.domains.add(domain.getAttribute("name").getValue());
}
}
{
Element teams = po_inventory.getChild("teams");
Iterator i = teams.getChildren("team").iterator();
while (i.hasNext()) {
Element team = (Element)i.next();
data.teams.add(team.getAttribute("name").getValue());
}
}
{
Element po_files = po_inventory.getChild("PoFiles");
Iterator i = po_files.getChildren("po").iterator();
while (i.hasNext()) {
Element po = (Element)i.next();
String value = po.getText();
data.po_files.add(
new PoFile(
po.getAttribute("domain").getValue(),
po.getAttribute("team").getValue(),
value.equals("") ? -1 : Integer.parseInt(value)));
}
}
// Special treatment of clisp. The percentages are incorrect.
data.domains.add("clisp");
if (!data.teams.contains("en"))
data.teams.add("en");
data.po_files.add(new PoFile("clisp","en",100));
data.po_files.add(new PoFile("clisp","de",99));
data.po_files.add(new PoFile("clisp","fr",99));
data.po_files.add(new PoFile("clisp","es",90));
data.po_files.add(new PoFile("clisp","nl",90));
try {
FileWriter f = new FileWriter("matrix.texi");
BufferedWriter bf = new BufferedWriter(f);
PrintWriter stream = new PrintWriter(bf);
String[] domains = (String[])data.domains.toArray(new String[0]);
Arrays.sort(domains);
String[] teams = (String[])data.teams.toArray(new String[0]);
Arrays.sort(teams);
int ndomains = domains.length;
int nteams = teams.length;
int[][] matrix = new int[ndomains][];
for (int d = 0; d < ndomains; d++)
matrix[d] = new int[nteams];
int[] total_per_domain = new int[ndomains];
int[] total_per_team = new int[nteams];
int total = 0;
{
Iterator i = data.po_files.iterator();
while (i.hasNext()) {
PoFile po = (PoFile)i.next();
if (po.percentage >= 50) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0)
throw new Error("didn't find team \""+po.team+"\"");
matrix[d][t] = TRUE;
total_per_domain[d]++;
total_per_team[t]++;
total++;
} else if (po.percentage < 0) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0)
throw new Error("didn't find team \""+po.team+"\"");
matrix[d][t] = EXTERNAL;
}
}
}
// Split into separate tables, to keep 80 column width.
int ngroups;
int[][] groups;
if (true) {
ngroups = 3;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/3+1 };
groups[1] = new int[] { nteams/3+1, (2*nteams)/3+1 };
groups[2] = new int[] { (2*nteams)/3+1, nteams };
} else if (true) {
ngroups = 2;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/2+1 };
groups[1] = new int[] { nteams/2+1, nteams };
} else {
ngroups = 1;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams };
}
stream.println("@example");
for (int group = 0; group < ngroups; group++) {
if (group > 0)
stream.println();
stream.println("@group");
if (group == 0)
stream.print("Ready PO files ");
else
stream.print(" ");
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
for (int d = 0; d < ndomains; d++) {
stream.print(domains[d]);
spaces(stream,16 - domains[d].length());
stream.print('|');
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
if (matrix[d][t] == TRUE) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("[]");
spaces(stream,(i+1)/2);
} else if (matrix[d][t] == EXTERNAL) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("()");
spaces(stream,(i+1)/2);
} else {
spaces(stream,teams[t].length());
}
}
stream.print(' ');
stream.print('|');
if (group == ngroups-1) {
stream.print(' ');
String s = Integer.toString(total_per_domain[d]);
spaces(stream,2-s.length());
stream.print(s);
}
stream.println();
}
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
if (group == ngroups-1) {
String s = Integer.toString(nteams);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" teams ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
if (group == ngroups-1) {
String s = Integer.toString(ndomains);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" domains ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
String s = Integer.toString(total_per_team[t]);
int i = teams[t].length()-2;
spaces(stream,i/2 + (2-s.length()));
stream.print(s);
spaces(stream,(i+1)/2);
}
if (group == ngroups-1) {
stream.print(' ');
stream.print(' ');
String s = Integer.toString(total);
spaces(stream,3-s.length());
stream.print(s);
}
stream.println();
stream.println("@end group");
}
stream.println("@end example");
stream.close();
bf.close();
f.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
| public static void main (String[] args) {
Data data = new Data();
SAXBuilder builder = new SAXBuilder(/*true*/); // "true" turns on validation
Document doc;
try {
doc = builder.build(new File("matrix.xml"));
} catch (JDOMException e) {
e.printStackTrace();
doc = null;
System.exit(1);
}
Element po_inventory = doc.getRootElement();
{
Element domains = po_inventory.getChild("domains");
Iterator i = domains.getChildren("domain").iterator();
while (i.hasNext()) {
Element domain = (Element)i.next();
data.domains.add(domain.getAttribute("name").getValue());
}
}
{
Element teams = po_inventory.getChild("teams");
Iterator i = teams.getChildren("team").iterator();
while (i.hasNext()) {
Element team = (Element)i.next();
data.teams.add(team.getAttribute("name").getValue());
}
}
{
Element po_files = po_inventory.getChild("PoFiles");
Iterator i = po_files.getChildren("po").iterator();
while (i.hasNext()) {
Element po = (Element)i.next();
String value = po.getText();
data.po_files.add(
new PoFile(
po.getAttribute("domain").getValue(),
po.getAttribute("team").getValue(),
value.equals("") ? -1 : Integer.parseInt(value)));
}
}
// Special treatment of clisp. The percentages are incorrect.
data.domains.add("clisp");
if (!data.teams.contains("en"))
data.teams.add("en");
data.po_files.add(new PoFile("clisp","en",100));
data.po_files.add(new PoFile("clisp","de",99));
data.po_files.add(new PoFile("clisp","fr",99));
data.po_files.add(new PoFile("clisp","es",90));
data.po_files.add(new PoFile("clisp","nl",90));
try {
FileWriter f = new FileWriter("matrix.texi");
BufferedWriter bf = new BufferedWriter(f);
PrintWriter stream = new PrintWriter(bf);
String[] domains = (String[])data.domains.toArray(new String[0]);
Arrays.sort(domains);
String[] teams = (String[])data.teams.toArray(new String[0]);
Arrays.sort(teams);
int ndomains = domains.length;
int nteams = teams.length;
int[][] matrix = new int[ndomains][];
for (int d = 0; d < ndomains; d++)
matrix[d] = new int[nteams];
int[] total_per_domain = new int[ndomains];
int[] total_per_team = new int[nteams];
int total = 0;
{
Iterator i = data.po_files.iterator();
while (i.hasNext()) {
PoFile po = (PoFile)i.next();
if (po.percentage >= 50) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0)
throw new Error("didn't find team \""+po.team+"\"");
matrix[d][t] = TRUE;
total_per_domain[d]++;
total_per_team[t]++;
total++;
} else if (po.percentage < 0) {
int d = Arrays.binarySearch(domains,po.domain);
if (d < 0)
throw new Error("didn't find domain \""+po.domain+"\"");
int t = Arrays.binarySearch(teams,po.team);
if (t < 0) {
System.err.println(po.domain+": didn't find team \""+po.team+"\"");
continue;
}
matrix[d][t] = EXTERNAL;
}
}
}
// Split into separate tables, to keep 80 column width.
int ngroups;
int[][] groups;
if (true) {
ngroups = 3;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/3+1 };
groups[1] = new int[] { nteams/3+1, (2*nteams)/3+1 };
groups[2] = new int[] { (2*nteams)/3+1, nteams };
} else if (true) {
ngroups = 2;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams/2+1 };
groups[1] = new int[] { nteams/2+1, nteams };
} else {
ngroups = 1;
groups = new int[ngroups][];
groups[0] = new int[] { 0, nteams };
}
stream.println("@example");
for (int group = 0; group < ngroups; group++) {
if (group > 0)
stream.println();
stream.println("@group");
if (group == 0)
stream.print("Ready PO files ");
else
stream.print(" ");
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
for (int d = 0; d < ndomains; d++) {
stream.print(domains[d]);
spaces(stream,16 - domains[d].length());
stream.print('|');
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
if (matrix[d][t] == TRUE) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("[]");
spaces(stream,(i+1)/2);
} else if (matrix[d][t] == EXTERNAL) {
int i = teams[t].length()-2;
spaces(stream,i/2);
stream.print("()");
spaces(stream,(i+1)/2);
} else {
spaces(stream,teams[t].length());
}
}
stream.print(' ');
stream.print('|');
if (group == ngroups-1) {
stream.print(' ');
String s = Integer.toString(total_per_domain[d]);
spaces(stream,2-s.length());
stream.print(s);
}
stream.println();
}
stream.print(" +");
for (int t = groups[group][0]; t < groups[group][1]; t++)
for (int i = teams[t].length() + 1; i > 0; i--)
stream.print('-');
stream.println("-+");
if (group == ngroups-1) {
String s = Integer.toString(nteams);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" teams ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++)
stream.print(" "+teams[t]);
stream.println();
if (group == ngroups-1) {
String s = Integer.toString(ndomains);
spaces(stream,4-s.length());
stream.print(s);
stream.print(" domains ");
} else {
stream.print(" ");
}
for (int t = groups[group][0]; t < groups[group][1]; t++) {
stream.print(' ');
String s = Integer.toString(total_per_team[t]);
int i = teams[t].length()-2;
spaces(stream,i/2 + (2-s.length()));
stream.print(s);
spaces(stream,(i+1)/2);
}
if (group == ngroups-1) {
stream.print(' ');
stream.print(' ');
String s = Integer.toString(total);
spaces(stream,3-s.length());
stream.print(s);
}
stream.println();
stream.println("@end group");
}
stream.println("@end example");
stream.close();
bf.close();
f.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
|
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/MultiValueEditSubmission.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/MultiValueEditSubmission.java
index 7ee3acb20..90fa9aa7f 100644
--- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/MultiValueEditSubmission.java
+++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/VTwo/MultiValueEditSubmission.java
@@ -1,297 +1,297 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONObject;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditElementVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.N3Validator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;
public class MultiValueEditSubmission {
String editKey;
private Map<String,List<Literal>> literalsFromForm ;
private Map<String,List<String>> urisFromForm ;
private Map<String,String> validationErrors;
private BasicValidationVTwo basicValidation;
private Map<String, List<FileItem>> filesFromForm;
private static Model literalCreationModel;
private String entityToReturnTo;
static{
literalCreationModel = ModelFactory.createDefaultModel();
}
public MultiValueEditSubmission(Map<String,String[]> queryParameters, EditConfigurationVTwo editConfig){
if( editConfig == null )
throw new Error("EditSubmission needs an EditConfiguration");
this.editKey = editConfig.getEditKey();
if( this.editKey == null || this.editKey.trim().length() == 0)
throw new Error("EditSubmission needs an 'editKey' parameter from the EditConfiguration");
entityToReturnTo = editConfig.getEntityToReturnTo();
validationErrors = new HashMap<String,String>();
this.urisFromForm = new HashMap<String,List<String>>();
for( String var: editConfig.getUrisOnform() ){
String[] valuesArray = queryParameters.get( var );
//String uri = null;
List<String> values = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( values != null && values.size() > 0){
//Iterate through the values and check to see if they should be added or removed from form
urisFromForm.put(var, values);
for(String uri : values) {
if( uri != null && uri.length() == 0 && editConfig.getNewResources().containsKey(var) ){
log.debug("A new resource URI will be made for var " + var + " since it was blank on the form.");
urisFromForm.remove(var);
}
}
} else {
log.debug("No value found for query parameter " + var);
}
}
this.literalsFromForm =new HashMap<String,List<Literal>>();
for(String var: editConfig.getLiteralsOnForm() ){
FieldVTwo field = editConfig.getField(var);
if( field == null ) {
log.error("could not find field " + var + " in EditConfiguration" );
continue;
} else if( field.getEditElement() != null ){
log.debug("skipping field with edit element, it should not be in literals on form list");
}else{
String[] valuesArray = queryParameters.get(var);
List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( valueList != null && valueList.size() > 0 ) {
List<Literal> literalsArray = new ArrayList<Literal>();
//now support multiple values
for(String value:valueList) {
value = EditN3Utils.stripInvalidXMLChars(value);
//Add to array of literals corresponding to this variable
if (!StringUtils.isEmpty(value)) {
literalsArray.add(createLiteral(
value,
field.getRangeDatatypeUri(),
field.getRangeLang()));
}
}
literalsFromForm.put(var, literalsArray);
}else{
log.debug("could not find value for parameter " + var );
}
}
}
if( log.isDebugEnabled() ){
for( String key : literalsFromForm.keySet() ){
log.debug( key + " literal " + literalsFromForm.get(key) );
}
for( String key : urisFromForm.keySet() ){
log.debug( key + " uri " + urisFromForm.get(key) );
}
}
processEditElementFields(editConfig,queryParameters);
//Incorporating basic validation
//Validate URIS
this.basicValidation = new BasicValidationVTwo(editConfig, this);
Map<String,String> errors = basicValidation.validateUris( urisFromForm );
- //Validate literals
- errors = basicValidation.validateLiterals( literalsFromForm );
+ //Validate literals and add errors to the list of existing errors
+ errors.putAll(basicValidation.validateLiterals( literalsFromForm ));
if( errors != null ) {
validationErrors.putAll( errors);
}
if(editConfig.getValidators() != null ){
for( N3ValidatorVTwo validator : editConfig.getValidators()){
if( validator != null ){
//throw new Error("need to implemente a validator interface that works with the new MultivalueEditSubmission.");
errors = validator.validate(editConfig, this);
if ( errors != null )
validationErrors.putAll(errors);
}
}
}
if( log.isDebugEnabled() )
log.debug( this.toString() );
}
protected void processEditElementFields(EditConfigurationVTwo editConfig, Map<String,String[]> queryParameters ){
for( String fieldName : editConfig.getFields().keySet()){
FieldVTwo field = editConfig.getFields().get(fieldName);
if( field != null && field.getEditElement() != null ){
EditElementVTwo element = field.getEditElement();
log.debug("Checking EditElement for field " + fieldName + " type: " + element.getClass().getName());
//check for validation error messages
Map<String,String> errMsgs =
element.getValidationMessages(fieldName, editConfig, queryParameters);
validationErrors.putAll(errMsgs);
if( errMsgs == null || errMsgs.isEmpty()){
//only check for uris and literals when element has no validation errors
Map<String,List<String>> urisFromElement = element.getURIs(fieldName, editConfig, queryParameters);
if( urisFromElement != null )
urisFromForm.putAll(urisFromElement);
Map<String,List<Literal>> literalsFromElement = element.getLiterals(fieldName, editConfig, queryParameters);
if( literalsFromElement != null )
literalsFromForm.putAll(literalsFromElement);
}else{
log.debug("got validation errors for field " + fieldName + " not processing field for literals or URIs");
}
}
}
}
/* maybe this could be static */
public Literal createLiteral(String value, String datatypeUri, String lang) {
if( datatypeUri != null ){
if( "http://www.w3.org/2001/XMLSchema:anyURI".equals(datatypeUri) ){
try {
return literalCreationModel.createTypedLiteral( URLEncoder.encode(value, "UTF8"), datatypeUri);
} catch (UnsupportedEncodingException e) {
log.error(e, e);
}
}
return literalCreationModel.createTypedLiteral(value, datatypeUri);
}else if( lang != null && lang.length() > 0 )
return literalCreationModel.createLiteral(value, lang);
else
return ResourceFactory.createPlainLiteral(value);
}
private static final String DATE_TIME_URI = XSD.dateTime.getURI();
private static final String DATE_URI = XSD.date.getURI();
private static final String TIME_URI = XSD.time.getURI();
private static DateTimeFormatter dformater = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:00");
private static DateTimeFormatter dateFormater = DateTimeFormat.forPattern("yyyy-MM-dd");
public Map<String,String> getValidationErrors(){
return validationErrors;
}
public Map<String, List<Literal>> getLiteralsFromForm() {
return literalsFromForm;
}
public Map<String, List<String>> getUrisFromForm() {
return urisFromForm;
}
/**
* need to generate something like
* "09:10:11"^^<http://www.w3.org/2001/XMLSchema#time>
*/
public Literal getTime(Map<String,String[]> queryParameters,String fieldName) {
List<String> hour = Arrays.asList(queryParameters.get("hour" + fieldName));
List<String> minute = Arrays.asList(queryParameters.get("minute" + fieldName));
if ( hour == null || hour.size() == 0 ||
minute == null || minute.size() == 0 ) {
log.info("Could not find query parameter values for time field " + fieldName);
validationErrors.put(fieldName, "time must be supplied");
return null;
}
int hourInt = -1;
int minuteInt = -1;
String hourParamStr = hour.get(0);
String minuteParamStr = minute.get(0);
// if all fields are blank, just return a null value
if (hourParamStr.length() == 0 && minuteParamStr.length() == 0) {
return null;
}
String errors = "";
try{
hourInt = Integer.parseInt(hour.get(0));
if (hourInt < 0 || hourInt > 23) {
throw new NumberFormatException();
}
} catch( NumberFormatException nfe ) {
errors += "Please enter a valid hour. ";
}
try{
minuteInt = Integer.parseInt(minute.get(0));
if (minuteInt < 0 || minuteInt > 59) {
throw new NumberFormatException();
}
} catch( NumberFormatException nfe ) {
errors += "Please enter a valid minute. ";
}
if( errors.length() > 0 ){
validationErrors.put( fieldName, errors);
return null;
}
String hourStr = (hourInt < 10) ? "0" + Integer.toString(hourInt) : Integer.toString(hourInt);
String minuteStr = (minuteInt < 10) ? "0" + Integer.toString(minuteInt) : Integer.toString(minuteInt);
String secondStr = "00";
return new EditLiteral(hourStr + ":" + minuteStr + ":" + secondStr, TIME_URI, null);
}
public void setLiteralsFromForm(Map<String, List<Literal>> literalsFromForm) {
this.literalsFromForm = literalsFromForm;
}
public void setUrisFromForm(Map<String, List<String>> urisFromForm) {
this.urisFromForm = urisFromForm;
}
public String toString(){
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
private Log log = LogFactory.getLog(MultiValueEditSubmission.class);
public String getEntityToReturnTo() {
return entityToReturnTo;
}
public void setEntityToReturnTo(String string) {
entityToReturnTo = string;
}
}
| true | true | public MultiValueEditSubmission(Map<String,String[]> queryParameters, EditConfigurationVTwo editConfig){
if( editConfig == null )
throw new Error("EditSubmission needs an EditConfiguration");
this.editKey = editConfig.getEditKey();
if( this.editKey == null || this.editKey.trim().length() == 0)
throw new Error("EditSubmission needs an 'editKey' parameter from the EditConfiguration");
entityToReturnTo = editConfig.getEntityToReturnTo();
validationErrors = new HashMap<String,String>();
this.urisFromForm = new HashMap<String,List<String>>();
for( String var: editConfig.getUrisOnform() ){
String[] valuesArray = queryParameters.get( var );
//String uri = null;
List<String> values = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( values != null && values.size() > 0){
//Iterate through the values and check to see if they should be added or removed from form
urisFromForm.put(var, values);
for(String uri : values) {
if( uri != null && uri.length() == 0 && editConfig.getNewResources().containsKey(var) ){
log.debug("A new resource URI will be made for var " + var + " since it was blank on the form.");
urisFromForm.remove(var);
}
}
} else {
log.debug("No value found for query parameter " + var);
}
}
this.literalsFromForm =new HashMap<String,List<Literal>>();
for(String var: editConfig.getLiteralsOnForm() ){
FieldVTwo field = editConfig.getField(var);
if( field == null ) {
log.error("could not find field " + var + " in EditConfiguration" );
continue;
} else if( field.getEditElement() != null ){
log.debug("skipping field with edit element, it should not be in literals on form list");
}else{
String[] valuesArray = queryParameters.get(var);
List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( valueList != null && valueList.size() > 0 ) {
List<Literal> literalsArray = new ArrayList<Literal>();
//now support multiple values
for(String value:valueList) {
value = EditN3Utils.stripInvalidXMLChars(value);
//Add to array of literals corresponding to this variable
if (!StringUtils.isEmpty(value)) {
literalsArray.add(createLiteral(
value,
field.getRangeDatatypeUri(),
field.getRangeLang()));
}
}
literalsFromForm.put(var, literalsArray);
}else{
log.debug("could not find value for parameter " + var );
}
}
}
if( log.isDebugEnabled() ){
for( String key : literalsFromForm.keySet() ){
log.debug( key + " literal " + literalsFromForm.get(key) );
}
for( String key : urisFromForm.keySet() ){
log.debug( key + " uri " + urisFromForm.get(key) );
}
}
processEditElementFields(editConfig,queryParameters);
//Incorporating basic validation
//Validate URIS
this.basicValidation = new BasicValidationVTwo(editConfig, this);
Map<String,String> errors = basicValidation.validateUris( urisFromForm );
//Validate literals
errors = basicValidation.validateLiterals( literalsFromForm );
if( errors != null ) {
validationErrors.putAll( errors);
}
if(editConfig.getValidators() != null ){
for( N3ValidatorVTwo validator : editConfig.getValidators()){
if( validator != null ){
//throw new Error("need to implemente a validator interface that works with the new MultivalueEditSubmission.");
errors = validator.validate(editConfig, this);
if ( errors != null )
validationErrors.putAll(errors);
}
}
}
if( log.isDebugEnabled() )
log.debug( this.toString() );
}
| public MultiValueEditSubmission(Map<String,String[]> queryParameters, EditConfigurationVTwo editConfig){
if( editConfig == null )
throw new Error("EditSubmission needs an EditConfiguration");
this.editKey = editConfig.getEditKey();
if( this.editKey == null || this.editKey.trim().length() == 0)
throw new Error("EditSubmission needs an 'editKey' parameter from the EditConfiguration");
entityToReturnTo = editConfig.getEntityToReturnTo();
validationErrors = new HashMap<String,String>();
this.urisFromForm = new HashMap<String,List<String>>();
for( String var: editConfig.getUrisOnform() ){
String[] valuesArray = queryParameters.get( var );
//String uri = null;
List<String> values = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( values != null && values.size() > 0){
//Iterate through the values and check to see if they should be added or removed from form
urisFromForm.put(var, values);
for(String uri : values) {
if( uri != null && uri.length() == 0 && editConfig.getNewResources().containsKey(var) ){
log.debug("A new resource URI will be made for var " + var + " since it was blank on the form.");
urisFromForm.remove(var);
}
}
} else {
log.debug("No value found for query parameter " + var);
}
}
this.literalsFromForm =new HashMap<String,List<Literal>>();
for(String var: editConfig.getLiteralsOnForm() ){
FieldVTwo field = editConfig.getField(var);
if( field == null ) {
log.error("could not find field " + var + " in EditConfiguration" );
continue;
} else if( field.getEditElement() != null ){
log.debug("skipping field with edit element, it should not be in literals on form list");
}else{
String[] valuesArray = queryParameters.get(var);
List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( valueList != null && valueList.size() > 0 ) {
List<Literal> literalsArray = new ArrayList<Literal>();
//now support multiple values
for(String value:valueList) {
value = EditN3Utils.stripInvalidXMLChars(value);
//Add to array of literals corresponding to this variable
if (!StringUtils.isEmpty(value)) {
literalsArray.add(createLiteral(
value,
field.getRangeDatatypeUri(),
field.getRangeLang()));
}
}
literalsFromForm.put(var, literalsArray);
}else{
log.debug("could not find value for parameter " + var );
}
}
}
if( log.isDebugEnabled() ){
for( String key : literalsFromForm.keySet() ){
log.debug( key + " literal " + literalsFromForm.get(key) );
}
for( String key : urisFromForm.keySet() ){
log.debug( key + " uri " + urisFromForm.get(key) );
}
}
processEditElementFields(editConfig,queryParameters);
//Incorporating basic validation
//Validate URIS
this.basicValidation = new BasicValidationVTwo(editConfig, this);
Map<String,String> errors = basicValidation.validateUris( urisFromForm );
//Validate literals and add errors to the list of existing errors
errors.putAll(basicValidation.validateLiterals( literalsFromForm ));
if( errors != null ) {
validationErrors.putAll( errors);
}
if(editConfig.getValidators() != null ){
for( N3ValidatorVTwo validator : editConfig.getValidators()){
if( validator != null ){
//throw new Error("need to implemente a validator interface that works with the new MultivalueEditSubmission.");
errors = validator.validate(editConfig, this);
if ( errors != null )
validationErrors.putAll(errors);
}
}
}
if( log.isDebugEnabled() )
log.debug( this.toString() );
}
|
diff --git a/src/main/java/org/mcsoxford/rss/RSSLoader.java b/src/main/java/org/mcsoxford/rss/RSSLoader.java
index 92144a9..87460b8 100644
--- a/src/main/java/org/mcsoxford/rss/RSSLoader.java
+++ b/src/main/java/org/mcsoxford/rss/RSSLoader.java
@@ -1,447 +1,447 @@
/*
* Copyright (C) 2011 A. Horn
*
* 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.mcsoxford.rss;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Asynchronous loader for RSS feeds. RSS feeds can be loaded in FIFO order or
* based on priority. Objects of this type can be constructed with one of the
* provided static methods:
* <ul>
* <li>{@link #fifo()}</li>
* <li>{@link #fifo(int)}</li>
* <li>{@link #priority()}</li>
* <li>{@link #priority(int)}</li>
* </ul>
*
* Completed RSS feed loads can be retrieved with {@link RSSLoader#take()},
* {@link RSSLoader#poll()} or {@link RSSLoader#poll(long, TimeUnit)}.
*
* <p>
* <b>Usage Example</b>
*
* Suppose you want to load an array of RSS feed URIs concurrently before
* retrieving the results one at a time. You could write this as:
*
* <pre>
* {@code
* void fetchRSS(String[] uris) throws InterruptedException {
* RSSLoader loader = RSSLoader.fifo();
* for (String uri : uris) {
* loader.load(uri);
* }
*
* Future<RSSFeed> future;
* RSSFeed feed;
* for (int i = 0; i < uris.length; i++) {
* future = loader.take();
* try {
* feed = future.get();
* use(feed);
* } catch (ExecutionException ignore) {}
* }
* }}
*
* </p>
*
* @author A. Horn
*/
public class RSSLoader {
/**
* Human-readable name of the thread loading RSS feeds
*/
private final static String DEFAULT_THREAD_NAME = "Asynchronous RSS feed loader";
/**
* Arrange incoming load requests on this queue.
*/
private final BlockingQueue<RSSFuture> in;
/**
* Once the an RSS feed has completed loading, place the result on this queue.
*/
private final BlockingQueue<RSSFuture> out;
/**
* Flag changes are visible after operations on {@link #in} queue.
*/
private boolean stopped;
/**
* Create an object which can load RSS feeds asynchronously in FIFO order.
*
* @see #fifo(int)
*/
public static RSSLoader fifo() {
return new RSSLoader(new LinkedBlockingQueue<RSSFuture>());
}
/**
* Create an object which can load RSS feeds asynchronously in FIFO order.
*
* @param capacity
* expected number of URIs to be loaded at a given time
*/
public static RSSLoader fifo(int capacity) {
return new RSSLoader(new LinkedBlockingQueue<RSSFuture>(capacity));
}
/**
* Create an object which can load RSS feeds asynchronously based on priority.
*
* @see #priority(int)
*/
public static RSSLoader priority() {
return new RSSLoader(new PriorityBlockingQueue<RSSFuture>());
}
/**
* Create an object which can load RSS feeds asynchronously based on priority.
*
* @param capacity
* expected number of URIs to be loaded at a given time
*/
public static RSSLoader priority(int capacity) {
return new RSSLoader(new PriorityBlockingQueue<RSSFuture>(capacity));
}
/**
* Instantiate an object which can load RSS feeds asynchronously. The provided
* {@link BlockingQueue} implementation determines the load behaviour.
*
* @see LinkedBlockingQueue
* @see PriorityBlockingQueue
*/
RSSLoader(BlockingQueue<RSSFuture> in) {
this.in = in;
this.out = new LinkedBlockingQueue<RSSFuture>();
// start separate thread for loading of RSS feeds
new Thread(new Loader(new RSSReader()), DEFAULT_THREAD_NAME).start();
}
/**
* Returns {@code true} if RSS feeds are currently being loaded, {@code false}
* otherwise.
*/
public boolean isLoading() {
// order of conjuncts matters because of happens-before relationship
return !in.isEmpty() && !stopped;
}
/**
* Stop thread after finishing loading pending RSS feed URIs. If this loader
* has been constructed with {@link #priority()} or {@link #priority(int)},
* only RSS feed loads with priority strictly greater than seven (7) are going
* to be completed.
* <p>
* Subsequent invocations of {@link #load(String)} and
* {@link #load(String, int)} return {@code null}.
*/
public void stop() {
// flag writings happen-before enqueue
stopped = true;
in.offer(SENTINEL);
}
/**
* Loads the specified RSS feed URI asynchronously. If this loader has been
* constructed with {@link #priority()} or {@link #priority(int)}, then a
* default priority of three (3) is used. Otherwise, RSS feeds are loaded in
* FIFO order.
* <p>
* Returns {@code null} if the RSS feed URI cannot be scheduled for loading
* due to resource constraints or if {@link #stop()} has been previously
* called.
* <p>
* Completed RSS feed loads can be retrieved by calling {@link #take()}.
* Alternatively, non-blocking polling is possible with {@link #poll()}.
*
* @param uri
* RSS feed URI to be loaded
*
* @return Future representing the RSS feed scheduled for loading,
* {@code null} if scheduling failed
*/
public Future<RSSFeed> load(String uri) {
return load(uri, RSSFuture.DEFAULT_PRIORITY);
}
/**
* Loads the specified RSS feed URI asynchronously. For the specified priority
* to determine the relative loading order of RSS feeds, this loader must have
* been constructed with {@link #priority()} or {@link #priority(int)}.
* Otherwise, RSS feeds are loaded in FIFO order.
* <p>
* Returns {@code null} if the RSS feed URI cannot be scheduled for loading
* due to resource constraints or if {@link #stop()} has been previously
* called.
* <p>
* Completed RSS feed loads can be retrieved by calling {@link #take()}.
* Alternatively, non-blocking polling is possible with {@link #poll()}.
*
* @param uri
* RSS feed URI to be loaded
* @param priority
* larger integer gives higher priority
*
* @return Future representing the RSS feed scheduled for loading,
* {@code null} if scheduling failed
*/
public Future<RSSFeed> load(String uri, int priority) {
if (uri == null) {
throw new IllegalArgumentException("RSS feed URI must not be null.");
}
// optimization (after flag changes have become visible)
if (stopped) {
return null;
}
// flag readings happen-after enqueue
final RSSFuture future = new RSSFuture(uri, priority);
final boolean ok = in.offer(future);
if (!ok || stopped) {
return null;
}
return future;
}
/**
* Retrieves and removes the next Future representing the result of loading an
* RSS feed, waiting if none are yet present.
*
* @return the {@link Future} representing the loaded RSS feed
*
* @throws InterruptedException
* if interrupted while waiting
*/
public Future<RSSFeed> take() throws InterruptedException {
return out.take();
}
/**
* Retrieves and removes the next Future representing the result of loading an
* RSS feed or {@code null} if none are present.
*
* @return the {@link Future} representing the loaded RSS feed, or
* {@code null} if none are present
*
* @throws InterruptedException
* if interrupted while waiting
*/
public Future<RSSFeed> poll() {
return out.poll();
}
/**
* Retrieves and removes the Future representing the result of loading an RSS
* feed, waiting if necessary up to the specified wait time if none are yet
* present.
*
* @param timeout
* how long to wait before giving up, in units of {@code unit}
* @param unit
* a {@link TimeUnit} determining how to interpret the
* {@code timeout} parameter
* @return the {@link Future} representing the loaded RSS feed, or
* {@code null} if none are present within the specified time interval
* @throws InterruptedException
* if interrupted while waiting
*/
public Future<RSSFeed> poll(long timeout, TimeUnit unit) throws InterruptedException {
return out.poll(timeout, unit);
}
/**
* Internal consumer of RSS feed URIs stored in the blocking queue.
*/
class Loader implements Runnable {
private final RSSReader reader;
Loader(RSSReader reader) {
this.reader = reader;
}
/**
* Keep on loading RSS feeds by dequeuing incoming tasks until the sentinel
* is encountered.
*/
@Override
public void run() {
RSSFuture future = null;
try {
RSSFeed feed;
while ((future = in.take()) != SENTINEL) {
if (future.status.compareAndSet(RSSFuture.READY, RSSFuture.LOADING)) {
// perform loading outside of locked region
feed = reader.load(future.uri);
// set successfully loaded RSS feed
future.set(feed, /* error */null);
// ensure RSSFuture::isDone() returns true
future.status.compareAndSet(RSSFuture.LOADING, RSSFuture.LOADED);
// enable caller to identify the next completed RSS feed load
out.add(future);
}
}
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
} catch (RSSReaderException e) {
// set cause for load() error
future.set(/* feed */null, e);
}
}
}
/**
* Internal sentinel to stop the thread that is loading RSS feeds.
*/
private final static RSSFuture SENTINEL = new RSSFuture(null, /* priority */7);
/**
* Offer callers control over the asynchronous loading of an RSS feed.
*/
static class RSSFuture implements Future<RSSFeed>, Comparable<RSSFuture> {
static final int DEFAULT_PRIORITY = 3;
static final int READY = 0;
static final int LOADING = 1;
static final int LOADED = 2;
static final int CANCELLED = 4;
/** RSS feed URI */
final String uri;
/** Larger integer gives higher priority */
final int priority;
AtomicInteger status;
boolean waiting;
RSSFeed feed;
Exception cause;
RSSFuture(String uri, int priority) {
this.uri = uri;
this.priority = priority;
status = new AtomicInteger(READY);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return isCancelled() || status.compareAndSet(READY, CANCELLED);
}
@Override
public boolean isCancelled() {
return status.get() == CANCELLED;
}
@Override
public boolean isDone() {
return (status.get() & (LOADED | CANCELLED)) != 0;
}
@Override
public synchronized RSSFeed get() throws InterruptedException, ExecutionException {
if (feed == null && cause == null) {
try {
waiting = true;
// guard against spurious wakeups
while (waiting) {
wait();
}
} finally {
waiting = false;
}
}
if (cause != null) {
throw new ExecutionException(cause);
}
return feed;
}
@Override
public synchronized RSSFeed get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (feed == null && cause == null) {
try {
waiting = true;
final long timeoutMillis = unit.toMillis(timeout);
final long startMillis = System.currentTimeMillis();
// guard against spurious wakeups
while (waiting) {
wait(timeoutMillis);
// check timeout
- if (System.currentTimeMillis() - startMillis < timeoutMillis) {
+ if (System.currentTimeMillis() - startMillis > timeoutMillis) {
throw new TimeoutException("RSS feed loading timed out");
}
}
} finally {
waiting = false;
}
}
if (cause != null) {
throw new ExecutionException(cause);
}
return feed;
}
synchronized void set(RSSFeed feed, Exception cause) {
this.feed = feed;
this.cause = cause;
if (waiting) {
waiting = false;
notifyAll();
}
}
@Override
public int compareTo(RSSFuture other) {
// Note: head of PriorityQueue implementation is the least element
return other.priority - priority;
}
}
}
| true | true | public synchronized RSSFeed get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (feed == null && cause == null) {
try {
waiting = true;
final long timeoutMillis = unit.toMillis(timeout);
final long startMillis = System.currentTimeMillis();
// guard against spurious wakeups
while (waiting) {
wait(timeoutMillis);
// check timeout
if (System.currentTimeMillis() - startMillis < timeoutMillis) {
throw new TimeoutException("RSS feed loading timed out");
}
}
} finally {
waiting = false;
}
}
if (cause != null) {
throw new ExecutionException(cause);
}
return feed;
}
| public synchronized RSSFeed get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (feed == null && cause == null) {
try {
waiting = true;
final long timeoutMillis = unit.toMillis(timeout);
final long startMillis = System.currentTimeMillis();
// guard against spurious wakeups
while (waiting) {
wait(timeoutMillis);
// check timeout
if (System.currentTimeMillis() - startMillis > timeoutMillis) {
throw new TimeoutException("RSS feed loading timed out");
}
}
} finally {
waiting = false;
}
}
if (cause != null) {
throw new ExecutionException(cause);
}
return feed;
}
|
diff --git a/modules/axiom-impl/src/main/java/org/apache/axiom/soap/impl/llom/SOAPFaultImpl.java b/modules/axiom-impl/src/main/java/org/apache/axiom/soap/impl/llom/SOAPFaultImpl.java
index 0ab016508..203431e6b 100644
--- a/modules/axiom-impl/src/main/java/org/apache/axiom/soap/impl/llom/SOAPFaultImpl.java
+++ b/modules/axiom-impl/src/main/java/org/apache/axiom/soap/impl/llom/SOAPFaultImpl.java
@@ -1,239 +1,239 @@
/*
* Copyright 2004,2005 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.axiom.soap.impl.llom;
import org.apache.axiom.om.OMConstants;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axiom.om.impl.OMNodeEx;
import org.apache.axiom.om.impl.util.OMSerializerUtil;
import org.apache.axiom.om.impl.llom.OMElementImpl;
import org.apache.axiom.om.impl.serialize.StreamWriterToContentHandlerConverter;
import org.apache.axiom.soap.SOAP12Constants;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.soap.SOAPConstants;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPFault;
import org.apache.axiom.soap.SOAPFaultCode;
import org.apache.axiom.soap.SOAPFaultDetail;
import org.apache.axiom.soap.SOAPFaultNode;
import org.apache.axiom.soap.SOAPFaultReason;
import org.apache.axiom.soap.SOAPFaultRole;
import org.apache.axiom.soap.SOAPProcessingException;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Iterator;
/**
* Class SOAPFaultImpl
*/
public abstract class SOAPFaultImpl extends SOAPElement
implements SOAPFault, OMConstants {
protected Exception e;
protected SOAPFaultImpl(OMNamespace ns, SOAPFactory factory) {
super(SOAPConstants.SOAPFAULT_LOCAL_NAME, ns, factory);
}
/**
* Constructor SOAPFaultImpl
*
* @param parent
* @param e
*/
public SOAPFaultImpl(SOAPBody parent, Exception e, SOAPFactory factory) throws SOAPProcessingException {
super(parent, SOAPConstants.SOAPFAULT_LOCAL_NAME, true, factory);
setException(e);
}
public void setException(Exception e) {
this.e = e;
putExceptionToSOAPFault(e);
}
public SOAPFaultImpl(SOAPBody parent, SOAPFactory factory) throws SOAPProcessingException {
super(parent, SOAPConstants.SOAPFAULT_LOCAL_NAME, true, factory);
}
/**
* Constructor SOAPFaultImpl
*
* @param parent
* @param builder
*/
public SOAPFaultImpl(SOAPBody parent, OMXMLParserWrapper builder,
SOAPFactory factory) {
super(parent, SOAPConstants.SOAPFAULT_LOCAL_NAME, builder, factory);
}
protected abstract SOAPFaultDetail getNewSOAPFaultDetail(SOAPFault fault) throws SOAPProcessingException;
// --------------- Getters and Settors --------------------------- //
public void setCode(SOAPFaultCode soapFaultCode) throws SOAPProcessingException {
setNewElement(getCode(), soapFaultCode);
}
public SOAPFaultCode getCode() {
return (SOAPFaultCode) this.getChildWithName(
SOAP12Constants.SOAP_FAULT_CODE_LOCAL_NAME);
}
public void setReason(SOAPFaultReason reason) throws SOAPProcessingException {
setNewElement(getReason(), reason);
}
public SOAPFaultReason getReason() {
return (SOAPFaultReason) this.getChildWithName(
SOAP12Constants.SOAP_FAULT_REASON_LOCAL_NAME);
}
public void setNode(SOAPFaultNode node) throws SOAPProcessingException {
setNewElement(getNode(), node);
}
public SOAPFaultNode getNode() {
return (SOAPFaultNode) this.getChildWithName(
SOAP12Constants.SOAP_FAULT_NODE_LOCAL_NAME);
}
public void setRole(SOAPFaultRole role) throws SOAPProcessingException {
setNewElement(getRole(), role);
}
public SOAPFaultRole getRole() {
return (SOAPFaultRoleImpl) this.getChildWithName(
SOAP12Constants.SOAP_FAULT_ROLE_LOCAL_NAME);
}
public void setDetail(SOAPFaultDetail detail) throws SOAPProcessingException {
setNewElement(getDetail(), detail);
}
public SOAPFaultDetail getDetail() {
return (SOAPFaultDetail) this.getChildWithName(
SOAP12Constants.SOAP_FAULT_DETAIL_LOCAL_NAME);
}
/**
* If exception detailElement is not there we will return null
*/
public Exception getException() throws OMException {
SOAPFaultDetail detail = getDetail();
if (detail == null) {
return null;
}
OMElement exceptionElement = getDetail().getFirstChildWithName(
new QName(SOAPConstants.SOAP_FAULT_DETAIL_EXCEPTION_ENTRY));
if (exceptionElement != null && exceptionElement.getText() != null) {
return new Exception(exceptionElement.getText());
}
return null;
}
protected void putExceptionToSOAPFault(Exception e) throws SOAPProcessingException {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
sw.flush();
SOAPFaultDetail detail = getDetail();
if (getDetail() == null) {
detail = getNewSOAPFaultDetail(this);
setDetail(detail);
}
OMElement faultDetailEnty = new OMElementImpl(
SOAPConstants.SOAP_FAULT_DETAIL_EXCEPTION_ENTRY, null, detail,
factory);
faultDetailEnty.setText(sw.getBuffer().toString());
}
protected void setNewElement(OMElement myElement, OMElement newElement) {
if (myElement != null) {
myElement.discard();
}
if (newElement != null && newElement.getParent() != null) {
newElement.discard();
}
this.addChild(newElement);
myElement = newElement;
}
protected OMElement getChildWithName(String childName) {
Iterator childrenIter = getChildren();
while (childrenIter.hasNext()) {
OMNode node = (OMNode) childrenIter.next();
if (node.getType() == OMNode.ELEMENT_NODE &&
childName.equals(((OMElement) node).getLocalName())) {
return (OMElement) node;
}
}
return null;
}
protected void internalSerialize(XMLStreamWriter writer, boolean cache) throws XMLStreamException {
// select the builder
short builderType = PULL_TYPE_BUILDER; // default is pull type
if (builder != null) {
builderType = this.builder.getBuilderType();
}
if ((builderType == PUSH_TYPE_BUILDER)
&& (builder.getRegisteredContentHandler() == null)) {
builder.registerExternalContentHandler(new StreamWriterToContentHandlerConverter(writer));
}
// this is a special case. This fault element may contain its children in any order. But spec mandates a specific order
// the overriding of the method will facilitate that. Not sure this is the best method to do this :(
build();
OMSerializerUtil.serializeStartpart(this, writer);
SOAPFaultCode faultCode = getCode();
if (faultCode != null) {
- ((OMNodeEx) faultCode).serialize(writer);
+ ((OMNodeEx) faultCode).internalSerialize(writer);
}
SOAPFaultReason faultReason = getReason();
if (faultReason != null) {
- ((OMNodeEx) faultReason).serialize(writer);
+ ((OMNodeEx) faultReason).internalSerialize(writer);
}
serializeFaultNode(writer);
SOAPFaultRole faultRole = getRole();
if (faultRole != null && faultRole.getText() != null && !"".equals(faultRole.getText())) {
- ((OMNodeEx) faultRole).serialize(writer);
+ ((OMNodeEx) faultRole).internalSerialize(writer);
}
SOAPFaultDetail faultDetail = getDetail();
if (faultDetail != null) {
- ((OMNodeEx) faultDetail).serialize(writer);
+ ((OMNodeEx) faultDetail).internalSerialize(writer);
}
OMSerializerUtil.serializeEndpart(writer);
}
protected abstract void serializeFaultNode(XMLStreamWriter writer) throws XMLStreamException;
}
| false | true | protected void internalSerialize(XMLStreamWriter writer, boolean cache) throws XMLStreamException {
// select the builder
short builderType = PULL_TYPE_BUILDER; // default is pull type
if (builder != null) {
builderType = this.builder.getBuilderType();
}
if ((builderType == PUSH_TYPE_BUILDER)
&& (builder.getRegisteredContentHandler() == null)) {
builder.registerExternalContentHandler(new StreamWriterToContentHandlerConverter(writer));
}
// this is a special case. This fault element may contain its children in any order. But spec mandates a specific order
// the overriding of the method will facilitate that. Not sure this is the best method to do this :(
build();
OMSerializerUtil.serializeStartpart(this, writer);
SOAPFaultCode faultCode = getCode();
if (faultCode != null) {
((OMNodeEx) faultCode).serialize(writer);
}
SOAPFaultReason faultReason = getReason();
if (faultReason != null) {
((OMNodeEx) faultReason).serialize(writer);
}
serializeFaultNode(writer);
SOAPFaultRole faultRole = getRole();
if (faultRole != null && faultRole.getText() != null && !"".equals(faultRole.getText())) {
((OMNodeEx) faultRole).serialize(writer);
}
SOAPFaultDetail faultDetail = getDetail();
if (faultDetail != null) {
((OMNodeEx) faultDetail).serialize(writer);
}
OMSerializerUtil.serializeEndpart(writer);
}
| protected void internalSerialize(XMLStreamWriter writer, boolean cache) throws XMLStreamException {
// select the builder
short builderType = PULL_TYPE_BUILDER; // default is pull type
if (builder != null) {
builderType = this.builder.getBuilderType();
}
if ((builderType == PUSH_TYPE_BUILDER)
&& (builder.getRegisteredContentHandler() == null)) {
builder.registerExternalContentHandler(new StreamWriterToContentHandlerConverter(writer));
}
// this is a special case. This fault element may contain its children in any order. But spec mandates a specific order
// the overriding of the method will facilitate that. Not sure this is the best method to do this :(
build();
OMSerializerUtil.serializeStartpart(this, writer);
SOAPFaultCode faultCode = getCode();
if (faultCode != null) {
((OMNodeEx) faultCode).internalSerialize(writer);
}
SOAPFaultReason faultReason = getReason();
if (faultReason != null) {
((OMNodeEx) faultReason).internalSerialize(writer);
}
serializeFaultNode(writer);
SOAPFaultRole faultRole = getRole();
if (faultRole != null && faultRole.getText() != null && !"".equals(faultRole.getText())) {
((OMNodeEx) faultRole).internalSerialize(writer);
}
SOAPFaultDetail faultDetail = getDetail();
if (faultDetail != null) {
((OMNodeEx) faultDetail).internalSerialize(writer);
}
OMSerializerUtil.serializeEndpart(writer);
}
|
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java b/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
index d60890c9..45e33e77 100644
--- a/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
+++ b/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
@@ -1,675 +1,683 @@
package com.redhat.ceylon.compiler.js;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.redhat.ceylon.compiler.loader.MetamodelGenerator;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
/** A convenience class to help with the handling of certain type declarations. */
public class TypeUtils {
final TypeDeclaration tuple;
final TypeDeclaration iterable;
final TypeDeclaration sequential;
final TypeDeclaration numeric;
final TypeDeclaration _integer;
final TypeDeclaration _float;
final TypeDeclaration _null;
final TypeDeclaration anything;
final TypeDeclaration callable;
final TypeDeclaration empty;
final TypeDeclaration metaClass;
TypeUtils(Module languageModule) {
com.redhat.ceylon.compiler.typechecker.model.Package pkg = languageModule.getPackage("ceylon.language");
tuple = (TypeDeclaration)pkg.getMember("Tuple", null, false);
iterable = (TypeDeclaration)pkg.getMember("Iterable", null, false);
sequential = (TypeDeclaration)pkg.getMember("Sequential", null, false);
numeric = (TypeDeclaration)pkg.getMember("Numeric", null, false);
_integer = (TypeDeclaration)pkg.getMember("Integer", null, false);
_float = (TypeDeclaration)pkg.getMember("Float", null, false);
_null = (TypeDeclaration)pkg.getMember("Null", null, false);
anything = (TypeDeclaration)pkg.getMember("Anything", null, false);
callable = (TypeDeclaration)pkg.getMember("Callable", null, false);
empty = (TypeDeclaration)pkg.getMember("Empty", null, false);
pkg = languageModule.getPackage("ceylon.language.model");
metaClass = (TypeDeclaration)pkg.getMember("Class", null, false);
}
/** Prints the type arguments, usually for their reification. */
public static void printTypeArguments(Node node, Map<TypeParameter,ProducedType> targs, GenerateJsVisitor gen) {
gen.out("{");
boolean first = true;
for (Map.Entry<TypeParameter,ProducedType> e : targs.entrySet()) {
if (first) {
first = false;
} else {
gen.out(",");
}
gen.out(e.getKey().getName(), ":");
final ProducedType pt = e.getValue();
if (pt == null) {
gen.out("'", e.getKey().getName(), "'");
continue;
}
final TypeDeclaration d = pt.getDeclaration();
boolean composite = d instanceof UnionType || d instanceof IntersectionType;
boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty();
boolean closeBracket = false;
if (composite) {
outputTypeList(node, d, gen, true);
} else if (d instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)d, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(
gen.isImported(node == null ? null : node.getUnit().getPackage(), pt.getDeclaration()),
pt, gen);
closeBracket = true;
}
if (hasParams) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
if (closeBracket) {
gen.out("}");
}
}
gen.out("}");
}
static void outputQualifiedTypename(final boolean imported, ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration t = pt.getDeclaration();
final String qname = t.getQualifiedNameString();
if (qname.equals("ceylon.language::Nothing")) {
//Hack in the model means hack here as well
gen.out(GenerateJsVisitor.getClAlias(), "Nothing");
} else if (qname.equals("ceylon.language::null") || qname.equals("ceylon.language::Null")) {
gen.out(GenerateJsVisitor.getClAlias(), "Null");
} else if (pt.isUnknown()) {
gen.out(GenerateJsVisitor.getClAlias(), "Anything");
} else {
if (t.isAlias()) {
t = t.getExtendedTypeDeclaration();
}
boolean qual = false;
if (t.getScope() instanceof ClassOrInterface) {
List<ClassOrInterface> parents = new ArrayList<>();
ClassOrInterface parent = (ClassOrInterface)t.getScope();
parents.add(0, parent);
while (parent.getScope() instanceof ClassOrInterface) {
parent = (ClassOrInterface)parent.getScope();
parents.add(0, parent);
}
qual = true;
for (ClassOrInterface p : parents) {
gen.out(gen.getNames().name(p), ".");
}
} else if (imported) {
//This wasn't needed but now we seem to get imported decls with no package when compiling ceylon.language.model types
final String modAlias = gen.getNames().moduleAlias(t.getUnit().getPackage().getModule());
if (modAlias != null && !modAlias.isEmpty()) {
gen.out(modAlias, ".");
}
qual = true;
}
String tname = gen.getNames().name(t);
if (!qual && isReservedTypename(tname)) {
gen.out(tname, "$");
} else {
gen.out(tname);
}
}
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void typeNameOrList(Node node, ProducedType pt, GenerateJsVisitor gen, boolean typeReferences) {
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputTypeList(node, type, gen, typeReferences);
} else if (typeReferences) {
if (type instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)type, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(node == null ? null : node.getUnit().getPackage(), type), pt, gen);
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
gen.out("}");
}
} else {
gen.out("'", type.getQualifiedNameString(), "'");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputTypeList(Node node, TypeDeclaration type, GenerateJsVisitor gen, boolean typeReferences) {
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
typeNameOrList(node, t, gen, typeReferences);
first = false;
}
gen.out("]}");
}
/** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */
static void resolveTypeParameter(Node node, TypeParameter tp, GenerateJsVisitor gen) {
Scope parent = node.getScope();
while (parent != null && parent != tp.getContainer()) {
parent = parent.getScope();
}
if (tp.getContainer() instanceof ClassOrInterface) {
if (parent == tp.getContainer()) {
if (((ClassOrInterface)tp.getContainer()).isAlias()) {
//when resolving for aliases we just take the type arguments from the alias call
gen.out("$$targs$$.", tp.getName());
} else {
gen.self((ClassOrInterface)tp.getContainer());
gen.out(".$$targs$$.", tp.getName());
}
} else {
//This can happen in expressions such as Singleton(n) when n is dynamic
gen.out("{/*NO PARENT*/t:", GenerateJsVisitor.getClAlias(), "Anything}");
}
} else {
//it has to be a method, right?
//We need to find the index of the parameter where the argument occurs
//...and it could be null...
int plistCount = -1;
ProducedType type = null;
for (Iterator<ParameterList> iter0 = ((Method)tp.getContainer()).getParameterLists().iterator();
type == null && iter0.hasNext();) {
plistCount++;
for (Iterator<Parameter> iter1 = iter0.next().getParameters().iterator();
type == null && iter1.hasNext();) {
if (type == null) {
type = typeContainsTypeParameter(iter1.next().getType(), tp);
}
}
}
//The ProducedType that we find corresponds to a parameter, whose type can be:
//A type parameter in the method, in which case we just use the argument's type (may be null)
//A component of a union/intersection type, in which case we just use the argument's type (may be null)
//A type argument of the argument's type, in which case we must get the reified generic from the argument
if (tp.getContainer() == parent) {
gen.out("$$$mptypes.", tp.getName());
} else {
gen.out("/*METHOD TYPEPARM plist ", Integer.toString(plistCount), "#",
tp.getName(), "*/'", type.getProducedTypeQualifiedName(), "'");
}
}
}
static ProducedType typeContainsTypeParameter(ProducedType td, TypeParameter tp) {
TypeDeclaration d = td.getDeclaration();
if (d == tp) {
return td;
} else if (d instanceof UnionType || d instanceof IntersectionType) {
List<ProducedType> comps = td.getCaseTypes();
if (comps == null) comps = td.getSupertypes();
for (ProducedType sub : comps) {
td = typeContainsTypeParameter(sub, tp);
if (td != null) {
return td;
}
}
} else if (d instanceof ClassOrInterface) {
for (ProducedType sub : td.getTypeArgumentList()) {
if (typeContainsTypeParameter(sub, tp) != null) {
return td;
}
}
}
return null;
}
static boolean isReservedTypename(String typeName) {
return JsCompiler.compilingLanguageModule && (typeName.equals("Object") || typeName.equals("Number")
|| typeName.equals("Array")) || typeName.equals("String") || typeName.equals("Boolean");
}
/** Find the type with the specified declaration among the specified type's supertypes, case types, satisfied types, etc. */
static ProducedType findSupertype(TypeDeclaration d, ProducedType pt) {
if (pt.getDeclaration().equals(d)) {
return pt;
}
List<ProducedType> list = pt.getSupertypes() == null ? pt.getCaseTypes() : pt.getSupertypes();
for (ProducedType t : list) {
if (t.getDeclaration().equals(d)) {
return t;
}
}
return null;
}
static Map<TypeParameter, ProducedType> matchTypeParametersWithArguments(List<TypeParameter> params, List<ProducedType> targs) {
if (params != null && targs != null && params.size() == targs.size()) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
for (int i = 0; i < targs.size(); i++) {
r.put(params.get(i), targs.get(i));
}
return r;
}
return null;
}
Map<TypeParameter, ProducedType> wrapAsIterableArguments(ProducedType pt) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
r.put(iterable.getTypeParameters().get(0), pt);
r.put(iterable.getTypeParameters().get(1), _null.getType());
return r;
}
static boolean isUnknown(ProducedType pt) {
return pt == null || pt.isUnknown();
}
static boolean isUnknown(Parameter param) {
return param == null || isUnknown(param.getType());
}
static boolean isUnknown(Declaration d) {
return d == null || d.getQualifiedNameString().equals("UnknownType");
}
/** Generates the code to throw an Exception if a dynamic object is not of the specified type. */
static void generateDynamicCheck(Tree.Term term, final ProducedType t, final GenerateJsVisitor gen) {
String tmp = gen.getNames().createTempVariable();
gen.out("(", tmp, "=");
term.visit(gen);
gen.out(",", GenerateJsVisitor.getClAlias(), "isOfType(", tmp, ",");
TypeUtils.typeNameOrList(term, t, gen, true);
gen.out(")?", tmp, ":", GenerateJsVisitor.getClAlias(), "throwexc('dynamic objects cannot be used here'))");
}
static void encodeParameterListForRuntime(ParameterList plist, GenerateJsVisitor gen) {
boolean first = true;
gen.out("[");
for (Parameter p : plist.getParameters()) {
if (first) first=false; else gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'", p.getName(), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
if (p.isSequenced()) {
gen.out("seq:1,");
}
if (p.isDefaulted()) {
gen.out(MetamodelGenerator.KEY_DEFAULT, ":1,");
}
gen.out(MetamodelGenerator.KEY_TYPE, ":");
metamodelTypeNameOrList(gen.getCurrentPackage(), p.getType(), gen);
gen.out("}");
}
gen.out("]");
}
/** This method encodes the type parameters of a Tuple (taken from a Callable) in the same way
* as a parameter list for runtime. */
void encodeTupleAsParameterListForRuntime(ProducedType _callable, GenerateJsVisitor gen) {
if (!_callable.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) {
gen.out("[/*WARNING: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]");
return;
}
List<ProducedType> targs = _callable.getTypeArgumentList();
if (targs == null || targs.size() != 2) {
gen.out("[/*WARNING: missing argument types for Callable*/]");
return;
}
ProducedType _tuple = targs.get(1);
gen.out("[");
int pos = 1;
while (!(empty.equals(_tuple.getDeclaration()) || _tuple.getDeclaration() instanceof TypeParameter)) {
if (pos > 1) gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos++), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
gen.out(MetamodelGenerator.KEY_TYPE, ":");
if (tuple.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen);
_tuple = _tuple.getTypeArgumentList().get(2);
} else if (sequential.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(0), gen);
_tuple = _tuple.getTypeArgumentList().get(0);
} else {
System.out.println("WTF? Tuple is actually " + _tuple.getProducedTypeQualifiedName() + ", " + _tuple.getClass().getName());
if (pos > 100) {
System.exit(1);
}
}
gen.out("}");
}
gen.out("]");
}
static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen) {
if (d.getAnnotations() == null || d.getAnnotations().isEmpty()) {
encodeForRuntime(d, gen, null);
} else {
encodeForRuntime(d, gen, new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":function(){return[");
boolean first = true;
for (Annotation a : d.getAnnotations()) {
if (first) first=false; else gen.out(",");
Declaration ad = d.getUnit().getPackage().getMemberOrParameter(d.getUnit(), a.getName(), null, false);
if (ad instanceof Method) {
gen.qualify(null, ad);
gen.out(gen.getNames().name(ad), "(");
if (a.getPositionalArguments() == null) {
for (Parameter p : ((Method)ad).getParameterLists().get(0).getParameters()) {
String v = a.getNamedArguments().get(p.getName());
gen.out(v == null ? "undefined" : v);
}
} else {
boolean farg = true;
for (String s : a.getPositionalArguments()) {
if (farg)farg=false; else gen.out(",");
gen.out(s);
}
}
gen.out(")");
} else {
gen.out("null/*MISSING DECLARATION FOR ANNOTATION ", a.getName(), "*/");
}
}
gen.out("];}");
}
});
}
}
/** Output a metamodel map for runtime use. */
static void encodeForRuntime(final Declaration d, final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
final boolean include = annotations != null && !annotations.getAnnotations().isEmpty();
encodeForRuntime(d, gen, include ? new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":");
outputAnnotationsFunction(annotations, gen);
}
} : null);
}
static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
+ boolean comma = false;
for(TypeParameter tp : tparms) {
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
- gen.out("'var':'out',");
+ gen.out("'var':'out'");
+ comma = true;
} else if (tp.isContravariant()) {
- gen.out("'var':'in',");
+ gen.out("'var':'in'");
+ comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
+ if (comma)gen.out(",");
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
+ comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
+ if (comma)gen.out(",");
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
+ comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
- gen.out(",'def':");
+ if (comma)gen.out(",");
+ gen.out("'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("};}");
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void metamodelTypeNameOrList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
if (pt == null) {
//In dynamic blocks we sometimes get a null producedType
pt = ((TypeDeclaration)pkg.getModule().getLanguageModule().getDirectPackage(
"ceylon.language").getDirectMember("Anything", null, false)).getType();
}
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputMetamodelTypeList(pkg, pt, gen);
} else if (type instanceof TypeParameter) {
gen.out("'", type.getNameAsString(), "'");
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(pkg, type), pt, gen);
//Type Parameters
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:{");
boolean first = true;
for (Map.Entry<TypeParameter, ProducedType> e : pt.getTypeArguments().entrySet()) {
if (first) first=false; else gen.out(",");
gen.out(e.getKey().getNameAsString(), ":");
metamodelTypeNameOrList(pkg, e.getValue(), gen);
}
gen.out("}");
}
gen.out("}");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputMetamodelTypeList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration type = pt.getDeclaration();
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
metamodelTypeNameOrList(pkg, t, gen);
first = false;
}
gen.out("]}");
}
ProducedType tupleFromParameters(List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) {
if (params == null || params.isEmpty()) {
return empty.getType();
}
ProducedType tt = empty.getType();
ProducedType et = null;
for (int i = params.size()-1; i>=0; i--) {
com.redhat.ceylon.compiler.typechecker.model.Parameter p = params.get(i);
if (et == null) {
et = p.getType();
} else {
UnionType ut = new UnionType(p.getModel().getUnit());
ArrayList<ProducedType> types = new ArrayList<>();
if (et.getCaseTypes() == null || et.getCaseTypes().isEmpty()) {
types.add(et);
} else {
types.addAll(et.getCaseTypes());
}
types.add(p.getType());
ut.setCaseTypes(types);
et = ut.getType();
}
Map<TypeParameter,ProducedType> args = new HashMap<>();
for (TypeParameter tp : tuple.getTypeParameters()) {
if ("First".equals(tp.getName())) {
args.put(tp, p.getType());
} else if ("Element".equals(tp.getName())) {
args.put(tp, et);
} else if ("Rest".equals(tp.getName())) {
args.put(tp, tt);
}
}
if (i == params.size()-1) {
tt = tuple.getType();
}
tt = tt.substitute(args);
}
return tt;
}
/** Outputs a function that returns the specified annotations, so that they can be loaded lazily. */
static void outputAnnotationsFunction(final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
if (annotations == null || annotations.getAnnotations().isEmpty()) {
gen.out("[]");
} else {
gen.out("function(){return[");
boolean first = true;
for (Tree.Annotation a : annotations.getAnnotations()) {
if (first) first=false; else gen.out(",");
gen.getInvoker().generateInvocation(a);
}
gen.out("];}");
}
}
/** Abstraction for a callback that generates the runtime annotations list as part of the metamodel. */
static interface RuntimeMetamodelAnnotationGenerator {
public void generateAnnotations();
}
}
| false | true | static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
for(TypeParameter tp : tparms) {
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out',");
} else if (tp.isContravariant()) {
gen.out("'var':'in',");
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (tp.getDefaultTypeArgument() != null) {
gen.out(",'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("};}");
}
| static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
boolean comma = false;
for(TypeParameter tp : tparms) {
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out'");
comma = true;
} else if (tp.isContravariant()) {
gen.out("'var':'in'");
comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
if (comma)gen.out(",");
gen.out("'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("};}");
}
|
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/rest/login/AccountStatus.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/rest/login/AccountStatus.java
index 0463d62f5..4cd4d76b0 100644
--- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/rest/login/AccountStatus.java
+++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/rest/login/AccountStatus.java
@@ -1,43 +1,51 @@
package net.cyklotron.cms.modules.rest.login;
import java.security.Principal;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.objectledge.authentication.AuthenticationException;
import org.objectledge.authentication.BlockedReason;
import org.objectledge.authentication.UserManager;
@Path("/login")
public class AccountStatus
{
private final UserManager userManager;
@Inject
public AccountStatus(UserManager userManager)
{
this.userManager = userManager;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
- public Response getAccountStatus(@QueryParam("uid") String uid) throws AuthenticationException
+ public Response getAccountStatus(@QueryParam("uid") String uid)
{
- Principal account = userManager.getUserByLogin(uid);
- if(userManager.isUserPasswordExpired(account))
+ try
{
- userManager.setUserShadowFlag(account, BlockedReason.PASSWORD_EXPIRED.getCode().toString());
- }
- Long expiration = userManager.getUserPasswordExpirationDays(account);
- BlockedReason blockedReason = userManager.checkAccountFlag(account);
- AccountStatusDto result = new AccountStatusDto(uid, blockedReason.getShortReason(), expiration);
- return Response.ok(result).build();
+ Principal account = userManager.getUserByLogin(uid);
+ if(userManager.isUserPasswordExpired(account))
+ {
+ userManager.setUserShadowFlag(account, BlockedReason.PASSWORD_EXPIRED.getCode().toString());
+ }
+ Long expiration = userManager.getUserPasswordExpirationDays(account);
+ BlockedReason blockedReason = userManager.checkAccountFlag(account);
+ AccountStatusDto result = new AccountStatusDto(uid, blockedReason.getShortReason(), expiration);
+ return Response.ok(result).build();
+ }
+ catch(AuthenticationException e)
+ {
+ AccountStatusDto result = new AccountStatusDto(uid, "invalid_credentials", 0L);
+ return Response.ok(result).build();
+ }
}
}
| false | true | public Response getAccountStatus(@QueryParam("uid") String uid) throws AuthenticationException
{
Principal account = userManager.getUserByLogin(uid);
if(userManager.isUserPasswordExpired(account))
{
userManager.setUserShadowFlag(account, BlockedReason.PASSWORD_EXPIRED.getCode().toString());
}
Long expiration = userManager.getUserPasswordExpirationDays(account);
BlockedReason blockedReason = userManager.checkAccountFlag(account);
AccountStatusDto result = new AccountStatusDto(uid, blockedReason.getShortReason(), expiration);
return Response.ok(result).build();
}
| public Response getAccountStatus(@QueryParam("uid") String uid)
{
try
{
Principal account = userManager.getUserByLogin(uid);
if(userManager.isUserPasswordExpired(account))
{
userManager.setUserShadowFlag(account, BlockedReason.PASSWORD_EXPIRED.getCode().toString());
}
Long expiration = userManager.getUserPasswordExpirationDays(account);
BlockedReason blockedReason = userManager.checkAccountFlag(account);
AccountStatusDto result = new AccountStatusDto(uid, blockedReason.getShortReason(), expiration);
return Response.ok(result).build();
}
catch(AuthenticationException e)
{
AccountStatusDto result = new AccountStatusDto(uid, "invalid_credentials", 0L);
return Response.ok(result).build();
}
}
|
diff --git a/src/main/java/com/flagstone/transform/shape/DefineMorphShape.java b/src/main/java/com/flagstone/transform/shape/DefineMorphShape.java
index b8a5da0..8414e25 100644
--- a/src/main/java/com/flagstone/transform/shape/DefineMorphShape.java
+++ b/src/main/java/com/flagstone/transform/shape/DefineMorphShape.java
@@ -1,591 +1,596 @@
/*
* DefineMorphShape.java
* Transform
*
* Copyright (c) 2001-2010 Flagstone Software Ltd. 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 Flagstone Software Ltd. 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.flagstone.transform.shape;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.flagstone.transform.coder.CoderException;
import com.flagstone.transform.coder.Context;
import com.flagstone.transform.coder.DefineTag;
import com.flagstone.transform.coder.Encoder;
import com.flagstone.transform.coder.MovieTypes;
import com.flagstone.transform.coder.SWFDecoder;
import com.flagstone.transform.coder.SWFEncoder;
import com.flagstone.transform.coder.SWFFactory;
import com.flagstone.transform.datatype.Bounds;
import com.flagstone.transform.exception.IllegalArgumentRangeException;
import com.flagstone.transform.fillstyle.FillStyle;
import com.flagstone.transform.linestyle.MorphLineStyle;
/**
* DefineMorphShape defines a shape that will morph from one form into another.
*
* <p>
* Only the start and end shapes are defined the Flash Player will perform the
* interpolation that transforms the shape at each staging in the morphing
* process.
* </p>
*
* <p>
* Morphing can be applied to any shape, however there are a few restrictions:
* </p>
*
* <ul>
* <li>The start and end shapes must have the same number of edges (Line and
* Curve objects).</li>
* <li>The fill style (Solid, Bitmap or Gradient) must be the same in the start
* and end shape.</li>
* <li>If a bitmap fill style is used then the same image must be used in the
* start and end shapes.</li>
* <li>If a gradient fill style is used then the gradient must contain the same
* number of points in the start and end shape.</li>
* <li>The start and end shape must contain the same set of ShapeStyle objects.</li>
* </ul>
*
* <p>
* To perform the morphing of a shape the shape is placed in the display list
* using a PlaceObject2 object. The ratio attribute in the PlaceObject2 object
* defines the progress of the morphing process. The ratio ranges between 0 and
* 65535 where 0 represents the start of the morphing process and 65535, the
* end.
* </p>
*
* <p>
* The edges in the shapes may change their type when a shape is morphed.
* Straight edges can become curves and vice versa.
* </p>
*
*/
//TODO(class)
public final class DefineMorphShape implements DefineTag {
private static final String FORMAT = "DefineMorphShape: { identifier=%d;"
+ " startBounds=%s; endBounds=%s; fillStyles=%s; lineStyles=%s;"
+ " startShape=%s; endShape=%s }";
private int identifier;
private Bounds startBounds;
private Bounds endBounds;
private List<FillStyle> fillStyles;
private List<MorphLineStyle> lineStyles;
private Shape startShape;
private Shape endShape;
private transient int length;
private transient int fillBits;
private transient int lineBits;
/**
* Creates and initialises a DefineMorphShape object using values encoded
* in the Flash binary format.
*
* @param coder
* an SWFDecoder object that contains the encoded Flash data.
*
* @param context
* a Context object used to manage the decoders for different
* type of object and to pass information on how objects are
* decoded.
*
* @throws CoderException
* if an error occurs while decoding the data.
*/
// TODO(optimise)
public DefineMorphShape(final SWFDecoder coder, final Context context)
throws CoderException {
final int start = coder.getPointer();
length = coder.readWord(2, false) & 0x3F;
if (length == 0x3F) {
length = coder.readWord(4, false);
}
final int end = coder.getPointer() + (length << 3);
final Map<Integer, Integer> vars = context.getVariables();
vars.put(Context.TRANSPARENT, 1);
vars.put(Context.ARRAY_EXTENDED, 1);
vars.put(Context.TYPE, MovieTypes.DEFINE_MORPH_SHAPE);
identifier = coder.readWord(2, false);
startBounds = new Bounds(coder);
endBounds = new Bounds(coder);
fillStyles = new ArrayList<FillStyle>();
lineStyles = new ArrayList<MorphLineStyle>();
// offset to the start of the second shape
coder.readWord(4, false);
// final int first = coder.getPointer();
int fillStyleCount = coder.readByte();
if (vars.containsKey(Context.ARRAY_EXTENDED)
&& (fillStyleCount == 0xFF)) {
fillStyleCount = coder.readWord(2, false);
}
final SWFFactory<FillStyle> decoder = context.getRegistry()
.getMorphFillStyleDecoder();
FillStyle fillStyle;
int type;
for (int i = 0; i < fillStyleCount; i++) {
type = coder.scanByte();
fillStyle = decoder.getObject(coder, context);
if (fillStyle == null) {
throw new CoderException(String.valueOf(type), start >>> 3, 0,
0, "Unsupported FillStyle");
}
fillStyles.add(fillStyle);
}
int lineStyleCount = coder.readByte();
if (vars.containsKey(Context.ARRAY_EXTENDED)
&& (lineStyleCount == 0xFF)) {
lineStyleCount = coder.readWord(2, false);
}
for (int i = 0; i < lineStyleCount; i++) {
lineStyles.add(new MorphLineStyle(coder, context));
}
if (context.getRegistry().getShapeDecoder() == null) {
startShape = new Shape();
startShape.add(new ShapeData(new byte[length
- ((coder.getPointer() - start) >> 3)]));
endShape = new Shape();
endShape.add(new ShapeData(new byte[length
- ((coder.getPointer() - start) >> 3)]));
} else {
startShape = new Shape(coder, context);
endShape = new Shape(coder, context);
}
vars.remove(Context.TRANSPARENT);
vars.put(Context.ARRAY_EXTENDED, 1);
vars.remove(Context.TYPE);
if (coder.getPointer() != end) {
- throw new CoderException(getClass().getName(), start >> 3, length,
- (coder.getPointer() - end) >> 3);
+ final int delta = (coder.getPointer() - end) >> 3;
+ if (delta == -33) {
+ coder.setPointer(end);
+ } else {
+ throw new CoderException(getClass().getName(), start >> 3, length,
+ (coder.getPointer() - end) >> 3);
+ }
}
}
/**
* Creates a DefineMorphShape object.
*
* @param uid
* an unique identifier for this object. Must be in the range
* 1..65535.
* @param startBounds
* the bounding rectangle enclosing the start shape. Must not be
* null.
* @param endBounds
* the bounding rectangle enclosing the end shape. Must not be
* null.
* @param fills
* an array of MorphSolidFill, MorphBitmapFill and
* MorphGradientFill objects. Must not be null.
* @param lines
* an array of MorphLineStyle objects. Must not be null.
* @param startShape
* the shape at the start of the morphing process. Must not be
* null.
* @param endShape
* the shape at the end of the morphing process. Must not be
* null.
*/
public DefineMorphShape(final int uid, final Bounds startBounds,
final Bounds endBounds, final List<FillStyle> fills,
final List<MorphLineStyle> lines, final Shape startShape,
final Shape endShape) {
setIdentifier(uid);
setStartBounds(startBounds);
setEndBounds(endBounds);
setFillStyles(fills);
setLineStyles(lines);
setStartShape(startShape);
setEndShape(endShape);
}
/**
* Creates and initialises a DefineMorphShape object using the values copied
* from another DefineMorphShape object.
*
* @param object
* a DefineMorphShape object from which the values will be
* copied.
*/
public DefineMorphShape(final DefineMorphShape object) {
identifier = object.identifier;
startBounds = object.startBounds;
endBounds = object.endBounds;
fillStyles = new ArrayList<FillStyle>(object.fillStyles.size());
for (final FillStyle style : object.fillStyles) {
fillStyles.add(style.copy());
}
lineStyles = new ArrayList<MorphLineStyle>(object.lineStyles.size());
for (final MorphLineStyle style : object.lineStyles) {
lineStyles.add(style.copy());
}
startShape = object.startShape.copy();
endShape = object.endShape.copy();
}
/** TODO(method). */
public int getIdentifier() {
return identifier;
}
/** TODO(method). */
public void setIdentifier(final int uid) {
if ((uid < 1) || (uid > 65535)) {
throw new IllegalArgumentRangeException(1, 65536, uid);
}
identifier = uid;
}
/**
* Returns the width of the shape at the start of the morphing process.
*/
public int getWidth() {
return startBounds.getWidth();
}
/**
* Returns the height of the shape at the start of the morphing process.
*/
public int getHeight() {
return startBounds.getHeight();
}
/**
* Add a LineStyle object to the array of line styles.
*
* @param aLineStyle
* and LineStyle object. Must not be null.
*/
public DefineMorphShape add(final MorphLineStyle aLineStyle) {
lineStyles.add(aLineStyle);
return this;
}
/**
* Add the fill style object to the array of fill styles.
*
* @param aFillStyle
* an FillStyle object. Must not be null.
*/
public DefineMorphShape add(final FillStyle aFillStyle) {
fillStyles.add(aFillStyle);
return this;
}
/**
* Returns the Bounds object that defines the bounding rectangle enclosing
* the start shape.
*/
public Bounds getStartBounds() {
return startBounds;
}
/**
* Returns the Bounds object that defines the bounding rectangle enclosing
* the end shape.
*/
public Bounds getEndBounds() {
return endBounds;
}
/**
* Returns the array of fill styles (MorphSolidFill, MorphBitmapFill and
* MorphGradientFill objects) for the shapes.
*/
public List<FillStyle> getFillStyles() {
return fillStyles;
}
/**
* Returns the array of line styles (MorphLineStyle objects) for the shapes.
*/
public List<MorphLineStyle> getLineStyles() {
return lineStyles;
}
/**
* Returns the starting shape.
*/
public Shape getStartShape() {
return startShape;
}
/**
* Returns the ending shape.
*/
public Shape getEndShape() {
return endShape;
}
/**
* Sets the starting bounds of the shape.
*
* @param aBounds
* the bounding rectangle enclosing the start shape. Must not be
* null.
*/
public void setStartBounds(final Bounds aBounds) {
if (aBounds == null) {
throw new NullPointerException();
}
startBounds = aBounds;
}
/**
* Sets the ending bounds of the shape.
*
* @param aBounds
* the bounding rectangle enclosing the end shape. Must not be
* null.
*/
public void setEndBounds(final Bounds aBounds) {
if (aBounds == null) {
throw new NullPointerException();
}
endBounds = aBounds;
}
/**
* Sets the array of morph fill styles.
*
* @param anArray
* an array of MorphSolidFill, MorphBitmapFill and
* MorphGradientFill objects. Must not be null.
*/
public void setFillStyles(final List<FillStyle> anArray) {
if (anArray == null) {
throw new NullPointerException();
}
fillStyles = anArray;
}
/**
* Sets the array of morph line styles.
*
* @param anArray
* an array of MorphLineStyle objects. Must not be null.
*/
public void setLineStyles(final List<MorphLineStyle> anArray) {
if (anArray == null) {
throw new NullPointerException();
}
lineStyles = anArray;
}
/**
* Sets the shape that will be displayed at the start of the morphing
* process.
*
* @param aShape
* the shape at the start of the morphing process. Must not be
* null.
*/
public void setStartShape(final Shape aShape) {
if (aShape == null) {
throw new NullPointerException();
}
startShape = aShape;
}
/**
* Sets the shape that will be displayed at the end of the morphing process.
*
* @param aShape
* the shape at the end of the morphing process. Must not be
* null.
*/
public void setEndShape(final Shape aShape) {
if (aShape == null) {
throw new NullPointerException();
}
endShape = aShape;
}
/** TODO(method). */
public DefineMorphShape copy() {
return new DefineMorphShape(this);
}
@Override
public String toString() {
return String.format(FORMAT, identifier, startBounds, endBounds,
fillStyles, lineStyles, startShape, endShape);
}
// TODO(optimise)
/** {@inheritDoc} */
public int prepareToEncode(final SWFEncoder coder, final Context context) {
fillBits = Encoder.unsignedSize(fillStyles.size());
lineBits = Encoder.unsignedSize(lineStyles.size());
final Map<Integer, Integer> vars = context.getVariables();
if (vars.containsKey(Context.POSTSCRIPT)) {
if (fillBits == 0) {
fillBits = 1;
}
if (lineBits == 0) {
lineBits = 1;
}
}
vars.put(Context.TRANSPARENT, 1);
length = 2 + startBounds.prepareToEncode(coder, context);
length += endBounds.prepareToEncode(coder, context);
length += 4;
length += (fillStyles.size() >= 255) ? 3 : 1;
for (final FillStyle style : fillStyles) {
length += style.prepareToEncode(coder, context);
}
length += (lineStyles.size() >= 255) ? 3 : 1;
for (final MorphLineStyle style : lineStyles) {
length += style.prepareToEncode(coder, context);
}
vars.put(Context.ARRAY_EXTENDED, 1);
vars.put(Context.FILL_SIZE, fillBits);
vars.put(Context.LINE_SIZE, lineBits);
length += startShape.prepareToEncode(coder, context);
// Number of Fill and Line bits is zero for end shape.
vars.put(Context.FILL_SIZE, 0);
vars.put(Context.LINE_SIZE, 0);
length += endShape.prepareToEncode(coder, context);
vars.remove(Context.ARRAY_EXTENDED);
vars.remove(Context.TRANSPARENT);
return (length > 62 ? 6 : 2) + length;
}
// TODO(optimise)
/** {@inheritDoc} */
public void encode(final SWFEncoder coder, final Context context)
throws CoderException {
final int start = coder.getPointer();
if (length >= 63) {
coder.writeWord((MovieTypes.DEFINE_MORPH_SHAPE << 6) | 0x3F, 2);
coder.writeWord(length, 4);
} else {
coder.writeWord((MovieTypes.DEFINE_MORPH_SHAPE << 6) | length, 2);
}
final int end = coder.getPointer() + (length << 3);
coder.writeWord(identifier, 2);
final Map<Integer, Integer> vars = context.getVariables();
vars.put(Context.TRANSPARENT, 1);
startBounds.encode(coder, context);
endBounds.encode(coder, context);
final int offsetStart = coder.getPointer();
coder.writeWord(0, 4);
if (fillStyles.size() >= 255) {
coder.writeWord(0xFF, 1);
coder.writeWord(fillStyles.size(), 2);
} else {
coder.writeWord(fillStyles.size(), 1);
}
for (final FillStyle style : fillStyles) {
style.encode(coder, context);
}
if (lineStyles.size() >= 255) {
coder.writeWord(0xFF, 1);
coder.writeWord(lineStyles.size(), 2);
} else {
coder.writeWord(lineStyles.size(), 1);
}
for (final MorphLineStyle style : lineStyles) {
style.encode(coder, context);
}
vars.put(Context.ARRAY_EXTENDED, 1);
vars.put(Context.FILL_SIZE, fillBits);
vars.put(Context.LINE_SIZE, lineBits);
startShape.encode(coder, context);
final int offsetEnd = (coder.getPointer() - offsetStart) >> 3;
final int currentCursor = coder.getPointer();
coder.setPointer(offsetStart);
coder.writeWord(offsetEnd - 4, 4);
coder.setPointer(currentCursor);
// Number of Fill and Line bits is zero for end shape.
vars.put(Context.FILL_SIZE, 0);
vars.put(Context.LINE_SIZE, 0);
endShape.encode(coder, context);
vars.remove(Context.ARRAY_EXTENDED);
vars.remove(Context.TRANSPARENT);
if (coder.getPointer() != end) {
throw new CoderException(getClass().getName(), start >> 3, length,
(coder.getPointer() - end) >> 3);
}
}
}
| true | true | public DefineMorphShape(final SWFDecoder coder, final Context context)
throws CoderException {
final int start = coder.getPointer();
length = coder.readWord(2, false) & 0x3F;
if (length == 0x3F) {
length = coder.readWord(4, false);
}
final int end = coder.getPointer() + (length << 3);
final Map<Integer, Integer> vars = context.getVariables();
vars.put(Context.TRANSPARENT, 1);
vars.put(Context.ARRAY_EXTENDED, 1);
vars.put(Context.TYPE, MovieTypes.DEFINE_MORPH_SHAPE);
identifier = coder.readWord(2, false);
startBounds = new Bounds(coder);
endBounds = new Bounds(coder);
fillStyles = new ArrayList<FillStyle>();
lineStyles = new ArrayList<MorphLineStyle>();
// offset to the start of the second shape
coder.readWord(4, false);
// final int first = coder.getPointer();
int fillStyleCount = coder.readByte();
if (vars.containsKey(Context.ARRAY_EXTENDED)
&& (fillStyleCount == 0xFF)) {
fillStyleCount = coder.readWord(2, false);
}
final SWFFactory<FillStyle> decoder = context.getRegistry()
.getMorphFillStyleDecoder();
FillStyle fillStyle;
int type;
for (int i = 0; i < fillStyleCount; i++) {
type = coder.scanByte();
fillStyle = decoder.getObject(coder, context);
if (fillStyle == null) {
throw new CoderException(String.valueOf(type), start >>> 3, 0,
0, "Unsupported FillStyle");
}
fillStyles.add(fillStyle);
}
int lineStyleCount = coder.readByte();
if (vars.containsKey(Context.ARRAY_EXTENDED)
&& (lineStyleCount == 0xFF)) {
lineStyleCount = coder.readWord(2, false);
}
for (int i = 0; i < lineStyleCount; i++) {
lineStyles.add(new MorphLineStyle(coder, context));
}
if (context.getRegistry().getShapeDecoder() == null) {
startShape = new Shape();
startShape.add(new ShapeData(new byte[length
- ((coder.getPointer() - start) >> 3)]));
endShape = new Shape();
endShape.add(new ShapeData(new byte[length
- ((coder.getPointer() - start) >> 3)]));
} else {
startShape = new Shape(coder, context);
endShape = new Shape(coder, context);
}
vars.remove(Context.TRANSPARENT);
vars.put(Context.ARRAY_EXTENDED, 1);
vars.remove(Context.TYPE);
if (coder.getPointer() != end) {
throw new CoderException(getClass().getName(), start >> 3, length,
(coder.getPointer() - end) >> 3);
}
}
| public DefineMorphShape(final SWFDecoder coder, final Context context)
throws CoderException {
final int start = coder.getPointer();
length = coder.readWord(2, false) & 0x3F;
if (length == 0x3F) {
length = coder.readWord(4, false);
}
final int end = coder.getPointer() + (length << 3);
final Map<Integer, Integer> vars = context.getVariables();
vars.put(Context.TRANSPARENT, 1);
vars.put(Context.ARRAY_EXTENDED, 1);
vars.put(Context.TYPE, MovieTypes.DEFINE_MORPH_SHAPE);
identifier = coder.readWord(2, false);
startBounds = new Bounds(coder);
endBounds = new Bounds(coder);
fillStyles = new ArrayList<FillStyle>();
lineStyles = new ArrayList<MorphLineStyle>();
// offset to the start of the second shape
coder.readWord(4, false);
// final int first = coder.getPointer();
int fillStyleCount = coder.readByte();
if (vars.containsKey(Context.ARRAY_EXTENDED)
&& (fillStyleCount == 0xFF)) {
fillStyleCount = coder.readWord(2, false);
}
final SWFFactory<FillStyle> decoder = context.getRegistry()
.getMorphFillStyleDecoder();
FillStyle fillStyle;
int type;
for (int i = 0; i < fillStyleCount; i++) {
type = coder.scanByte();
fillStyle = decoder.getObject(coder, context);
if (fillStyle == null) {
throw new CoderException(String.valueOf(type), start >>> 3, 0,
0, "Unsupported FillStyle");
}
fillStyles.add(fillStyle);
}
int lineStyleCount = coder.readByte();
if (vars.containsKey(Context.ARRAY_EXTENDED)
&& (lineStyleCount == 0xFF)) {
lineStyleCount = coder.readWord(2, false);
}
for (int i = 0; i < lineStyleCount; i++) {
lineStyles.add(new MorphLineStyle(coder, context));
}
if (context.getRegistry().getShapeDecoder() == null) {
startShape = new Shape();
startShape.add(new ShapeData(new byte[length
- ((coder.getPointer() - start) >> 3)]));
endShape = new Shape();
endShape.add(new ShapeData(new byte[length
- ((coder.getPointer() - start) >> 3)]));
} else {
startShape = new Shape(coder, context);
endShape = new Shape(coder, context);
}
vars.remove(Context.TRANSPARENT);
vars.put(Context.ARRAY_EXTENDED, 1);
vars.remove(Context.TYPE);
if (coder.getPointer() != end) {
final int delta = (coder.getPointer() - end) >> 3;
if (delta == -33) {
coder.setPointer(end);
} else {
throw new CoderException(getClass().getName(), start >> 3, length,
(coder.getPointer() - end) >> 3);
}
}
}
|
diff --git a/src/org/rsbot/script/methods/Walking.java b/src/org/rsbot/script/methods/Walking.java
index 9b15c675..45acb619 100644
--- a/src/org/rsbot/script/methods/Walking.java
+++ b/src/org/rsbot/script/methods/Walking.java
@@ -1,567 +1,568 @@
package org.rsbot.script.methods;
import org.rsbot.script.wrappers.*;
import java.awt.*;
/**
* Walking related operations.
*/
public class Walking extends MethodProvider {
public final int INTERFACE_RUN_ORB = 750;
Walking(final MethodContext ctx) {
super(ctx);
}
private RSPath lastPath;
private RSTile lastDestination;
private RSTile lastStep;
/**
* Creates a new path based on a provided array of tile waypoints.
*
* @param tiles The waypoint tiles.
* @return An RSTilePath.
*/
public RSTilePath newTilePath(final RSTile[] tiles) {
if (tiles == null) {
throw new IllegalArgumentException("null waypoint list");
}
return new RSTilePath(methods, tiles);
}
/**
* Generates a path from the player's current location to a destination
* tile.
*
* @param destination The destination tile.
* @return The path as an RSTile array.
*/
public RSPath getPath(final RSTile destination) {
return new RSLocalPath(methods, destination);
}
/**
* Determines whether or not a given tile is in the loaded map area.
*
* @param tile The tile to check.
* @return <tt>true</tt> if local; otherwise <tt>false</tt>.
*/
public boolean isLocal(final RSTile tile) {
int[][] flags = getCollisionFlags(methods.game.getPlane());
int x = tile.getX() - methods.game.getBaseX();
int y = tile.getY() - methods.game.getBaseY();
return (flags != null && x >= 0 && y >= 0 && x < flags.length && y < flags.length);
}
/**
* Walks one tile towards the given destination using a generated path.
*
* @param destination The destination tile.
* @return <tt>true</tt> if the next tile was walked to; otherwise
* <tt>false</tt>.
*/
public boolean walkTo(final RSTile destination) {
if (destination.equals(lastDestination)
&& methods.calc.distanceTo(lastStep) < 10) {
return lastPath.traverse();
}
lastDestination = destination;
lastPath = getPath(destination);
if (!lastPath.isValid()) {
return false;
}
lastStep = lastPath.getNext();
return lastPath.traverse();
}
/**
* Walks to the given tile using the minimap with 1 tile randomness.
*
* @param t The tile to walk to.
* @return <tt>true</tt> if the tile was clicked; otherwise <tt>false</tt>.
* @see #walkTileMM(RSTile, int, int)
*/
public boolean walkTileMM(final RSTile t) {
return walkTileMM(t, 0, 0);
}
/**
* Walks to the given tile using the minimap with given randomness.
*
* @param t The tile to walk to.
* @param x The x randomness (between 0 and x-1).
* @param y The y randomness (between 0 and y-1).
* @return <tt>true</tt> if the tile was clicked; otherwise <tt>false</tt>.
*/
public boolean walkTileMM(final RSTile t, final int x, final int y) {
/*RSTile dest = new RSTile(t.getX() + random(0, x), t.getY()
+ random(0, y)); You can't just add randomness to the tile, it should be subtracted.*/
- int xx = dest.getX(), yy = dest.getY();
+ int xx = t.getX(), yy = t.getY();
if (x > 0) {
if (random(1, 2) == random(1, 2)) {
xx += random(0, x);
} else {
xx -= random(0, x);
}
}
if (y > 0) {
if (random(1, 2) == random(1, 2)) {
yy += random(0, y);
} else {
yy -= random(0, y);
}
}
RSTile dest = new RSTile(xx, yy);
if (!methods.calc.tileOnMap(dest)) {
dest = getClosestTileOnMap(dest);
}
Point p = methods.calc.tileToMinimap(dest);
if (p.x != -1 && p.y != -1) {
- int xx = p.x, yy = p.y;
+ xx = p.x;
+ yy = p.y;
if (random(1, 2) == random(1, 2)) {
xx += random(0, 50);
} else {
xx -= random(0, 50);
}
if (random(1, 2) == random(1, 2)) {
yy += random(0, 50);
} else {
yy -= random(0, 50);
}
methods.mouse.move(xx, yy);
p = methods.calc.tileToMinimap(dest);
if (p.x == -1 || p.y == -1) {
return false;
}
methods.mouse.move(p);
Point p2 = methods.calc.tileToMinimap(dest);
if (p2.x != -1 && p2.y != -1) {
methods.mouse.move(p2);
if (!methods.mouse.getLocation().equals(p2)) {
methods.mouse.hop(p2);
}
methods.mouse.click(p2, true);
return true;
}
}
return false;
}
/**
* Walks to the given tile using the minimap with given randomness.
*
* @param t The tile to walk to.
* @param r The maximum deviation from the tile to allow.
* @return <tt>true</tt> if the tile was clicked; otherwise <tt>false</tt>.
*/
public boolean walkTileMM(final RSTile t, final int r) {
int x = t.getX();
int y = t.getY();
if (random(1, 2) == random(1, 2)) {
x += random(0, r);
} else {
x -= random(0, r);
}
if (random(1, 2) == random(1, 2)) {
y += random(0, r);
} else {
y -= random(0, r);
}
RSTile dest = new RSTile(x, y);
if (methods.players.getMyPlayer().getLocation().equals(dest)) {
return false;
}
return walkTileMM(dest, 0, 0);
}
/**
* Walks to a tile using onScreen clicks and not the MiniMap. If the tile is
* not on the screen, it will find the closest tile that is on screen and it
* will walk there instead.
*
* @param tileToWalk Tile to walk.
* @return True if successful.
*/
public boolean walkTileOnScreen(final RSTile tileToWalk) {
return methods.tiles.doAction(methods.calc.getTileOnScreen(tileToWalk),
"Walk ");
}
/**
* Rests until 100% energy
*
* @return <tt>true</tt> if rest was enabled; otherwise false.
* @see #rest(int)
*/
public boolean rest() {
return rest(100);
}
/**
* Rests until a certain amount of energy is reached.
*
* @param stopEnergy Amount of energy at which it should stop resting.
* @return <tt>true</tt> if rest was enabled; otherwise false.
*/
public boolean rest(final int stopEnergy) {
int energy = getEnergy();
for (int d = 0; d < 5; d++) {
methods.interfaces.getComponent(INTERFACE_RUN_ORB, 1).doAction(
"Rest");
methods.mouse.moveSlightly();
sleep(random(400, 600));
int anim = methods.players.getMyPlayer().getAnimation();
if (anim == 12108 || anim == 2033 || anim == 2716 || anim == 11786
|| anim == 5713) {
break;
}
if (d == 4) {
return false;
}
}
while (energy < stopEnergy) {
sleep(random(250, 500));
energy = getEnergy();
}
return true;
}
/**
* Turns run on or off using the game GUI controls.
*
* @param enable <tt>true</tt> to enable run, <tt>false</tt> to disable it.
*/
public void setRun(final boolean enable) {
if (isRunEnabled() != enable) {
methods.interfaces.getComponent(INTERFACE_RUN_ORB, 0).doClick();
}
}
/**
* Generates a path from the player's current location to a destination
* tile.
*
* @param destination The destination tile.
* @return The path as an RSTile array.
*/
@Deprecated
public RSTile[] findPath(RSTile destination) {
RSLocalPath path = new RSLocalPath(methods, destination);
if (path.isValid()) {
RSTilePath tp = path.getCurrentTilePath();
if (tp != null) {
return tp.toArray();
}
}
return new RSTile[0];
}
/**
* Randomizes a single tile.
*
* @param tile The RSTile to randomize.
* @param maxXDeviation Max X distance from tile.getX().
* @param maxYDeviation Max Y distance from tile.getY().
* @return The randomized tile.
* @deprecated Use
* {@link org.rsbot.script.wrappers.RSTile#randomize(int, int)}.
*/
@Deprecated
public RSTile randomize(RSTile tile, int maxXDeviation, int maxYDeviation) {
return tile.randomize(maxXDeviation, maxYDeviation);
}
/**
* Returns the closest tile on the minimap to a given tile.
*
* @param tile The destination tile.
* @return Returns the closest tile to the destination on the minimap.
*/
public RSTile getClosestTileOnMap(final RSTile tile) {
if (!methods.calc.tileOnMap(tile) && methods.game.isLoggedIn()) {
RSTile loc = methods.players.getMyPlayer().getLocation();
RSTile walk = new RSTile((loc.getX() + tile.getX()) / 2,
(loc.getY() + tile.getY()) / 2);
return methods.calc.tileOnMap(walk) ? walk
: getClosestTileOnMap(walk);
}
return tile;
}
/**
* Returns whether or not run is enabled.
*
* @return <tt>true</tt> if run mode is enabled; otherwise <tt>false</tt>.
*/
public boolean isRunEnabled() {
return methods.settings.getSetting(173) == 1;
}
/**
* Returns the player's current run energy.
*
* @return The player's current run energy.
*/
public int getEnergy() {
try {
return Integer.parseInt(methods.interfaces.getComponent(750, 5)
.getText());
} catch (NumberFormatException e) {
return 0;
}
}
/**
* Gets the destination tile (where the flag is on the minimap). If there is
* no destination currently, null will be returned.
*
* @return The current destination tile, or null.
*/
public RSTile getDestination() {
if (methods.client.getDestX() <= 0) {
return null;
}
return new RSTile(
methods.client.getDestX() + methods.client.getBaseX(),
methods.client.getDestY() + methods.client.getBaseY());
}
/**
* Gets the collision flags for a given floor level in the loaded region.
*
* @param plane The floor level (0, 1, 2 or 3).
* @return the collision flags.
*/
public int[][] getCollisionFlags(final int plane) {
return methods.client.getRSGroundDataArray()[plane].getBlocks();
}
/**
* Returns the collision map offset from the current region base on a given
* plane.
*
* @param plane The floor level.
* @return The offset as an RSTile.
*/
public RSTile getCollisionOffset(final int plane) {
org.rsbot.client.RSGroundData data = methods.client
.getRSGroundDataArray()[plane];
return new RSTile(data.getX(), data.getY());
}
// DEPRECATED
/**
* Randomizes a single tile.
*
* @param tile The RSTile to randomize.
* @param maxXDeviation Max X distance from tile.getX().
* @param maxYDeviation Max Y distance from tile.getY().
* @return The randomized tile.
* @deprecated Use
* {@link #randomize(org.rsbot.script.wrappers.RSTile, int, int)}
* .
*/
@Deprecated
public RSTile randomizeTile(RSTile tile, int maxXDeviation,
int maxYDeviation) {
return randomize(tile, maxXDeviation, maxYDeviation);
}
/**
* Walks towards the end of a path. This method should be looped.
*
* @param path The path to walk along.
* @return <tt>true</tt> if the next tile was reached; otherwise
* <tt>false</tt>.
* @see #walkPathMM(RSTile[], int)
*/
@Deprecated
public boolean walkPathMM(RSTile[] path) {
return walkPathMM(path, 16);
}
/**
* Walks towards the end of a path. This method should be looped.
*
* @param path The path to walk along.
* @param maxDist See {@link #nextTile(RSTile[], int)}.
* @return <tt>true</tt> if the next tile was reached; otherwise
* <tt>false</tt>.
* @see #walkPathMM(RSTile[], int, int)
*/
@Deprecated
public boolean walkPathMM(RSTile[] path, int maxDist) {
return walkPathMM(path, maxDist, 1, 1);
}
/**
* Walks towards the end of a path. This method should be looped.
*
* @param path The path to walk along.
* @param randX The X value to randomize each tile in the path by.
* @param randY The Y value to randomize each tile in the path by.
* @return <tt>true</tt> if the next tile was reached; otherwise
* <tt>false</tt>.
* @see #walkPathMM(RSTile[], int, int, int)
*/
@Deprecated
public boolean walkPathMM(RSTile[] path, int randX, int randY) {
return walkPathMM(path, 16, randX, randY);
}
/**
* Walks towards the end of a path. This method should be looped.
*
* @param path The path to walk along.
* @param maxDist See {@link #nextTile(RSTile[], int)}.
* @param randX The X value to randomize each tile in the path by.
* @param randY The Y value to randomize each tile in the path by.
* @return <tt>true</tt> if the next tile was reached; otherwise
* <tt>false</tt>.
*/
@Deprecated
public boolean walkPathMM(RSTile[] path, int maxDist, int randX, int randY) {
try {
RSTile next = nextTile(path, maxDist);
return next != null && walkTileMM(next, randX, randY);
} catch (Exception e) {
return false;
}
}
/**
* Walks to the end of a path via the screen. This method should be looped.
*
* @param path The path to walk along.
* @return <tt>true</tt> if the next tile was reached; otherwise
* <tt>false</tt>.
* @see #walkPathOnScreen(RSTile[], int)
*/
@Deprecated
public boolean walkPathOnScreen(RSTile[] path) {
return walkPathOnScreen(path, 16);
}
/**
* Walks a path using onScreen clicks and not the MiniMap. If the next tile
* is not on the screen, it will find the closest tile that is on screen and
* it will walk there instead.
*
* @param path Path to walk.
* @param maxDist Max distance between tiles in the path.
* @return True if successful.
*/
@Deprecated
public boolean walkPathOnScreen(RSTile[] path, int maxDist) {
RSTile next = nextTile(path, maxDist);
if (next != null) {
RSTile os = methods.calc.getTileOnScreen(next);
return os != null && methods.tiles.doAction(os, "Walk");
}
return false;
}
/**
* Reverses an array of tiles.
*
* @param other The <tt>RSTile</tt> path array to reverse.
* @return The reverse <tt>RSTile</tt> path for the given <tt>RSTile</tt>
* path.
*/
@Deprecated
public RSTile[] reversePath(RSTile[] other) {
RSTile[] t = new RSTile[other.length];
for (int i = 0; i < t.length; i++) {
t[i] = other[other.length - i - 1];
}
return t;
}
/**
* Returns the next tile to walk to on a path.
*
* @param path The path.
* @return The next <tt>RSTile</tt> to walk to on the provided path; or
* <code>null</code> if far from path or at destination.
* @see #nextTile(RSTile[], int)
*/
@Deprecated
public RSTile nextTile(RSTile path[]) {
return nextTile(path, 17);
}
/**
* Returns the next tile to walk to in a path.
*
* @param path The path.
* @param skipDist If the distance to the tile after the next in the path is less
* than or equal to this distance, the tile after next will be
* returned rather than the next tile, skipping one. This
* interlacing aids continuous walking.
* @return The next <tt>RSTile</tt> to walk to on the provided path; or
* <code>null</code> if far from path or at destination.
*/
@Deprecated
public RSTile nextTile(RSTile path[], int skipDist) {
int dist = 99;
int closest = -1;
for (int i = path.length - 1; i >= 0; i--) {
RSTile tile = path[i];
int d = methods.calc.distanceTo(tile);
if (d < dist) {
dist = d;
closest = i;
}
}
int feasibleTileIndex = -1;
for (int i = closest; i < path.length; i++) {
if (methods.calc.distanceTo(path[i]) <= skipDist) {
feasibleTileIndex = i;
} else {
break;
}
}
if (feasibleTileIndex == -1) {
return null;
} else {
return path[feasibleTileIndex];
}
}
/**
* Randomizes a path of tiles.
*
* @param path The RSTiles to randomize.
* @param maxXDeviation Max X distance from tile.getX().
* @param maxYDeviation Max Y distance from tile.getY().
* @return The new, randomized path.
*/
@Deprecated
public RSTile[] randomizePath(RSTile[] path, int maxXDeviation,
int maxYDeviation) {
RSTile[] rez = new RSTile[path.length];
for (int i = 0; i < path.length; i++) {
rez[i] = randomize(path[i], maxXDeviation, maxYDeviation);
}
return rez;
}
/**
* Returns the web of a path.
*
* @param to The tile to walk to.
* @return Returns the web allocation.
*/
public Web getWebPath(final RSTile to) {
return new Web(methods, methods.players.getMyPlayer().getLocation(), to);
}
}
| false | true | public boolean walkTileMM(final RSTile t, final int x, final int y) {
/*RSTile dest = new RSTile(t.getX() + random(0, x), t.getY()
+ random(0, y)); You can't just add randomness to the tile, it should be subtracted.*/
int xx = dest.getX(), yy = dest.getY();
if (x > 0) {
if (random(1, 2) == random(1, 2)) {
xx += random(0, x);
} else {
xx -= random(0, x);
}
}
if (y > 0) {
if (random(1, 2) == random(1, 2)) {
yy += random(0, y);
} else {
yy -= random(0, y);
}
}
RSTile dest = new RSTile(xx, yy);
if (!methods.calc.tileOnMap(dest)) {
dest = getClosestTileOnMap(dest);
}
Point p = methods.calc.tileToMinimap(dest);
if (p.x != -1 && p.y != -1) {
int xx = p.x, yy = p.y;
if (random(1, 2) == random(1, 2)) {
xx += random(0, 50);
} else {
xx -= random(0, 50);
}
if (random(1, 2) == random(1, 2)) {
yy += random(0, 50);
} else {
yy -= random(0, 50);
}
methods.mouse.move(xx, yy);
p = methods.calc.tileToMinimap(dest);
if (p.x == -1 || p.y == -1) {
return false;
}
methods.mouse.move(p);
Point p2 = methods.calc.tileToMinimap(dest);
if (p2.x != -1 && p2.y != -1) {
methods.mouse.move(p2);
if (!methods.mouse.getLocation().equals(p2)) {
methods.mouse.hop(p2);
}
methods.mouse.click(p2, true);
return true;
}
}
return false;
}
| public boolean walkTileMM(final RSTile t, final int x, final int y) {
/*RSTile dest = new RSTile(t.getX() + random(0, x), t.getY()
+ random(0, y)); You can't just add randomness to the tile, it should be subtracted.*/
int xx = t.getX(), yy = t.getY();
if (x > 0) {
if (random(1, 2) == random(1, 2)) {
xx += random(0, x);
} else {
xx -= random(0, x);
}
}
if (y > 0) {
if (random(1, 2) == random(1, 2)) {
yy += random(0, y);
} else {
yy -= random(0, y);
}
}
RSTile dest = new RSTile(xx, yy);
if (!methods.calc.tileOnMap(dest)) {
dest = getClosestTileOnMap(dest);
}
Point p = methods.calc.tileToMinimap(dest);
if (p.x != -1 && p.y != -1) {
xx = p.x;
yy = p.y;
if (random(1, 2) == random(1, 2)) {
xx += random(0, 50);
} else {
xx -= random(0, 50);
}
if (random(1, 2) == random(1, 2)) {
yy += random(0, 50);
} else {
yy -= random(0, 50);
}
methods.mouse.move(xx, yy);
p = methods.calc.tileToMinimap(dest);
if (p.x == -1 || p.y == -1) {
return false;
}
methods.mouse.move(p);
Point p2 = methods.calc.tileToMinimap(dest);
if (p2.x != -1 && p2.y != -1) {
methods.mouse.move(p2);
if (!methods.mouse.getLocation().equals(p2)) {
methods.mouse.hop(p2);
}
methods.mouse.click(p2, true);
return true;
}
}
return false;
}
|
diff --git a/src/org/biojava/bio/structure/io/FileConvert.java b/src/org/biojava/bio/structure/io/FileConvert.java
index 62ea75a71..c727509df 100644
--- a/src/org/biojava/bio/structure/io/FileConvert.java
+++ b/src/org/biojava/bio/structure/io/FileConvert.java
@@ -1,425 +1,425 @@
/*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on 26.04.2004
* @author Andreas Prlic
*
*/
package org.biojava.bio.structure.io;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.Chain;
import org.biojava.bio.structure.Group;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.utils.xml.XMLWriter;
/** Methods to convert a structure object into different file formats.
* @author Andreas Prlic
* @since 1.4
*/
public class FileConvert {
Structure structure ;
boolean printConnections;
/**
* Constructs a FileConvert object.
*
* @param struc a Structure object
*/
public FileConvert(Structure struc) {
structure = struc ;
printConnections = true;
}
/** align a string to the right
* length is the total length the new string should take, inlcuding spaces on the left
* incredible that this tool is missing in java !!!
*/
private String alignRight(String input, int length){
String spaces = " " ;
int n = input.length();
int diff = length - n ;
String s = "";
if (n < length) {
s = spaces.substring(0,diff) + input;
} else {
// does not work
return input ;
}
return s;
}
/** returns if the Connections should be added
* default is true;
* @return if the printConnections flag is set
*/
public boolean doPrintConnections() {
return printConnections;
}
/** enable/disable printing of connections
* connections are sometimes buggy in PDB files
* so there are some cases where one might turn this off.
* @param printConnections
*/
public void setPrintConnections(boolean printConnections) {
this.printConnections = printConnections;
}
/** prints the connections in PDB style
*
* Thanks to Tamas Horvath for this one
*/
private String printPDBConnections(){
StringBuffer str = new StringBuffer();
List cons = (ArrayList) structure.getConnections();
for (int cnr = 0; cnr<cons.size();cnr++){
HashMap con = (HashMap) cons.get(cnr);
Integer as = (Integer) con.get("atomserial");
String atomserial = "";
String bond1 = "";
String bond2 = "";
String bond3 = "";
String bond4 = "";
String hyd1 = "";
String hyd2 = "";
String salt1 = "";
String hyd3 = "";
String hyd4 = "";
String salt2 = "";
if (con.containsKey("bond1")) bond1 = con.get("bond1").toString();
if (con.containsKey("bond2")) bond2 = con.get("bond2").toString();
if (con.containsKey("bond3")) bond3 = con.get("bond3").toString();
if (con.containsKey("bond4")) bond4 = con.get("bond4").toString();
if (con.containsKey("hyd1")) hyd1 = con.get("hyd1").toString();
if (con.containsKey("hyd2")) hyd2 = con.get("hyd2").toString();
if (con.containsKey("salt1")) salt1 = con.get("salt1").toString();
if (con.containsKey("hyd3")) hyd3 = con.get("hyd3").toString();
if (con.containsKey("hyd4")) hyd4 = con.get("hyd4").toString();
if (con.containsKey("salt2")) salt2 = con.get("salt2").toString();
atomserial = alignRight(""+as,5) ;
bond1 = alignRight(bond1,5) ;
bond2 = alignRight(bond2,5) ;
bond3 = alignRight(bond3,5) ;
bond4 = alignRight(bond4,5) ;
hyd1 = alignRight(hyd1,5) ;
hyd2 = alignRight(hyd2,5) ;
salt1 = alignRight(salt1,5) ;
hyd3 = alignRight(hyd3,5) ;
hyd4 = alignRight(hyd4,5) ;
salt2 = alignRight(salt2,5) ;
String connectLine = "CONECT" + atomserial + bond1 + bond2 + bond3 +
bond4 + hyd1 + hyd2 + salt1 + hyd3 + hyd4 + salt2;
str.append(connectLine + "\n");
}
return str.toString();
}
/** Convert a structure into a PDB file.
* @return a String representing a PDB file.
*/
public String toPDB() {
StringBuffer str = new StringBuffer();
//int i = 0 ;
// Locale should be english, e.g. in DE separator is "," -> PDB files have "." !
DecimalFormat d3 = (DecimalFormat)NumberFormat.getInstance(java.util.Locale.UK);
d3.setMaximumIntegerDigits(3);
d3.setMinimumFractionDigits(3);
d3.setMaximumFractionDigits(3);
DecimalFormat d2 = (DecimalFormat)NumberFormat.getInstance(java.util.Locale.UK);
d2.setMaximumIntegerDigits(3);
d3.setMinimumFractionDigits(3);
d3.setMaximumFractionDigits(3);
// do for all models
int nrModels = structure.nrModels() ;
if ( structure.isNmr()) {
str.append("EXPDTA NMR, "+ nrModels+" STRUCTURES\n") ;
}
for (int m = 0 ; m < nrModels ; m++) {
ArrayList model = (ArrayList)structure.getModel(m);
// todo support NMR structures ...
if ( structure.isNmr()) {
str.append("MODEL " + (m+1)+"\n");
}
// do for all chains
int nrChains = model.size();
for ( int c =0; c<nrChains;c++) {
Chain chain = (Chain)model.get(c);
String chainID = chain.getName();
//if ( chainID.equals(DEFAULTCHAIN) ) chainID = " ";
// do for all groups
int nrGroups = chain.getLength();
for ( int h=0; h<nrGroups;h++){
Group g= chain.getGroup(h);
String type = g.getType() ;
String record = "" ;
if ( type.equals("hetatm") ) {
record = "HETATM";
} else {
record = "ATOM ";
}
// format output ...
int groupsize = g.size();
String resName = g.getPDBName();
String pdbcode = g.getPDBCode();
String line = "" ;
// iteratate over all atoms ...
for ( int atompos = 0 ; atompos < groupsize; atompos++) {
Atom a = null ;
try {
a = g.getAtom(atompos);
} catch ( StructureException e) {
System.err.println(e);
continue ;
}
int seri = a.getPDBserial() ;
String serial = alignRight(""+seri,5) ;
String fullname = a.getFullName() ;
Character altLoc = a.getAltLoc() ;
String resseq = "" ;
if ( hasInsertionCode(pdbcode) )
resseq = alignRight(""+pdbcode,5);
else
resseq = alignRight(""+pdbcode,4)+" ";
String x = alignRight(""+d3.format(a.getX()),8);
String y = alignRight(""+d3.format(a.getY()),8);
String z = alignRight(""+d3.format(a.getZ()),8);
String occupancy = alignRight(""+d2.format(a.getOccupancy()),6) ;
String tempfactor = alignRight(""+d2.format(a.getTempFactor()),6);
//System.out.println("fullname,zise:" + fullname + " " + fullname.length());
line = record + serial + " " + fullname +altLoc
+ resName + " " + chainID + resseq
+ " " + x+y+z
+ occupancy + tempfactor;
str.append(line + "\n");
//System.out.println(line);
}
}
}
if ( structure.isNmr()) {
str.append("ENDMDL\n");
}
}
if ( doPrintConnections() )
str.append(printPDBConnections());
return str.toString() ;
}
/** test if pdbserial has an insertion code */
private boolean hasInsertionCode(String pdbserial) {
try {
Integer.parseInt(pdbserial) ;
} catch (NumberFormatException e) {
return true ;
}
return false ;
}
/** convert a protein Structure to a DAS Structure XML response .
* @param xw a XMLWriter object
* @throws IOException ...
*
*/
public void toDASStructure(XMLWriter xw)
throws IOException
{
/*xmlns="http://www.sanger.ac.uk/xml/das/2004/06/17/dasalignment.xsd" xmlns:align="http://www.sanger.ac.uk/xml/das/2004/06/17/alignment.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance" xsd:schemaLocation="http://www.sanger.ac.uk/xml/das/2004/06/17/dasalignment.xsd http://www.sanger.ac.uk/xml/das//2004/06/17/dasalignment.xsd"*/
HashMap header = (HashMap) structure.getHeader();
xw.openTag("object");
xw.attribute("dbAccessionId",structure.getPDBCode());
xw.attribute("intObjectId" ,structure.getPDBCode());
// missing modification date
String modificationDate = (String)header.get("modDate") ;
xw.attribute("objectVersion",modificationDate);
xw.attribute("type","protein structure");
xw.attribute("dbSource","PDB");
- xw.attribute("dbVersion","20060707");
- xw.attribute("dbCoordSys","PDBresnum");
+ xw.attribute("dbVersion","20070116");
+ xw.attribute("dbCoordSys","PDBresnum,Protein Structure");
// do we need object details ???
xw.closeTag("object");
// do for all models
for (int modelnr = 0;modelnr<structure.nrModels();modelnr++){
// do for all chains:
for (int chainnr = 0;chainnr<structure.size(modelnr);chainnr++){
Chain chain = (Chain)structure.getChain(modelnr,chainnr);
xw.openTag("chain");
xw.attribute("id",chain.getName());
xw.attribute("SwissprotId",chain.getSwissprotId() );
if (structure.isNmr()){
xw.attribute("model",Integer.toString(modelnr+1));
}
//do for all groups:
for (int groupnr =0;groupnr<chain.getLength();groupnr++){
Group gr = chain.getGroup(groupnr);
xw.openTag("group");
xw.attribute("name",gr.getPDBName());
xw.attribute("type",gr.getType());
xw.attribute("groupID",gr.getPDBCode());
// do for all atoms:
//Atom[] atoms = gr.getAtoms();
ArrayList atoms = (ArrayList) gr.getAtoms();
for (int atomnr=0;atomnr<atoms.size();atomnr++){
Atom atom = (Atom)atoms.get(atomnr);
xw.openTag("atom");
xw.attribute("atomID",Integer.toString(atom.getPDBserial()));
xw.attribute("atomName",atom.getFullName());
xw.attribute("x",Double.toString(atom.getX()));
xw.attribute("y",Double.toString(atom.getY()));
xw.attribute("z",Double.toString(atom.getZ()));
xw.closeTag("atom");
}
xw.closeTag("group") ;
}
xw.closeTag("chain");
}
}
if ( doPrintConnections() ) {
// do connectivity for all chains:
List cons = (ArrayList) structure.getConnections();
for (int cnr = 0; cnr<cons.size();cnr++){
/*
the HashMap for a single CONECT line contains the following fields:
<ul>
<li>atomserial (mandatory) : Atom serial number
<li>bond1 .. bond4 (optional): Serial number of bonded atom
<li>hydrogen1 .. hydrogen4 (optional):Serial number of hydrogen bonded atom
<li>salt1 .. salt2 (optional): Serial number of salt bridged atom
</ul>
*/
HashMap con = (HashMap)cons.get(cnr);
Integer as = (Integer)con.get("atomserial");
int atomserial = as.intValue();
ArrayList atomids = new ArrayList() ;
// test salt and hydrogen first //
if (con.containsKey("salt1")) atomids.add(con.get("salt1"));
if (con.containsKey("salt2")) atomids.add(con.get("salt2"));
if (atomids.size()!=0){
addConnection(xw,"salt",atomserial,atomids);
atomids = new ArrayList() ;
}
if (con.containsKey("hydrogen1")) atomids.add(con.get("hydrogen1"));
if (con.containsKey("hydrogen2")) atomids.add(con.get("hydrogen2"));
if (con.containsKey("hydrogen3")) atomids.add(con.get("hydrogen3"));
if (con.containsKey("hydrogen4")) atomids.add(con.get("hydrogen4"));
if (atomids.size()!=0){
addConnection(xw,"hydrogen",atomserial,atomids);
atomids = new ArrayList() ;
}
if (con.containsKey("bond1")) atomids.add(con.get("bond1"));
if (con.containsKey("bond2")) atomids.add(con.get("bond2"));
if (con.containsKey("bond3")) atomids.add(con.get("bond3"));
if (con.containsKey("bond4")) atomids.add(con.get("bond4"));
if (atomids.size()!=0){
addConnection(xw,"bond",atomserial,atomids);
}
}
}
}
private void addConnection(XMLWriter xw,String connType, int atomserial, ArrayList atomids){
try{
xw.openTag("connect");
xw.attribute("atomSerial",Integer.toString(atomserial));
xw.attribute("type",connType);
for (int i=0;i<atomids.size();i++){
Integer atomid = (Integer)atomids.get(i);
if ( atomid == null)
continue;
int aid = atomid.intValue();
xw.openTag("atomID");
xw.attribute("atomID",Integer.toString(aid));
xw.closeTag("atomID");
}
xw.closeTag("connect");
} catch( Exception e) {
e.printStackTrace();
}
}
}
| true | true | public void toDASStructure(XMLWriter xw)
throws IOException
{
/*xmlns="http://www.sanger.ac.uk/xml/das/2004/06/17/dasalignment.xsd" xmlns:align="http://www.sanger.ac.uk/xml/das/2004/06/17/alignment.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance" xsd:schemaLocation="http://www.sanger.ac.uk/xml/das/2004/06/17/dasalignment.xsd http://www.sanger.ac.uk/xml/das//2004/06/17/dasalignment.xsd"*/
HashMap header = (HashMap) structure.getHeader();
xw.openTag("object");
xw.attribute("dbAccessionId",structure.getPDBCode());
xw.attribute("intObjectId" ,structure.getPDBCode());
// missing modification date
String modificationDate = (String)header.get("modDate") ;
xw.attribute("objectVersion",modificationDate);
xw.attribute("type","protein structure");
xw.attribute("dbSource","PDB");
xw.attribute("dbVersion","20060707");
xw.attribute("dbCoordSys","PDBresnum");
// do we need object details ???
xw.closeTag("object");
// do for all models
for (int modelnr = 0;modelnr<structure.nrModels();modelnr++){
// do for all chains:
for (int chainnr = 0;chainnr<structure.size(modelnr);chainnr++){
Chain chain = (Chain)structure.getChain(modelnr,chainnr);
xw.openTag("chain");
xw.attribute("id",chain.getName());
xw.attribute("SwissprotId",chain.getSwissprotId() );
if (structure.isNmr()){
xw.attribute("model",Integer.toString(modelnr+1));
}
//do for all groups:
for (int groupnr =0;groupnr<chain.getLength();groupnr++){
Group gr = chain.getGroup(groupnr);
xw.openTag("group");
xw.attribute("name",gr.getPDBName());
xw.attribute("type",gr.getType());
xw.attribute("groupID",gr.getPDBCode());
// do for all atoms:
//Atom[] atoms = gr.getAtoms();
ArrayList atoms = (ArrayList) gr.getAtoms();
for (int atomnr=0;atomnr<atoms.size();atomnr++){
Atom atom = (Atom)atoms.get(atomnr);
xw.openTag("atom");
xw.attribute("atomID",Integer.toString(atom.getPDBserial()));
xw.attribute("atomName",atom.getFullName());
xw.attribute("x",Double.toString(atom.getX()));
xw.attribute("y",Double.toString(atom.getY()));
xw.attribute("z",Double.toString(atom.getZ()));
xw.closeTag("atom");
}
xw.closeTag("group") ;
}
xw.closeTag("chain");
}
}
if ( doPrintConnections() ) {
// do connectivity for all chains:
List cons = (ArrayList) structure.getConnections();
for (int cnr = 0; cnr<cons.size();cnr++){
/*
the HashMap for a single CONECT line contains the following fields:
<ul>
<li>atomserial (mandatory) : Atom serial number
<li>bond1 .. bond4 (optional): Serial number of bonded atom
<li>hydrogen1 .. hydrogen4 (optional):Serial number of hydrogen bonded atom
<li>salt1 .. salt2 (optional): Serial number of salt bridged atom
</ul>
*/
HashMap con = (HashMap)cons.get(cnr);
Integer as = (Integer)con.get("atomserial");
int atomserial = as.intValue();
ArrayList atomids = new ArrayList() ;
// test salt and hydrogen first //
if (con.containsKey("salt1")) atomids.add(con.get("salt1"));
if (con.containsKey("salt2")) atomids.add(con.get("salt2"));
if (atomids.size()!=0){
addConnection(xw,"salt",atomserial,atomids);
atomids = new ArrayList() ;
}
if (con.containsKey("hydrogen1")) atomids.add(con.get("hydrogen1"));
if (con.containsKey("hydrogen2")) atomids.add(con.get("hydrogen2"));
if (con.containsKey("hydrogen3")) atomids.add(con.get("hydrogen3"));
if (con.containsKey("hydrogen4")) atomids.add(con.get("hydrogen4"));
if (atomids.size()!=0){
addConnection(xw,"hydrogen",atomserial,atomids);
atomids = new ArrayList() ;
}
if (con.containsKey("bond1")) atomids.add(con.get("bond1"));
if (con.containsKey("bond2")) atomids.add(con.get("bond2"));
if (con.containsKey("bond3")) atomids.add(con.get("bond3"));
if (con.containsKey("bond4")) atomids.add(con.get("bond4"));
if (atomids.size()!=0){
addConnection(xw,"bond",atomserial,atomids);
}
}
}
}
| public void toDASStructure(XMLWriter xw)
throws IOException
{
/*xmlns="http://www.sanger.ac.uk/xml/das/2004/06/17/dasalignment.xsd" xmlns:align="http://www.sanger.ac.uk/xml/das/2004/06/17/alignment.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance" xsd:schemaLocation="http://www.sanger.ac.uk/xml/das/2004/06/17/dasalignment.xsd http://www.sanger.ac.uk/xml/das//2004/06/17/dasalignment.xsd"*/
HashMap header = (HashMap) structure.getHeader();
xw.openTag("object");
xw.attribute("dbAccessionId",structure.getPDBCode());
xw.attribute("intObjectId" ,structure.getPDBCode());
// missing modification date
String modificationDate = (String)header.get("modDate") ;
xw.attribute("objectVersion",modificationDate);
xw.attribute("type","protein structure");
xw.attribute("dbSource","PDB");
xw.attribute("dbVersion","20070116");
xw.attribute("dbCoordSys","PDBresnum,Protein Structure");
// do we need object details ???
xw.closeTag("object");
// do for all models
for (int modelnr = 0;modelnr<structure.nrModels();modelnr++){
// do for all chains:
for (int chainnr = 0;chainnr<structure.size(modelnr);chainnr++){
Chain chain = (Chain)structure.getChain(modelnr,chainnr);
xw.openTag("chain");
xw.attribute("id",chain.getName());
xw.attribute("SwissprotId",chain.getSwissprotId() );
if (structure.isNmr()){
xw.attribute("model",Integer.toString(modelnr+1));
}
//do for all groups:
for (int groupnr =0;groupnr<chain.getLength();groupnr++){
Group gr = chain.getGroup(groupnr);
xw.openTag("group");
xw.attribute("name",gr.getPDBName());
xw.attribute("type",gr.getType());
xw.attribute("groupID",gr.getPDBCode());
// do for all atoms:
//Atom[] atoms = gr.getAtoms();
ArrayList atoms = (ArrayList) gr.getAtoms();
for (int atomnr=0;atomnr<atoms.size();atomnr++){
Atom atom = (Atom)atoms.get(atomnr);
xw.openTag("atom");
xw.attribute("atomID",Integer.toString(atom.getPDBserial()));
xw.attribute("atomName",atom.getFullName());
xw.attribute("x",Double.toString(atom.getX()));
xw.attribute("y",Double.toString(atom.getY()));
xw.attribute("z",Double.toString(atom.getZ()));
xw.closeTag("atom");
}
xw.closeTag("group") ;
}
xw.closeTag("chain");
}
}
if ( doPrintConnections() ) {
// do connectivity for all chains:
List cons = (ArrayList) structure.getConnections();
for (int cnr = 0; cnr<cons.size();cnr++){
/*
the HashMap for a single CONECT line contains the following fields:
<ul>
<li>atomserial (mandatory) : Atom serial number
<li>bond1 .. bond4 (optional): Serial number of bonded atom
<li>hydrogen1 .. hydrogen4 (optional):Serial number of hydrogen bonded atom
<li>salt1 .. salt2 (optional): Serial number of salt bridged atom
</ul>
*/
HashMap con = (HashMap)cons.get(cnr);
Integer as = (Integer)con.get("atomserial");
int atomserial = as.intValue();
ArrayList atomids = new ArrayList() ;
// test salt and hydrogen first //
if (con.containsKey("salt1")) atomids.add(con.get("salt1"));
if (con.containsKey("salt2")) atomids.add(con.get("salt2"));
if (atomids.size()!=0){
addConnection(xw,"salt",atomserial,atomids);
atomids = new ArrayList() ;
}
if (con.containsKey("hydrogen1")) atomids.add(con.get("hydrogen1"));
if (con.containsKey("hydrogen2")) atomids.add(con.get("hydrogen2"));
if (con.containsKey("hydrogen3")) atomids.add(con.get("hydrogen3"));
if (con.containsKey("hydrogen4")) atomids.add(con.get("hydrogen4"));
if (atomids.size()!=0){
addConnection(xw,"hydrogen",atomserial,atomids);
atomids = new ArrayList() ;
}
if (con.containsKey("bond1")) atomids.add(con.get("bond1"));
if (con.containsKey("bond2")) atomids.add(con.get("bond2"));
if (con.containsKey("bond3")) atomids.add(con.get("bond3"));
if (con.containsKey("bond4")) atomids.add(con.get("bond4"));
if (atomids.size()!=0){
addConnection(xw,"bond",atomserial,atomids);
}
}
}
}
|
diff --git a/AnimationLib/src/me/captainbern/animationlib/animations/BlockAnimation.java b/AnimationLib/src/me/captainbern/animationlib/animations/BlockAnimation.java
index e2053e9..2000981 100644
--- a/AnimationLib/src/me/captainbern/animationlib/animations/BlockAnimation.java
+++ b/AnimationLib/src/me/captainbern/animationlib/animations/BlockAnimation.java
@@ -1,85 +1,85 @@
/*
* PlayerAnimationLib
* Copyright (C) 2013 CaptainBern
*
* 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 me.captainbern.animationlib.animations;
import java.util.Arrays;
import java.util.Collection;
import me.captainbern.animationlib.event.BlockAnimationEvent;
import me.captainbern.animationlib.utils.Packet;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
public enum BlockAnimation {
BLOCK_BREAK {
@Override
protected void broadcastAnimation(Block block, short damage) {
try{
- if(damage > 7 || damage > 0){
+ if(damage > 7 || damage < 0){
throw new NumberFormatException("damage needs to be between 0 and 7!");
}
Packet packet = new Packet("Packet55BlockBreakAnimation");
packet.setPrivateValue("a", 0);
packet.setPrivateValue("b", block.getX());
packet.setPrivateValue("c", block.getY());
packet.setPrivateValue("d", block.getZ());
packet.setPrivateValue("e", Integer.valueOf(Short.toString(damage)));
sendPacketNearby(block.getLocation(), Arrays.asList(packet), this, block);
}catch(Exception e){
Bukkit.getLogger().warning("[AnimationLib] Something went wrong shile crafting the Packet55BlockBreakAnimation packet! (BLOCK_BREAK)");
e.printStackTrace();
}
}
};
/* STOP ENUMS */
public void play(Block block, short damage){
broadcastAnimation(block, damage);
}
private static void sendPacketNearby(Location loc, Collection<Packet> packets, BlockAnimation ba, Block block) {
World world = loc.getWorld();
for(Player player : Bukkit.getOnlinePlayers()){
if(player == null || player.getWorld() != world){
continue;
}
BlockAnimationEvent event = new BlockAnimationEvent(block, ba);
Bukkit.getPluginManager().callEvent(event);
if(!event.isCancelled()){
for(Packet packet : packets){
packet.send(player);
}
}
}
}
protected void broadcastAnimation(Block block, short damage){
throw new UnsupportedOperationException("[AnimationLib] Unimplemented animation");
}
}
| true | true | protected void broadcastAnimation(Block block, short damage) {
try{
if(damage > 7 || damage > 0){
throw new NumberFormatException("damage needs to be between 0 and 7!");
}
Packet packet = new Packet("Packet55BlockBreakAnimation");
packet.setPrivateValue("a", 0);
packet.setPrivateValue("b", block.getX());
packet.setPrivateValue("c", block.getY());
packet.setPrivateValue("d", block.getZ());
packet.setPrivateValue("e", Integer.valueOf(Short.toString(damage)));
sendPacketNearby(block.getLocation(), Arrays.asList(packet), this, block);
}catch(Exception e){
Bukkit.getLogger().warning("[AnimationLib] Something went wrong shile crafting the Packet55BlockBreakAnimation packet! (BLOCK_BREAK)");
e.printStackTrace();
}
}
| protected void broadcastAnimation(Block block, short damage) {
try{
if(damage > 7 || damage < 0){
throw new NumberFormatException("damage needs to be between 0 and 7!");
}
Packet packet = new Packet("Packet55BlockBreakAnimation");
packet.setPrivateValue("a", 0);
packet.setPrivateValue("b", block.getX());
packet.setPrivateValue("c", block.getY());
packet.setPrivateValue("d", block.getZ());
packet.setPrivateValue("e", Integer.valueOf(Short.toString(damage)));
sendPacketNearby(block.getLocation(), Arrays.asList(packet), this, block);
}catch(Exception e){
Bukkit.getLogger().warning("[AnimationLib] Something went wrong shile crafting the Packet55BlockBreakAnimation packet! (BLOCK_BREAK)");
e.printStackTrace();
}
}
|
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/renderer/ImageRenderer.java b/orbisgis-core/src/main/java/org/orbisgis/core/renderer/ImageRenderer.java
index 6d58ddf68..177d23f67 100644
--- a/orbisgis-core/src/main/java/org/orbisgis/core/renderer/ImageRenderer.java
+++ b/orbisgis-core/src/main/java/org/orbisgis/core/renderer/ImageRenderer.java
@@ -1,104 +1,106 @@
/**
* 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 "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-1012 IRSTV (FR CNRS 2488)
*
* 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://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.core.renderer;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import org.gdms.data.DataSource;
import org.orbisgis.core.map.MapTransform;
import org.orbisgis.core.renderer.se.Symbolizer;
/**
* ImageRender extends the renderer in order to produce an image
* @author Maxence Laurent
*/
public class ImageRenderer extends Renderer {
private List<BufferedImage> imgSymbs = null;
private List<Symbolizer> symbols = null;
private List<Graphics2D> graphics = null;
@Override
protected void initGraphics2D(List<Symbolizer> symbs, Graphics2D g2, MapTransform mt) {
imgSymbs = new ArrayList<BufferedImage>();
symbols = symbs;
graphics = new ArrayList<Graphics2D>();
/**
* Create one buffered image for each Symbolizer present in the style. This way allows
* to render all symbolizer in one pass without encountering layer level issues
*/
for (Symbolizer s : symbs) {
BufferedImage bufImg = new BufferedImage(mt.getWidth(), mt.getHeight(), BufferedImage.TYPE_INT_ARGB);
- graphics.add(bufImg.createGraphics());
+ Graphics2D sG2 = bufImg.createGraphics();
+ sG2.addRenderingHints(mt.getRenderingHints());
+ graphics.add(sG2);
imgSymbs.add(bufImg);
}
}
@Override
protected Graphics2D getGraphics2D(Symbolizer s) {
return graphics.get(symbols.indexOf(s));
}
@Override
protected void releaseGraphics2D(Graphics2D g2) {
}
@Override
protected void disposeLayer(Graphics2D g2) {
for (Graphics2D get : graphics){
get.dispose();
}
graphics.clear();
for (BufferedImage img : imgSymbs) {
g2.drawImage(img, null, null);
}
}
@Override
protected void beginLayer(String name) {
// nothing to do
}
@Override
protected void endLayer(String name) {
// nothing to do
}
@Override
protected void beginFeature(long id, DataSource sds) {
}
@Override
protected void endFeature(long id, DataSource sds) {
}
}
| true | true | protected void initGraphics2D(List<Symbolizer> symbs, Graphics2D g2, MapTransform mt) {
imgSymbs = new ArrayList<BufferedImage>();
symbols = symbs;
graphics = new ArrayList<Graphics2D>();
/**
* Create one buffered image for each Symbolizer present in the style. This way allows
* to render all symbolizer in one pass without encountering layer level issues
*/
for (Symbolizer s : symbs) {
BufferedImage bufImg = new BufferedImage(mt.getWidth(), mt.getHeight(), BufferedImage.TYPE_INT_ARGB);
graphics.add(bufImg.createGraphics());
imgSymbs.add(bufImg);
}
}
| protected void initGraphics2D(List<Symbolizer> symbs, Graphics2D g2, MapTransform mt) {
imgSymbs = new ArrayList<BufferedImage>();
symbols = symbs;
graphics = new ArrayList<Graphics2D>();
/**
* Create one buffered image for each Symbolizer present in the style. This way allows
* to render all symbolizer in one pass without encountering layer level issues
*/
for (Symbolizer s : symbs) {
BufferedImage bufImg = new BufferedImage(mt.getWidth(), mt.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D sG2 = bufImg.createGraphics();
sG2.addRenderingHints(mt.getRenderingHints());
graphics.add(sG2);
imgSymbs.add(bufImg);
}
}
|
diff --git a/src/main/java/me/chaseoes/tf2/Schedulers.java b/src/main/java/me/chaseoes/tf2/Schedulers.java
index 202ffc8..ea67f85 100644
--- a/src/main/java/me/chaseoes/tf2/Schedulers.java
+++ b/src/main/java/me/chaseoes/tf2/Schedulers.java
@@ -1,213 +1,215 @@
package me.chaseoes.tf2;
import java.util.HashMap;
import me.chaseoes.tf2.capturepoints.CapturePointUtilities;
import me.chaseoes.tf2.utilities.Localizer;
import me.chaseoes.tf2.utilities.LocationStore;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
public class Schedulers {
private TF2 plugin;
static Schedulers instance = new Schedulers();
Integer afkchecker;
public HashMap<String, Integer> redcounter = new HashMap<String, Integer>();
public HashMap<String, Integer> countdowns = new HashMap<String, Integer>();
public HashMap<String, Integer> timelimitcounter = new HashMap<String, Integer>();
BukkitTask reminderTimer = null;
private Schedulers() {
}
public static Schedulers getSchedulers() {
return instance;
}
public void setup(TF2 p) {
plugin = p;
}
public void startAFKChecker() {
final Integer afklimit = plugin.getConfig().getInt("afk-timer");
afkchecker = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
try {
for (Map map : MapUtilities.getUtilities().getMaps()) {
for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) {
Player player = plugin.getServer().getPlayerExact(p);
if (player == null) {
continue;
}
Integer afktime = LocationStore.getAFKTime(player);
Location lastloc = LocationStore.getLastLocation(player);
Location currentloc = new Location(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
if (lastloc != null) {
if (lastloc.getWorld().getName().equals(currentloc.getWorld().getName()) && lastloc.getBlockX() == currentloc.getBlockX() && lastloc.getBlockY() == currentloc.getBlockY() && lastloc.getBlockZ() == currentloc.getBlockZ()) {
if (afktime == null) {
LocationStore.setAFKTime(player, 1);
} else {
LocationStore.setAFKTime(player, afktime + 1);
}
if (afklimit.equals(afktime)) {
GameUtilities.getUtilities().getGamePlayer(player).getGame().leaveGame(player);
player.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KICKED-FOR-AFK"));
LocationStore.setAFKTime(player, null);
LocationStore.unsetLastLocation(player);
}
} else {
LocationStore.setAFKTime(player, null);
LocationStore.unsetLastLocation(player);
}
LocationStore.setLastLocation(player);
} else {
LocationStore.setLastLocation(player);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0L, 20L);
int remindEvery = plugin.getConfig().getInt("capture-reminder");
if (remindEvery != 0) {
reminderTimer = plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() {
@Override
public void run() {
try {
for (Map map : MapUtilities.getUtilities().getMaps()) {
for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) {
- Player player = Bukkit.getPlayerExact(p);
- if (player == null) {
- continue;
- }
- player.getLocation().getWorld().strikeLightningEffect(CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation());
+ Player player = Bukkit.getPlayerExact(p);
+ if (player == null) {
+ continue;
+ }
+ if (CapturePointUtilities.getUtilities().getFirstUncaptured(map) != null && CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation() != null) {
+ player.getLocation().getWorld().strikeLightningEffect(CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation());
+ }
}
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0L, remindEvery * 20L);
}
}
public void stopAFKChecker() {
if (afkchecker != null) {
plugin.getServer().getScheduler().cancelTask(afkchecker);
}
afkchecker = null;
}
public void startRedTeamCountdown(final Map map) {
final Game game = GameUtilities.getUtilities().getGame(map);
if (redcounter.containsKey(map.getName())) {
return;
}
redcounter.put(map.getName(), plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
int secondsleft = map.getRedTeamTeleportTime();
@Override
public void run() {
if (secondsleft > 0) {
if (secondsleft % 10 == 0 || secondsleft < 6) {
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("RED-TEAM-TELEPORTED-IN").replace("%time", secondsleft + ""), Team.RED);
}
} else {
stopRedTeamCountdown(map.getName());
}
secondsleft--;
}
}, 0L, 20L));
}
public void startCountdown(final Map map) {
final Game game = GameUtilities.getUtilities().getGame(map);
game.setStatus(GameStatus.STARTING);
if (countdowns.containsKey(map.getName())) {
return;
}
countdowns.put(map.getName(), plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
int secondsLeft = plugin.getConfig().getInt("countdown");
@Override
public void run() {
if (secondsLeft > 0) {
if (secondsLeft % 10 == 0 || secondsLeft < 6) {
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("GAME-STARTING-IN").replace("%time", secondsLeft + ""));
}
secondsLeft--;
} else {
game.startMatch();
stopCountdown(map.getName());
}
}
}, 0L, 20L));
}
public void startTimeLimitCounter(final Map map) {
final Game game = GameUtilities.getUtilities().getGame(map);
final int limit = map.getTimelimit();
if (timelimitcounter.containsKey(map.getName())) {
return;
}
timelimitcounter.put(map.getName(), plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
int current = 0;
int secondsleft = map.getTimelimit();
@Override
public void run() {
try {
game.time = current;
if (secondsleft > 0) {
if (secondsleft % 60 == 0 || secondsleft < 10) {
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("GAME-ENDING-IN").replace("%time", game.getTimeLeftPretty()));
}
}
secondsleft--;
if (current >= limit) {
game.winMatch(Team.BLUE);
stopTimeLimitCounter(map.getName());
}
current++;
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0L, 20L));
}
public void stopRedTeamCountdown(String map) {
if (redcounter.get(map) != null) {
plugin.getServer().getScheduler().cancelTask(redcounter.get(map));
redcounter.remove(map);
}
}
public void stopTimeLimitCounter(String map) {
if (timelimitcounter.get(map) != null) {
plugin.getServer().getScheduler().cancelTask(timelimitcounter.get(map));
timelimitcounter.remove(map);
}
}
public void stopCountdown(String map) {
if (countdowns.get(map) != null) {
plugin.getServer().getScheduler().cancelTask(countdowns.get(map));
countdowns.remove(map);
}
}
}
| true | true | public void startAFKChecker() {
final Integer afklimit = plugin.getConfig().getInt("afk-timer");
afkchecker = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
try {
for (Map map : MapUtilities.getUtilities().getMaps()) {
for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) {
Player player = plugin.getServer().getPlayerExact(p);
if (player == null) {
continue;
}
Integer afktime = LocationStore.getAFKTime(player);
Location lastloc = LocationStore.getLastLocation(player);
Location currentloc = new Location(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
if (lastloc != null) {
if (lastloc.getWorld().getName().equals(currentloc.getWorld().getName()) && lastloc.getBlockX() == currentloc.getBlockX() && lastloc.getBlockY() == currentloc.getBlockY() && lastloc.getBlockZ() == currentloc.getBlockZ()) {
if (afktime == null) {
LocationStore.setAFKTime(player, 1);
} else {
LocationStore.setAFKTime(player, afktime + 1);
}
if (afklimit.equals(afktime)) {
GameUtilities.getUtilities().getGamePlayer(player).getGame().leaveGame(player);
player.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KICKED-FOR-AFK"));
LocationStore.setAFKTime(player, null);
LocationStore.unsetLastLocation(player);
}
} else {
LocationStore.setAFKTime(player, null);
LocationStore.unsetLastLocation(player);
}
LocationStore.setLastLocation(player);
} else {
LocationStore.setLastLocation(player);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0L, 20L);
int remindEvery = plugin.getConfig().getInt("capture-reminder");
if (remindEvery != 0) {
reminderTimer = plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() {
@Override
public void run() {
try {
for (Map map : MapUtilities.getUtilities().getMaps()) {
for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) {
Player player = Bukkit.getPlayerExact(p);
if (player == null) {
continue;
}
player.getLocation().getWorld().strikeLightningEffect(CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation());
}
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0L, remindEvery * 20L);
}
}
| public void startAFKChecker() {
final Integer afklimit = plugin.getConfig().getInt("afk-timer");
afkchecker = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
try {
for (Map map : MapUtilities.getUtilities().getMaps()) {
for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) {
Player player = plugin.getServer().getPlayerExact(p);
if (player == null) {
continue;
}
Integer afktime = LocationStore.getAFKTime(player);
Location lastloc = LocationStore.getLastLocation(player);
Location currentloc = new Location(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
if (lastloc != null) {
if (lastloc.getWorld().getName().equals(currentloc.getWorld().getName()) && lastloc.getBlockX() == currentloc.getBlockX() && lastloc.getBlockY() == currentloc.getBlockY() && lastloc.getBlockZ() == currentloc.getBlockZ()) {
if (afktime == null) {
LocationStore.setAFKTime(player, 1);
} else {
LocationStore.setAFKTime(player, afktime + 1);
}
if (afklimit.equals(afktime)) {
GameUtilities.getUtilities().getGamePlayer(player).getGame().leaveGame(player);
player.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KICKED-FOR-AFK"));
LocationStore.setAFKTime(player, null);
LocationStore.unsetLastLocation(player);
}
} else {
LocationStore.setAFKTime(player, null);
LocationStore.unsetLastLocation(player);
}
LocationStore.setLastLocation(player);
} else {
LocationStore.setLastLocation(player);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0L, 20L);
int remindEvery = plugin.getConfig().getInt("capture-reminder");
if (remindEvery != 0) {
reminderTimer = plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() {
@Override
public void run() {
try {
for (Map map : MapUtilities.getUtilities().getMaps()) {
for (String p : GameUtilities.getUtilities().getGame(map).getPlayersIngame()) {
Player player = Bukkit.getPlayerExact(p);
if (player == null) {
continue;
}
if (CapturePointUtilities.getUtilities().getFirstUncaptured(map) != null && CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation() != null) {
player.getLocation().getWorld().strikeLightningEffect(CapturePointUtilities.getUtilities().getFirstUncaptured(map).getLocation());
}
}
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0L, remindEvery * 20L);
}
}
|
diff --git a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java
index 7c3e7b41d..fd369ce43 100644
--- a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java
+++ b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/ompi/OMPIProxyRuntimeClient.java
@@ -1,224 +1,223 @@
package org.eclipse.ptp.rtsystem.ompi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.BitSet;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.ptp.core.ControlSystemChoices;
import org.eclipse.ptp.core.IModelManager;
import org.eclipse.ptp.core.MonitoringSystemChoices;
import org.eclipse.ptp.core.PTPCorePlugin;
import org.eclipse.ptp.core.PreferenceConstants;
import org.eclipse.ptp.core.util.Queue;
import org.eclipse.ptp.rtsystem.IRuntimeProxy;
import org.eclipse.ptp.rtsystem.proxy.ProxyRuntimeClient;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener;
import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeErrorEvent;
import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNewJobEvent;
import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNodeAttributeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeNodesEvent;
import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeProcessAttributeEvent;
import org.eclipse.ptp.rtsystem.proxy.event.ProxyRuntimeProcessesEvent;
public class OMPIProxyRuntimeClient extends ProxyRuntimeClient implements IRuntimeProxy, IProxyRuntimeEventListener {
protected Queue events = new Queue();
protected BitSet waitEvents = new BitSet();
protected IModelManager modelManager;
public OMPIProxyRuntimeClient(IModelManager modelManager) {
super();
super.addRuntimeEventListener(this);
this.modelManager = modelManager;
}
public int runJob(String[] args) throws IOException {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NEWJOB);
run(args);
IProxyRuntimeEvent event = waitForRuntimeEvent();
return ((ProxyRuntimeNewJobEvent)event).getJobID();
}
public int getJobProcesses(int jobID) throws IOException {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCS);
getProcesses(jobID);
IProxyRuntimeEvent event = waitForRuntimeEvent();
return ((ProxyRuntimeProcessesEvent)event).getNumProcs();
}
public String[] getProcessAttributesBlocking(int jobID, int procID, String keys) throws IOException {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCATTR);
getProcessAttribute(jobID, procID, keys);
IProxyRuntimeEvent event = waitForRuntimeEvent();
return ((ProxyRuntimeProcessAttributeEvent)event).getValues();
}
public String[] getAllProcessesAttribuesBlocking(int jobID, String keys) throws IOException {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_PROCATTR);
getProcessAttribute(jobID, -1, keys);
IProxyRuntimeEvent event = waitForRuntimeEvent();
return ((ProxyRuntimeProcessAttributeEvent)event).getValues();
}
public int getNumNodesBlocking(int machineID) throws IOException {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODES);
getNodes(machineID);
IProxyRuntimeEvent event = waitForRuntimeEvent();
return ((ProxyRuntimeNodesEvent)event).getNumNodes();
}
public String[] getNodeAttributesBlocking(int machID, int nodeID, String keys) throws IOException {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODEATTR);
getNodeAttribute(machID, nodeID, keys);
IProxyRuntimeEvent event = waitForRuntimeEvent();
return ((ProxyRuntimeNodeAttributeEvent)event).getValues();
}
public String[] getAllNodesAttributesBlocking(int machID, String keys) throws IOException {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_NODEATTR);
getNodeAttribute(machID, -1, keys);
IProxyRuntimeEvent event = waitForRuntimeEvent();
return ((ProxyRuntimeNodeAttributeEvent)event).getValues();
}
public boolean startup(final IProgressMonitor monitor) {
System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . .");
Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences();
String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH);
System.out.println("ORTE_SERVER path = '"+proxyPath+"'");
if(proxyPath.equals("")) {
String err = "Could not start the ORTE server. Check the "+
"PTP/Open RTE preferences page and be certain that the path and arguments "+
"are correct. Defaulting to Simulation Mode.";
System.err.println(err);
PTPCorePlugin.errorDialog("ORTE Server Start Failure", err, null);
int MSI = MonitoringSystemChoices.SIMULATED;
int CSI = ControlSystemChoices.SIMULATED;
preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI);
preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI);
PTPCorePlugin.getDefault().savePluginPreferences();
return false;
}
final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH);
try {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED);
sessionCreate();
if (preferences.getBoolean(PreferenceConstants.ORTE_LAUNCH_MANUALLY)) {
monitor.subTask("Waiting for manual lauch of orte_server on port "+getSessionPort()+"...");
} else {
Thread runThread = new Thread("Proxy Server Thread") {
public void run() {
String cmd = proxyPath2 + " --port="+getSessionPort();
System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'");
try {
- Process process = Runtime.getRuntime ().exec(cmd);
- InputStreamReader reader = new InputStreamReader (process.getErrorStream());
- BufferedReader buf_reader = new BufferedReader (reader);
+ Process process = Runtime.getRuntime().exec(cmd);
+ BufferedReader buf_reader = new BufferedReader (new InputStreamReader(process.getErrorStream()));
- String line = buf_reader.readLine();
- if (line != null) {
- PTPCorePlugin.errorDialog("Running Proxy Server", line, null);
+ String line;
+ while ((line = buf_reader.readLine()) != null) {
+ PTPCorePlugin.log(line);
}
} catch(IOException e) {
PTPCorePlugin.errorDialog("Running Proxy Server", null, e);
if (monitor != null) {
monitor.setCanceled(true);
}
}
}
};
runThread.setDaemon(true);
runThread.start();
}
System.out.println("Waiting on accept.");
waitForRuntimeEvent(monitor);
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK);
sendCommand("STARTDAEMON");
waitForRuntimeEvent();
} catch (IOException e) {
System.err.println("Exception starting up proxy. :(");
try {
sessionFinish();
} catch (IOException e1) {
PTPCorePlugin.log(e1);
}
return false;
}
return true;
}
public void shutdown() {
try {
System.out.println("OMPIProxyRuntimeClient shutting down server...");
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK);
sessionFinish();
waitForRuntimeEvent();
System.out.println("OMPIProxyRuntimeClient shut down.");
} catch (IOException e) {
// TODO Auto-generated catch block
PTPCorePlugin.log(e);
}
}
private void setWaitEvent(int eventID) {
waitEvents.set(eventID);
waitEvents.set(IProxyRuntimeEvent.EVENT_RUNTIME_ERROR); // always check for errors
}
private IProxyRuntimeEvent waitForRuntimeEvent() throws IOException {
return waitForRuntimeEvent(null);
}
private synchronized IProxyRuntimeEvent waitForRuntimeEvent(IProgressMonitor monitor) throws IOException {
IProxyRuntimeEvent event = null;
System.out.println("OMPIProxyRuntimeClient waiting on " + waitEvents.toString());
while (this.events.isEmpty()) {
try {
wait(500);
} catch (InterruptedException e) {
}
if (monitor != null && monitor.isCanceled()) {
throw new IOException("Cancelled by user");
}
}
System.out.println("OMPIProxyRuntimeClient awoke!");
try {
event = (IProxyRuntimeEvent) this.events.removeItem();
} catch (InterruptedException e) {
waitEvents.clear();
throw new IOException(e.getMessage());
}
if (event instanceof ProxyRuntimeErrorEvent) {
waitEvents.clear();
throw new IOException(((ProxyRuntimeErrorEvent)event).getErrorMessage());
}
waitEvents.clear();
return event;
}
/*
* Only handle events we're interested in
*/
public synchronized void handleEvent(IProxyRuntimeEvent e) {
System.out.println("OMPIProxyRuntimeClient got event: " + e.toString());
if (waitEvents.get(e.getEventID())) {
System.out.println("OMPIProxyRuntimeClient notifying...");
this.events.addItem(e);
notifyAll();
}
}
}
| false | true | public boolean startup(final IProgressMonitor monitor) {
System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . .");
Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences();
String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH);
System.out.println("ORTE_SERVER path = '"+proxyPath+"'");
if(proxyPath.equals("")) {
String err = "Could not start the ORTE server. Check the "+
"PTP/Open RTE preferences page and be certain that the path and arguments "+
"are correct. Defaulting to Simulation Mode.";
System.err.println(err);
PTPCorePlugin.errorDialog("ORTE Server Start Failure", err, null);
int MSI = MonitoringSystemChoices.SIMULATED;
int CSI = ControlSystemChoices.SIMULATED;
preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI);
preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI);
PTPCorePlugin.getDefault().savePluginPreferences();
return false;
}
final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH);
try {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED);
sessionCreate();
if (preferences.getBoolean(PreferenceConstants.ORTE_LAUNCH_MANUALLY)) {
monitor.subTask("Waiting for manual lauch of orte_server on port "+getSessionPort()+"...");
} else {
Thread runThread = new Thread("Proxy Server Thread") {
public void run() {
String cmd = proxyPath2 + " --port="+getSessionPort();
System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'");
try {
Process process = Runtime.getRuntime ().exec(cmd);
InputStreamReader reader = new InputStreamReader (process.getErrorStream());
BufferedReader buf_reader = new BufferedReader (reader);
String line = buf_reader.readLine();
if (line != null) {
PTPCorePlugin.errorDialog("Running Proxy Server", line, null);
}
} catch(IOException e) {
PTPCorePlugin.errorDialog("Running Proxy Server", null, e);
if (monitor != null) {
monitor.setCanceled(true);
}
}
}
};
runThread.setDaemon(true);
runThread.start();
}
System.out.println("Waiting on accept.");
waitForRuntimeEvent(monitor);
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK);
sendCommand("STARTDAEMON");
waitForRuntimeEvent();
} catch (IOException e) {
System.err.println("Exception starting up proxy. :(");
try {
sessionFinish();
} catch (IOException e1) {
PTPCorePlugin.log(e1);
}
return false;
}
return true;
}
| public boolean startup(final IProgressMonitor monitor) {
System.out.println("OMPIProxyRuntimeClient - firing up proxy, waiting for connecting. Please wait! This can take a minute . . .");
Preferences preferences = PTPCorePlugin.getDefault().getPluginPreferences();
String proxyPath = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH);
System.out.println("ORTE_SERVER path = '"+proxyPath+"'");
if(proxyPath.equals("")) {
String err = "Could not start the ORTE server. Check the "+
"PTP/Open RTE preferences page and be certain that the path and arguments "+
"are correct. Defaulting to Simulation Mode.";
System.err.println(err);
PTPCorePlugin.errorDialog("ORTE Server Start Failure", err, null);
int MSI = MonitoringSystemChoices.SIMULATED;
int CSI = ControlSystemChoices.SIMULATED;
preferences.setValue(PreferenceConstants.MONITORING_SYSTEM_SELECTION, MSI);
preferences.setValue(PreferenceConstants.CONTROL_SYSTEM_SELECTION, CSI);
PTPCorePlugin.getDefault().savePluginPreferences();
return false;
}
final String proxyPath2 = preferences.getString(PreferenceConstants.ORTE_SERVER_PATH);
try {
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_CONNECTED);
sessionCreate();
if (preferences.getBoolean(PreferenceConstants.ORTE_LAUNCH_MANUALLY)) {
monitor.subTask("Waiting for manual lauch of orte_server on port "+getSessionPort()+"...");
} else {
Thread runThread = new Thread("Proxy Server Thread") {
public void run() {
String cmd = proxyPath2 + " --port="+getSessionPort();
System.out.println("RUNNING PROXY SERVER COMMAND: '"+cmd+"'");
try {
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader buf_reader = new BufferedReader (new InputStreamReader(process.getErrorStream()));
String line;
while ((line = buf_reader.readLine()) != null) {
PTPCorePlugin.log(line);
}
} catch(IOException e) {
PTPCorePlugin.errorDialog("Running Proxy Server", null, e);
if (monitor != null) {
monitor.setCanceled(true);
}
}
}
};
runThread.setDaemon(true);
runThread.start();
}
System.out.println("Waiting on accept.");
waitForRuntimeEvent(monitor);
setWaitEvent(IProxyRuntimeEvent.EVENT_RUNTIME_OK);
sendCommand("STARTDAEMON");
waitForRuntimeEvent();
} catch (IOException e) {
System.err.println("Exception starting up proxy. :(");
try {
sessionFinish();
} catch (IOException e1) {
PTPCorePlugin.log(e1);
}
return false;
}
return true;
}
|
diff --git a/src/main/java/no/hials/muldvarpweb/service/CourseService.java b/src/main/java/no/hials/muldvarpweb/service/CourseService.java
index 279f6bf..6bda9cc 100644
--- a/src/main/java/no/hials/muldvarpweb/service/CourseService.java
+++ b/src/main/java/no/hials/muldvarpweb/service/CourseService.java
@@ -1,318 +1,317 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package no.hials.muldvarpweb.service;
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.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import no.hials.muldvarpweb.domain.*;
/**
*
* @author kristoffer
*/
@Stateless
@Path("course")
public class CourseService {
@PersistenceContext
EntityManager em;
@GET
@Produces({MediaType.APPLICATION_JSON})
public List<Course> findCourses() {
return em.createQuery("SELECT c from Course c", Course.class).getResultList();
}
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON})
public Course getCourse(@PathParam("id") Integer id) {
TypedQuery<Course> q = em.createQuery("Select c from Course c where c.id = :id", Course.class);
q.setParameter("id", id);
return q.getSingleResult();
}
public List<Course> getCourse(String name) {
TypedQuery<Course> q = em.createQuery("Select c from Course c where c.name LIKE :name", Course.class);
q.setParameter("name", "%" + name + "%");
return q.getResultList();
}
@GET
@Path("edit/{cid}/{themeid}/{taskid}/{val}")
public String setTask(@PathParam("cid") Integer cid,
@PathParam("themeid") Integer themeid,
@PathParam("taskid") Integer taskid,
@PathParam("val") Integer val) {
// Sette task som done
// ide: bruke lagre knapp og lagre alt i ett
String retval = "ERROR\n";
Course c = getCourse(cid);
List<Theme> themes = c.getThemes();
Theme theme = null;
for(int i = 0; i < themes.size(); i++) {
if(themes.get(i).getId() == themeid) {
theme = themes.get(i);
break;
}
}
if(theme != null) {
List<Task> tasks = theme.getTasks();
for(int i = 0; i < tasks.size(); i++) {
if(tasks.get(i).getId() == taskid) {
Task task = tasks.get(i);
if(val == 1) {
task.setDone(true);
} else if (val == 0) {
task.setDone(false);
}
editTask(c, theme, task);
retval = "Task completed";
}
}
} else {
retval += "Theme == null";
}
return retval;
}
public void addCourse(Course course) {
persist(course);
}
public void persist(Course c) {
c = em.merge(c);
em.persist(c);
}
public void addNewRevCourse(Course course) {
course = new Course(course.getName(), course.getDetail(), course.getImageurl(), course.getRevision(), course.getThemes(), course.getObligatoryTasks(), course.getExams(), course.getTeachers(), course.getProgrammes());
course.setRevision(course.getRevision()+1);
persist(course);
}
public void editCourse(Course course) {
persist(course);
}
public void removeCourse(Course course) {
course = em.merge(course);
em.remove(course);
}
public void addTheme(Course course, Theme theme) {
course.addTheme(theme);
persist(course);
}
public void editTheme(Course course, Theme theme) {
course.editTheme(theme);
persist(course);
}
public void removeTheme(Course course, Theme theme) {
course.removeTheme(theme);
persist(course);
}
public void addTask(Course course, Theme theme, Task task) {
course.addTask(theme, task);
persist(course);
}
public void editTask(Course course, Theme theme, Task task) {
course.editTask(theme, task);
persist(course);
}
public void removeTask(Course course, Theme theme, Task task) {
course.removeTask(theme, task);
persist(course);
}
public void addObligatoryTask(Course course, ObligatoryTask obligtask) {
course.addObligatoryTask(obligtask);
persist(course);
}
public void editObligatoryTask(Course course, ObligatoryTask obligtask) {
course.editObligatoryTask(obligtask);
persist(course);
}
public void removeObligatoryTask(Course course, ObligatoryTask obligtask) {
course.removeObligatoryTask(obligtask);
persist(course);
}
public void acceptObligatoryTask(Course course, ObligatoryTask obligtask) {
obligtask.acceptTask();
editObligatoryTask(course, obligtask);
}
public void addExam(Course course, Exam exam) {
course.addExam(exam);
persist(course);
}
public void editExam(Course course, Exam exam) {
course.editExam(exam);
persist(course);
}
public void removeExam(Course course, Exam exam) {
course.removeExam(exam);
persist(course);
}
public void addProgramme(Course c, Programme p) {
c.addProgramme(p);
editCourse(c);
}
public void addQuestion(Course selected, Theme selectedTheme, Task selectedTask, Question newQuestion) {
selectedTask.addQuestion(newQuestion);
editTask(selected, selectedTheme, selectedTask);
}
public void editQuestion(Course selected, Theme selectedTheme, Task selectedTask, Question q) {
selectedTask.editQuestion(q);
editTask(selected, selectedTheme, selectedTask);
}
public void addAlternative(Course selected, Theme selectedTheme, Task selectedTask, Question selectedQuestion, Alternative newAlternative) {
selectedQuestion.addAlternative(newAlternative);
editQuestion(selected, selectedTheme, selectedTask, selectedQuestion);
}
public void setAnswer(Course selected, Theme selectedTheme, Task selectedTask, Question q, Alternative a) {
q.setAnswer(a);
editQuestion(selected, selectedTheme, selectedTask, q);
}
public void removeQuestion(Course selected, Theme selectedTheme, Task selectedTask, Question q) {
selectedTask.removeQuestion(q);
editTask(selected, selectedTheme, selectedTask);
}
public void removeAlternative(Course selected, Theme selectedTheme, Task selectedTask, Question selectedQuestion, Alternative a) {
selectedQuestion.removeAlternative(a);
editQuestion(selected, selectedTheme, selectedTask, selectedQuestion);
}
public void makeTestData() {
Course retVal = new Course("Fagnavn");
retVal.setDetail("Details");
DateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss");
Date date = new Date();
ArrayList<ObligatoryTask> obligTasks = new ArrayList<ObligatoryTask>();
try {
date = df.parse("2013-11-28T12:34:56");
} catch (ParseException ex) {
Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex);
}
ObligatoryTask oblig1 = new ObligatoryTask("Obligatorisk 1");
oblig1.setDueDate(date);
obligTasks.add(oblig1);
oblig1 = new ObligatoryTask("Obligatorisk 2");
Calendar c = Calendar.getInstance();
int year = 2012;
int month = 11;
int day = 28;
int hour = 12;
int minute = 34;
c.clear();
c.set(year, month, day, hour, minute);
oblig1.setDueDate(c.getTime());
oblig1.setDone(true);
obligTasks.add(oblig1);
retVal.setObligatoryTasks(obligTasks);
try {
date = df.parse("2011-12-31T12:34:56");
} catch (ParseException ex) {
Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList<Exam> exams = new ArrayList<Exam>();
Exam exam = new Exam("Eksamen 1");
exam.setExamDate(date);
exams.add(exam);
exam = new Exam("Eksamen 2");
exam.setExamDate(date);
exams.add(exam);
retVal.setExams(exams);
ArrayList<Theme> themes = new ArrayList<Theme>();
Theme theme1 = new Theme("Kult tema");
ArrayList<Task> tasks = new ArrayList<Task>();
Task task = new Task("Oppgave 1.1");
tasks.add(task);
task = new Task("Oppgave 1.2");
tasks.add(task);
theme1.setTasks(tasks);
themes.add(theme1);
Theme theme2 = new Theme("Dummy tema");
ArrayList<Task> tasks2 = new ArrayList<Task>();
task = new Task("Les dette");
task.setDone(true);
task.setContentType("PDF");
tasks2.add(task);
task = new Task("Quiz");
task.setContentType("Quiz");
ArrayList<Question> questions = new ArrayList<Question>();
Question q = new Question();
q.setName("Spørsmål");
ArrayList<Alternative> alts = new ArrayList<Alternative>();
Alternative a = new Alternative();
a.setName("Alternativ 1");
alts.add(a);
a = new Alternative();
a.setName("Alternativ 2");
alts.add(a);
q.setAlternatives(alts);
questions.add(q);
task.setQuestions(questions);
tasks2.add(task);
task = new Task("Læringsvideo 1");
task.setContent_url("XsFR8DbSRQE");
task.setContentType("Video");
tasks2.add(task);
theme2.setTasks(tasks2);
themes.add(theme2);
retVal.setThemes(themes);
em.persist(retVal);
- ArrayList<Programme> programmes = new ArrayList<Programme>();
Programme prog = new Programme("Test program", "blablabla");
prog.addCourse(retVal);
retVal.addProgramme(prog);
retVal = em.merge(retVal);
}
}
| true | true | public void makeTestData() {
Course retVal = new Course("Fagnavn");
retVal.setDetail("Details");
DateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss");
Date date = new Date();
ArrayList<ObligatoryTask> obligTasks = new ArrayList<ObligatoryTask>();
try {
date = df.parse("2013-11-28T12:34:56");
} catch (ParseException ex) {
Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex);
}
ObligatoryTask oblig1 = new ObligatoryTask("Obligatorisk 1");
oblig1.setDueDate(date);
obligTasks.add(oblig1);
oblig1 = new ObligatoryTask("Obligatorisk 2");
Calendar c = Calendar.getInstance();
int year = 2012;
int month = 11;
int day = 28;
int hour = 12;
int minute = 34;
c.clear();
c.set(year, month, day, hour, minute);
oblig1.setDueDate(c.getTime());
oblig1.setDone(true);
obligTasks.add(oblig1);
retVal.setObligatoryTasks(obligTasks);
try {
date = df.parse("2011-12-31T12:34:56");
} catch (ParseException ex) {
Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList<Exam> exams = new ArrayList<Exam>();
Exam exam = new Exam("Eksamen 1");
exam.setExamDate(date);
exams.add(exam);
exam = new Exam("Eksamen 2");
exam.setExamDate(date);
exams.add(exam);
retVal.setExams(exams);
ArrayList<Theme> themes = new ArrayList<Theme>();
Theme theme1 = new Theme("Kult tema");
ArrayList<Task> tasks = new ArrayList<Task>();
Task task = new Task("Oppgave 1.1");
tasks.add(task);
task = new Task("Oppgave 1.2");
tasks.add(task);
theme1.setTasks(tasks);
themes.add(theme1);
Theme theme2 = new Theme("Dummy tema");
ArrayList<Task> tasks2 = new ArrayList<Task>();
task = new Task("Les dette");
task.setDone(true);
task.setContentType("PDF");
tasks2.add(task);
task = new Task("Quiz");
task.setContentType("Quiz");
ArrayList<Question> questions = new ArrayList<Question>();
Question q = new Question();
q.setName("Spørsmål");
ArrayList<Alternative> alts = new ArrayList<Alternative>();
Alternative a = new Alternative();
a.setName("Alternativ 1");
alts.add(a);
a = new Alternative();
a.setName("Alternativ 2");
alts.add(a);
q.setAlternatives(alts);
questions.add(q);
task.setQuestions(questions);
tasks2.add(task);
task = new Task("Læringsvideo 1");
task.setContent_url("XsFR8DbSRQE");
task.setContentType("Video");
tasks2.add(task);
theme2.setTasks(tasks2);
themes.add(theme2);
retVal.setThemes(themes);
em.persist(retVal);
ArrayList<Programme> programmes = new ArrayList<Programme>();
Programme prog = new Programme("Test program", "blablabla");
prog.addCourse(retVal);
retVal.addProgramme(prog);
retVal = em.merge(retVal);
}
| public void makeTestData() {
Course retVal = new Course("Fagnavn");
retVal.setDetail("Details");
DateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss");
Date date = new Date();
ArrayList<ObligatoryTask> obligTasks = new ArrayList<ObligatoryTask>();
try {
date = df.parse("2013-11-28T12:34:56");
} catch (ParseException ex) {
Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex);
}
ObligatoryTask oblig1 = new ObligatoryTask("Obligatorisk 1");
oblig1.setDueDate(date);
obligTasks.add(oblig1);
oblig1 = new ObligatoryTask("Obligatorisk 2");
Calendar c = Calendar.getInstance();
int year = 2012;
int month = 11;
int day = 28;
int hour = 12;
int minute = 34;
c.clear();
c.set(year, month, day, hour, minute);
oblig1.setDueDate(c.getTime());
oblig1.setDone(true);
obligTasks.add(oblig1);
retVal.setObligatoryTasks(obligTasks);
try {
date = df.parse("2011-12-31T12:34:56");
} catch (ParseException ex) {
Logger.getLogger(CourseService.class.getName()).log(Level.SEVERE, null, ex);
}
ArrayList<Exam> exams = new ArrayList<Exam>();
Exam exam = new Exam("Eksamen 1");
exam.setExamDate(date);
exams.add(exam);
exam = new Exam("Eksamen 2");
exam.setExamDate(date);
exams.add(exam);
retVal.setExams(exams);
ArrayList<Theme> themes = new ArrayList<Theme>();
Theme theme1 = new Theme("Kult tema");
ArrayList<Task> tasks = new ArrayList<Task>();
Task task = new Task("Oppgave 1.1");
tasks.add(task);
task = new Task("Oppgave 1.2");
tasks.add(task);
theme1.setTasks(tasks);
themes.add(theme1);
Theme theme2 = new Theme("Dummy tema");
ArrayList<Task> tasks2 = new ArrayList<Task>();
task = new Task("Les dette");
task.setDone(true);
task.setContentType("PDF");
tasks2.add(task);
task = new Task("Quiz");
task.setContentType("Quiz");
ArrayList<Question> questions = new ArrayList<Question>();
Question q = new Question();
q.setName("Spørsmål");
ArrayList<Alternative> alts = new ArrayList<Alternative>();
Alternative a = new Alternative();
a.setName("Alternativ 1");
alts.add(a);
a = new Alternative();
a.setName("Alternativ 2");
alts.add(a);
q.setAlternatives(alts);
questions.add(q);
task.setQuestions(questions);
tasks2.add(task);
task = new Task("Læringsvideo 1");
task.setContent_url("XsFR8DbSRQE");
task.setContentType("Video");
tasks2.add(task);
theme2.setTasks(tasks2);
themes.add(theme2);
retVal.setThemes(themes);
em.persist(retVal);
Programme prog = new Programme("Test program", "blablabla");
prog.addCourse(retVal);
retVal.addProgramme(prog);
retVal = em.merge(retVal);
}
|
diff --git a/src/net/sf/gogui/gtpadapter/Main.java b/src/net/sf/gogui/gtpadapter/Main.java
index 523fc905..c55e28d8 100644
--- a/src/net/sf/gogui/gtpadapter/Main.java
+++ b/src/net/sf/gogui/gtpadapter/Main.java
@@ -1,133 +1,135 @@
//----------------------------------------------------------------------------
// $Id$
// $Source$
//----------------------------------------------------------------------------
package net.sf.gogui.gtpadapter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import net.sf.gogui.go.GoPoint;
import net.sf.gogui.utils.Options;
import net.sf.gogui.utils.StringUtils;
import net.sf.gogui.version.Version;
//----------------------------------------------------------------------------
/** GtpAdapter main function. */
public class Main
{
/** GtpAdapter main function. */
public static void main(String[] args)
{
try
{
String options[] = {
"config:",
"emuhandicap",
"emuloadsgf",
"fillpasses",
"gtpfile:",
"help",
"log:",
"noscore",
"name:",
"resign:",
"size:",
"verbose",
"version",
"version1"
};
Options opt = Options.parse(args, options);
if (opt.isSet("help"))
{
printUsage(System.out);
return;
}
if (opt.isSet("version"))
{
System.out.println("GtpAdapter " + Version.get());
return;
}
boolean verbose = opt.isSet("verbose");
boolean noScore = opt.isSet("noscore");
boolean version1 = opt.isSet("version1");
boolean emuHandicap = opt.isSet("emuhandicap");
boolean emuLoadsgf = opt.isSet("emuloadsgf");
boolean fillPasses = opt.isSet("fillpasses");
String name = opt.getString("name", null);
String gtpFile = opt.getString("gtpfile", null);
- int size = opt.getInteger("size", -1, 1, GoPoint.MAXSIZE);
boolean resign = opt.isSet("resign");
int resignScore = opt.getInteger("resign");
ArrayList arguments = opt.getArguments();
if (arguments.size() != 1)
{
printUsage(System.err);
System.exit(-1);
}
PrintStream log = null;
if (opt.isSet("log"))
{
File file = new File(opt.getString("log"));
log = new PrintStream(new FileOutputStream(file));
}
String program = (String)arguments.get(0);
GtpAdapter adapter
= new GtpAdapter(program, log, gtpFile, verbose);
if (emuLoadsgf)
adapter.setEmuLoadSgf();
if (emuHandicap)
adapter.setEmuHandicap();
if (noScore)
adapter.setNoScore();
if (version1)
adapter.setVersion1();
if (fillPasses)
adapter.setFillPasses();
if (resign)
adapter.setResign(resignScore);
- if (size > 0)
+ if (opt.isSet("size"))
+ {
+ int size = opt.getInteger("size", 0, 1, GoPoint.MAXSIZE);
adapter.setFixedSize(size);
+ }
adapter.mainLoop(System.in, System.out);
adapter.close();
if (log != null)
log.close();
}
catch (Throwable t)
{
StringUtils.printException(t);
System.exit(-1);
}
}
/** Make constructor unavailable; class is for namespace only. */
private Main()
{
}
private static void printUsage(PrintStream out)
{
String helpText =
"Usage: java -jar gtpadapter.jar program\n" +
"\n" +
"-config config file\n" +
"-emuhandicap emulate free handicap commands\n" +
"-emuloadsgf emulate loadsgf commands\n" +
"-fillpasses fill non-alternating moves with pass moves\n" +
"-gtpfile file with GTP commands to send at startup\n" +
"-help print help and exit\n" +
"-log file log GTP stream to file\n" +
"-noscore hide score commands\n" +
"-resign score resign if estimated score is below threshold\n" +
"-size accept only this board size\n" +
"-verbose log GTP stream to stderr\n" +
"-version print version and exit\n" +
"-version2 translate GTP version 2 for version 1 programs\n";
out.print(helpText);
}
}
//----------------------------------------------------------------------------
| false | true | public static void main(String[] args)
{
try
{
String options[] = {
"config:",
"emuhandicap",
"emuloadsgf",
"fillpasses",
"gtpfile:",
"help",
"log:",
"noscore",
"name:",
"resign:",
"size:",
"verbose",
"version",
"version1"
};
Options opt = Options.parse(args, options);
if (opt.isSet("help"))
{
printUsage(System.out);
return;
}
if (opt.isSet("version"))
{
System.out.println("GtpAdapter " + Version.get());
return;
}
boolean verbose = opt.isSet("verbose");
boolean noScore = opt.isSet("noscore");
boolean version1 = opt.isSet("version1");
boolean emuHandicap = opt.isSet("emuhandicap");
boolean emuLoadsgf = opt.isSet("emuloadsgf");
boolean fillPasses = opt.isSet("fillpasses");
String name = opt.getString("name", null);
String gtpFile = opt.getString("gtpfile", null);
int size = opt.getInteger("size", -1, 1, GoPoint.MAXSIZE);
boolean resign = opt.isSet("resign");
int resignScore = opt.getInteger("resign");
ArrayList arguments = opt.getArguments();
if (arguments.size() != 1)
{
printUsage(System.err);
System.exit(-1);
}
PrintStream log = null;
if (opt.isSet("log"))
{
File file = new File(opt.getString("log"));
log = new PrintStream(new FileOutputStream(file));
}
String program = (String)arguments.get(0);
GtpAdapter adapter
= new GtpAdapter(program, log, gtpFile, verbose);
if (emuLoadsgf)
adapter.setEmuLoadSgf();
if (emuHandicap)
adapter.setEmuHandicap();
if (noScore)
adapter.setNoScore();
if (version1)
adapter.setVersion1();
if (fillPasses)
adapter.setFillPasses();
if (resign)
adapter.setResign(resignScore);
if (size > 0)
adapter.setFixedSize(size);
adapter.mainLoop(System.in, System.out);
adapter.close();
if (log != null)
log.close();
}
catch (Throwable t)
{
StringUtils.printException(t);
System.exit(-1);
}
}
| public static void main(String[] args)
{
try
{
String options[] = {
"config:",
"emuhandicap",
"emuloadsgf",
"fillpasses",
"gtpfile:",
"help",
"log:",
"noscore",
"name:",
"resign:",
"size:",
"verbose",
"version",
"version1"
};
Options opt = Options.parse(args, options);
if (opt.isSet("help"))
{
printUsage(System.out);
return;
}
if (opt.isSet("version"))
{
System.out.println("GtpAdapter " + Version.get());
return;
}
boolean verbose = opt.isSet("verbose");
boolean noScore = opt.isSet("noscore");
boolean version1 = opt.isSet("version1");
boolean emuHandicap = opt.isSet("emuhandicap");
boolean emuLoadsgf = opt.isSet("emuloadsgf");
boolean fillPasses = opt.isSet("fillpasses");
String name = opt.getString("name", null);
String gtpFile = opt.getString("gtpfile", null);
boolean resign = opt.isSet("resign");
int resignScore = opt.getInteger("resign");
ArrayList arguments = opt.getArguments();
if (arguments.size() != 1)
{
printUsage(System.err);
System.exit(-1);
}
PrintStream log = null;
if (opt.isSet("log"))
{
File file = new File(opt.getString("log"));
log = new PrintStream(new FileOutputStream(file));
}
String program = (String)arguments.get(0);
GtpAdapter adapter
= new GtpAdapter(program, log, gtpFile, verbose);
if (emuLoadsgf)
adapter.setEmuLoadSgf();
if (emuHandicap)
adapter.setEmuHandicap();
if (noScore)
adapter.setNoScore();
if (version1)
adapter.setVersion1();
if (fillPasses)
adapter.setFillPasses();
if (resign)
adapter.setResign(resignScore);
if (opt.isSet("size"))
{
int size = opt.getInteger("size", 0, 1, GoPoint.MAXSIZE);
adapter.setFixedSize(size);
}
adapter.mainLoop(System.in, System.out);
adapter.close();
if (log != null)
log.close();
}
catch (Throwable t)
{
StringUtils.printException(t);
System.exit(-1);
}
}
|
diff --git a/src/ca/strangebrew/DilutedRecipe.java b/src/ca/strangebrew/DilutedRecipe.java
index 591643c..4d163e9 100644
--- a/src/ca/strangebrew/DilutedRecipe.java
+++ b/src/ca/strangebrew/DilutedRecipe.java
@@ -1,117 +1,118 @@
package ca.strangebrew;
public class DilutedRecipe extends Recipe {
private Quantity addVol;
// A diluted recipe can only be created from an undiluted recipe
private DilutedRecipe() {
}
// Create a new Diluted Recipe with 0 added water
public DilutedRecipe(Recipe r) {
super(r);
this.addVol = new Quantity(super.getVolUnits(), 0);
}
// Create a diluted recipe from a recipe and an amount of dilution volumn
public DilutedRecipe(Recipe r, Quantity dil) {
super(r);
this.addVol = new Quantity(dil);
}
// Specialized Functions
public double getAddVol(final String u) {
return this.addVol.getValueAs(u);
}
public void setAddVol(final Quantity a) {
addVol = a;
}
private double calcDilutionFactor() {
return (this.getAddVol(super.getVolUnits()) + super.getFinalWortVol(super.getVolUnits())) / super.getFinalWortVol(super.getVolUnits());
}
// Overrides
public void setVolUnits(final String v) {
super.setVolUnits(v);
this.addVol.setUnits(v);
}
public double getFinalWortVol(final String s) {
return this.getAddVol(s) + super.getFinalWortVol(s);
}
public double getColour() {
return getColour(getColourMethod());
}
public double getColour(final String method) {
return BrewCalcs.calcColour(getMcu() / this.calcDilutionFactor(), method);
}
public double getIbu() {
return super.getIbu() / this.calcDilutionFactor();
}
public double getEstOg() {
return ((super.getEstOg() - 1) / this.calcDilutionFactor()) + 1;
}
public double getAlcohol() {
return super.getAlcohol() / this.calcDilutionFactor();
}
public String toXML(final String printOptions) {
StringBuffer unDil = new StringBuffer(super.toXML(printOptions));
String dil = "";
// This is UGGLY! :)
dil += " <ADDED_VOLUME>" + SBStringUtils.format(addVol.getValue(), 2) + "</ADDED_VOLUME>\n";
+ dil += " <UNITS>" + addVol.getUnits() + "</UNITS>\n";
int offset = unDil.indexOf("</DETAILS>\n");
unDil.insert(offset, dil);
return unDil.toString();
}
public String toText() {
String unDil = super.toText();
unDil += "Dilute With: " + SBStringUtils.format(addVol.getValue(), 2) + addVol.getUnits() + "\n";
return unDil;
}
// public double getBUGU() {
// double bugu = 0.0;
// if ( estOg != 1.0 ) {
// bugu = ibu / ((estOg - 1) * 1000);
// }
// return bugu;
// }
// Accessors to original numbers for DilPanel
public double getOrigFinalWortVol(final String s) {
return super.getFinalWortVol(s);
}
public double getOrigColour() {
return super.getColour();
}
public double getOrigColour(final String method) {
return super.getColour(method);
}
public double getOrigIbu() {
return super.getIbu();
}
public double getOrigEstOg() {
return super.getEstOg();
}
public double getOrigAlcohol() {
return super.getAlcohol();
}
}
| true | true | public String toXML(final String printOptions) {
StringBuffer unDil = new StringBuffer(super.toXML(printOptions));
String dil = "";
// This is UGGLY! :)
dil += " <ADDED_VOLUME>" + SBStringUtils.format(addVol.getValue(), 2) + "</ADDED_VOLUME>\n";
int offset = unDil.indexOf("</DETAILS>\n");
unDil.insert(offset, dil);
return unDil.toString();
}
| public String toXML(final String printOptions) {
StringBuffer unDil = new StringBuffer(super.toXML(printOptions));
String dil = "";
// This is UGGLY! :)
dil += " <ADDED_VOLUME>" + SBStringUtils.format(addVol.getValue(), 2) + "</ADDED_VOLUME>\n";
dil += " <UNITS>" + addVol.getUnits() + "</UNITS>\n";
int offset = unDil.indexOf("</DETAILS>\n");
unDil.insert(offset, dil);
return unDil.toString();
}
|
diff --git a/org.caleydo.view.stratomex/src/org/caleydo/view/stratomex/brick/layout/HeaderBrickLayoutTemplate.java b/org.caleydo.view.stratomex/src/org/caleydo/view/stratomex/brick/layout/HeaderBrickLayoutTemplate.java
index 69c2ff854..27fc10d01 100644
--- a/org.caleydo.view.stratomex/src/org/caleydo/view/stratomex/brick/layout/HeaderBrickLayoutTemplate.java
+++ b/org.caleydo.view.stratomex/src/org/caleydo/view/stratomex/brick/layout/HeaderBrickLayoutTemplate.java
@@ -1,537 +1,538 @@
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.view.stratomex.brick.layout;
import java.util.ArrayList;
import java.util.List;
import javax.media.opengl.GLContext;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.event.data.ReplaceTablePerspectiveEvent;
import org.caleydo.core.manager.GeneralManager;
import org.caleydo.core.util.clusterer.gui.ClusterDialog;
import org.caleydo.core.util.clusterer.initialization.ClusterConfiguration;
import org.caleydo.core.view.listener.RemoveTablePerspectiveEvent;
import org.caleydo.core.view.opengl.layout.Column;
import org.caleydo.core.view.opengl.layout.ElementLayout;
import org.caleydo.core.view.opengl.layout.Row;
import org.caleydo.core.view.opengl.layout.util.ColorRenderer;
import org.caleydo.core.view.opengl.layout.util.LineSeparatorRenderer;
import org.caleydo.core.view.opengl.layout.util.Zoomer;
import org.caleydo.core.view.opengl.picking.APickingListener;
import org.caleydo.core.view.opengl.picking.Pick;
import org.caleydo.core.view.opengl.util.button.Button;
import org.caleydo.core.view.opengl.util.button.ButtonRenderer;
import org.caleydo.core.view.opengl.util.texture.EIconTextures;
import org.caleydo.view.stratomex.EPickingType;
import org.caleydo.view.stratomex.GLStratomex;
import org.caleydo.view.stratomex.brick.GLBrick;
import org.caleydo.view.stratomex.brick.configurer.IBrickConfigurer;
import org.caleydo.view.stratomex.brick.ui.HandleRenderer;
import org.caleydo.view.stratomex.column.BrickColumn;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* Brick layout for central brick in {@link BrickColumn} containing a caption bar, toolbar, footer bar and view.
*
* @author Christian Partl
*
*/
public class HeaderBrickLayoutTemplate extends ABrickLayoutConfiguration {
protected static final int TOOLBAR_HEIGHT_PIXELS = 16;
protected static final int HEADER_BAR_HEIGHT_PIXELS = 12;
protected static final int FOOTER_BAR_HEIGHT_PIXELS = 12;
protected static final int LINE_SEPARATOR_HEIGHT_PIXELS = 3;
protected static final int BUTTON_HEIGHT_PIXELS = 16;
protected static final int BUTTON_WIDTH_PIXELS = 16;
protected static final int HANDLE_SIZE_PIXELS = 8;
protected static final int CLUSTER_BUTTON_ID = 0;
protected static final int LOCK_RESIZING_BUTTON_ID = 1;
protected static final int REMOVE_COLUMN_BUTTON_ID = 2;
protected static final int DEFAULT_HANDLES = HandleRenderer.MOVE_HORIZONTALLY_HANDLE
| HandleRenderer.ALL_RESIZE_HANDLES | HandleRenderer.ALL_EXPAND_HANDLES;
// protected ArrayList<BrickViewSwitchingButton> viewSwitchingButtons;
protected List<ElementLayout> headerBarElements;
protected List<ElementLayout> toolBarElements;
protected List<ElementLayout> footerBarElements;
// protected Button heatMapButton;
// protected Button parCoordsButton;
// protected Button histogramButton;
// protected Button overviewHeatMapButton;
// protected Button clusterButton;
protected Button lockResizingButton;
protected boolean showToolBar;
protected boolean showFooterBar;
protected boolean showClusterButton = false;
protected int guiElementsHeight = 0;
protected Row headerBar;
protected ToolBar toolBar;
protected Row footerBar;
public HeaderBrickLayoutTemplate(GLBrick brick, BrickColumn brickColumn, GLStratomex stratomex) {
super(brick, brickColumn, stratomex);
// viewSwitchingButtons = new ArrayList<BrickViewSwitchingButton>();
this.stratomex = stratomex;
headerBarElements = new ArrayList<ElementLayout>();
footerBarElements = new ArrayList<ElementLayout>();
toolBarElements = new ArrayList<ElementLayout>();
footerBar = new Row();
registerPickingListeners();
// viewTypeChanged(getDefaultViewType());
}
@Override
public void setLockResizing(boolean lockResizing) {
if (lockResizingButton != null)
lockResizingButton.setSelected(lockResizing);
}
@Override
public void setStaticLayouts() {
guiElementsHeight = 0;
Row baseRow = new Row("baseRow");
baseRow.setFrameColor(1, 0, 0, 0.5f);
baseRow.setFrameColor(0, 0, 1, 0);
baseElementLayout = baseRow;
Column baseColumn = new Column("baseColumn");
baseColumn.setFrameColor(0, 1, 0, 0);
ElementLayout spacingLayoutY = new ElementLayout("spacingLayoutY");
spacingLayoutY.setPixelSizeY(SPACING_PIXELS);
spacingLayoutY.setPixelSizeX(0);
headerBar = createHeaderBar();
toolBar = createToolBar();
if (showToolBar) {
baseColumn.append(toolBar);
// baseColumn.append(lineSeparatorLayout);
// guiElementsHeight += (2 * SPACING_PIXELS)
// + LINE_SEPARATOR_HEIGHT_PIXELS;
}
baseRow.setRenderer(borderedAreaRenderer);
if (handles == null) {
handles = DEFAULT_HANDLES;
}
if (this.handleRenderer != null)
this.handleRenderer.destroy(GLContext.getCurrentGL().getGL2());
handleRenderer = new HandleRenderer(brick, HANDLE_SIZE_PIXELS, brick.getTextureManager(), handles);
baseRow.addForeGroundRenderer(handleRenderer);
ElementLayout spacingLayoutX = new ElementLayout("spacingLayoutX");
spacingLayoutX.setPixelSizeX(SPACING_PIXELS);
spacingLayoutX.setRatioSizeY(0);
baseRow.append(spacingLayoutX);
baseRow.append(baseColumn);
baseRow.append(spacingLayoutX);
ElementLayout dimensionBarLayout = new ElementLayout("dimensionBar");
dimensionBarLayout.setFrameColor(1, 0, 1, 0);
dimensionBarLayout.setPixelSizeY(FOOTER_BAR_HEIGHT_PIXELS);
if (viewLayout == null) {
viewLayout = new ElementLayout("viewLayout");
viewLayout.setFrameColor(1, 0, 0, 1);
viewLayout.addBackgroundRenderer(new ColorRenderer(new float[] { 1, 1, 1, 1 }));
Zoomer zoomer = new Zoomer(stratomex, viewLayout);
viewLayout.setZoomer(zoomer);
}
viewLayout.setRenderer(viewRenderer);
viewLayout.addForeGroundRenderer(innerBorderedAreaRenderer);
// captionRow.append(spacingLayoutX);
ElementLayout lineSeparatorLayout = new ElementLayout("lineSeparator");
lineSeparatorLayout.setPixelSizeY(LINE_SEPARATOR_HEIGHT_PIXELS);
lineSeparatorLayout.setRatioSizeX(1);
lineSeparatorLayout.setRenderer(new LineSeparatorRenderer(false));
// ElementLayout dimensionBarLaylout = new
// ElementLayout("dimensionBar");
// dimensionBarLaylout.setPixelGLConverter(pixelGLConverter);
// dimensionBarLaylout.setPixelSizeY(FOOTER_BAR_HEIGHT_PIXELS);
// dimensionBarLaylout.setRatioSizeX(1);
// dimensionBarLaylout.setRenderer(new DimensionBarRenderer(brick));
baseColumn.append(spacingLayoutY);
guiElementsHeight += SPACING_PIXELS;
if (showFooterBar) {
footerBar = createFooterBar();
baseColumn.append(footerBar);
baseColumn.append(spacingLayoutY);
guiElementsHeight += SPACING_PIXELS + FOOTER_BAR_HEIGHT_PIXELS;
}
// if (!dimensionGroup.isProportionalMode())
baseColumn.append(viewLayout);
baseColumn.append(spacingLayoutY);
baseColumn.append(headerBar);
baseColumn.append(spacingLayoutY);
guiElementsHeight += (2 * SPACING_PIXELS) + HEADER_BAR_HEIGHT_PIXELS;
}
protected Row createFooterBar() {
Row footerBar = new Row("footerBar");
footerBar.setPixelSizeY(FOOTER_BAR_HEIGHT_PIXELS);
for (ElementLayout element : footerBarElements) {
footerBar.append(element);
}
return footerBar;
}
protected Row createHeaderBar() {
Row headerBar = new Row();
headerBar.setPixelSizeY(HEADER_BAR_HEIGHT_PIXELS);
for (ElementLayout element : headerBarElements) {
headerBar.append(element);
}
ElementLayout spacingLayoutX = new ElementLayout("spacingLayoutX");
spacingLayoutX.setPixelSizeX(SPACING_PIXELS);
spacingLayoutX.setRatioSizeY(0);
return headerBar;
}
/**
* Creates the toolbar containing buttons for view switching.
*
* @param pixelHeight
* @return
*/
protected ToolBar createToolBar() {
if (this.toolBar != null) {
this.toolBar.clear();
this.toolBar.destroy(GLContext.getCurrentGL().getGL2());
}
ToolBar toolBar = new ToolBar("ToolBarRow", brick);
toolBar.setPixelSizeY(0);
ElementLayout spacingLayoutX = new ElementLayout("spacingLayoutX");
spacingLayoutX.setPixelSizeX(SPACING_PIXELS);
spacingLayoutX.setRatioSizeY(0);
toolBar.append(spacingLayoutX);
for (ElementLayout element : toolBarElements) {
toolBar.append(element);
}
ElementLayout greedyXLayout = new ElementLayout("greedy");
greedyXLayout.setGrabX(true);
greedyXLayout.setRatioSizeY(0);
toolBar.append(greedyXLayout);
if (showClusterButton) {
Button clusterButton = new Button(EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(), brick.getID(),
EIconTextures.CLUSTER_ICON);
ElementLayout clusterButtonLayout = new ElementLayout("clusterButton");
clusterButtonLayout.setPixelSizeX(BUTTON_WIDTH_PIXELS);
clusterButtonLayout.setPixelSizeY(BUTTON_HEIGHT_PIXELS);
clusterButtonLayout
.setRenderer(new ButtonRenderer.Builder(brick.getStratomex(), clusterButton)
.textureManager(brick.getTextureManager()).zCoordinate(DefaultBrickLayoutTemplate.BUTTON_Z)
.build());
toolBar.append(clusterButtonLayout);
toolBar.append(spacingLayoutX);
brick.getStratomex().removeAllIDPickingListeners(EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(),
brick.getID());
brick.getStratomex().addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
ClusterConfiguration clusterConfiguration = new ClusterConfiguration();
TablePerspective oldTablePerspective = brick.getBrickColumn().getTablePerspective();
clusterConfiguration.setSourceDimensionPerspective(oldTablePerspective
.getDimensionPerspective());
clusterConfiguration.setSourceRecordPerspective(oldTablePerspective.getRecordPerspective());
ATableBasedDataDomain dataDomain = oldTablePerspective.getDataDomain();
// here we create the new record perspective
// which is
// intended to be used once the clustering is
// complete
Perspective newRecordPerspective = new Perspective(dataDomain, dataDomain.getRecordIDType());
+ newRecordPerspective.setLabel("Currently clustering...", false);
// we temporarily set the old va to the new
// perspective,
// to avoid empty bricks
newRecordPerspective.setVirtualArray(oldTablePerspective.getRecordPerspective()
.getVirtualArray());
clusterConfiguration.setOptionalTargetRecordPerspective(newRecordPerspective);
ClusterDialog dialog = new ClusterDialog(new Shell(), brick.getDataDomain(),
clusterConfiguration);
if (dialog.open() == Window.OK) {
dataDomain.getTable().registerRecordPerspective(newRecordPerspective);
TablePerspective newTablePerspective = dataDomain.getTablePerspective(
newRecordPerspective.getPerspectiveID(), oldTablePerspective
.getDimensionPerspective().getPerspectiveID());
ReplaceTablePerspectiveEvent rEvent = new ReplaceTablePerspectiveEvent(brick
.getBrickColumn().getStratomexView().getID(), newTablePerspective,
oldTablePerspective);
GeneralManager.get().getEventPublisher().triggerEvent(rEvent);
}
// clusterConfiguration =
// dialog.getClusterConfiguration();
// if (clusterConfiguration == null)
// return;
}
});
}
}, EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(), brick.getID());
}
brick.getStratomex().addIDPickingTooltipListener("Cluster", EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(),
brick.getID());
Button removeColumnButton = new Button(EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID(),
EIconTextures.REMOVE);
ElementLayout removeColumnButtonLayout = new ElementLayout("removeColumnButton");
removeColumnButtonLayout.setPixelSizeX(BUTTON_WIDTH_PIXELS);
removeColumnButtonLayout.setPixelSizeY(BUTTON_HEIGHT_PIXELS);
removeColumnButtonLayout.setRenderer(new ButtonRenderer.Builder(brick.getStratomex(), removeColumnButton)
.textureManager(brick.getTextureManager()).zCoordinate(DefaultBrickLayoutTemplate.BUTTON_Z).build());
toolBar.append(removeColumnButtonLayout);
toolBar.append(spacingLayoutX);
brick.getStratomex().removeAllIDPickingListeners(EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID());
brick.getStratomex().addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
RemoveTablePerspectiveEvent event = new RemoveTablePerspectiveEvent(brick.getBrickColumn()
.getTablePerspective(), brick.getStratomex());
event.setSender(this);
GeneralManager.get().getEventPublisher().triggerEvent(event);
}
});
}
}, EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID());
brick.getStratomex().addIDPickingTooltipListener("Remove column", EPickingType.REMOVE_COLUMN_BUTTON.name(),
brick.getID());
return toolBar;
}
@Override
protected void registerPickingListeners() {
// brick.removeAllIDPickingListeners(pickingType, pickedObjectID)
brick.addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
// boolean isResizingLocked = !lockResizingButton.isSelected();
// brick.setSizeFixed(isResizingLocked);
// lockResizingButton.setSelected(isResizingLocked);
}
}, EPickingType.BRICK_LOCK_RESIZING_BUTTON.name(), LOCK_RESIZING_BUTTON_ID);
brick.getStratomex().addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
if (brickColumn.isDetailBrickShown() && brickColumn.isExpandLeft())
return;
brickColumn.showDetailedBrick(brick, false);
}
}, EPickingType.EXPAND_RIGHT_HANDLE.name(), brick.getID());
brick.getStratomex().addIDPickingTooltipListener("Show in detail", EPickingType.EXPAND_RIGHT_HANDLE.name(),
brick.getID());
brick.getStratomex().addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
if (brickColumn.isDetailBrickShown() && !brickColumn.isExpandLeft())
return;
brickColumn.showDetailedBrick(brick, true);
}
}, EPickingType.EXPAND_LEFT_HANDLE.name(), brick.getID());
brick.getStratomex().addIDPickingTooltipListener("Show in detail", EPickingType.EXPAND_LEFT_HANDLE.name(),
brick.getID());
}
@Override
public int getMinHeightPixels() {
if (viewRenderer == null)
return 20;
return guiElementsHeight + viewRenderer.getMinHeightPixels();
}
@Override
public int getMinWidthPixels() {
int headerBarWidth = calcSumPixelWidth(headerBar);
int toolBarWidth = showToolBar ? calcSumPixelWidth(toolBar) : 0;
int footerBarWidth = showFooterBar ? calcSumPixelWidth(footerBar) : 0;
int minGuiElementWidth = Math.max(headerBarWidth, Math.max(toolBarWidth, footerBarWidth)) + 2 * SPACING_PIXELS;
if (viewRenderer == null)
return minGuiElementWidth;
return Math.max(minGuiElementWidth, (2 * SPACING_PIXELS) + viewRenderer.getMinWidthPixels());
// return pixelGLConverter.getPixelWidthForGLWidth(dimensionGroup
// .getMinWidth());
}
@Override
public ABrickLayoutConfiguration getCollapsedLayoutTemplate() {
return new CompactHeaderBrickLayoutTemplate(brick, brickColumn, stratomex);
}
@Override
public ABrickLayoutConfiguration getExpandedLayoutTemplate() {
return this;
}
/**
* @return The elements displayed in the header bar.
*/
public List<ElementLayout> getHeaderBarElements() {
return headerBarElements;
}
/**
* Sets the elements that should appear in the header bar. The elements will placed from left to right using the
* order of the specified list.
*
* @param headerBarElements
*/
public void setHeaderBarElements(List<ElementLayout> headerBarElements) {
this.headerBarElements = headerBarElements;
}
/**
* @return The elements displayed in the tool bar.
*/
public List<ElementLayout> getToolBarElements() {
return toolBarElements;
}
/**
* Sets the elements that should appear in the tool bar. The elements will placed from left to right using the order
* of the specified list.
*
* @param toolBarElements
*/
public void setToolBarElements(List<ElementLayout> toolBarElements) {
this.toolBarElements = toolBarElements;
}
/**
* @return The elements displayed in the footer bar.
*/
public List<ElementLayout> getFooterBarElements() {
return footerBarElements;
}
/**
* Sets the elements that should appear in the footer bar. The elements will placed from left to right using the
* order of the specified list.
*
* @param footerBarElements
*/
public void setFooterBarElements(List<ElementLayout> footerBarElements) {
this.footerBarElements = footerBarElements;
}
/**
* @return True, if the toolbar is shown, false otherwise.
*/
public boolean isShowToolBar() {
return showToolBar;
}
/**
* Specifies whether the toolbar shall be shown.
*
* @param showToolBar
*/
public void showToolBar(boolean showToolBar) {
this.showToolBar = showToolBar;
}
/**
* @return True, if the footer bar is shown, false otherwise.
*/
public boolean isShowFooterBar() {
return showFooterBar;
}
/**
* Specifies whether the footer bar shall be shown.
*
* @param showFooterBar
*/
public void showFooterBar(boolean showFooterBar) {
this.showFooterBar = showFooterBar;
}
public void showClusterButton(boolean showClusterButton) {
this.showClusterButton = showClusterButton;
}
@Override
public void destroy() {
super.destroy();
brick.getStratomex().removeAllIDPickingListeners(EPickingType.EXPAND_LEFT_HANDLE.name(), brick.getID());
brick.getStratomex().removeAllIDPickingListeners(EPickingType.EXPAND_RIGHT_HANDLE.name(), brick.getID());
brick.getStratomex().removeAllIDPickingListeners(EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(),
brick.getID());
brick.getStratomex().removeAllIDPickingListeners(EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID());
brick.removeAllIDPickingListeners(EPickingType.BRICK_LOCK_RESIZING_BUTTON.name(), LOCK_RESIZING_BUTTON_ID);
}
@Override
public void configure(IBrickConfigurer configurer) {
configurer.configure(this);
}
@Override
public ToolBar getToolBar() {
return toolBar;
}
}
| true | true | protected ToolBar createToolBar() {
if (this.toolBar != null) {
this.toolBar.clear();
this.toolBar.destroy(GLContext.getCurrentGL().getGL2());
}
ToolBar toolBar = new ToolBar("ToolBarRow", brick);
toolBar.setPixelSizeY(0);
ElementLayout spacingLayoutX = new ElementLayout("spacingLayoutX");
spacingLayoutX.setPixelSizeX(SPACING_PIXELS);
spacingLayoutX.setRatioSizeY(0);
toolBar.append(spacingLayoutX);
for (ElementLayout element : toolBarElements) {
toolBar.append(element);
}
ElementLayout greedyXLayout = new ElementLayout("greedy");
greedyXLayout.setGrabX(true);
greedyXLayout.setRatioSizeY(0);
toolBar.append(greedyXLayout);
if (showClusterButton) {
Button clusterButton = new Button(EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(), brick.getID(),
EIconTextures.CLUSTER_ICON);
ElementLayout clusterButtonLayout = new ElementLayout("clusterButton");
clusterButtonLayout.setPixelSizeX(BUTTON_WIDTH_PIXELS);
clusterButtonLayout.setPixelSizeY(BUTTON_HEIGHT_PIXELS);
clusterButtonLayout
.setRenderer(new ButtonRenderer.Builder(brick.getStratomex(), clusterButton)
.textureManager(brick.getTextureManager()).zCoordinate(DefaultBrickLayoutTemplate.BUTTON_Z)
.build());
toolBar.append(clusterButtonLayout);
toolBar.append(spacingLayoutX);
brick.getStratomex().removeAllIDPickingListeners(EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(),
brick.getID());
brick.getStratomex().addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
ClusterConfiguration clusterConfiguration = new ClusterConfiguration();
TablePerspective oldTablePerspective = brick.getBrickColumn().getTablePerspective();
clusterConfiguration.setSourceDimensionPerspective(oldTablePerspective
.getDimensionPerspective());
clusterConfiguration.setSourceRecordPerspective(oldTablePerspective.getRecordPerspective());
ATableBasedDataDomain dataDomain = oldTablePerspective.getDataDomain();
// here we create the new record perspective
// which is
// intended to be used once the clustering is
// complete
Perspective newRecordPerspective = new Perspective(dataDomain, dataDomain.getRecordIDType());
// we temporarily set the old va to the new
// perspective,
// to avoid empty bricks
newRecordPerspective.setVirtualArray(oldTablePerspective.getRecordPerspective()
.getVirtualArray());
clusterConfiguration.setOptionalTargetRecordPerspective(newRecordPerspective);
ClusterDialog dialog = new ClusterDialog(new Shell(), brick.getDataDomain(),
clusterConfiguration);
if (dialog.open() == Window.OK) {
dataDomain.getTable().registerRecordPerspective(newRecordPerspective);
TablePerspective newTablePerspective = dataDomain.getTablePerspective(
newRecordPerspective.getPerspectiveID(), oldTablePerspective
.getDimensionPerspective().getPerspectiveID());
ReplaceTablePerspectiveEvent rEvent = new ReplaceTablePerspectiveEvent(brick
.getBrickColumn().getStratomexView().getID(), newTablePerspective,
oldTablePerspective);
GeneralManager.get().getEventPublisher().triggerEvent(rEvent);
}
// clusterConfiguration =
// dialog.getClusterConfiguration();
// if (clusterConfiguration == null)
// return;
}
});
}
}, EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(), brick.getID());
}
brick.getStratomex().addIDPickingTooltipListener("Cluster", EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(),
brick.getID());
Button removeColumnButton = new Button(EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID(),
EIconTextures.REMOVE);
ElementLayout removeColumnButtonLayout = new ElementLayout("removeColumnButton");
removeColumnButtonLayout.setPixelSizeX(BUTTON_WIDTH_PIXELS);
removeColumnButtonLayout.setPixelSizeY(BUTTON_HEIGHT_PIXELS);
removeColumnButtonLayout.setRenderer(new ButtonRenderer.Builder(brick.getStratomex(), removeColumnButton)
.textureManager(brick.getTextureManager()).zCoordinate(DefaultBrickLayoutTemplate.BUTTON_Z).build());
toolBar.append(removeColumnButtonLayout);
toolBar.append(spacingLayoutX);
brick.getStratomex().removeAllIDPickingListeners(EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID());
brick.getStratomex().addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
RemoveTablePerspectiveEvent event = new RemoveTablePerspectiveEvent(brick.getBrickColumn()
.getTablePerspective(), brick.getStratomex());
event.setSender(this);
GeneralManager.get().getEventPublisher().triggerEvent(event);
}
});
}
}, EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID());
brick.getStratomex().addIDPickingTooltipListener("Remove column", EPickingType.REMOVE_COLUMN_BUTTON.name(),
brick.getID());
return toolBar;
}
| protected ToolBar createToolBar() {
if (this.toolBar != null) {
this.toolBar.clear();
this.toolBar.destroy(GLContext.getCurrentGL().getGL2());
}
ToolBar toolBar = new ToolBar("ToolBarRow", brick);
toolBar.setPixelSizeY(0);
ElementLayout spacingLayoutX = new ElementLayout("spacingLayoutX");
spacingLayoutX.setPixelSizeX(SPACING_PIXELS);
spacingLayoutX.setRatioSizeY(0);
toolBar.append(spacingLayoutX);
for (ElementLayout element : toolBarElements) {
toolBar.append(element);
}
ElementLayout greedyXLayout = new ElementLayout("greedy");
greedyXLayout.setGrabX(true);
greedyXLayout.setRatioSizeY(0);
toolBar.append(greedyXLayout);
if (showClusterButton) {
Button clusterButton = new Button(EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(), brick.getID(),
EIconTextures.CLUSTER_ICON);
ElementLayout clusterButtonLayout = new ElementLayout("clusterButton");
clusterButtonLayout.setPixelSizeX(BUTTON_WIDTH_PIXELS);
clusterButtonLayout.setPixelSizeY(BUTTON_HEIGHT_PIXELS);
clusterButtonLayout
.setRenderer(new ButtonRenderer.Builder(brick.getStratomex(), clusterButton)
.textureManager(brick.getTextureManager()).zCoordinate(DefaultBrickLayoutTemplate.BUTTON_Z)
.build());
toolBar.append(clusterButtonLayout);
toolBar.append(spacingLayoutX);
brick.getStratomex().removeAllIDPickingListeners(EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(),
brick.getID());
brick.getStratomex().addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
ClusterConfiguration clusterConfiguration = new ClusterConfiguration();
TablePerspective oldTablePerspective = brick.getBrickColumn().getTablePerspective();
clusterConfiguration.setSourceDimensionPerspective(oldTablePerspective
.getDimensionPerspective());
clusterConfiguration.setSourceRecordPerspective(oldTablePerspective.getRecordPerspective());
ATableBasedDataDomain dataDomain = oldTablePerspective.getDataDomain();
// here we create the new record perspective
// which is
// intended to be used once the clustering is
// complete
Perspective newRecordPerspective = new Perspective(dataDomain, dataDomain.getRecordIDType());
newRecordPerspective.setLabel("Currently clustering...", false);
// we temporarily set the old va to the new
// perspective,
// to avoid empty bricks
newRecordPerspective.setVirtualArray(oldTablePerspective.getRecordPerspective()
.getVirtualArray());
clusterConfiguration.setOptionalTargetRecordPerspective(newRecordPerspective);
ClusterDialog dialog = new ClusterDialog(new Shell(), brick.getDataDomain(),
clusterConfiguration);
if (dialog.open() == Window.OK) {
dataDomain.getTable().registerRecordPerspective(newRecordPerspective);
TablePerspective newTablePerspective = dataDomain.getTablePerspective(
newRecordPerspective.getPerspectiveID(), oldTablePerspective
.getDimensionPerspective().getPerspectiveID());
ReplaceTablePerspectiveEvent rEvent = new ReplaceTablePerspectiveEvent(brick
.getBrickColumn().getStratomexView().getID(), newTablePerspective,
oldTablePerspective);
GeneralManager.get().getEventPublisher().triggerEvent(rEvent);
}
// clusterConfiguration =
// dialog.getClusterConfiguration();
// if (clusterConfiguration == null)
// return;
}
});
}
}, EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(), brick.getID());
}
brick.getStratomex().addIDPickingTooltipListener("Cluster", EPickingType.DIMENSION_GROUP_CLUSTER_BUTTON.name(),
brick.getID());
Button removeColumnButton = new Button(EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID(),
EIconTextures.REMOVE);
ElementLayout removeColumnButtonLayout = new ElementLayout("removeColumnButton");
removeColumnButtonLayout.setPixelSizeX(BUTTON_WIDTH_PIXELS);
removeColumnButtonLayout.setPixelSizeY(BUTTON_HEIGHT_PIXELS);
removeColumnButtonLayout.setRenderer(new ButtonRenderer.Builder(brick.getStratomex(), removeColumnButton)
.textureManager(brick.getTextureManager()).zCoordinate(DefaultBrickLayoutTemplate.BUTTON_Z).build());
toolBar.append(removeColumnButtonLayout);
toolBar.append(spacingLayoutX);
brick.getStratomex().removeAllIDPickingListeners(EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID());
brick.getStratomex().addIDPickingListener(new APickingListener() {
@Override
public void clicked(Pick pick) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
RemoveTablePerspectiveEvent event = new RemoveTablePerspectiveEvent(brick.getBrickColumn()
.getTablePerspective(), brick.getStratomex());
event.setSender(this);
GeneralManager.get().getEventPublisher().triggerEvent(event);
}
});
}
}, EPickingType.REMOVE_COLUMN_BUTTON.name(), brick.getID());
brick.getStratomex().addIDPickingTooltipListener("Remove column", EPickingType.REMOVE_COLUMN_BUTTON.name(),
brick.getID());
return toolBar;
}
|
diff --git a/Rania/src/com/game/rania/controller/LocationController.java b/Rania/src/com/game/rania/controller/LocationController.java
index 543c63b..361c279 100644
--- a/Rania/src/com/game/rania/controller/LocationController.java
+++ b/Rania/src/com/game/rania/controller/LocationController.java
@@ -1,382 +1,382 @@
package com.game.rania.controller;
import java.util.Collection;
import java.util.HashMap;
import com.badlogic.gdx.math.Vector2;
import com.game.rania.model.Location;
import com.game.rania.model.ParallaxLayer;
import com.game.rania.model.ParallaxObject;
import com.game.rania.model.Planet;
import com.game.rania.model.Player;
import com.game.rania.model.Radar;
import com.game.rania.model.Star;
import com.game.rania.model.User;
import com.game.rania.model.element.Group;
import com.game.rania.model.element.RegionID;
import com.game.rania.view.MainView;
public class LocationController {
private MainView mView = null;
private MainController mController = null;
private ClientController cController = null;
public LocationController(MainController mController, MainView mView, ClientController cController) {
this.mView = mView;
this.mController = mController;
this.cController = cController;
}
public void loadTextures(){
for (int i = 0; i < 18; i++)
mView.loadTexture("data/location/planets.png", RegionID.fromInt(RegionID.PLANET_0.ordinal() + i), i % 5 * 204, i / 5 * 204, 204, 204);
for (int i = 0; i < 8; i++)
- mView.loadTexture("data/backgrounds/nebulas(512x512).png", RegionID.fromInt(RegionID.NEBULA_0.ordinal() + i), i % 4 * 512, i / 4 * 512, 512, 512);
+ mView.loadTexture("data/backgrounds/nebulas.png", RegionID.fromInt(RegionID.NEBULA_0.ordinal() + i), i % 4 * 512, i / 4 * 512, 512, 512);
mView.loadTexture("data/location/star.png", RegionID.STAR);
mView.loadTexture("data/location/radar.png", RegionID.RADAR);
mView.loadTexture("data/location/sensor.png", RegionID.RADAR_SENSOR);
mView.loadTexture("data/location/radarObject.png", RegionID.RADAR_OBJECT);
mView.loadTexture("data/location/SpaceShip.png", RegionID.SHIP);
mView.loadTexture("data/backgrounds/space.png", RegionID.BACKGROUND_SPACE);
mView.loadTexture("data/backgrounds/stars.png", RegionID.BACKGROUND_STARS);
}
//list objects
private HashMap<Integer, Location> locations = null;
private HashMap<Integer, Planet> planets = new HashMap<Integer, Planet>();
private HashMap<Integer, User> users = null;
//objects
private Player player = null;
private Group background = null;
private Radar radar = null;
private Star star = null;
private Location currentLocation = null;
//help objects
private ShipController pController = null;
public void clearObjects(){
removePlayer();
removeBackground();
removeRadar();
removePlanets();
removeUsers();
}
public void loadLocations() {
locations = cController.getLocationList();
}
//player
public boolean loadPlayer(){
player = cController.getPlayerData();
if (player == null)
return false;
currentLocation = getNearLocation();
if (currentLocation == null)
return false;
return true;
}
public void setPlayer(Player newPlayer){
removePlayer();
player = newPlayer;
addPlayer();
}
public void addPlayer(){
if (player != null)
{
mController.addObject(player);
pController = new ShipController(player);
mController.addProcessor(pController);
}
}
public void removePlayer(){
if (player != null) {
mController.removeObject(player);
if (pController != null)
mController.removeProcessor(pController);
player = null;
}
}
//background
public void loadBackground(){
background = new Group();
background.addElement(new ParallaxLayer(RegionID.BACKGROUND_SPACE, 250, 300, -0.35f));
background.addElement(new ParallaxLayer(RegionID.BACKGROUND_STARS, -150, 0, -0.25f));
background.addElement(new ParallaxObject(RegionID.NEBULA_1, 500, 500, 45, 2, 2, -0.4f));
background.addElement(new ParallaxObject(RegionID.NEBULA_2, -500, 500, -45, 2, 2, -0.4f));
background.addElement(new ParallaxObject(RegionID.NEBULA_3, 500, -500, 0, 2, 2, -0.4f));
background.addElement(new ParallaxObject(RegionID.NEBULA_4, -500, -500, 200, 2, 2, -0.4f));
background.addElement(new ParallaxObject(RegionID.NEBULA_5, 1500, 1500, 45, 2, 2, -0.4f));
background.addElement(new ParallaxObject(RegionID.NEBULA_6, -1500, 1500, -45, 2, 2, -0.4f));
background.addElement(new ParallaxObject(RegionID.NEBULA_7, 1500, -1500, 0, 2, 2, -0.4f));
background.addElement(new ParallaxObject(RegionID.NEBULA_0, -1500, -1500, 200, 2, 2, -0.4f));
}
public void setBackground(Group newBackground){
removeBackground();
background = newBackground;
addBackground();
}
public void addBackground(){
if (background != null)
mController.addObject(background);
}
public void removeBackground(){
if (background != null) {
mController.removeObject(background);
background = null;
}
}
//radar
public void loadRadar(){
radar = new Radar(player,
(mView.getHUDCamera().getWidth() - mView.getTextureRegion(RegionID.RADAR).getRegionWidth()) * 0.5f,
(mView.getHUDCamera().getHeight() - mView.getTextureRegion(RegionID.RADAR).getRegionHeight()) * 0.5f,
2000);
}
public void setRadar(Radar newRadar){
removeRadar();
radar = newRadar;
addRadar();
}
public void addRadar(){
if (radar != null)
mController.addHUDObject(radar);
}
public void removeRadar(){
if (radar != null) {
mController.removeObject(radar);
radar = null;
}
}
//planets
public void loadPlanets(){
if (currentLocation == null)
return;
if (currentLocation.star == null)
currentLocation.star = new Star(currentLocation.starType, currentLocation.x, currentLocation.y, currentLocation.starRadius);
if (currentLocation.planets == null)
currentLocation.planets = cController.getPlanetList(currentLocation);
star = currentLocation.star;
planets.putAll(currentLocation.planets);
}
public void addPlanets(){
mController.addObject(star);
for (Planet planet : planets.values()) {
mController.addObject(planet);
}
}
public void removePlanets(){
if (star != null) {
mController.removeObject(star);
star = null;
}
for (Planet planet : planets.values()) {
mController.removeObject(planet);
}
planets.clear();
}
public void addPlanet(Planet planet){
if (planets.containsKey(planet.id))
return;
planets.put(planet.id, planet);
mController.addObject(planet);
}
public void removePlanet(Planet planet){
if (!planets.containsKey(planet.id))
return;
planets.remove(planet.id);
mController.removeObject(planet);
}
public void removePlanet(int id){
Planet planet = planets.get(id);
if (planet == null)
return;
planets.remove(id);
mController.removeObject(planet);
}
//users
public void loadUsers(){
users = cController.getUsersList();
}
public void updateUsers(){
removeUsers();
users = cController.getUsersList();
addUsers();
}
public void addUsers(){
for (User user : users.values()) {
mController.addObject(user);
}
}
public void removeUsers(){
for (User user : users.values()) {
mController.removeObject(user);
}
users.clear();
}
public void addUser(User user) {
if (users.containsKey(user.id))
return;
users.put(user.id, user);
mController.addObject(user);
}
public void removeUser(User user) {
if (!users.containsKey(user.id))
return;
users.remove(user.id);
mController.removeObject(user);
}
public void removeUser(int id) {
User user = users.get(id);
if (user == null)
return;
users.remove(id);
mController.removeObject(user);
}
//get objects
public Player getPlayer(){
return player;
}
public Radar getRadar(){
return radar;
}
public Star getStar(){
return star;
}
//get locations
public Collection<Location> getLocations(){
return locations.values();
}
public Location getLocation(int id){
return locations.get(id);
}
private Vector2 distanceVec = new Vector2();
private float distanceBuffer = 0.0f;
public Location getCurrentLocation(){
return currentLocation;
}
public Location getNearLocation(){
Location nearLocation = null;
float distance = Float.MAX_VALUE;
for (Location location : locations.values()) {
distanceVec.set(location.x - player.position.x, location.y - player.position.y);
distanceBuffer = distanceVec.len();
if (distance > distanceBuffer) {
distance = distanceBuffer;
nearLocation = location;
}
}
return nearLocation;
}
public Location getLocation(int x, int y){
for (Location loc : locations.values()) {
if (loc.x == x && loc.y == y)
return loc;
}
return null;
}
//get planets
public Collection<Planet> getPlanets(){
return planets.values();
}
public Collection<Planet> getPlanets(int idLocation){
Location location = locations.get(idLocation);
if (location == null)
return null;
if (location.planets == null)
location.planets = cController.getPlanetList(location);
return location.planets.values();
}
public Planet getPlanet(int id){
return planets.get(id);
}
public Planet getPlanet(String name){
for (Planet planet : planets.values()) {
if (planet.name.compareTo(name) == 0)
return planet;
}
return null;
}
//get users
public Collection<User> getUsers(){
return users.values();
}
public User getUser(int id){
return users.get(id);
}
public User getPilot(String name){
for (User user : users.values()) {
if (user.pilotName.compareTo(name) == 0)
return user;
}
return null;
}
public User getShip(String name){
for (User user : users.values()) {
if (user.shipName.compareTo(name) == 0)
return user;
}
return null;
}
private float updateTime = 0.0f;
public void update(float deltaTime){
updateTime += deltaTime;
if (updateTime > 1.0f){
Location newLocation = getNearLocation();
if (newLocation.id != currentLocation.id){
removePlanets();
currentLocation = newLocation;
loadPlanets();
addPlanets();
}
updateTime -= 1.0f;
}
}
}
| true | true | public void loadTextures(){
for (int i = 0; i < 18; i++)
mView.loadTexture("data/location/planets.png", RegionID.fromInt(RegionID.PLANET_0.ordinal() + i), i % 5 * 204, i / 5 * 204, 204, 204);
for (int i = 0; i < 8; i++)
mView.loadTexture("data/backgrounds/nebulas(512x512).png", RegionID.fromInt(RegionID.NEBULA_0.ordinal() + i), i % 4 * 512, i / 4 * 512, 512, 512);
mView.loadTexture("data/location/star.png", RegionID.STAR);
mView.loadTexture("data/location/radar.png", RegionID.RADAR);
mView.loadTexture("data/location/sensor.png", RegionID.RADAR_SENSOR);
mView.loadTexture("data/location/radarObject.png", RegionID.RADAR_OBJECT);
mView.loadTexture("data/location/SpaceShip.png", RegionID.SHIP);
mView.loadTexture("data/backgrounds/space.png", RegionID.BACKGROUND_SPACE);
mView.loadTexture("data/backgrounds/stars.png", RegionID.BACKGROUND_STARS);
}
| public void loadTextures(){
for (int i = 0; i < 18; i++)
mView.loadTexture("data/location/planets.png", RegionID.fromInt(RegionID.PLANET_0.ordinal() + i), i % 5 * 204, i / 5 * 204, 204, 204);
for (int i = 0; i < 8; i++)
mView.loadTexture("data/backgrounds/nebulas.png", RegionID.fromInt(RegionID.NEBULA_0.ordinal() + i), i % 4 * 512, i / 4 * 512, 512, 512);
mView.loadTexture("data/location/star.png", RegionID.STAR);
mView.loadTexture("data/location/radar.png", RegionID.RADAR);
mView.loadTexture("data/location/sensor.png", RegionID.RADAR_SENSOR);
mView.loadTexture("data/location/radarObject.png", RegionID.RADAR_OBJECT);
mView.loadTexture("data/location/SpaceShip.png", RegionID.SHIP);
mView.loadTexture("data/backgrounds/space.png", RegionID.BACKGROUND_SPACE);
mView.loadTexture("data/backgrounds/stars.png", RegionID.BACKGROUND_STARS);
}
|
diff --git a/taskflows/staging/server/src/de/zib/gndms/taskflows/staging/server/logic/ExternalProviderStageInAction.java b/taskflows/staging/server/src/de/zib/gndms/taskflows/staging/server/logic/ExternalProviderStageInAction.java
index 2d8e1590..a1569380 100644
--- a/taskflows/staging/server/src/de/zib/gndms/taskflows/staging/server/logic/ExternalProviderStageInAction.java
+++ b/taskflows/staging/server/src/de/zib/gndms/taskflows/staging/server/logic/ExternalProviderStageInAction.java
@@ -1,135 +1,138 @@
package de.zib.gndms.taskflows.staging.server.logic;
/*
* Copyright 2008-2011 Zuse Institute Berlin (ZIB)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import de.zib.gndms.kit.config.MapConfig;
import de.zib.gndms.logic.action.ProcessBuilderAction;
import de.zib.gndms.model.dspace.Slice;
import de.zib.gndms.neomodel.common.Dao;
import de.zib.gndms.neomodel.gorfx.Taskling;
import de.zib.gndms.stuff.Sleeper;
import de.zib.gndms.taskflows.staging.client.ProviderStageInMeta;
import de.zib.gndms.taskflows.staging.client.model.ProviderStageInOrder;
import org.jetbrains.annotations.NotNull;
import javax.persistence.EntityManager;
import java.io.File;
import static de.zib.gndms.taskflows.staging.server.logic.ExternalProviderStageInQuoteCalculator.GLOBUS_DEATH_DURATION;
/**
* ThingAMagic.
*
* @author try ste fan pla nti kow zib
* @version $Id$
*
* User: stepn Date: 27.10.2008 Time: 13:13:09
*/
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public class ExternalProviderStageInAction extends AbstractProviderStageInAction {
private static final int INITIAL_STRING_BUILDER_CAPACITY = 4096;
public ExternalProviderStageInAction() {
super( ProviderStageInMeta.PROVIDER_STAGING_KEY );
stagingIOHelper = new StagingIOFormatHelper();
}
public ExternalProviderStageInAction(@NotNull EntityManager em, @NotNull Dao dao, @NotNull Taskling model) {
super( ProviderStageInMeta.PROVIDER_STAGING_KEY, em, dao, model);
stagingIOHelper = new StagingIOFormatHelper();
}
@SuppressWarnings({ "HardcodedLineSeparator", "MagicNumber" })
@Override
protected void doStaging(
final MapConfig offerTypeConfigParam, final ProviderStageInOrder orderParam,
final Slice sliceParam) {
stagingIOHelper.formatFromMap( getOfferTypeConfig() );
prepareProxy( sliceParam );
final File sliceDir = new File(sliceParam.getSubspace().getPathForSlice(sliceParam));
final ProcessBuilder procBuilder = createProcessBuilder("stagingCommand", sliceDir);
if (procBuilder == null) {
fail(new IllegalStateException("No stagingCommand configured"));
return;
}
procBuilder.environment().put( "X509_USER_PROXY", sliceDir + PROXY_FILE_NAME );
final StringBuilder outRecv = new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY);
final StringBuilder errRecv = new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY);
final ProcessBuilderAction action = stagingIOHelper.createPBAction( orderParam, null, actualPermissions() );
action.setProcessBuilder(procBuilder);
action.setOutputReceiver(outRecv);
action.setErrorReceiver(errRecv);
int result = action.call();
removeProxy( sliceDir + PROXY_FILE_NAME );
switch (result) {
case 0:
getLogger().debug("Staging completed: " + outRecv.toString());
// this is now done in super.inProgress
// transitWithPayload(new ProviderStageInResult(sliceParam.getId()),
// TaskState.FINISHED);
break;
default:
if (result > 127) {
getLogger().debug( "Waiting for potential death of container..." );
Sleeper.sleepUninterruptible(GLOBUS_DEATH_DURATION);
}
- String log = "Staging failed! Staging script returned unexpected exit code: " + result +
+ String log = "Staging failed!" +
+ "\nStaging script returned unexpected exit code: " + result +
+ "\nWorked on slice: " + sliceParam.getId() +
+ "\nSlice directory: " + sliceDir +
"\nScript output was:\n" + errRecv.toString();
// trace( log, null ) ;
throw new IllegalStateException( log );
}
}
@Override
protected void callCancel(final MapConfig offerTypeConfigParam,
final ProviderStageInOrder orderParam,
final File sliceDir) {
final ProcessBuilder procBuilder = createProcessBuilder("cancelCommand", sliceDir);
if (procBuilder == null)
// MAYBE log this somewhere
return;
final StringBuilder outRecv = new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY);
final StringBuilder errRecv = new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY);
final ProcessBuilderAction action = stagingIOHelper.createPBAction( orderParam, null, actualPermissions() );
action.setProcessBuilder(procBuilder);
action.setOutputReceiver(outRecv);
action.setErrorReceiver(errRecv);
int result = action.call();
switch (result) {
case 0:
getLogger().debug( "Finished calling cancel: " + outRecv.toString() );
break;
default:
getLogger().info( "Failure during cancel: " + errRecv.toString() );
}
}
}
| true | true | protected void doStaging(
final MapConfig offerTypeConfigParam, final ProviderStageInOrder orderParam,
final Slice sliceParam) {
stagingIOHelper.formatFromMap( getOfferTypeConfig() );
prepareProxy( sliceParam );
final File sliceDir = new File(sliceParam.getSubspace().getPathForSlice(sliceParam));
final ProcessBuilder procBuilder = createProcessBuilder("stagingCommand", sliceDir);
if (procBuilder == null) {
fail(new IllegalStateException("No stagingCommand configured"));
return;
}
procBuilder.environment().put( "X509_USER_PROXY", sliceDir + PROXY_FILE_NAME );
final StringBuilder outRecv = new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY);
final StringBuilder errRecv = new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY);
final ProcessBuilderAction action = stagingIOHelper.createPBAction( orderParam, null, actualPermissions() );
action.setProcessBuilder(procBuilder);
action.setOutputReceiver(outRecv);
action.setErrorReceiver(errRecv);
int result = action.call();
removeProxy( sliceDir + PROXY_FILE_NAME );
switch (result) {
case 0:
getLogger().debug("Staging completed: " + outRecv.toString());
// this is now done in super.inProgress
// transitWithPayload(new ProviderStageInResult(sliceParam.getId()),
// TaskState.FINISHED);
break;
default:
if (result > 127) {
getLogger().debug( "Waiting for potential death of container..." );
Sleeper.sleepUninterruptible(GLOBUS_DEATH_DURATION);
}
String log = "Staging failed! Staging script returned unexpected exit code: " + result +
"\nScript output was:\n" + errRecv.toString();
// trace( log, null ) ;
throw new IllegalStateException( log );
}
}
| protected void doStaging(
final MapConfig offerTypeConfigParam, final ProviderStageInOrder orderParam,
final Slice sliceParam) {
stagingIOHelper.formatFromMap( getOfferTypeConfig() );
prepareProxy( sliceParam );
final File sliceDir = new File(sliceParam.getSubspace().getPathForSlice(sliceParam));
final ProcessBuilder procBuilder = createProcessBuilder("stagingCommand", sliceDir);
if (procBuilder == null) {
fail(new IllegalStateException("No stagingCommand configured"));
return;
}
procBuilder.environment().put( "X509_USER_PROXY", sliceDir + PROXY_FILE_NAME );
final StringBuilder outRecv = new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY);
final StringBuilder errRecv = new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY);
final ProcessBuilderAction action = stagingIOHelper.createPBAction( orderParam, null, actualPermissions() );
action.setProcessBuilder(procBuilder);
action.setOutputReceiver(outRecv);
action.setErrorReceiver(errRecv);
int result = action.call();
removeProxy( sliceDir + PROXY_FILE_NAME );
switch (result) {
case 0:
getLogger().debug("Staging completed: " + outRecv.toString());
// this is now done in super.inProgress
// transitWithPayload(new ProviderStageInResult(sliceParam.getId()),
// TaskState.FINISHED);
break;
default:
if (result > 127) {
getLogger().debug( "Waiting for potential death of container..." );
Sleeper.sleepUninterruptible(GLOBUS_DEATH_DURATION);
}
String log = "Staging failed!" +
"\nStaging script returned unexpected exit code: " + result +
"\nWorked on slice: " + sliceParam.getId() +
"\nSlice directory: " + sliceDir +
"\nScript output was:\n" + errRecv.toString();
// trace( log, null ) ;
throw new IllegalStateException( log );
}
}
|
diff --git a/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java b/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java
index 34a7b92..a0a9542 100644
--- a/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java
+++ b/osmdroid-android/src/main/java/org/osmdroid/views/overlay/SafeDrawOverlay.java
@@ -1,91 +1,98 @@
package org.osmdroid.views.overlay;
import org.osmdroid.ResourceProxy;
import org.osmdroid.views.MapView;
import org.osmdroid.views.safecanvas.ISafeCanvas;
import org.osmdroid.views.safecanvas.SafeTranslatedCanvas;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Build;
/**
* An overlay class that uses the safe drawing canvas to draw itself and can be zoomed in to high
* levels without drawing issues.
*
* @see {@link ISafeCanvas}
*/
public abstract class SafeDrawOverlay extends Overlay {
private static final SafeTranslatedCanvas sSafeCanvas = new SafeTranslatedCanvas();
private static final Matrix sMatrix = new Matrix();
private static final float[] sMatrixValues = new float[9];
private boolean mUseSafeCanvas = true;
protected abstract void drawSafe(final ISafeCanvas c, final MapView osmv, final boolean shadow);
public SafeDrawOverlay(Context ctx) {
super(ctx);
}
public SafeDrawOverlay(ResourceProxy pResourceProxy) {
super(pResourceProxy);
}
protected void draw(final Canvas c, final MapView osmv, final boolean shadow) {
sSafeCanvas.setCanvas(c);
if (this.isUsingSafeCanvas()) {
// Find the screen offset
Rect screenRect = osmv.getProjection().getScreenRect();
sSafeCanvas.xOffset = -screenRect.left;
sSafeCanvas.yOffset = -screenRect.top;
// Save the canvas state
c.save();
// Get the matrix values
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
sMatrix.set(osmv.getMatrix());
} else {
c.getMatrix(sMatrix);
}
sMatrix.getValues(sMatrixValues);
// If we're rotating, then reverse the rotation
// This gets us proper MSCALE values in the matrix.
final double angrad = Math.atan2(sMatrixValues[Matrix.MSKEW_Y],
sMatrixValues[Matrix.MSCALE_X]);
sMatrix.preRotate((float) -Math.toDegrees(angrad), screenRect.centerX(),
screenRect.centerY());
// Get the new matrix values to find the scaling factor
sMatrix.getValues(sMatrixValues);
// Shift the canvas to remove scroll, while accounting for scaling values
- c.translate(screenRect.left * sMatrixValues[Matrix.MSCALE_X], screenRect.top
- * sMatrixValues[Matrix.MSCALE_Y]);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
+ c.translate(screenRect.left * sMatrixValues[Matrix.MSCALE_X], screenRect.top
+ * sMatrixValues[Matrix.MSCALE_Y]);
+ } else {
+ c.getMatrix(sMatrix);
+ sMatrix.postTranslate(screenRect.left * sMatrixValues[Matrix.MSCALE_X],
+ screenRect.top * sMatrixValues[Matrix.MSCALE_Y]);
+ c.setMatrix(sMatrix);
+ }
} else {
sSafeCanvas.xOffset = 0;
sSafeCanvas.yOffset = 0;
}
this.drawSafe(sSafeCanvas, osmv, shadow);
if (this.isUsingSafeCanvas()) {
c.restore();
}
}
public boolean isUsingSafeCanvas() {
return mUseSafeCanvas;
}
public void setUseSafeCanvas(boolean useSafeCanvas) {
mUseSafeCanvas = useSafeCanvas;
}
}
| true | true | protected void draw(final Canvas c, final MapView osmv, final boolean shadow) {
sSafeCanvas.setCanvas(c);
if (this.isUsingSafeCanvas()) {
// Find the screen offset
Rect screenRect = osmv.getProjection().getScreenRect();
sSafeCanvas.xOffset = -screenRect.left;
sSafeCanvas.yOffset = -screenRect.top;
// Save the canvas state
c.save();
// Get the matrix values
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
sMatrix.set(osmv.getMatrix());
} else {
c.getMatrix(sMatrix);
}
sMatrix.getValues(sMatrixValues);
// If we're rotating, then reverse the rotation
// This gets us proper MSCALE values in the matrix.
final double angrad = Math.atan2(sMatrixValues[Matrix.MSKEW_Y],
sMatrixValues[Matrix.MSCALE_X]);
sMatrix.preRotate((float) -Math.toDegrees(angrad), screenRect.centerX(),
screenRect.centerY());
// Get the new matrix values to find the scaling factor
sMatrix.getValues(sMatrixValues);
// Shift the canvas to remove scroll, while accounting for scaling values
c.translate(screenRect.left * sMatrixValues[Matrix.MSCALE_X], screenRect.top
* sMatrixValues[Matrix.MSCALE_Y]);
} else {
sSafeCanvas.xOffset = 0;
sSafeCanvas.yOffset = 0;
}
this.drawSafe(sSafeCanvas, osmv, shadow);
if (this.isUsingSafeCanvas()) {
c.restore();
}
}
| protected void draw(final Canvas c, final MapView osmv, final boolean shadow) {
sSafeCanvas.setCanvas(c);
if (this.isUsingSafeCanvas()) {
// Find the screen offset
Rect screenRect = osmv.getProjection().getScreenRect();
sSafeCanvas.xOffset = -screenRect.left;
sSafeCanvas.yOffset = -screenRect.top;
// Save the canvas state
c.save();
// Get the matrix values
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
sMatrix.set(osmv.getMatrix());
} else {
c.getMatrix(sMatrix);
}
sMatrix.getValues(sMatrixValues);
// If we're rotating, then reverse the rotation
// This gets us proper MSCALE values in the matrix.
final double angrad = Math.atan2(sMatrixValues[Matrix.MSKEW_Y],
sMatrixValues[Matrix.MSCALE_X]);
sMatrix.preRotate((float) -Math.toDegrees(angrad), screenRect.centerX(),
screenRect.centerY());
// Get the new matrix values to find the scaling factor
sMatrix.getValues(sMatrixValues);
// Shift the canvas to remove scroll, while accounting for scaling values
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c.translate(screenRect.left * sMatrixValues[Matrix.MSCALE_X], screenRect.top
* sMatrixValues[Matrix.MSCALE_Y]);
} else {
c.getMatrix(sMatrix);
sMatrix.postTranslate(screenRect.left * sMatrixValues[Matrix.MSCALE_X],
screenRect.top * sMatrixValues[Matrix.MSCALE_Y]);
c.setMatrix(sMatrix);
}
} else {
sSafeCanvas.xOffset = 0;
sSafeCanvas.yOffset = 0;
}
this.drawSafe(sSafeCanvas, osmv, shadow);
if (this.isUsingSafeCanvas()) {
c.restore();
}
}
|
diff --git a/grails-datastore-simpledb/src/main/groovy/org/grails/datastore/mapping/simpledb/query/SimpleDBQuery.java b/grails-datastore-simpledb/src/main/groovy/org/grails/datastore/mapping/simpledb/query/SimpleDBQuery.java
index d6562974..c896e7e5 100644
--- a/grails-datastore-simpledb/src/main/groovy/org/grails/datastore/mapping/simpledb/query/SimpleDBQuery.java
+++ b/grails-datastore-simpledb/src/main/groovy/org/grails/datastore/mapping/simpledb/query/SimpleDBQuery.java
@@ -1,389 +1,393 @@
/* Copyright (C) 2011 SpringSource
*
* 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.grails.datastore.mapping.simpledb.query;
import java.util.*;
import org.grails.datastore.mapping.core.Session;
import org.grails.datastore.mapping.keyvalue.mapping.config.KeyValue;
import org.grails.datastore.mapping.model.PersistentEntity;
import org.grails.datastore.mapping.model.PersistentProperty;
import org.grails.datastore.mapping.model.types.Association;
import org.grails.datastore.mapping.model.types.ToOne;
import org.grails.datastore.mapping.query.Query;
import org.grails.datastore.mapping.simpledb.engine.SimpleDBNativeItem;
import org.grails.datastore.mapping.simpledb.engine.SimpleDBDomainResolver;
import org.grails.datastore.mapping.simpledb.engine.SimpleDBEntityPersister;
import org.grails.datastore.mapping.simpledb.util.SimpleDBConverterUtil;
import org.grails.datastore.mapping.simpledb.util.SimpleDBTemplate;
import com.amazonaws.services.simpledb.model.Item;
import org.grails.datastore.mapping.simpledb.util.SimpleDBUtil;
/**
* A {@link org.grails.datastore.mapping.query.Query} implementation for the SimpleDB store
*
* @author Roman Stepanenko
* @since 0.1
*/
@SuppressWarnings("rawtypes")
public class SimpleDBQuery extends Query {
protected SimpleDBDomainResolver domainResolver;
protected SimpleDBTemplate simpleDBTemplate;
protected SimpleDBEntityPersister simpleDBEntityPersister;
protected static Map<Class, QueryHandler> queryHandlers = new HashMap<Class, QueryHandler>();
protected static final String ITEM_NAME = "itemName()";
static{
queryHandlers.put(Equals.class, new QueryHandler<Equals>() {
public void handle(PersistentEntity entity, Equals criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
String stringValue = SimpleDBConverterUtil.convertToString(criterion.getValue(), entity.getMappingContext());
addSimpleComparison(clause, key, "=", stringValue);
}
});
queryHandlers.put(NotEquals.class, new QueryHandler<NotEquals>() {
public void handle(PersistentEntity entity, NotEquals criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
String stringValue = SimpleDBConverterUtil.convertToString(criterion.getValue(), entity.getMappingContext());
addSimpleComparison(clause, key, "!=", stringValue);
}
});
queryHandlers.put(IdEquals.class, new QueryHandler<IdEquals>() {
public void handle(PersistentEntity entity, IdEquals criterion, StringBuilder clause) {
String stringValue = SimpleDBConverterUtil.convertToString(criterion.getValue(), entity.getMappingContext());
addSimpleComparison(clause, ITEM_NAME, "=", stringValue);
}
});
queryHandlers.put(Like.class, new QueryHandler<Like>() {
public void handle(PersistentEntity entity, Like criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
String stringValue = SimpleDBConverterUtil.convertToString(criterion.getValue(), entity.getMappingContext());
addSimpleComparison(clause, key, "LIKE", stringValue);
}
});
queryHandlers.put(In.class, new QueryHandler<In>() {
public void handle(PersistentEntity entity, In criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
Collection<String> stringValues = SimpleDBConverterUtil.convertToStrings(criterion.getValues(), entity.getMappingContext());
clause.append(key).append(" IN (");
clause.append(SimpleDBUtil.quoteValues(stringValues)).append(")");
}
});
queryHandlers.put(Between.class, new QueryHandler<Between>() {
public void handle(PersistentEntity entity, Between criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
String fromStringValue = SimpleDBConverterUtil.convertToString(criterion.getFrom(), entity.getMappingContext());
String toStringValue = SimpleDBConverterUtil.convertToString(criterion.getTo(), entity.getMappingContext());
clause.append(key).append(" >= ").append(SimpleDBUtil.quoteValue(fromStringValue)).append(" AND ");
clause.append(key).append(" <= ").append(SimpleDBUtil.quoteValue(toStringValue));
}
});
queryHandlers.put(GreaterThan.class, new QueryHandler<GreaterThan>() {
public void handle(PersistentEntity entity, GreaterThan criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
String stringValue = SimpleDBConverterUtil.convertToString(criterion.getValue(), entity.getMappingContext());
addSimpleComparison(clause, key, ">", stringValue);
}
});
queryHandlers.put(GreaterThanEquals.class, new QueryHandler<GreaterThanEquals>() {
public void handle(PersistentEntity entity, GreaterThanEquals criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
String stringValue = SimpleDBConverterUtil.convertToString(criterion.getValue(), entity.getMappingContext());
addSimpleComparison(clause, key, ">=", stringValue);
}
});
queryHandlers.put(LessThan.class, new QueryHandler<LessThan>() {
public void handle(PersistentEntity entity, LessThan criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
String stringValue = SimpleDBConverterUtil.convertToString(criterion.getValue(), entity.getMappingContext());
addSimpleComparison(clause, key, "<", stringValue);
}
});
queryHandlers.put(LessThanEquals.class, new QueryHandler<LessThanEquals>() {
public void handle(PersistentEntity entity, LessThanEquals criterion, StringBuilder clause) {
String propertyName = criterion.getProperty();
String key = getSmartQuotedKey(entity, propertyName);
String stringValue = SimpleDBConverterUtil.convertToString(criterion.getValue(), entity.getMappingContext());
addSimpleComparison(clause, key, "<=", stringValue);
}
});
}
public SimpleDBQuery(Session session, PersistentEntity entity, SimpleDBDomainResolver domainResolver,
SimpleDBEntityPersister simpleDBEntityPersister, SimpleDBTemplate simpleDBTemplate) {
super(session, entity);
this.domainResolver = domainResolver;
this.simpleDBEntityPersister = simpleDBEntityPersister;
this.simpleDBTemplate = simpleDBTemplate;
}
@Override
protected List executeQuery(@SuppressWarnings("hiding") PersistentEntity entity, @SuppressWarnings("hiding") Junction criteria) {
// TODO - in case of sharding we should iterate over all domains for this PersistentEntity (ideally in parallel)
String domain = domainResolver.getAllDomainsForEntity().get(0);
final List<Projection> projectionList = projections().getProjectionList();
boolean hasCountProjection = false;
StringBuilder query;
if (projectionList.isEmpty()) {
query = new StringBuilder("select * from `").append(domain).append("`");
} else {
hasCountProjection = validateProjectionsAndCheckIfCountIsPresent(projectionList);
query = buildQueryForProjections(entity, domain, projectionList);
}
if (!criteria.getCriteria().isEmpty()) {
query.append(" where "); //things like TestEntity.list() result in empty criteria collection, so we should not have a 'where' clause at all
}
String clause = "";
Set<String> usedPropertyNames = new HashSet<String>();
if (criteria instanceof Conjunction) {
clause = buildCompositeClause(criteria, "AND", usedPropertyNames);
} else if (criteria instanceof Disjunction) {
clause = buildCompositeClause(criteria, "OR", usedPropertyNames);
} else {
throw new RuntimeException("not implemented: " + criteria.getClass().getName());
}
query.append(clause);
List<Order> orderBys = getOrderBy();
if (!orderBys.isEmpty()) {
if (orderBys.size() > 1) {
throw new UnsupportedOperationException("Only single 'order by' clause is supported. You have: " + orderBys.size());
}
@SuppressWarnings("hiding") Order orderBy = orderBys.get(0);
String orderByPropertyName = orderBy.getProperty();
String key = extractPropertyKey(orderByPropertyName, entity);
//AWS SimpleDB rule: if you use ORDER BY then you have to have a condition on that attribute in the where clause, otherwise it will throw an error
//so we check if that property was used in the clause and if not we add 'is not null' condition
if (!usedPropertyNames.contains(orderByPropertyName)) {
if (criteria.getCriteria().isEmpty()) { //we might have a case 'select * from X order by ABC' which must be fixed into 'select * from X where ABC IS NOT NULL order by ABC'
query.append(" where ");
} else {
query.append(" AND ");
}
query.append(SimpleDBUtil.quoteName(key)).append(" IS NOT NULL");
}
query.append(" ORDER BY ").append(SimpleDBUtil.quoteName(key)).append(" ").append(orderBy.getDirection());
}
//specify the limit on the returned results
int limit = max < 0 ? 2500 : max; //if user did not explicitly limit maxResults, use the maximum limit allowed dy AWS (if not specified explicitly it will use 100 limit)
query.append(" LIMIT ").append(limit);
List<Item> items = simpleDBTemplate.query(query.toString());
List<Object> results = new LinkedList<Object>();
if (projectionList.isEmpty()) {
for (Item item : items) {
results.add(createObjectFromItem(item));
}
} else {
if (hasCountProjection) { //count (*) is returned by AWS in a special way...
int count = Integer.parseInt(items.get(0).getAttributes().get(0).getValue());
results.add(count);
} else {
for (Projection projection : projectionList) {
if (IdProjection.class.equals(projection.getClass())) {
for (Item item : items) {
results.add(item.getName());
}
+ } else if (PropertyProjection.class.equals(projection.getClass())) {
+ for (Item item : items) {
+ String key = extractPropertyKey(((PropertyProjection) projection).getPropertyName(), entity);
+ results.addAll(SimpleDBUtil.collectAttributeValues(item, key));
+ }
}
- //todo for property projection
}
}
}
return results;
}
private StringBuilder buildQueryForProjections(PersistentEntity entity, String domain, List<Projection> projectionList) {
StringBuilder query = new StringBuilder("select ");
boolean isFirst = true;
for (Projection projection : projectionList) {
if (projectionList.size() > 1 && !isFirst) {
query.append(", ");
}
if (isFirst) {
isFirst = false;
}
if (CountProjection.class.equals(projection.getClass())) {
query.append("count(*)");
} else if (IdProjection.class.equals(projection.getClass())) {
query.append("itemName()");
} else if (PropertyProjection.class.equals(projection.getClass())) {
String key = getSmartQuotedKey(entity, ((PropertyProjection)projection).getPropertyName());
query.append(key);
}
}
query.append(" from `").append(domain).append("`");
return query;
}
/**
* make sure that only property, id, or count projections are provided, and that the combination of them is meaningful.
* Throws exception if something is invalid.
* @param projections
* @returns true if count projection is present, false otherwise.
*/
private boolean validateProjectionsAndCheckIfCountIsPresent(List<Projection> projections) {
//of the grouping projects AWS SimpleDB only supports count(*) projection, nothing else. Other kinds will have
//to be explicitly coded later...
boolean hasCountProjection = false;
for (Projection projection : projections) {
if (! (PropertyProjection.class.equals(projection.getClass()) ||
IdProjection.class.equals(projection.getClass()) ||
CountProjection.class.equals(projection.getClass())
) ) {
throw new UnsupportedOperationException("Currently projections of type " +
projection.getClass().getSimpleName() + " are not supported by this implementation");
}
if (CountProjection.class.equals(projection.getClass())) {
hasCountProjection = true;
}
}
if ( projections.size() > 1 && hasCountProjection ) {
throw new IllegalArgumentException("Can not mix count projection and other types of projections. You requested: "+projections);
}
return hasCountProjection;
}
@SuppressWarnings("unchecked")
private String buildCompositeClause(@SuppressWarnings("hiding") Junction criteria,
String booleanOperator, Set<String> usedPropertyNames) {
StringBuilder clause = new StringBuilder();
boolean first = true;
for (Criterion criterion : criteria.getCriteria()) {
if (first) {
//do nothing first time
first = false;
} else {
clause.append(" ").append(booleanOperator).append(" "); //prepend with operator
}
if (criterion instanceof PropertyCriterion) {
PropertyCriterion propertyCriterion = (PropertyCriterion) criterion;
String propertyName = propertyCriterion.getProperty();
usedPropertyNames.add(propertyName); //register the fact that the property did have some condition - it is needed if we use order by clause
QueryHandler queryHandler = queryHandlers.get(criterion.getClass());
if (queryHandler != null) {
queryHandler.handle(entity, criterion, clause);
} else {
throw new UnsupportedOperationException("Queries of type " +
criterion.getClass().getSimpleName() + " are not supported by this implementation");
}
} else if (criterion instanceof Conjunction) {
String innerClause = buildCompositeClause((Conjunction) criterion, "AND", usedPropertyNames);
addToMainClause(criteria, clause, innerClause);
} else if (criterion instanceof Disjunction) {
String innerClause = buildCompositeClause((Disjunction) criterion, "OR", usedPropertyNames);
addToMainClause(criteria, clause, innerClause);
} else if (criterion instanceof Negation) {
String innerClause = buildCompositeClause((Negation) criterion, "OR", usedPropertyNames); //when we negate we use OR by default
clause.append("NOT (").append(innerClause).append(")");
} else {
throw new UnsupportedOperationException("Queries of type " +
criterion.getClass().getSimpleName() + " are not supported by this implementation");
}
}
return clause.toString();
}
private void addToMainClause(@SuppressWarnings("hiding") Junction criteria, StringBuilder clause, String innerClause) {
boolean useParenthesis = criteria.getCriteria().size() > 1; //use parenthesis only when needed
if (useParenthesis) {
clause.append("(");
}
clause.append(innerClause);
if (useParenthesis) {
clause.append(")");
}
}
protected Object createObjectFromItem(Item item) {
final String id = item.getName();
return simpleDBEntityPersister.createObjectFromNativeEntry(getEntity(), id,
new SimpleDBNativeItem(item));
}
protected static interface QueryHandler<T> {
public void handle(PersistentEntity entity, T criterion, StringBuilder clause);
}
protected static String extractPropertyKey(String propertyName, PersistentEntity entity) {
PersistentProperty prop = entity.getPropertyByName(propertyName);
if (prop == null) {
throw new IllegalArgumentException(
"Could not find property '" + propertyName + "' in entity '" + entity.getName() + "'");
}
KeyValue kv = (KeyValue) prop.getMapping().getMappedForm();
String key = kv.getKey();
return key;
}
/**
* Assumes that the key is already quoted or is itemName()
* @param clause
* @param key
* @param comparison
* @param stringValue
*/
protected static void addSimpleComparison(StringBuilder clause, String key, String comparison, String stringValue) {
clause.append(key).append(" ").append(comparison).append(" ").append(SimpleDBUtil.quoteValue(stringValue));
}
/**
* Returns quoted mapped key OR if the property is an identity returns 'itemName()' - this is how AWS SimpleDB refers to primary key field.
* @param entity
* @param propertyName
* @return
*/
protected static String getSmartQuotedKey(PersistentEntity entity, String propertyName) {
if (entity.isIdentityName(propertyName)) {
return ITEM_NAME;
}
return SimpleDBUtil.quoteName(extractPropertyKey(propertyName, entity));
}
}
| false | true | protected List executeQuery(@SuppressWarnings("hiding") PersistentEntity entity, @SuppressWarnings("hiding") Junction criteria) {
// TODO - in case of sharding we should iterate over all domains for this PersistentEntity (ideally in parallel)
String domain = domainResolver.getAllDomainsForEntity().get(0);
final List<Projection> projectionList = projections().getProjectionList();
boolean hasCountProjection = false;
StringBuilder query;
if (projectionList.isEmpty()) {
query = new StringBuilder("select * from `").append(domain).append("`");
} else {
hasCountProjection = validateProjectionsAndCheckIfCountIsPresent(projectionList);
query = buildQueryForProjections(entity, domain, projectionList);
}
if (!criteria.getCriteria().isEmpty()) {
query.append(" where "); //things like TestEntity.list() result in empty criteria collection, so we should not have a 'where' clause at all
}
String clause = "";
Set<String> usedPropertyNames = new HashSet<String>();
if (criteria instanceof Conjunction) {
clause = buildCompositeClause(criteria, "AND", usedPropertyNames);
} else if (criteria instanceof Disjunction) {
clause = buildCompositeClause(criteria, "OR", usedPropertyNames);
} else {
throw new RuntimeException("not implemented: " + criteria.getClass().getName());
}
query.append(clause);
List<Order> orderBys = getOrderBy();
if (!orderBys.isEmpty()) {
if (orderBys.size() > 1) {
throw new UnsupportedOperationException("Only single 'order by' clause is supported. You have: " + orderBys.size());
}
@SuppressWarnings("hiding") Order orderBy = orderBys.get(0);
String orderByPropertyName = orderBy.getProperty();
String key = extractPropertyKey(orderByPropertyName, entity);
//AWS SimpleDB rule: if you use ORDER BY then you have to have a condition on that attribute in the where clause, otherwise it will throw an error
//so we check if that property was used in the clause and if not we add 'is not null' condition
if (!usedPropertyNames.contains(orderByPropertyName)) {
if (criteria.getCriteria().isEmpty()) { //we might have a case 'select * from X order by ABC' which must be fixed into 'select * from X where ABC IS NOT NULL order by ABC'
query.append(" where ");
} else {
query.append(" AND ");
}
query.append(SimpleDBUtil.quoteName(key)).append(" IS NOT NULL");
}
query.append(" ORDER BY ").append(SimpleDBUtil.quoteName(key)).append(" ").append(orderBy.getDirection());
}
//specify the limit on the returned results
int limit = max < 0 ? 2500 : max; //if user did not explicitly limit maxResults, use the maximum limit allowed dy AWS (if not specified explicitly it will use 100 limit)
query.append(" LIMIT ").append(limit);
List<Item> items = simpleDBTemplate.query(query.toString());
List<Object> results = new LinkedList<Object>();
if (projectionList.isEmpty()) {
for (Item item : items) {
results.add(createObjectFromItem(item));
}
} else {
if (hasCountProjection) { //count (*) is returned by AWS in a special way...
int count = Integer.parseInt(items.get(0).getAttributes().get(0).getValue());
results.add(count);
} else {
for (Projection projection : projectionList) {
if (IdProjection.class.equals(projection.getClass())) {
for (Item item : items) {
results.add(item.getName());
}
}
//todo for property projection
}
}
}
return results;
}
| protected List executeQuery(@SuppressWarnings("hiding") PersistentEntity entity, @SuppressWarnings("hiding") Junction criteria) {
// TODO - in case of sharding we should iterate over all domains for this PersistentEntity (ideally in parallel)
String domain = domainResolver.getAllDomainsForEntity().get(0);
final List<Projection> projectionList = projections().getProjectionList();
boolean hasCountProjection = false;
StringBuilder query;
if (projectionList.isEmpty()) {
query = new StringBuilder("select * from `").append(domain).append("`");
} else {
hasCountProjection = validateProjectionsAndCheckIfCountIsPresent(projectionList);
query = buildQueryForProjections(entity, domain, projectionList);
}
if (!criteria.getCriteria().isEmpty()) {
query.append(" where "); //things like TestEntity.list() result in empty criteria collection, so we should not have a 'where' clause at all
}
String clause = "";
Set<String> usedPropertyNames = new HashSet<String>();
if (criteria instanceof Conjunction) {
clause = buildCompositeClause(criteria, "AND", usedPropertyNames);
} else if (criteria instanceof Disjunction) {
clause = buildCompositeClause(criteria, "OR", usedPropertyNames);
} else {
throw new RuntimeException("not implemented: " + criteria.getClass().getName());
}
query.append(clause);
List<Order> orderBys = getOrderBy();
if (!orderBys.isEmpty()) {
if (orderBys.size() > 1) {
throw new UnsupportedOperationException("Only single 'order by' clause is supported. You have: " + orderBys.size());
}
@SuppressWarnings("hiding") Order orderBy = orderBys.get(0);
String orderByPropertyName = orderBy.getProperty();
String key = extractPropertyKey(orderByPropertyName, entity);
//AWS SimpleDB rule: if you use ORDER BY then you have to have a condition on that attribute in the where clause, otherwise it will throw an error
//so we check if that property was used in the clause and if not we add 'is not null' condition
if (!usedPropertyNames.contains(orderByPropertyName)) {
if (criteria.getCriteria().isEmpty()) { //we might have a case 'select * from X order by ABC' which must be fixed into 'select * from X where ABC IS NOT NULL order by ABC'
query.append(" where ");
} else {
query.append(" AND ");
}
query.append(SimpleDBUtil.quoteName(key)).append(" IS NOT NULL");
}
query.append(" ORDER BY ").append(SimpleDBUtil.quoteName(key)).append(" ").append(orderBy.getDirection());
}
//specify the limit on the returned results
int limit = max < 0 ? 2500 : max; //if user did not explicitly limit maxResults, use the maximum limit allowed dy AWS (if not specified explicitly it will use 100 limit)
query.append(" LIMIT ").append(limit);
List<Item> items = simpleDBTemplate.query(query.toString());
List<Object> results = new LinkedList<Object>();
if (projectionList.isEmpty()) {
for (Item item : items) {
results.add(createObjectFromItem(item));
}
} else {
if (hasCountProjection) { //count (*) is returned by AWS in a special way...
int count = Integer.parseInt(items.get(0).getAttributes().get(0).getValue());
results.add(count);
} else {
for (Projection projection : projectionList) {
if (IdProjection.class.equals(projection.getClass())) {
for (Item item : items) {
results.add(item.getName());
}
} else if (PropertyProjection.class.equals(projection.getClass())) {
for (Item item : items) {
String key = extractPropertyKey(((PropertyProjection) projection).getPropertyName(), entity);
results.addAll(SimpleDBUtil.collectAttributeValues(item, key));
}
}
}
}
}
return results;
}
|
diff --git a/brunson/src/player/Player.java b/brunson/src/player/Player.java
index 76999ef..81709ff 100644
--- a/brunson/src/player/Player.java
+++ b/brunson/src/player/Player.java
@@ -1,32 +1,33 @@
package player;
import cards.*;
public abstract class Player {
private Pile hand;
private int chips;
public Player(int buyin){
+ this.hand = new Pile();
chips = buyin;
}
public void addCard(Card card) {
hand.add(card);
}
public Pile getHand() {
return hand;
}
public int getStackSize() {
return chips;
}
public void updateStack(int delta) {
chips += delta;
}
//Returns the player's chosen action. 0 for fold, 1 for call and 2 for raise.
public abstract int getAction();
}
| true | true | public Player(int buyin){
chips = buyin;
}
| public Player(int buyin){
this.hand = new Pile();
chips = buyin;
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/variables/VariableOptionsAction.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/variables/VariableOptionsAction.java
index af46b399f..425e2a989 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/variables/VariableOptionsAction.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/variables/VariableOptionsAction.java
@@ -1,64 +1,65 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 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 implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.variables;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import org.eclipse.core.runtime.Preferences.PropertyChangeEvent;
import org.eclipse.debug.ui.IDebugView;
import org.eclipse.jdt.internal.debug.ui.SWTFactory;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
/**
* Action which opens preference settings for Java variables.
*/
public class VariableOptionsAction implements IViewActionDelegate, IPropertyChangeListener {
private IViewPart fPart;
/* (non-Javadoc)
* @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
*/
public void init(IViewPart view) {
fPart = view;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
SWTFactory.showPreferencePage("org.eclipse.jdt.debug.ui.JavaDetailFormattersPreferencePage", //$NON-NLS-1$
new String[] {"org.eclipse.jdt.debug.ui.JavaDetailFormattersPreferencePage", //$NON-NLS-1$
"org.eclipse.jdt.debug.ui.JavaLogicalStructuresPreferencePage", //$NON-NLS-1$
"org.eclipse.jdt.debug.ui.heapWalking", //$NON-NLS-1$
- "org.eclipse.jdt.debug.ui.JavaPrimitivesPreferencePage"}); //$NON-NLS-1$
+ "org.eclipse.jdt.debug.ui.JavaPrimitivesPreferencePage", //$NON-NLS-1$
+ "org.eclipse.debug.ui.DebugPreferencePage"}); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.Preferences.IPropertyChangeListener#propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fPart instanceof IDebugView) {
IDebugView view = (IDebugView) fPart;
view.getViewer().refresh();
}
}
}
| true | true | public void run(IAction action) {
SWTFactory.showPreferencePage("org.eclipse.jdt.debug.ui.JavaDetailFormattersPreferencePage", //$NON-NLS-1$
new String[] {"org.eclipse.jdt.debug.ui.JavaDetailFormattersPreferencePage", //$NON-NLS-1$
"org.eclipse.jdt.debug.ui.JavaLogicalStructuresPreferencePage", //$NON-NLS-1$
"org.eclipse.jdt.debug.ui.heapWalking", //$NON-NLS-1$
"org.eclipse.jdt.debug.ui.JavaPrimitivesPreferencePage"}); //$NON-NLS-1$
}
| public void run(IAction action) {
SWTFactory.showPreferencePage("org.eclipse.jdt.debug.ui.JavaDetailFormattersPreferencePage", //$NON-NLS-1$
new String[] {"org.eclipse.jdt.debug.ui.JavaDetailFormattersPreferencePage", //$NON-NLS-1$
"org.eclipse.jdt.debug.ui.JavaLogicalStructuresPreferencePage", //$NON-NLS-1$
"org.eclipse.jdt.debug.ui.heapWalking", //$NON-NLS-1$
"org.eclipse.jdt.debug.ui.JavaPrimitivesPreferencePage", //$NON-NLS-1$
"org.eclipse.debug.ui.DebugPreferencePage"}); //$NON-NLS-1$
}
|
diff --git a/mmstudio/src/org/micromanager/PresetEditor.java b/mmstudio/src/org/micromanager/PresetEditor.java
index 8690f16d1..a183ab15a 100644
--- a/mmstudio/src/org/micromanager/PresetEditor.java
+++ b/mmstudio/src/org/micromanager/PresetEditor.java
@@ -1,132 +1,132 @@
///////////////////////////////////////////////////////////////////////////////
//FILE: PresetEditor.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
//-----------------------------------------------------------------------------
//
// AUTHOR: Arthur Edelstein, June 2009
//
// COPYRIGHT: University of California, San Francisco, 2009
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager;
import org.micromanager.utils.PropertyItem;
import org.micromanager.utils.PropertyTableData;
import mmcorej.CMMCore;
import mmcorej.Configuration;
import mmcorej.StrVector;
import org.micromanager.utils.ReportingUtils;
public class PresetEditor extends ConfigDialog {
/**
*
*/
private static final long serialVersionUID = 8281144157746745260L;
public PresetEditor(String groupName, String presetName, MMStudioMainFrame gui, CMMCore core, boolean newItem) {
super(groupName, presetName, gui, core, newItem);
instructionsText_ = "Here you can specifiy the property values\nin a configuration preset.";
nameFieldLabelText_ = "Preset name:";
initName_ = presetName_;
TITLE = "Preset editor for the \"" + groupName + "\" configuration group";
showUnused_ = false;
showFlagsPanelVisible = false;
scrollPaneTop_ = 70;
numColumns=2;
data_ = new PropertyTableData(core_,groupName_,presetName_,1,2, this);
initializeData();
data_.setColumnNames("Property Name","Preset Value","");
data_.setShowReadOnly(true);
initialize();
}
public void okChosen() {
String newName = nameField_.getText();
if (writePreset(initName_,newName)) {
this.dispose();
}
}
public boolean writePreset(String initName, String newName) {
// Check to make sure a group name has been specified.
if (newName.length()==0) {
showMessageDialog("Please enter a name for this preset.");
return false;
}
// Avoid clashing names
StrVector groups = core_.getAvailableConfigs(groupName_);
for (int i=0;i<groups.size();i++)
if (groups.get(i).contentEquals(newName) && !newName.contentEquals(initName)) {
showMessageDialog("A preset by this name already exists in the \"" + groupName_ + "\" group.\nPlease enter a different name.");
return false;
}
StrVector cfgs = core_.getAvailableConfigs(groupName_);
try {
// Check if duplicate presets would be created
Configuration otherPreset;
boolean same;
for (int j=0;j<cfgs.size();j++) {
same = true;
if (newItem_ || ! cfgs.get(j).contentEquals(initName)) {
otherPreset = core_.getConfigData(groupName_, cfgs.get(j));
for (PropertyItem item:data_.getPropList()) {
if (item.confInclude)
if (otherPreset.isPropertyIncluded(item.device, item.name))
if (! item.getValueInCoreFormat().contentEquals(otherPreset.getSetting(item.device, item.name).getPropertyValue()) )
same = false;
}
if (same) {
- showMessageDialog("This combination of properties is already in found in the \"" + cfgs.get(j) + "\" preset.\nPlease choose unique property values for your new preset.");
+ showMessageDialog("This combination of properties is already found in the \"" + cfgs.get(j) + "\" preset.\nPlease choose unique property values for your new preset.");
return false;
}
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// Rename the preset if its name has changed
if (! newItem_ && !initName.contentEquals(newName))
try {
core_.renameConfig(groupName_, initName, newName);
} catch (Exception e1) {
// TODO Auto-generated catch block
ReportingUtils.logError(e1);
}
// Define the preset.
for (PropertyItem item_:data_.getPropList()) {
if (item_.confInclude) {
try {
core_.defineConfig(groupName_, newName, item_.device, item_.name, item_.getValueInCoreFormat());
} catch (Exception e) {
// TODO Auto-generated catch block
ReportingUtils.logError(e);
}
}
}
gui_.setConfigChanged(true);
return true;
}
}
| true | true | public boolean writePreset(String initName, String newName) {
// Check to make sure a group name has been specified.
if (newName.length()==0) {
showMessageDialog("Please enter a name for this preset.");
return false;
}
// Avoid clashing names
StrVector groups = core_.getAvailableConfigs(groupName_);
for (int i=0;i<groups.size();i++)
if (groups.get(i).contentEquals(newName) && !newName.contentEquals(initName)) {
showMessageDialog("A preset by this name already exists in the \"" + groupName_ + "\" group.\nPlease enter a different name.");
return false;
}
StrVector cfgs = core_.getAvailableConfigs(groupName_);
try {
// Check if duplicate presets would be created
Configuration otherPreset;
boolean same;
for (int j=0;j<cfgs.size();j++) {
same = true;
if (newItem_ || ! cfgs.get(j).contentEquals(initName)) {
otherPreset = core_.getConfigData(groupName_, cfgs.get(j));
for (PropertyItem item:data_.getPropList()) {
if (item.confInclude)
if (otherPreset.isPropertyIncluded(item.device, item.name))
if (! item.getValueInCoreFormat().contentEquals(otherPreset.getSetting(item.device, item.name).getPropertyValue()) )
same = false;
}
if (same) {
showMessageDialog("This combination of properties is already in found in the \"" + cfgs.get(j) + "\" preset.\nPlease choose unique property values for your new preset.");
return false;
}
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// Rename the preset if its name has changed
if (! newItem_ && !initName.contentEquals(newName))
try {
core_.renameConfig(groupName_, initName, newName);
} catch (Exception e1) {
// TODO Auto-generated catch block
ReportingUtils.logError(e1);
}
// Define the preset.
for (PropertyItem item_:data_.getPropList()) {
if (item_.confInclude) {
try {
core_.defineConfig(groupName_, newName, item_.device, item_.name, item_.getValueInCoreFormat());
} catch (Exception e) {
// TODO Auto-generated catch block
ReportingUtils.logError(e);
}
}
}
gui_.setConfigChanged(true);
return true;
}
| public boolean writePreset(String initName, String newName) {
// Check to make sure a group name has been specified.
if (newName.length()==0) {
showMessageDialog("Please enter a name for this preset.");
return false;
}
// Avoid clashing names
StrVector groups = core_.getAvailableConfigs(groupName_);
for (int i=0;i<groups.size();i++)
if (groups.get(i).contentEquals(newName) && !newName.contentEquals(initName)) {
showMessageDialog("A preset by this name already exists in the \"" + groupName_ + "\" group.\nPlease enter a different name.");
return false;
}
StrVector cfgs = core_.getAvailableConfigs(groupName_);
try {
// Check if duplicate presets would be created
Configuration otherPreset;
boolean same;
for (int j=0;j<cfgs.size();j++) {
same = true;
if (newItem_ || ! cfgs.get(j).contentEquals(initName)) {
otherPreset = core_.getConfigData(groupName_, cfgs.get(j));
for (PropertyItem item:data_.getPropList()) {
if (item.confInclude)
if (otherPreset.isPropertyIncluded(item.device, item.name))
if (! item.getValueInCoreFormat().contentEquals(otherPreset.getSetting(item.device, item.name).getPropertyValue()) )
same = false;
}
if (same) {
showMessageDialog("This combination of properties is already found in the \"" + cfgs.get(j) + "\" preset.\nPlease choose unique property values for your new preset.");
return false;
}
}
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
// Rename the preset if its name has changed
if (! newItem_ && !initName.contentEquals(newName))
try {
core_.renameConfig(groupName_, initName, newName);
} catch (Exception e1) {
// TODO Auto-generated catch block
ReportingUtils.logError(e1);
}
// Define the preset.
for (PropertyItem item_:data_.getPropList()) {
if (item_.confInclude) {
try {
core_.defineConfig(groupName_, newName, item_.device, item_.name, item_.getValueInCoreFormat());
} catch (Exception e) {
// TODO Auto-generated catch block
ReportingUtils.logError(e);
}
}
}
gui_.setConfigChanged(true);
return true;
}
|
diff --git a/organization/src/main/java/module/organization/presentationTier/renderers/providers/PersonAutoCompleteProvider.java b/organization/src/main/java/module/organization/presentationTier/renderers/providers/PersonAutoCompleteProvider.java
index 2398e3d..dd04790 100644
--- a/organization/src/main/java/module/organization/presentationTier/renderers/providers/PersonAutoCompleteProvider.java
+++ b/organization/src/main/java/module/organization/presentationTier/renderers/providers/PersonAutoCompleteProvider.java
@@ -1,89 +1,91 @@
/*
* @(#)PersonAutoCompleteProvider.java
*
* Copyright 2009 Instituto Superior Tecnico
* Founding Authors: João Figueiredo, Luis Cruz
*
* https://fenix-ashes.ist.utl.pt/
*
* This file is part of the Organization Module.
*
* The Organization Module 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.
*
* The Organization Module 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 the Organization Module. If not, see <http://www.gnu.org/licenses/>.
*
*/
package module.organization.presentationTier.renderers.providers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import module.organization.domain.Party;
import module.organization.domain.Person;
import pt.ist.bennu.core.domain.MyOrg;
import pt.ist.bennu.core.presentationTier.renderers.autoCompleteProvider.AutoCompleteProvider;
import pt.utl.ist.fenix.tools.util.StringNormalizer;
/**
*
* @author João Antunes
* @author João Figueiredo
*
*/
public class PersonAutoCompleteProvider implements AutoCompleteProvider {
@Override
public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) {
final List<Person> persons = new ArrayList<Person>();
final String trimmedValue = value.trim();
String[] values = StringNormalizer.normalize(value).toLowerCase().split(" ");
for (final Person person : getPersons(argsMap, value)) {
final String normalizedName = StringNormalizer.normalize(person.getName()).toLowerCase();
+ if (person.getUser() == null)
+ continue;
if (hasMatch(values, normalizedName)) {
persons.add(person);
}
- if (person.getUser() != null && person.getUser().getUsername().indexOf(value) >= 0) {
+ if (person.getUser().getUsername().indexOf(value) >= 0) {
persons.add(person);
}
if (persons.size() >= maxCount) {
break;
}
}
Collections.sort(persons, Party.COMPARATOR_BY_NAME);
return persons;
}
/**
* Should be overridden by subclasses to allow filtering of the Search
* Results
*/
protected Collection<Person> getPersons(Map<String, String> argsMap, String value) {
return MyOrg.getInstance().getPersonsSet();
}
private boolean hasMatch(final String[] input, final String unitNameParts) {
for (final String namePart : input) {
if (unitNameParts.indexOf(namePart) == -1) {
return false;
}
}
return true;
}
}
| false | true | public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) {
final List<Person> persons = new ArrayList<Person>();
final String trimmedValue = value.trim();
String[] values = StringNormalizer.normalize(value).toLowerCase().split(" ");
for (final Person person : getPersons(argsMap, value)) {
final String normalizedName = StringNormalizer.normalize(person.getName()).toLowerCase();
if (hasMatch(values, normalizedName)) {
persons.add(person);
}
if (person.getUser() != null && person.getUser().getUsername().indexOf(value) >= 0) {
persons.add(person);
}
if (persons.size() >= maxCount) {
break;
}
}
Collections.sort(persons, Party.COMPARATOR_BY_NAME);
return persons;
}
| public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) {
final List<Person> persons = new ArrayList<Person>();
final String trimmedValue = value.trim();
String[] values = StringNormalizer.normalize(value).toLowerCase().split(" ");
for (final Person person : getPersons(argsMap, value)) {
final String normalizedName = StringNormalizer.normalize(person.getName()).toLowerCase();
if (person.getUser() == null)
continue;
if (hasMatch(values, normalizedName)) {
persons.add(person);
}
if (person.getUser().getUsername().indexOf(value) >= 0) {
persons.add(person);
}
if (persons.size() >= maxCount) {
break;
}
}
Collections.sort(persons, Party.COMPARATOR_BY_NAME);
return persons;
}
|
diff --git a/default-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java b/default-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java
index dce24bcacd..611826548c 100644
--- a/default-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java
+++ b/default-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java
@@ -1,165 +1,166 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.partition.ldif.LdifPartition;
import org.apache.directory.server.core.schema.SchemaPartition;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.protocol.shared.transport.Transport;
import org.apache.directory.shared.ldap.schema.SchemaManager;
import org.apache.directory.shared.ldap.schema.ldif.extractor.SchemaLdifExtractor;
import org.apache.directory.shared.ldap.schema.ldif.extractor.impl.DefaultSchemaLdifExtractor;
import org.apache.directory.shared.ldap.schema.loader.ldif.LdifSchemaLoader;
import org.apache.directory.shared.ldap.schema.manager.impl.DefaultSchemaManager;
import org.apache.directory.shared.ldap.schema.registries.SchemaLoader;
import org.apache.directory.shared.ldap.util.ExceptionUtils;
import org.apache.mina.util.AvailablePortFinder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test class for ConfigPartitionReader
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class ConfigPartitionReaderTest
{
private static DirectoryService dirService;
private static LdapServer server;
private static SchemaManager schemaManager;
@BeforeClass
public static void readConfig() throws Exception
{
File workDir = new File( System.getProperty( "java.io.tmpdir" ) + "/server-work" );
+ FileUtils.deleteDirectory( workDir );
workDir.mkdir();
String workingDirectory = workDir.getPath();
// Extract the schema on disk (a brand new one) and load the registries
File schemaRepository = new File( workingDirectory, "schema" );
if ( schemaRepository.exists() )
{
FileUtils.deleteDirectory( schemaRepository );
}
SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( new File( workingDirectory ) );
extractor.extractOrCopy();
SchemaLoader loader = new LdifSchemaLoader( schemaRepository );
schemaManager = new DefaultSchemaManager( loader );
// We have to load the schema now, otherwise we won't be able
// to initialize the Partitions, as we won't be able to parse
// and normalize their suffix DN
schemaManager.loadAllEnabled();
List<Throwable> errors = schemaManager.getErrors();
if ( errors.size() != 0 )
{
throw new Exception( "Schema load failed : " + ExceptionUtils.printErrors( errors ) );
}
LdifConfigExtractor.extract( workDir, true );
LdifPartition configPartition = new LdifPartition();
configPartition.setId( "config" );
configPartition.setSuffix( "ou=config" );
configPartition.setSchemaManager( schemaManager );
configPartition.setWorkingDirectory( workingDirectory + "/config" );
configPartition.setPartitionDir( new File( configPartition.getWorkingDirectory() ) );
configPartition.initialize();
ConfigPartitionReader cpReader = new ConfigPartitionReader( configPartition );
dirService = cpReader.getDirectoryService();
SchemaPartition schemaPartition = dirService.getSchemaService().getSchemaPartition();
// Init the schema partition's wrapped LdifPartition
LdifPartition wrappedPartition = new LdifPartition();
wrappedPartition.setWorkingDirectory( new File( workDir, schemaPartition.getId() ).getAbsolutePath() );
schemaPartition.setWrappedPartition( wrappedPartition );
schemaPartition.setSchemaManager( schemaManager );
dirService.setWorkingDirectory( workDir );
dirService.setSchemaManager( schemaManager );
dirService.startup();
server = cpReader.getLdapServer();
server.setDirectoryService( dirService );
// this is a hack to use a different port than the one
// configured in the actual configuration data
// in case the configured port is already in use during the test run
Transport[] transports = server.getTransports();
for( Transport t : transports )
{
int port = t.getPort();
port = AvailablePortFinder.getNextAvailable( port );
t.setPort( port );
t.init();
}
server.start();
}
@AfterClass
public static void cleanup() throws Exception
{
server.stop();
dirService.shutdown();
}
@Test
public void testDirService()
{
assertTrue( dirService.isStarted() );
assertEquals( "default", dirService.getInstanceId() );
}
@Test
public void testLdapServer()
{
assertTrue( server.isStarted() );
assertEquals( dirService, server.getDirectoryService() );
}
}
| true | true | public static void readConfig() throws Exception
{
File workDir = new File( System.getProperty( "java.io.tmpdir" ) + "/server-work" );
workDir.mkdir();
String workingDirectory = workDir.getPath();
// Extract the schema on disk (a brand new one) and load the registries
File schemaRepository = new File( workingDirectory, "schema" );
if ( schemaRepository.exists() )
{
FileUtils.deleteDirectory( schemaRepository );
}
SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( new File( workingDirectory ) );
extractor.extractOrCopy();
SchemaLoader loader = new LdifSchemaLoader( schemaRepository );
schemaManager = new DefaultSchemaManager( loader );
// We have to load the schema now, otherwise we won't be able
// to initialize the Partitions, as we won't be able to parse
// and normalize their suffix DN
schemaManager.loadAllEnabled();
List<Throwable> errors = schemaManager.getErrors();
if ( errors.size() != 0 )
{
throw new Exception( "Schema load failed : " + ExceptionUtils.printErrors( errors ) );
}
LdifConfigExtractor.extract( workDir, true );
LdifPartition configPartition = new LdifPartition();
configPartition.setId( "config" );
configPartition.setSuffix( "ou=config" );
configPartition.setSchemaManager( schemaManager );
configPartition.setWorkingDirectory( workingDirectory + "/config" );
configPartition.setPartitionDir( new File( configPartition.getWorkingDirectory() ) );
configPartition.initialize();
ConfigPartitionReader cpReader = new ConfigPartitionReader( configPartition );
dirService = cpReader.getDirectoryService();
SchemaPartition schemaPartition = dirService.getSchemaService().getSchemaPartition();
// Init the schema partition's wrapped LdifPartition
LdifPartition wrappedPartition = new LdifPartition();
wrappedPartition.setWorkingDirectory( new File( workDir, schemaPartition.getId() ).getAbsolutePath() );
schemaPartition.setWrappedPartition( wrappedPartition );
schemaPartition.setSchemaManager( schemaManager );
dirService.setWorkingDirectory( workDir );
dirService.setSchemaManager( schemaManager );
dirService.startup();
server = cpReader.getLdapServer();
server.setDirectoryService( dirService );
// this is a hack to use a different port than the one
// configured in the actual configuration data
// in case the configured port is already in use during the test run
Transport[] transports = server.getTransports();
for( Transport t : transports )
{
int port = t.getPort();
port = AvailablePortFinder.getNextAvailable( port );
t.setPort( port );
t.init();
}
server.start();
}
| public static void readConfig() throws Exception
{
File workDir = new File( System.getProperty( "java.io.tmpdir" ) + "/server-work" );
FileUtils.deleteDirectory( workDir );
workDir.mkdir();
String workingDirectory = workDir.getPath();
// Extract the schema on disk (a brand new one) and load the registries
File schemaRepository = new File( workingDirectory, "schema" );
if ( schemaRepository.exists() )
{
FileUtils.deleteDirectory( schemaRepository );
}
SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( new File( workingDirectory ) );
extractor.extractOrCopy();
SchemaLoader loader = new LdifSchemaLoader( schemaRepository );
schemaManager = new DefaultSchemaManager( loader );
// We have to load the schema now, otherwise we won't be able
// to initialize the Partitions, as we won't be able to parse
// and normalize their suffix DN
schemaManager.loadAllEnabled();
List<Throwable> errors = schemaManager.getErrors();
if ( errors.size() != 0 )
{
throw new Exception( "Schema load failed : " + ExceptionUtils.printErrors( errors ) );
}
LdifConfigExtractor.extract( workDir, true );
LdifPartition configPartition = new LdifPartition();
configPartition.setId( "config" );
configPartition.setSuffix( "ou=config" );
configPartition.setSchemaManager( schemaManager );
configPartition.setWorkingDirectory( workingDirectory + "/config" );
configPartition.setPartitionDir( new File( configPartition.getWorkingDirectory() ) );
configPartition.initialize();
ConfigPartitionReader cpReader = new ConfigPartitionReader( configPartition );
dirService = cpReader.getDirectoryService();
SchemaPartition schemaPartition = dirService.getSchemaService().getSchemaPartition();
// Init the schema partition's wrapped LdifPartition
LdifPartition wrappedPartition = new LdifPartition();
wrappedPartition.setWorkingDirectory( new File( workDir, schemaPartition.getId() ).getAbsolutePath() );
schemaPartition.setWrappedPartition( wrappedPartition );
schemaPartition.setSchemaManager( schemaManager );
dirService.setWorkingDirectory( workDir );
dirService.setSchemaManager( schemaManager );
dirService.startup();
server = cpReader.getLdapServer();
server.setDirectoryService( dirService );
// this is a hack to use a different port than the one
// configured in the actual configuration data
// in case the configured port is already in use during the test run
Transport[] transports = server.getTransports();
for( Transport t : transports )
{
int port = t.getPort();
port = AvailablePortFinder.getNextAvailable( port );
t.setPort( port );
t.init();
}
server.start();
}
|
diff --git a/android/src/ca/ilanguage/rhok/imageupload/App.java b/android/src/ca/ilanguage/rhok/imageupload/App.java
index 2cc7c6d..587f2c0 100644
--- a/android/src/ca/ilanguage/rhok/imageupload/App.java
+++ b/android/src/ca/ilanguage/rhok/imageupload/App.java
@@ -1,12 +1,13 @@
package ca.ilanguage.rhok.imageupload;
import java.io.File;
import android.content.Context;
public class App {
public static String getOriginalImageFolder(Context context) {
- return context.getExternalFilesDir(null).getAbsolutePath();
+ File f = context.getExternalFilesDir(null);
+ return f.getAbsolutePath()+f.pathSeparator+"orig";
}
}
| true | true | public static String getOriginalImageFolder(Context context) {
return context.getExternalFilesDir(null).getAbsolutePath();
}
| public static String getOriginalImageFolder(Context context) {
File f = context.getExternalFilesDir(null);
return f.getAbsolutePath()+f.pathSeparator+"orig";
}
|
diff --git a/src/com/UBC417/A1/Data/Seat.java b/src/com/UBC417/A1/Data/Seat.java
index 225207e..1dcdae2 100644
--- a/src/com/UBC417/A1/Data/Seat.java
+++ b/src/com/UBC417/A1/Data/Seat.java
@@ -1,87 +1,88 @@
package com.UBC417.A1.Data;
import java.util.ConcurrentModificationException;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Transaction;
//Helper class for flight seats.
public class Seat {
// Create a seat on a specific flight,
// @store = true, when you want to commit entity to the datastore
// = false, when you want to commit entity later, like in a batch operation
public static Entity CreateSeat(String SeatID, Key FlightKey, boolean store) {
Entity e = new Entity("Seat", SeatID, FlightKey);
e.setProperty("PersonSitting", null);
if (store) {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
ds.put(e);
}
return e;
}
// Frees specific seat(SeatID) on flight(FlightKey)
public static void FreeSeat(String SeatID, Key FlightKey) {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
try {
Entity e = ds.get(KeyFactory.createKey(FlightKey, "Seat", SeatID));
e.setProperty("PersonSitting", null);
ds.put(e);
} catch (EntityNotFoundException e) {
}
}
//Returns all free seats on a specific flight(FlightKey)
public static Iterable<Entity> GetFreeSeats(Key FlightKey) {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Seat").setAncestor(FlightKey).addFilter(
"PersonSitting", FilterOperator.EQUAL, null);
return ds.prepare(q).asIterable();
}
//Reserves a specific seat(SeatID) on a specific flight(FlightKey)
public static boolean ReserveSeat(Key FlightKey, String SeatID,
String FirstName, String LastName) throws EntityNotFoundException {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
+ // Problem 2: Retry failed transactions
int retries = 10;
while (true) {
Transaction tx = ds.beginTransaction();
try {
Entity e = ds.get(tx,
KeyFactory.createKey(FlightKey, "Seat", SeatID));
if (e.getProperty("PersonSitting") != null)
return false;
e.setProperty("PersonSitting", FirstName + " " + LastName);
ds.put(tx, e);
tx.commit();
return true;
} catch (ConcurrentModificationException e) {
if (retries == 0) {
throw e;
}
--retries;
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
}
}
| true | true | public static boolean ReserveSeat(Key FlightKey, String SeatID,
String FirstName, String LastName) throws EntityNotFoundException {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
int retries = 10;
while (true) {
Transaction tx = ds.beginTransaction();
try {
Entity e = ds.get(tx,
KeyFactory.createKey(FlightKey, "Seat", SeatID));
if (e.getProperty("PersonSitting") != null)
return false;
e.setProperty("PersonSitting", FirstName + " " + LastName);
ds.put(tx, e);
tx.commit();
return true;
} catch (ConcurrentModificationException e) {
if (retries == 0) {
throw e;
}
--retries;
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
}
| public static boolean ReserveSeat(Key FlightKey, String SeatID,
String FirstName, String LastName) throws EntityNotFoundException {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
// Problem 2: Retry failed transactions
int retries = 10;
while (true) {
Transaction tx = ds.beginTransaction();
try {
Entity e = ds.get(tx,
KeyFactory.createKey(FlightKey, "Seat", SeatID));
if (e.getProperty("PersonSitting") != null)
return false;
e.setProperty("PersonSitting", FirstName + " " + LastName);
ds.put(tx, e);
tx.commit();
return true;
} catch (ConcurrentModificationException e) {
if (retries == 0) {
throw e;
}
--retries;
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
}
|
diff --git a/org.gitools.ui.app/src/main/java/org/gitools/ui/app/heatmap/panel/details/DetailsPanel.java b/org.gitools.ui.app/src/main/java/org/gitools/ui/app/heatmap/panel/details/DetailsPanel.java
index b5106c36..592b242f 100644
--- a/org.gitools.ui.app/src/main/java/org/gitools/ui/app/heatmap/panel/details/DetailsPanel.java
+++ b/org.gitools.ui.app/src/main/java/org/gitools/ui/app/heatmap/panel/details/DetailsPanel.java
@@ -1,191 +1,191 @@
/*
* #%L
* gitools-ui-app
* %%
* Copyright (C) 2013 Universitat Pompeu Fabra - Biomedical Genomics group
* %%
* 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/gpl-3.0.html>.
* #L%
*/
package org.gitools.ui.app.heatmap.panel.details;
import org.apache.commons.lang.StringUtils;
import org.gitools.heatmap.Heatmap;
import org.gitools.heatmap.HeatmapDimension;
import org.gitools.heatmap.HeatmapLayer;
import org.gitools.heatmap.decorator.Decoration;
import org.gitools.heatmap.decorator.Decorator;
import org.gitools.heatmap.decorator.DetailsDecoration;
import org.gitools.heatmap.header.HeatmapHeader;
import org.gitools.ui.app.actions.edit.EditHeaderAction;
import org.gitools.ui.app.actions.edit.EditLayerAction;
import org.gitools.ui.app.heatmap.panel.details.boxes.DetailsBox;
import org.gitools.ui.app.heatmap.popupmenus.PopupMenuActions;
import org.jdesktop.swingx.JXTaskPaneContainer;
import org.jdesktop.swingx.plaf.LookAndFeelAddons;
import org.jdesktop.swingx.plaf.metal.MetalLookAndFeelAddons;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
/**
* A details panel with three collapsible panels
*/
public class DetailsPanel extends JXTaskPaneContainer {
private DetailsBox columnsBox;
private DetailsBox rowsBox;
private DetailsBox layersBox;
private JLabel hintLabel;
/**
* Instantiates a new details panel.
*
* @param heatmap the heatmap
*/
public DetailsPanel(final Heatmap heatmap) {
super();
try {
LookAndFeelAddons.setAddon(MetalLookAndFeelAddons.class);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
setBackground(Color.WHITE);
// Changes to track
heatmap.getRows().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
update(heatmap.getRows(), rowsBox);
updateLayers(heatmap, layersBox);
}
});
heatmap.getColumns().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
update(heatmap.getColumns(), columnsBox);
updateLayers(heatmap, layersBox);
}
});
PropertyChangeListener updateLayers = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateLayers(heatmap, layersBox);
}
};
heatmap.getLayers().addPropertyChangeListener(updateLayers);
heatmap.getLayers().getTopLayer().addPropertyChangeListener(updateLayers);
add(columnsBox = new DetailsBox("Column", PopupMenuActions.DETAILS_COLUMNS) {
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapHeader) {
new EditHeaderAction((HeatmapHeader) reference).actionPerformed(null);
}
}
});
columnsBox.setCollapsed(true);
add(rowsBox = new DetailsBox("Row", PopupMenuActions.DETAILS_ROWS) {
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapHeader) {
new EditHeaderAction((HeatmapHeader) reference).actionPerformed(null);
}
}
});
rowsBox.setCollapsed(true);
add(layersBox = new DetailsBox("Values", PopupMenuActions.DETAILS_LAYERS) {
@Override
protected void onMouseClick(DetailsDecoration detail) {
heatmap.getLayers().setTopLayerIndex(detail.getIndex());
}
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapLayer) {
new EditLayerAction((HeatmapLayer) reference).actionPerformed(null);
}
}
});
hintLabel = new JLabel();
- hintLabel.setText("<html><body><i>Right click</i> on any layer or header id to " +
- "<b>adjust visualization and other settings</b>.</body></html>");
+ hintLabel.setText("<html><body><p><i>Right click</i> on any layer or header id to<br>" +
+ "<b>adjust visualization and other settings</b>.</p></body></html>");
add(hintLabel);
update(heatmap.getRows(), rowsBox);
update(heatmap.getColumns(), columnsBox);
updateLayers(heatmap, layersBox);
}
private static void update(HeatmapDimension rows, DetailsBox rowsBox) {
String lead = rows.getFocus();
String label = StringUtils.capitalize(rows.getId().getLabel());
if (lead != null) {
rowsBox.setTitle(label + ": " + lead + " [" + (rows.indexOf(lead) + 1) + "]");
} else {
rowsBox.setTitle(label);
}
List<DetailsDecoration> details = new ArrayList<>();
rows.populateDetails(details);
rowsBox.draw(details);
}
private static void updateLayers(Heatmap heatmap, DetailsBox layersBox) {
String col = heatmap.getColumns().getFocus();
String row = heatmap.getRows().getFocus();
if (col != null && row != null) {
Decorator decorator = heatmap.getLayers().getTopLayer().getDecorator();
Decoration decoration = new Decoration();
boolean showValue = decorator.isShowValue();
decorator.setShowValue(true);
decoration.reset();
HeatmapLayer layer = heatmap.getLayers().getTopLayer();
decorator.decorate(decoration, layer.getLongFormatter(), heatmap, layer, row, col);
decorator.setShowValue(showValue);
layersBox.setTitle("Values: " + decoration.getFormatedValue());
} else {
layersBox.setTitle("Values");
}
List<DetailsDecoration> layersDetails = new ArrayList<>();
heatmap.getLayers().populateDetails(layersDetails, heatmap, heatmap.getRows().getFocus(), heatmap.getColumns().getFocus());
layersBox.draw(layersDetails);
}
}
| true | true | public DetailsPanel(final Heatmap heatmap) {
super();
try {
LookAndFeelAddons.setAddon(MetalLookAndFeelAddons.class);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
setBackground(Color.WHITE);
// Changes to track
heatmap.getRows().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
update(heatmap.getRows(), rowsBox);
updateLayers(heatmap, layersBox);
}
});
heatmap.getColumns().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
update(heatmap.getColumns(), columnsBox);
updateLayers(heatmap, layersBox);
}
});
PropertyChangeListener updateLayers = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateLayers(heatmap, layersBox);
}
};
heatmap.getLayers().addPropertyChangeListener(updateLayers);
heatmap.getLayers().getTopLayer().addPropertyChangeListener(updateLayers);
add(columnsBox = new DetailsBox("Column", PopupMenuActions.DETAILS_COLUMNS) {
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapHeader) {
new EditHeaderAction((HeatmapHeader) reference).actionPerformed(null);
}
}
});
columnsBox.setCollapsed(true);
add(rowsBox = new DetailsBox("Row", PopupMenuActions.DETAILS_ROWS) {
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapHeader) {
new EditHeaderAction((HeatmapHeader) reference).actionPerformed(null);
}
}
});
rowsBox.setCollapsed(true);
add(layersBox = new DetailsBox("Values", PopupMenuActions.DETAILS_LAYERS) {
@Override
protected void onMouseClick(DetailsDecoration detail) {
heatmap.getLayers().setTopLayerIndex(detail.getIndex());
}
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapLayer) {
new EditLayerAction((HeatmapLayer) reference).actionPerformed(null);
}
}
});
hintLabel = new JLabel();
hintLabel.setText("<html><body><i>Right click</i> on any layer or header id to " +
"<b>adjust visualization and other settings</b>.</body></html>");
add(hintLabel);
update(heatmap.getRows(), rowsBox);
update(heatmap.getColumns(), columnsBox);
updateLayers(heatmap, layersBox);
}
| public DetailsPanel(final Heatmap heatmap) {
super();
try {
LookAndFeelAddons.setAddon(MetalLookAndFeelAddons.class);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
setBackground(Color.WHITE);
// Changes to track
heatmap.getRows().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
update(heatmap.getRows(), rowsBox);
updateLayers(heatmap, layersBox);
}
});
heatmap.getColumns().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
update(heatmap.getColumns(), columnsBox);
updateLayers(heatmap, layersBox);
}
});
PropertyChangeListener updateLayers = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateLayers(heatmap, layersBox);
}
};
heatmap.getLayers().addPropertyChangeListener(updateLayers);
heatmap.getLayers().getTopLayer().addPropertyChangeListener(updateLayers);
add(columnsBox = new DetailsBox("Column", PopupMenuActions.DETAILS_COLUMNS) {
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapHeader) {
new EditHeaderAction((HeatmapHeader) reference).actionPerformed(null);
}
}
});
columnsBox.setCollapsed(true);
add(rowsBox = new DetailsBox("Row", PopupMenuActions.DETAILS_ROWS) {
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapHeader) {
new EditHeaderAction((HeatmapHeader) reference).actionPerformed(null);
}
}
});
rowsBox.setCollapsed(true);
add(layersBox = new DetailsBox("Values", PopupMenuActions.DETAILS_LAYERS) {
@Override
protected void onMouseClick(DetailsDecoration detail) {
heatmap.getLayers().setTopLayerIndex(detail.getIndex());
}
@Override
protected void onMouseDblClick(DetailsDecoration detail) {
Object reference = detail.getReference();
if (reference instanceof HeatmapLayer) {
new EditLayerAction((HeatmapLayer) reference).actionPerformed(null);
}
}
});
hintLabel = new JLabel();
hintLabel.setText("<html><body><p><i>Right click</i> on any layer or header id to<br>" +
"<b>adjust visualization and other settings</b>.</p></body></html>");
add(hintLabel);
update(heatmap.getRows(), rowsBox);
update(heatmap.getColumns(), columnsBox);
updateLayers(heatmap, layersBox);
}
|
diff --git a/src/me/mcandze/plugin/zeareas/area/Area2D.java b/src/me/mcandze/plugin/zeareas/area/Area2D.java
index 0ccb037..228349f 100644
--- a/src/me/mcandze/plugin/zeareas/area/Area2D.java
+++ b/src/me/mcandze/plugin/zeareas/area/Area2D.java
@@ -1,79 +1,82 @@
package me.mcandze.plugin.zeareas.area;
import java.util.ArrayList;
import java.util.List;
import me.mcandze.plugin.zeareas.util.BlockLocation;
import org.bukkit.Location;
import org.bukkit.World;
/**
* A class for 2-dimensional areas.
* It simply ignores the Y-axis and creates a cuboid from sky to bedrock, limited by the Z and X axis.
* @author andreas
*
*/
public class Area2D extends CuboidArea{
private BlockLocation location1, location2;
private World world;
private double lowX, lowZ, highX, highZ;
private AreaOwner owner;
public Area2D(Location location1, Location location2){
this.location1 = BlockLocation.toBlockLocation(location1);
this.location2 = BlockLocation.toBlockLocation(location2);
this.world = location1.getWorld();
this.recalcMinimum();
this.owner = new OwnerServer();
}
public Area2D(Location location1, Location location2, AreaOwner owner){
this(location1, location2);
this.owner = owner;
}
@Override
public List<BlockLocation> getPoints() {
List<BlockLocation> toReturn = new ArrayList<BlockLocation>();
toReturn.add(location1);
toReturn.add(location2);
return toReturn;
}
@Override
public boolean isLocationInArea(BlockLocation location) {
double x = location.getX();
double z = location.getZ();
return location.getWorld().equals(this.world) && (x > lowX && x < highX && z > lowZ && z < highZ);
}
/**
* Re-calculates the furthermost points on the z and x axis for measurement.
*/
public void recalcMinimum(){
lowX = Math.min(location1.getX(), location2.getX());
lowZ = Math.min(location1.getZ(), location2.getZ());
highX = Math.max(location1.getX(), location2.getX());
highZ = Math.max(location1.getZ(), location2.getZ());
}
/**
* Get the World this area is located in.
* @return
*/
public World getWorld() {
return world;
}
@Override
public BlockLocation[] getCorners() {
BlockLocation[] list = new BlockLocation[4];
list[0] = this.location1;
list[1] = this.location2;
list[2] = new BlockLocation(Math.max(list[0].getX(), list[1].getX()),
Math.max(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
- return null;
+ list[3] = new BlockLocation(Math.min(list[0].getX(), list[1].getX()),
+ Math.max(list[0].getZ(), list[1].getZ()),
+ list[0].getY(), list[0].getWorld());
+ return list;
}
}
| true | true | public BlockLocation[] getCorners() {
BlockLocation[] list = new BlockLocation[4];
list[0] = this.location1;
list[1] = this.location2;
list[2] = new BlockLocation(Math.max(list[0].getX(), list[1].getX()),
Math.max(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
return null;
}
| public BlockLocation[] getCorners() {
BlockLocation[] list = new BlockLocation[4];
list[0] = this.location1;
list[1] = this.location2;
list[2] = new BlockLocation(Math.max(list[0].getX(), list[1].getX()),
Math.max(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
list[3] = new BlockLocation(Math.min(list[0].getX(), list[1].getX()),
Math.max(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
return list;
}
|
diff --git a/src/java/com/eviware/soapui/security/SecurityCheckResult.java b/src/java/com/eviware/soapui/security/SecurityCheckResult.java
index 250f80d23..bb3783193 100644
--- a/src/java/com/eviware/soapui/security/SecurityCheckResult.java
+++ b/src/java/com/eviware/soapui/security/SecurityCheckResult.java
@@ -1,157 +1,157 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI 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 at gnu.org.
*/
package com.eviware.soapui.security;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import com.eviware.soapui.security.SecurityCheckRequestResult.SecurityCheckStatus;
import com.eviware.soapui.security.check.AbstractSecurityCheck;
import com.eviware.soapui.support.action.swing.ActionList;
/**
* A SecurityCheck result represents result of one request (modified by a
* security check and run)
*
* @author dragica.soldo
*/
public class SecurityCheckResult
{
public SecurityCheckStatus status = SecurityCheckStatus.OK;
public AbstractSecurityCheck securityCheck;
private long size;
private boolean discarded;
private List<SecurityCheckRequestResult> securityRequestResultList;
private long timeTaken = 0;
private long timeStamp;
private StringBuffer testLog = new StringBuffer();
public SecurityCheckResult( AbstractSecurityCheck securityCheck )
{
this.securityCheck = securityCheck;
securityRequestResultList = new ArrayList<SecurityCheckRequestResult>();
}
public List<SecurityCheckRequestResult> getSecurityRequestResultList()
{
return securityRequestResultList;
}
public SecurityCheckStatus getStatus()
{
return status;
}
public AbstractSecurityCheck getSecurityCheck()
{
return securityCheck;
}
/**
* Returns a list of actions that can be applied to this result
*/
public ActionList getActions()
{
return null;
}
public void addSecurityRequestResult( SecurityCheckRequestResult secReqResult )
{
if( securityRequestResultList != null )
securityRequestResultList.add( secReqResult );
// calulate time taken
timeTaken += secReqResult.getTimeTaken();
// calculate time stamp (when test is started)
if( securityRequestResultList.size() == 1 )
timeStamp = securityRequestResultList.get( 0 ).getTimeStamp();
else if( timeStamp > secReqResult.getTimeStamp() )
timeStamp = secReqResult.getTimeStamp();
// calculate status ( one failed fails whole test )
if( status == SecurityCheckStatus.OK )
status = secReqResult.getStatus();
this.testLog.append( "SecurityRequest " ).append( securityRequestResultList.indexOf( secReqResult ) ).append(
secReqResult.getStatus().toString() ).append( ": took " ).append( secReqResult.getTimeTaken() ).append(
" ms" );
for( String s : secReqResult.getMessages() )
- testLog.append( "\n -> " ).append( secReqResult.getMessages() );
+ testLog.append( "\n -> " ).append( s );
}
public long getTimeTaken()
{
return timeTaken;
}
/**
* Used for calculating the output
*
* @return the number of bytes in this result
*/
public long getSize()
{
return size;
}
/**
* Writes this result to the specified writer, used for logging.
*/
public void writeTo( PrintWriter writer )
{
}
/**
* Can discard any result data that may be taking up memory. Timing-values
* must not be discarded.
*/
public void discard()
{
}
public boolean isDiscarded()
{
return discarded;
}
/**
* Returns time stamp when test is started.
*
* @return
*/
public long getTimeStamp()
{
return timeStamp;
}
/**
* Raturns Security Test Log
*/
public String getSecurityTestLog()
{
StringBuffer tl = new StringBuffer().append( "SecurityCheck " ).append( " [" ).append(
securityCheck.getTestStep().getName() ).append( "] " ).append( status.toString() ).append( ": took " )
.append( timeTaken ).append( " ms" );
tl.append( testLog );
return tl.toString();
}
}
| true | true | public void addSecurityRequestResult( SecurityCheckRequestResult secReqResult )
{
if( securityRequestResultList != null )
securityRequestResultList.add( secReqResult );
// calulate time taken
timeTaken += secReqResult.getTimeTaken();
// calculate time stamp (when test is started)
if( securityRequestResultList.size() == 1 )
timeStamp = securityRequestResultList.get( 0 ).getTimeStamp();
else if( timeStamp > secReqResult.getTimeStamp() )
timeStamp = secReqResult.getTimeStamp();
// calculate status ( one failed fails whole test )
if( status == SecurityCheckStatus.OK )
status = secReqResult.getStatus();
this.testLog.append( "SecurityRequest " ).append( securityRequestResultList.indexOf( secReqResult ) ).append(
secReqResult.getStatus().toString() ).append( ": took " ).append( secReqResult.getTimeTaken() ).append(
" ms" );
for( String s : secReqResult.getMessages() )
testLog.append( "\n -> " ).append( secReqResult.getMessages() );
}
| public void addSecurityRequestResult( SecurityCheckRequestResult secReqResult )
{
if( securityRequestResultList != null )
securityRequestResultList.add( secReqResult );
// calulate time taken
timeTaken += secReqResult.getTimeTaken();
// calculate time stamp (when test is started)
if( securityRequestResultList.size() == 1 )
timeStamp = securityRequestResultList.get( 0 ).getTimeStamp();
else if( timeStamp > secReqResult.getTimeStamp() )
timeStamp = secReqResult.getTimeStamp();
// calculate status ( one failed fails whole test )
if( status == SecurityCheckStatus.OK )
status = secReqResult.getStatus();
this.testLog.append( "SecurityRequest " ).append( securityRequestResultList.indexOf( secReqResult ) ).append(
secReqResult.getStatus().toString() ).append( ": took " ).append( secReqResult.getTimeTaken() ).append(
" ms" );
for( String s : secReqResult.getMessages() )
testLog.append( "\n -> " ).append( s );
}
|
diff --git a/Youtube/src/me/gameplax/youtube/Eventsalle.java b/Youtube/src/me/gameplax/youtube/Eventsalle.java
index bd25d9a..ac68622 100644
--- a/Youtube/src/me/gameplax/youtube/Eventsalle.java
+++ b/Youtube/src/me/gameplax/youtube/Eventsalle.java
@@ -1,96 +1,96 @@
package me.gameplax.youtube;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
public class Eventsalle implements Listener {
@EventHandler
public void onPlayerDeathEvent(PlayerDeathEvent event){
Player p = event.getEntity().getPlayer();
event.setDeathMessage(null);
p.setHealth(20);
p.setFoodLevel(20);
p.setFireTicks(0);
p.teleport(new Location(Bukkit.getServer().getWorld("world"), -13, 93, 371));
}
@EventHandler
public void onPLayInteract(PlayerInteractEvent e){
if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Block i = e.getClickedBlock();
if(i.getState() instanceof Sign){
Player p = e.getPlayer();
String playername = p.getPlayer().getName();
BlockState stateBlock = i.getState();
Sign sign = (Sign) stateBlock;
if(sign.getLine(0).equalsIgnoreCase("YouTube") && sign.getLine(1).equalsIgnoreCase("Start")){
World welt = p.getWorld();
- Location loc1 = new Location(welt, -156, 66, 441);
- Location loc2 = new Location(welt, -167, 65, 447);
- Location loc3 = new Location(welt, -177, 65, 458);
- Location loc4 = new Location(welt, -186, 65, 443);
+ Location loc1 = new Location(welt, x, y, z);
+ Location loc2 = new Location(welt, x, y, z);
+ Location loc3 = new Location(welt, x, y, z);
+ Location loc4 = new Location(welt, x, y, z);
Random rnd = new Random();
int zufallszahl = rnd.nextInt(3);
Location loc = null;
switch(zufallszahl){
case 0:
loc = loc1;
break;
case 1:
loc = loc2;
break;
case 2:
loc = loc3;
break;
case 3:
loc = loc4;
}
p.teleport(loc);
}
}
}
}
}
| true | true | public void onPLayInteract(PlayerInteractEvent e){
if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Block i = e.getClickedBlock();
if(i.getState() instanceof Sign){
Player p = e.getPlayer();
String playername = p.getPlayer().getName();
BlockState stateBlock = i.getState();
Sign sign = (Sign) stateBlock;
if(sign.getLine(0).equalsIgnoreCase("YouTube") && sign.getLine(1).equalsIgnoreCase("Start")){
World welt = p.getWorld();
Location loc1 = new Location(welt, -156, 66, 441);
Location loc2 = new Location(welt, -167, 65, 447);
Location loc3 = new Location(welt, -177, 65, 458);
Location loc4 = new Location(welt, -186, 65, 443);
Random rnd = new Random();
int zufallszahl = rnd.nextInt(3);
Location loc = null;
switch(zufallszahl){
case 0:
loc = loc1;
break;
case 1:
loc = loc2;
break;
case 2:
loc = loc3;
break;
case 3:
loc = loc4;
}
p.teleport(loc);
}
}
}
}
| public void onPLayInteract(PlayerInteractEvent e){
if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Block i = e.getClickedBlock();
if(i.getState() instanceof Sign){
Player p = e.getPlayer();
String playername = p.getPlayer().getName();
BlockState stateBlock = i.getState();
Sign sign = (Sign) stateBlock;
if(sign.getLine(0).equalsIgnoreCase("YouTube") && sign.getLine(1).equalsIgnoreCase("Start")){
World welt = p.getWorld();
Location loc1 = new Location(welt, x, y, z);
Location loc2 = new Location(welt, x, y, z);
Location loc3 = new Location(welt, x, y, z);
Location loc4 = new Location(welt, x, y, z);
Random rnd = new Random();
int zufallszahl = rnd.nextInt(3);
Location loc = null;
switch(zufallszahl){
case 0:
loc = loc1;
break;
case 1:
loc = loc2;
break;
case 2:
loc = loc3;
break;
case 3:
loc = loc4;
}
p.teleport(loc);
}
}
}
}
|
diff --git a/src/net/adbenson/codekata/parser/AccountNumberParser.java b/src/net/adbenson/codekata/parser/AccountNumberParser.java
index b95e55a..a8fbc0b 100644
--- a/src/net/adbenson/codekata/parser/AccountNumberParser.java
+++ b/src/net/adbenson/codekata/parser/AccountNumberParser.java
@@ -1,64 +1,65 @@
package net.adbenson.codekata.parser;
import java.util.ArrayList;
import java.util.List;
import net.adbenson.codekata.common.Config;
import net.adbenson.codekata.model.AccountNumber;
import net.adbenson.codekata.model.Digit;
/**
* DigitNumberParser class parses a set of lines as a single account number
* @author Andrew
*
*/
public class AccountNumberParser {
/**
* The parser that will identify the actual digits of the nuber
*/
private DigitParser digitParser;
/**
* Parses an account number model to a long number
* @param account
* @return
*/
public AccountNumber parse(List<String> accountNumberLines) {
List<Digit> digits = new ArrayList<Digit>();
long number = 0;
for(int i=0; i<Config.DIGITS_PER_NUMBER; i++) {
//Find the digit value
List<String> rows = separateDigits(accountNumberLines, i);
Digit digit = digitParser.parse(rows);
//Left-shift it to find the actual value
//The value of the digit increases L-R but we read R-L, so invert the index
int power = Config.DIGITS_PER_NUMBER - i - 1;
number += digit.getValue() * Math.round(Math.pow(10, power));
+ digits.add(digit);
}
AccountNumber account = new AccountNumber(digits, number);
return account;
}
public List<String> separateDigits(List<String> lines, int offset) {
offset *= Config.CHARACTERS_PER_DIGIT;
List<String> rows = new ArrayList<String>();
for (String line : lines) {
String row = line.substring(offset, offset
+ Config.CHARACTERS_PER_DIGIT);
rows.add(row);
}
return rows;
}
public void setDigitParser(DigitParser digitParser) {
this.digitParser = digitParser;
}
}
| true | true | public AccountNumber parse(List<String> accountNumberLines) {
List<Digit> digits = new ArrayList<Digit>();
long number = 0;
for(int i=0; i<Config.DIGITS_PER_NUMBER; i++) {
//Find the digit value
List<String> rows = separateDigits(accountNumberLines, i);
Digit digit = digitParser.parse(rows);
//Left-shift it to find the actual value
//The value of the digit increases L-R but we read R-L, so invert the index
int power = Config.DIGITS_PER_NUMBER - i - 1;
number += digit.getValue() * Math.round(Math.pow(10, power));
}
AccountNumber account = new AccountNumber(digits, number);
return account;
}
| public AccountNumber parse(List<String> accountNumberLines) {
List<Digit> digits = new ArrayList<Digit>();
long number = 0;
for(int i=0; i<Config.DIGITS_PER_NUMBER; i++) {
//Find the digit value
List<String> rows = separateDigits(accountNumberLines, i);
Digit digit = digitParser.parse(rows);
//Left-shift it to find the actual value
//The value of the digit increases L-R but we read R-L, so invert the index
int power = Config.DIGITS_PER_NUMBER - i - 1;
number += digit.getValue() * Math.round(Math.pow(10, power));
digits.add(digit);
}
AccountNumber account = new AccountNumber(digits, number);
return account;
}
|
diff --git a/src/test/java/org/paules/geckoboard/api/widget/BulletGraphTest.java b/src/test/java/org/paules/geckoboard/api/widget/BulletGraphTest.java
index 61c46a8..b8d1f0b 100644
--- a/src/test/java/org/paules/geckoboard/api/widget/BulletGraphTest.java
+++ b/src/test/java/org/paules/geckoboard/api/widget/BulletGraphTest.java
@@ -1,65 +1,61 @@
package org.paules.geckoboard.api.widget;
import java.io.IOException;
import java.util.Arrays;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.junit.Assert;
import org.junit.Test;
import org.paules.geckoboard.api.json.RAGColor;
public class BulletGraphTest {
@Test
public void testJson() throws JsonProcessingException, IOException {
BulletGraph widget = new BulletGraph( "1234", false );
widget.setAxisPoints( Arrays.asList( new String[] { "1", "2", "3", "4", "8", "0" } ) );
widget.setComparative( "10" );
widget.setLabel( "test-label" );
widget.setProjected( 10, 100 );
widget.setSubLabel( "sub-test-label" );
widget.setCurrent( 1, 10 );
widget.addRange( 0, 10, RAGColor.RED );
widget.addRange( 10, 20, RAGColor.AMBER );
widget.addRange( 20, 30, RAGColor.GREEN );
ObjectMapper om = new ObjectMapper();
JsonNode data = om.readTree( widget.toJson() );
Assert.assertNotNull( data.get( "data" ) );
JsonNode node = data.get( "data" );
- JsonNode itemNode = node.get( "item" );
- Assert.assertTrue( itemNode.isArray() );
- ArrayNode items = ( ArrayNode ) itemNode;
- Assert.assertEquals( 1, items.size() );
- JsonNode item = items.get( 0 );
+ JsonNode item = node.get( "item" );
Assert.assertEquals( "test-label", item.get( "label" ).asText() );
Assert.assertEquals( "sub-test-label", item.get( "sublabel" ).asText() );
Assert.assertTrue( item.get( "axis" ).get( "point" ).isArray() );
ArrayNode points = ( ArrayNode ) item.get( "axis" ).get( "point" );
Assert.assertEquals( 6, points.size() );
Assert.assertEquals( 4, points.get( 3 ).asInt() );
Assert.assertEquals( 8, points.get( 4 ).asInt() );
Assert.assertEquals( 0, points.get( 5 ).asInt() );
Assert.assertTrue( item.get( "range" ).isArray() );
ArrayNode ranges = ( ArrayNode ) item.get( "range" );
Assert.assertEquals( 3, ranges.size() );
Assert.assertEquals( "red", ranges.get( 0 ).get( "color" ).asText() );
Assert.assertEquals( 0, ranges.get( 0 ).get( "start" ).asInt() );
Assert.assertEquals( 10, ranges.get( 0 ).get( "end" ).asInt() );
// "measure\":{\"current\":{\"start\":1,\"end\":10},\"projected\":{\"start\":10,\"end\":100},\"comparative\":{\"point\":10}}}],\"orientation\":\"horizontal\"}}"
Assert.assertEquals( 1, item.get( "measure" ).get( "current" ).get( "start" ).asInt() );
Assert.assertEquals( 10, item.get( "measure" ).get( "current" ).get( "end" ).asInt() );
Assert.assertEquals( 10, item.get( "measure" ).get( "projected" ).get( "start" ).asInt() );
Assert.assertEquals( 100, item.get( "measure" ).get( "projected" ).get( "end" ).asInt() );
Assert.assertEquals( 10, item.get( "comparative" ).get( "point" ).asInt() );
Assert.assertEquals( "horizontal", node.get( "orientation" ).asText() );
}
}
| true | true | public void testJson() throws JsonProcessingException, IOException {
BulletGraph widget = new BulletGraph( "1234", false );
widget.setAxisPoints( Arrays.asList( new String[] { "1", "2", "3", "4", "8", "0" } ) );
widget.setComparative( "10" );
widget.setLabel( "test-label" );
widget.setProjected( 10, 100 );
widget.setSubLabel( "sub-test-label" );
widget.setCurrent( 1, 10 );
widget.addRange( 0, 10, RAGColor.RED );
widget.addRange( 10, 20, RAGColor.AMBER );
widget.addRange( 20, 30, RAGColor.GREEN );
ObjectMapper om = new ObjectMapper();
JsonNode data = om.readTree( widget.toJson() );
Assert.assertNotNull( data.get( "data" ) );
JsonNode node = data.get( "data" );
JsonNode itemNode = node.get( "item" );
Assert.assertTrue( itemNode.isArray() );
ArrayNode items = ( ArrayNode ) itemNode;
Assert.assertEquals( 1, items.size() );
JsonNode item = items.get( 0 );
Assert.assertEquals( "test-label", item.get( "label" ).asText() );
Assert.assertEquals( "sub-test-label", item.get( "sublabel" ).asText() );
Assert.assertTrue( item.get( "axis" ).get( "point" ).isArray() );
ArrayNode points = ( ArrayNode ) item.get( "axis" ).get( "point" );
Assert.assertEquals( 6, points.size() );
Assert.assertEquals( 4, points.get( 3 ).asInt() );
Assert.assertEquals( 8, points.get( 4 ).asInt() );
Assert.assertEquals( 0, points.get( 5 ).asInt() );
Assert.assertTrue( item.get( "range" ).isArray() );
ArrayNode ranges = ( ArrayNode ) item.get( "range" );
Assert.assertEquals( 3, ranges.size() );
Assert.assertEquals( "red", ranges.get( 0 ).get( "color" ).asText() );
Assert.assertEquals( 0, ranges.get( 0 ).get( "start" ).asInt() );
Assert.assertEquals( 10, ranges.get( 0 ).get( "end" ).asInt() );
// "measure\":{\"current\":{\"start\":1,\"end\":10},\"projected\":{\"start\":10,\"end\":100},\"comparative\":{\"point\":10}}}],\"orientation\":\"horizontal\"}}"
Assert.assertEquals( 1, item.get( "measure" ).get( "current" ).get( "start" ).asInt() );
Assert.assertEquals( 10, item.get( "measure" ).get( "current" ).get( "end" ).asInt() );
Assert.assertEquals( 10, item.get( "measure" ).get( "projected" ).get( "start" ).asInt() );
Assert.assertEquals( 100, item.get( "measure" ).get( "projected" ).get( "end" ).asInt() );
Assert.assertEquals( 10, item.get( "comparative" ).get( "point" ).asInt() );
Assert.assertEquals( "horizontal", node.get( "orientation" ).asText() );
}
| public void testJson() throws JsonProcessingException, IOException {
BulletGraph widget = new BulletGraph( "1234", false );
widget.setAxisPoints( Arrays.asList( new String[] { "1", "2", "3", "4", "8", "0" } ) );
widget.setComparative( "10" );
widget.setLabel( "test-label" );
widget.setProjected( 10, 100 );
widget.setSubLabel( "sub-test-label" );
widget.setCurrent( 1, 10 );
widget.addRange( 0, 10, RAGColor.RED );
widget.addRange( 10, 20, RAGColor.AMBER );
widget.addRange( 20, 30, RAGColor.GREEN );
ObjectMapper om = new ObjectMapper();
JsonNode data = om.readTree( widget.toJson() );
Assert.assertNotNull( data.get( "data" ) );
JsonNode node = data.get( "data" );
JsonNode item = node.get( "item" );
Assert.assertEquals( "test-label", item.get( "label" ).asText() );
Assert.assertEquals( "sub-test-label", item.get( "sublabel" ).asText() );
Assert.assertTrue( item.get( "axis" ).get( "point" ).isArray() );
ArrayNode points = ( ArrayNode ) item.get( "axis" ).get( "point" );
Assert.assertEquals( 6, points.size() );
Assert.assertEquals( 4, points.get( 3 ).asInt() );
Assert.assertEquals( 8, points.get( 4 ).asInt() );
Assert.assertEquals( 0, points.get( 5 ).asInt() );
Assert.assertTrue( item.get( "range" ).isArray() );
ArrayNode ranges = ( ArrayNode ) item.get( "range" );
Assert.assertEquals( 3, ranges.size() );
Assert.assertEquals( "red", ranges.get( 0 ).get( "color" ).asText() );
Assert.assertEquals( 0, ranges.get( 0 ).get( "start" ).asInt() );
Assert.assertEquals( 10, ranges.get( 0 ).get( "end" ).asInt() );
// "measure\":{\"current\":{\"start\":1,\"end\":10},\"projected\":{\"start\":10,\"end\":100},\"comparative\":{\"point\":10}}}],\"orientation\":\"horizontal\"}}"
Assert.assertEquals( 1, item.get( "measure" ).get( "current" ).get( "start" ).asInt() );
Assert.assertEquals( 10, item.get( "measure" ).get( "current" ).get( "end" ).asInt() );
Assert.assertEquals( 10, item.get( "measure" ).get( "projected" ).get( "start" ).asInt() );
Assert.assertEquals( 100, item.get( "measure" ).get( "projected" ).get( "end" ).asInt() );
Assert.assertEquals( 10, item.get( "comparative" ).get( "point" ).asInt() );
Assert.assertEquals( "horizontal", node.get( "orientation" ).asText() );
}
|
diff --git a/src/org/apxeolog/salem/widgets/SWidgetOptions.java b/src/org/apxeolog/salem/widgets/SWidgetOptions.java
index e3eb6ca..f730bfa 100644
--- a/src/org/apxeolog/salem/widgets/SWidgetOptions.java
+++ b/src/org/apxeolog/salem/widgets/SWidgetOptions.java
@@ -1,883 +1,883 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package org.apxeolog.salem.widgets;
import haven.Audio;
import haven.Button;
import haven.CheckBox;
import haven.Coord;
import haven.GOut;
import haven.GameUI;
import haven.GameUI.Hidewnd;
import haven.Label;
import haven.Loading;
import haven.Resource;
import haven.RichText;
import haven.Scrollbar;
import haven.Tabs;
import haven.Tabs.Tab;
import haven.TextEntry;
import haven.WItem;
import haven.Widget;
import java.awt.event.KeyEvent;
import java.awt.font.TextAttribute;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import org.apxeolog.salem.SChatWrapper;
import org.apxeolog.salem.config.MinimapHighlightConfig;
import org.apxeolog.salem.config.MinimapHighlightConfig.HighlightInfo;
import org.apxeolog.salem.config.ToolbarsConfig.TBSlot;
import org.apxeolog.salem.config.ToolbarsConfig;
import org.apxeolog.salem.config.XConfig;
import org.apxeolog.salem.config.XMLConfigProvider;
public class SWidgetOptions extends Hidewnd {
public static final RichText.Foundry foundry = new RichText.Foundry(
TextAttribute.FAMILY, "SansSerif", TextAttribute.SIZE, 10);
private Tabs body;
@Override
public void unlink() {
XMLConfigProvider.save();
ToolbarsConfig.updateToolbars(ui.root);
super.unlink();
}
@Override
protected void maximize() {
super.maximize();
for (Tab t : body.tabs) t.hide();
body.showtab(ftab);
};
Tab ftab;
int tb_buf_mode = -1;
int tb_buf_key = -1;
public SWidgetOptions(Coord c, Widget parent) {
super(c, new Coord(345, 300), parent, "Options");
body = new Tabs(Coord.z, new Coord(345, 290), this);
Tab tab;
{ /* Highlight TAB */
tab = body.new Tab(new Coord(90, 10), 70, "Highlight") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Highlight options:");
final HideInfo hinfo = new HideInfo(new Coord(180, 60), new Coord(150, 200), tab);
new HideList(new Coord(20, 60), new Coord(150, 200), tab) {
@Override
protected void changed(HighlightInfo hl) {
hinfo.setCurrent(hl);
}
};
}
{ /* Toolbars TAB */
tab = body.new Tab(new Coord(170, 10), 70, "Toolbars") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Defined toolbars:");
final TextEntry hotkeyGrabber = new TextEntry(new Coord(180, 60), new Coord(80, 20), tab, "") {
@Override
public boolean type(char c, KeyEvent e){
return true;
}
@Override
public boolean keydown(KeyEvent event) {
int kcode = event.getKeyCode();
String hotkey = String.valueOf(KeyEvent.getKeyText(kcode)).toLowerCase();
if(hotkey.equals("shift") || hotkey.equals("ctrl") || hotkey.equals("alt"))
return true;
hotkey = hotkey.toUpperCase();
String mods = "";
if(event.isControlDown())
mods += "Ctrl+";
if(event.isAltDown())
mods += "Alt+";
if(event.isShiftDown())
mods += "Shift+";
settext(mods+hotkey);
tb_buf_mode = event.getModifiersEx();
tb_buf_key = event.getKeyCode();
return true;
}
};
final TextEntry toolbarName = new TextEntry(new Coord(20, 190), new Coord(90, 20), tab, "ToolbarName");
final SlotsList slotSet = new SlotsList(new Coord(180, 90), new Coord(150, 120), tab) {
@Override
protected void changed(int index) {
hotkeyGrabber.settext("");
}
};
final ToolbarsList toolbarsList = new ToolbarsList(new Coord(20, 60), new Coord(150, 120), tab, ToolbarsConfig.definedToolbars) {
@Override
protected void changed(int index) {
if (index == -1) return;
toolbarName.settext(getSelectedToolbar().tbName);
slotSet.setupToolbar(getSelectedToolbar());
}
};
new Button(new Coord(120, 190), 50, tab, "Add") {
@Override
public void click() {
if (!ToolbarsConfig.definedToolbars.containsKey(toolbarName.text)) {
toolbarsList.addToolbar(toolbarName.text);
}
};
};
new Button(new Coord(30, 220), 60, tab, "Remove") {
@Override
public void click() {
if (toolbarsList.getSelectedToolbar() != null) {
toolbarsList.removeCurrent();
slotSet.setupToolbar(null);
}
};
};
new Button(new Coord(100, 220), 60, tab, "Toggle") {
@Override
public void click() {
if (toolbarsList.getSelectedToolbar() != null) {
toolbarsList.toggleCurrent();
}
};
};
new Label(new Coord(220, 40), tab, "Toolbar settings:");
new Button(new Coord(270, 60), 60, tab, "Add") {
@Override
public void click() {
if (tb_buf_key > -1 && tb_buf_mode > -1)
slotSet.addSlot(tb_buf_mode, tb_buf_key);
};
};
new Button(new Coord(190, 220), 60, tab, "Set") {
@Override
public void click() {
if (tb_buf_key > -1 && tb_buf_mode > -1)
slotSet.setSlot(tb_buf_mode, tb_buf_key);
};
};
new Button(new Coord(260, 220), 60, tab, "Remove") {
@Override
public void click() {
slotSet.removeCurrent();
};
};
}
{ /* IRC TAB */
- tab = body.new Tab(new Coord(230, 10), 70, "IRC") {
+ tab = body.new Tab(new Coord(250, 10), 70, "IRC") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Enter IRC settings here. All changes will be saved.");
new Label(new Coord(20, 60), tab, "IRC Server:");
new TextEntry(new Coord(20, 80), new Coord(100, 20), tab, XConfig.mp_irc_server) {
@Override
public void changed() {
XConfig.mp_irc_server = this.text;
}
};
new Label(new Coord(20, 100), tab, "Username:");
new TextEntry(new Coord(20, 120), new Coord(100, 20), tab, XConfig.mp_irc_username) {
@Override
public void changed() {
XConfig.mp_irc_username = this.text;
}
};
new Label(new Coord(130, 100), tab, "Password:");
new TextEntry(new Coord(130, 120), new Coord(100, 20), tab, XConfig.mp_irc_password) {
@Override
public void changed() {
XConfig.mp_irc_password = this.text;
}
};
- CheckBox checkb = new CheckBox(new Coord(20, 180), tab, "Connect automatically") {
+ CheckBox checkb = new CheckBox(new Coord(20, 140), tab, "Connect automatically") {
@Override
public void changed(boolean val) {
XConfig.mp_irc_autoconnect = val;
}
};
checkb.set(XConfig.mp_irc_autoconnect);
- new Button(new Coord(40, 200), 50, tab, "Connect") {
+ new Button(new Coord(20, 180), 50, tab, "Connect") {
@Override
public void click() {
SChatWrapper.startIRCProvider();
}
};
}
{ /* General TAB */
GameUI gui = getparent(GameUI.class);
ftab = tab = body.new Tab(new Coord(10, 10), 70, "General") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Button(new Coord(200, 40), 120, tab, "Logout") {
@Override
public void click() {
ui.sess.close();
if(!XConfig.cl_render_on)
XConfig.cl_render_on = true;
}
};
new Label(new Coord(250, 190), tab, "SFX volume");
(new Scrollbar(new Coord(285, 85), 100, tab, 0, 100) {
{
val = max - XConfig.cl_sfx_volume;
}
@Override
public void changed() {
XConfig.cl_sfx_volume = max - val;
XMLConfigProvider.save();
double vol = (max-val)/100.;
Audio.setvolume(vol);
}
@Override
public Object tooltip(Coord c, boolean a) {
return Integer.toString(max - val);
}
@Override
public boolean mousewheel(Coord c, int amount) {
if(val+amount < min)
val = min;
else if(val+amount > max)
val = max;
else
val = val + amount;
changed();
return (true);
}
}).changed();
CheckBox checkb = new CheckBox(new Coord(20, 40), tab, "Toogle shadows") {
@Override
public void changed(boolean val) {
GameUI gui = getparent(GameUI.class);
if (gui != null) gui.setShadows(val);
}
};
if (gui != null) checkb.set(gui.togglesdw);
checkb = new CheckBox(new Coord(20, 80), tab, "Dump minimaps") {
@Override
public void changed(boolean val) {
XConfig.cl_dump_minimaps = val;
XMLConfigProvider.save();
}
};
checkb.set(XConfig.cl_dump_minimaps);
checkb = new CheckBox(new Coord(20, 120), tab, "New tempers") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_tempers = val;
GameUI gui = getparent(GameUI.class);
if (gui != null) gui.updateTempersToConfig();
XMLConfigProvider.save();
}
};
checkb.set(XConfig.cl_use_new_tempers);
new Label(new Coord(20, 160), tab, "Windows header align:");
final CheckBox[] aligns = new CheckBox[3];
aligns[0] = new CheckBox(new Coord(20, 170), tab, "Left") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_LEFT;
aligns[1].a = false;
aligns[2].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[1] = new CheckBox(new Coord(80, 170), tab, "Center") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_CENTER;
aligns[0].a = false;
aligns[2].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[2] = new CheckBox(new Coord(140, 170), tab, "Right") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_RIGHT;
aligns[0].a = false;
aligns[1].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[XConfig.cl_swindow_header_align].a = true;
checkb = new CheckBox(new Coord(20, 210), tab, "Use Free Camera") {
@Override
public void changed(boolean val) {
XConfig.cl_use_free_cam = val;
XMLConfigProvider.save();
GameUI ui = getparent(GameUI.class);
if (ui != null && ui.map != null) ui.map.setupCamera();
}
};
checkb.set(XConfig.cl_use_free_cam);
checkb = new CheckBox(new Coord(20, 250), tab, "Use New Chat") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_chat = val;
XMLConfigProvider.save();
GameUI ui = getparent(GameUI.class);
if (ui.bdsChatB != null) {
if (XConfig.cl_use_new_chat) {
ui.bdsChatB.show();
} else {
ui.bdsChatB.hide();
}
}
}
};
checkb.set(XConfig.cl_use_new_chat);
checkb = new CheckBox(new Coord(120, 250), tab, "Use New Toolbars") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_toolbars = val;
XMLConfigProvider.save();
ToolbarsConfig.updateToolbars(parent.ui.root);
}
};
checkb.set(XConfig.cl_use_new_toolbars);
}
body.showtab(ftab);
}
public static class HideInfo extends Widget {
protected HighlightInfo current;
protected CheckBox curCheck;
public HideInfo(Coord c, Coord sz, Widget parent) {
super(c, sz, parent);
curCheck = new CheckBox(new Coord(10, 90), this, "Visible");
curCheck.hide();
}
public void setCurrent(HighlightInfo hl) {
current = hl;
curCheck.show();
curCheck.a = hl.getBool();
}
@Override
public void wdgmsg(Widget sender, String msg, Object... args) {
if (sender == curCheck && msg.equals("ch")) {
boolean val = (Boolean) args[0];
current.setBool(val);
} else super.wdgmsg(sender, msg, args);
}
@Override
public void draw(GOut g) {
g.chcolor(0, 0, 0, 255);
g.frect(Coord.z, sz);
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
g.chcolor();
if (current != null) {
try {
g.image(current.getTex(), new Coord(10, 10), new Coord(40, 40));
g.atext(current.getTooltip(), new Coord(60, 30), 0, 0);
} catch (Loading e) {
g.image(WItem.missing.layer(Resource.imgc).tex(), new Coord(10, 10), new Coord(40, 40));
g.atext("...", new Coord(100, 30), 1, 1);
}
}
super.draw(g);
}
}
public static class HideList extends Widget {
private int h;
private Scrollbar sb;
private int sel;
public HighlightInfo[] hlList;
private final Comparator<HighlightInfo> hlComparator = new Comparator<HighlightInfo>() {
@Override
public int compare(HighlightInfo a, HighlightInfo b) {
return (a.getTooltip().compareTo(b.getTooltip()));
}
};
public HideList(Coord c, Coord sz, Widget parent) {
super(c, sz, parent);
h = sz.y / 20;
sel = -1;
sb = new Scrollbar(new Coord(sz.x, 0), sz.y, this, 0, 0);
updateList();
}
public void updateList() {
hlList = MinimapHighlightConfig.getHashMap().values().toArray(new HighlightInfo[MinimapHighlightConfig.getHashMap().size()]);
Arrays.sort(hlList, hlComparator);
sb.val = 0;
sb.max = hlList.length - h;
sel = -1;
}
@Override
public void draw(GOut g) {
g.chcolor(0, 0, 0, 255);
g.frect(Coord.z, sz);
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
g.chcolor();
for (int i = 0; i < h; i++) {
if (i + sb.val >= hlList.length) continue;
HighlightInfo hl = hlList[i + sb.val];
if (i + sb.val == sel) {
g.chcolor(255, 255, 0, 128);
g.frect(new Coord(0, i * 20), new Coord(sz.x, 20));
g.chcolor();
}
try {
g.image(hl.getTex(), new Coord(0, i * 20), new Coord(20, 20));
if (hl.getBool()) {
g.chcolor(128, 255, 128, 255);
} else {
g.chcolor(255, 128, 128, 255);
}
g.atext(hl.getTooltip(), new Coord(25, i * 20 + 10), 0, 0.5);
} catch (Loading e) {
g.image(WItem.missing.layer(Resource.imgc).tex(), new Coord(0, i * 20), new Coord(20, 20));
g.atext("...", new Coord(25, i * 20 + 10), 0, 0.5);
}
g.chcolor();
}
super.draw(g);
}
@Override
public boolean mousewheel(Coord c, int amount) {
sb.ch(amount);
return (true);
}
@Override
public boolean mousedown(Coord c, int button) {
if (super.mousedown(c, button))
return (true);
if (button == 1) {
sel = (c.y / 20) + sb.val;
if (sel >= hlList.length)
sel = -1;
changed((sel < 0) ? null : hlList[sel]);
return (true);
}
return (false);
}
protected void changed(HighlightInfo hl) {
}
public void unsel() {
sel = -1;
changed(null);
}
}
public static class TextList extends Widget {
private int iCannotRememberWhyDoINeedThisVariable;
private Scrollbar scrollbar;
private int selectedIndex;
private ArrayList<String> textList;
public TextList(Coord c, Coord sz, Widget parent) {
super(c, sz, parent);
iCannotRememberWhyDoINeedThisVariable = sz.y / 20;
scrollbar = new Scrollbar(new Coord(sz.x, 0), sz.y, this, 0, 0);
scrollbar.val = 0;
selectedIndex = -1;
textList = new ArrayList<String>();
}
public void addText(String text) {
textList.add(text);
scrollbar.max = textList.size() - iCannotRememberWhyDoINeedThisVariable;
}
public String getSelectedText() {
if (selectedIndex >= 0 && selectedIndex < textList.size()) return textList.get(selectedIndex);
return null;
}
public int getSelectedIndex() {
return selectedIndex;
}
public void removeCurrent() {
textList.remove(selectedIndex);
scrollbar.max = textList.size() - iCannotRememberWhyDoINeedThisVariable;
selectedIndex = -1;
}
@Override
public void draw(GOut g) {
g.chcolor(0, 0, 0, 255);
g.frect(Coord.z, sz);
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
g.chcolor();
for (int i = 0; i < iCannotRememberWhyDoINeedThisVariable; i++) {
if (i + scrollbar.val >= textList.size()) continue;
String hl = textList.get(i + scrollbar.val);
if (i + scrollbar.val == selectedIndex) {
g.chcolor(255, 255, 0, 128);
g.frect(new Coord(0, i * 20), new Coord(sz.x, 20));
g.chcolor();
}
g.atext(hl, new Coord(25, i * 20 + 10), 0, 0.5);
g.chcolor();
}
super.draw(g);
}
@Override
public boolean mousewheel(Coord c, int amount) {
scrollbar.ch(amount);
return (true);
}
@Override
public boolean mousedown(Coord c, int button) {
if (super.mousedown(c, button))
return (true);
if (button == 1) {
selectedIndex = (c.y / 20) + scrollbar.val;
if (selectedIndex >= textList.size())
selectedIndex = -1;
changed(selectedIndex);
return (true);
}
return (false);
}
protected void changed(int index) {
}
public void unsel() {
selectedIndex = -1;
changed(selectedIndex);
}
}
/* Toolbars */
public static class ToolbarsList extends Widget {
private int iCannotRememberWhyDoINeedThisVariable;
private Scrollbar scrollbar;
private int selectedIndex;
private ArrayList<String> textListBuf;
private HashMap<String, ToolbarsConfig> toolbarsMap;
public ToolbarsList(Coord c, Coord sz, Widget parent, HashMap<String, ToolbarsConfig> tbMap) {
super(c, sz, parent);
iCannotRememberWhyDoINeedThisVariable = sz.y / 20;
scrollbar = new Scrollbar(new Coord(sz.x, 0), sz.y, this, 0, 0);
scrollbar.val = 0;
toolbarsMap = tbMap;
selectedIndex = -1;
textListBuf = new ArrayList<String>();
for (String str : toolbarsMap.keySet()) {
textListBuf.add(str);
}
}
public void addToolbar(String text) {
ToolbarsConfig newtb = new ToolbarsConfig(text);
toolbarsMap.put(text, newtb);
textListBuf.add(text);
scrollbar.max = textListBuf.size() - iCannotRememberWhyDoINeedThisVariable;
}
public ToolbarsConfig getSelectedToolbar() {
if (selectedIndex >= 0 && selectedIndex < textListBuf.size()) return toolbarsMap.get(textListBuf.get(selectedIndex));
return null;
}
public int getSelectedIndex() {
return selectedIndex;
}
public void removeCurrent() {
toolbarsMap.remove(textListBuf.get(selectedIndex));
textListBuf.remove(selectedIndex);
scrollbar.max = textListBuf.size() - iCannotRememberWhyDoINeedThisVariable;
selectedIndex = -1;
}
public void toggleCurrent() {
ToolbarsConfig tbcfg = getSelectedToolbar();
if (tbcfg != null) {
tbcfg.toggle();
}
}
@Override
public void draw(GOut g) {
g.chcolor(0, 0, 0, 255);
g.frect(Coord.z, sz);
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
g.chcolor();
for (int i = 0; i < iCannotRememberWhyDoINeedThisVariable; i++) {
if (i + scrollbar.val >= textListBuf.size()) continue;
String hl = textListBuf.get(i + scrollbar.val);
ToolbarsConfig tbc = toolbarsMap.get(hl);
if (i + scrollbar.val == selectedIndex) {
g.chcolor(255, 255, 0, 128);
g.frect(new Coord(0, i * 20), new Coord(sz.x, 20));
g.chcolor();
}
if (tbc.enabled)
g.chcolor(0, 255, 0, 192);
else
g.chcolor(255, 255, 255, 192);
g.atext(hl, new Coord(5, i * 20 + 10), 0, 0.5);
g.chcolor();
}
super.draw(g);
}
@Override
public boolean mousewheel(Coord c, int amount) {
scrollbar.ch(amount);
return (true);
}
@Override
public boolean mousedown(Coord c, int button) {
if (super.mousedown(c, button))
return (true);
if (button == 1) {
selectedIndex = (c.y / 20) + scrollbar.val;
if (selectedIndex >= textListBuf.size())
selectedIndex = -1;
changed(selectedIndex);
return (true);
}
return (false);
}
protected void changed(int index) {
}
public void unsel() {
selectedIndex = -1;
changed(selectedIndex);
}
}
public static class SlotsList extends Widget {
private int iCannotRememberWhyDoINeedThisVariable;
private Scrollbar scrollbar;
private int selectedIndex;
private ToolbarsConfig assocedToolbar;
public SlotsList(Coord c, Coord sz, Widget parent) {
super(c, sz, parent);
iCannotRememberWhyDoINeedThisVariable = sz.y / 20;
scrollbar = new Scrollbar(new Coord(sz.x, 0), sz.y, this, 0, 0);
scrollbar.val = 0;
selectedIndex = -1;
}
public void setSlot(int mode, int key) {
TBSlot slot = getSelectedSlot();
if (slot != null) {
slot.sKey = key;
slot.sMode = mode;
slot.rebuildString();
}
}
public void setupToolbar(ToolbarsConfig tb) {
assocedToolbar = tb;
scrollbar.max = size() - iCannotRememberWhyDoINeedThisVariable;
}
public int size() {
if (assocedToolbar != null) {
return assocedToolbar.slotList.size();
} else return 0;
}
public void addSlot(int mode, int key) {
TBSlot slot = new TBSlot(mode, key);
if (assocedToolbar != null)
assocedToolbar.slotList.add(slot);
scrollbar.max = size() - iCannotRememberWhyDoINeedThisVariable;
}
public TBSlot getSelectedSlot() {
if (selectedIndex >= 0 && selectedIndex < size()) return assocedToolbar.slotList.get(selectedIndex);
return null;
}
public int getSelectedIndex() {
return selectedIndex;
}
public void removeCurrent() {
if (size() <= 0 || selectedIndex < 0) return;
assocedToolbar.slotList.remove(selectedIndex);
scrollbar.max = size() - iCannotRememberWhyDoINeedThisVariable;
selectedIndex = -1;
}
@Override
public void draw(GOut g) {
g.chcolor(0, 0, 0, 255);
g.frect(Coord.z, sz);
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
g.chcolor();
for (int i = 0; i < iCannotRememberWhyDoINeedThisVariable; i++) {
if (i + scrollbar.val >= size()) continue;
TBSlot hl = assocedToolbar.slotList.get(i + scrollbar.val);
if (i + scrollbar.val == selectedIndex) {
g.chcolor(255, 255, 0, 128);
g.frect(new Coord(0, i * 20), new Coord(sz.x, 20));
g.chcolor();
}
g.atext(hl.getString(), new Coord(5, i * 20 + 10), 0, 0.5);
g.chcolor();
}
super.draw(g);
}
@Override
public boolean mousewheel(Coord c, int amount) {
scrollbar.ch(amount);
return (true);
}
@Override
public boolean mousedown(Coord c, int button) {
if (super.mousedown(c, button))
return (true);
if (button == 1) {
selectedIndex = (c.y / 20) + scrollbar.val;
if (selectedIndex >= size())
selectedIndex = -1;
changed(selectedIndex);
return (true);
}
return (false);
}
protected void changed(int index) {
}
public void unsel() {
selectedIndex = -1;
changed(selectedIndex);
}
}
}
| false | true | public SWidgetOptions(Coord c, Widget parent) {
super(c, new Coord(345, 300), parent, "Options");
body = new Tabs(Coord.z, new Coord(345, 290), this);
Tab tab;
{ /* Highlight TAB */
tab = body.new Tab(new Coord(90, 10), 70, "Highlight") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Highlight options:");
final HideInfo hinfo = new HideInfo(new Coord(180, 60), new Coord(150, 200), tab);
new HideList(new Coord(20, 60), new Coord(150, 200), tab) {
@Override
protected void changed(HighlightInfo hl) {
hinfo.setCurrent(hl);
}
};
}
{ /* Toolbars TAB */
tab = body.new Tab(new Coord(170, 10), 70, "Toolbars") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Defined toolbars:");
final TextEntry hotkeyGrabber = new TextEntry(new Coord(180, 60), new Coord(80, 20), tab, "") {
@Override
public boolean type(char c, KeyEvent e){
return true;
}
@Override
public boolean keydown(KeyEvent event) {
int kcode = event.getKeyCode();
String hotkey = String.valueOf(KeyEvent.getKeyText(kcode)).toLowerCase();
if(hotkey.equals("shift") || hotkey.equals("ctrl") || hotkey.equals("alt"))
return true;
hotkey = hotkey.toUpperCase();
String mods = "";
if(event.isControlDown())
mods += "Ctrl+";
if(event.isAltDown())
mods += "Alt+";
if(event.isShiftDown())
mods += "Shift+";
settext(mods+hotkey);
tb_buf_mode = event.getModifiersEx();
tb_buf_key = event.getKeyCode();
return true;
}
};
final TextEntry toolbarName = new TextEntry(new Coord(20, 190), new Coord(90, 20), tab, "ToolbarName");
final SlotsList slotSet = new SlotsList(new Coord(180, 90), new Coord(150, 120), tab) {
@Override
protected void changed(int index) {
hotkeyGrabber.settext("");
}
};
final ToolbarsList toolbarsList = new ToolbarsList(new Coord(20, 60), new Coord(150, 120), tab, ToolbarsConfig.definedToolbars) {
@Override
protected void changed(int index) {
if (index == -1) return;
toolbarName.settext(getSelectedToolbar().tbName);
slotSet.setupToolbar(getSelectedToolbar());
}
};
new Button(new Coord(120, 190), 50, tab, "Add") {
@Override
public void click() {
if (!ToolbarsConfig.definedToolbars.containsKey(toolbarName.text)) {
toolbarsList.addToolbar(toolbarName.text);
}
};
};
new Button(new Coord(30, 220), 60, tab, "Remove") {
@Override
public void click() {
if (toolbarsList.getSelectedToolbar() != null) {
toolbarsList.removeCurrent();
slotSet.setupToolbar(null);
}
};
};
new Button(new Coord(100, 220), 60, tab, "Toggle") {
@Override
public void click() {
if (toolbarsList.getSelectedToolbar() != null) {
toolbarsList.toggleCurrent();
}
};
};
new Label(new Coord(220, 40), tab, "Toolbar settings:");
new Button(new Coord(270, 60), 60, tab, "Add") {
@Override
public void click() {
if (tb_buf_key > -1 && tb_buf_mode > -1)
slotSet.addSlot(tb_buf_mode, tb_buf_key);
};
};
new Button(new Coord(190, 220), 60, tab, "Set") {
@Override
public void click() {
if (tb_buf_key > -1 && tb_buf_mode > -1)
slotSet.setSlot(tb_buf_mode, tb_buf_key);
};
};
new Button(new Coord(260, 220), 60, tab, "Remove") {
@Override
public void click() {
slotSet.removeCurrent();
};
};
}
{ /* IRC TAB */
tab = body.new Tab(new Coord(230, 10), 70, "IRC") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Enter IRC settings here. All changes will be saved.");
new Label(new Coord(20, 60), tab, "IRC Server:");
new TextEntry(new Coord(20, 80), new Coord(100, 20), tab, XConfig.mp_irc_server) {
@Override
public void changed() {
XConfig.mp_irc_server = this.text;
}
};
new Label(new Coord(20, 100), tab, "Username:");
new TextEntry(new Coord(20, 120), new Coord(100, 20), tab, XConfig.mp_irc_username) {
@Override
public void changed() {
XConfig.mp_irc_username = this.text;
}
};
new Label(new Coord(130, 100), tab, "Password:");
new TextEntry(new Coord(130, 120), new Coord(100, 20), tab, XConfig.mp_irc_password) {
@Override
public void changed() {
XConfig.mp_irc_password = this.text;
}
};
CheckBox checkb = new CheckBox(new Coord(20, 180), tab, "Connect automatically") {
@Override
public void changed(boolean val) {
XConfig.mp_irc_autoconnect = val;
}
};
checkb.set(XConfig.mp_irc_autoconnect);
new Button(new Coord(40, 200), 50, tab, "Connect") {
@Override
public void click() {
SChatWrapper.startIRCProvider();
}
};
}
{ /* General TAB */
GameUI gui = getparent(GameUI.class);
ftab = tab = body.new Tab(new Coord(10, 10), 70, "General") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Button(new Coord(200, 40), 120, tab, "Logout") {
@Override
public void click() {
ui.sess.close();
if(!XConfig.cl_render_on)
XConfig.cl_render_on = true;
}
};
new Label(new Coord(250, 190), tab, "SFX volume");
(new Scrollbar(new Coord(285, 85), 100, tab, 0, 100) {
{
val = max - XConfig.cl_sfx_volume;
}
@Override
public void changed() {
XConfig.cl_sfx_volume = max - val;
XMLConfigProvider.save();
double vol = (max-val)/100.;
Audio.setvolume(vol);
}
@Override
public Object tooltip(Coord c, boolean a) {
return Integer.toString(max - val);
}
@Override
public boolean mousewheel(Coord c, int amount) {
if(val+amount < min)
val = min;
else if(val+amount > max)
val = max;
else
val = val + amount;
changed();
return (true);
}
}).changed();
CheckBox checkb = new CheckBox(new Coord(20, 40), tab, "Toogle shadows") {
@Override
public void changed(boolean val) {
GameUI gui = getparent(GameUI.class);
if (gui != null) gui.setShadows(val);
}
};
if (gui != null) checkb.set(gui.togglesdw);
checkb = new CheckBox(new Coord(20, 80), tab, "Dump minimaps") {
@Override
public void changed(boolean val) {
XConfig.cl_dump_minimaps = val;
XMLConfigProvider.save();
}
};
checkb.set(XConfig.cl_dump_minimaps);
checkb = new CheckBox(new Coord(20, 120), tab, "New tempers") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_tempers = val;
GameUI gui = getparent(GameUI.class);
if (gui != null) gui.updateTempersToConfig();
XMLConfigProvider.save();
}
};
checkb.set(XConfig.cl_use_new_tempers);
new Label(new Coord(20, 160), tab, "Windows header align:");
final CheckBox[] aligns = new CheckBox[3];
aligns[0] = new CheckBox(new Coord(20, 170), tab, "Left") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_LEFT;
aligns[1].a = false;
aligns[2].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[1] = new CheckBox(new Coord(80, 170), tab, "Center") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_CENTER;
aligns[0].a = false;
aligns[2].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[2] = new CheckBox(new Coord(140, 170), tab, "Right") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_RIGHT;
aligns[0].a = false;
aligns[1].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[XConfig.cl_swindow_header_align].a = true;
checkb = new CheckBox(new Coord(20, 210), tab, "Use Free Camera") {
@Override
public void changed(boolean val) {
XConfig.cl_use_free_cam = val;
XMLConfigProvider.save();
GameUI ui = getparent(GameUI.class);
if (ui != null && ui.map != null) ui.map.setupCamera();
}
};
checkb.set(XConfig.cl_use_free_cam);
checkb = new CheckBox(new Coord(20, 250), tab, "Use New Chat") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_chat = val;
XMLConfigProvider.save();
GameUI ui = getparent(GameUI.class);
if (ui.bdsChatB != null) {
if (XConfig.cl_use_new_chat) {
ui.bdsChatB.show();
} else {
ui.bdsChatB.hide();
}
}
}
};
checkb.set(XConfig.cl_use_new_chat);
checkb = new CheckBox(new Coord(120, 250), tab, "Use New Toolbars") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_toolbars = val;
XMLConfigProvider.save();
ToolbarsConfig.updateToolbars(parent.ui.root);
}
};
checkb.set(XConfig.cl_use_new_toolbars);
}
body.showtab(ftab);
}
| public SWidgetOptions(Coord c, Widget parent) {
super(c, new Coord(345, 300), parent, "Options");
body = new Tabs(Coord.z, new Coord(345, 290), this);
Tab tab;
{ /* Highlight TAB */
tab = body.new Tab(new Coord(90, 10), 70, "Highlight") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Highlight options:");
final HideInfo hinfo = new HideInfo(new Coord(180, 60), new Coord(150, 200), tab);
new HideList(new Coord(20, 60), new Coord(150, 200), tab) {
@Override
protected void changed(HighlightInfo hl) {
hinfo.setCurrent(hl);
}
};
}
{ /* Toolbars TAB */
tab = body.new Tab(new Coord(170, 10), 70, "Toolbars") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Defined toolbars:");
final TextEntry hotkeyGrabber = new TextEntry(new Coord(180, 60), new Coord(80, 20), tab, "") {
@Override
public boolean type(char c, KeyEvent e){
return true;
}
@Override
public boolean keydown(KeyEvent event) {
int kcode = event.getKeyCode();
String hotkey = String.valueOf(KeyEvent.getKeyText(kcode)).toLowerCase();
if(hotkey.equals("shift") || hotkey.equals("ctrl") || hotkey.equals("alt"))
return true;
hotkey = hotkey.toUpperCase();
String mods = "";
if(event.isControlDown())
mods += "Ctrl+";
if(event.isAltDown())
mods += "Alt+";
if(event.isShiftDown())
mods += "Shift+";
settext(mods+hotkey);
tb_buf_mode = event.getModifiersEx();
tb_buf_key = event.getKeyCode();
return true;
}
};
final TextEntry toolbarName = new TextEntry(new Coord(20, 190), new Coord(90, 20), tab, "ToolbarName");
final SlotsList slotSet = new SlotsList(new Coord(180, 90), new Coord(150, 120), tab) {
@Override
protected void changed(int index) {
hotkeyGrabber.settext("");
}
};
final ToolbarsList toolbarsList = new ToolbarsList(new Coord(20, 60), new Coord(150, 120), tab, ToolbarsConfig.definedToolbars) {
@Override
protected void changed(int index) {
if (index == -1) return;
toolbarName.settext(getSelectedToolbar().tbName);
slotSet.setupToolbar(getSelectedToolbar());
}
};
new Button(new Coord(120, 190), 50, tab, "Add") {
@Override
public void click() {
if (!ToolbarsConfig.definedToolbars.containsKey(toolbarName.text)) {
toolbarsList.addToolbar(toolbarName.text);
}
};
};
new Button(new Coord(30, 220), 60, tab, "Remove") {
@Override
public void click() {
if (toolbarsList.getSelectedToolbar() != null) {
toolbarsList.removeCurrent();
slotSet.setupToolbar(null);
}
};
};
new Button(new Coord(100, 220), 60, tab, "Toggle") {
@Override
public void click() {
if (toolbarsList.getSelectedToolbar() != null) {
toolbarsList.toggleCurrent();
}
};
};
new Label(new Coord(220, 40), tab, "Toolbar settings:");
new Button(new Coord(270, 60), 60, tab, "Add") {
@Override
public void click() {
if (tb_buf_key > -1 && tb_buf_mode > -1)
slotSet.addSlot(tb_buf_mode, tb_buf_key);
};
};
new Button(new Coord(190, 220), 60, tab, "Set") {
@Override
public void click() {
if (tb_buf_key > -1 && tb_buf_mode > -1)
slotSet.setSlot(tb_buf_mode, tb_buf_key);
};
};
new Button(new Coord(260, 220), 60, tab, "Remove") {
@Override
public void click() {
slotSet.removeCurrent();
};
};
}
{ /* IRC TAB */
tab = body.new Tab(new Coord(250, 10), 70, "IRC") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Label(new Coord(20, 40), tab, "Enter IRC settings here. All changes will be saved.");
new Label(new Coord(20, 60), tab, "IRC Server:");
new TextEntry(new Coord(20, 80), new Coord(100, 20), tab, XConfig.mp_irc_server) {
@Override
public void changed() {
XConfig.mp_irc_server = this.text;
}
};
new Label(new Coord(20, 100), tab, "Username:");
new TextEntry(new Coord(20, 120), new Coord(100, 20), tab, XConfig.mp_irc_username) {
@Override
public void changed() {
XConfig.mp_irc_username = this.text;
}
};
new Label(new Coord(130, 100), tab, "Password:");
new TextEntry(new Coord(130, 120), new Coord(100, 20), tab, XConfig.mp_irc_password) {
@Override
public void changed() {
XConfig.mp_irc_password = this.text;
}
};
CheckBox checkb = new CheckBox(new Coord(20, 140), tab, "Connect automatically") {
@Override
public void changed(boolean val) {
XConfig.mp_irc_autoconnect = val;
}
};
checkb.set(XConfig.mp_irc_autoconnect);
new Button(new Coord(20, 180), 50, tab, "Connect") {
@Override
public void click() {
SChatWrapper.startIRCProvider();
}
};
}
{ /* General TAB */
GameUI gui = getparent(GameUI.class);
ftab = tab = body.new Tab(new Coord(10, 10), 70, "General") {
@Override
public void draw(GOut g) {
g.chcolor(255, 255, 255, 255);
g.rect(Coord.z, sz.add(1, 1));
super.draw(g);
}
};
new Button(new Coord(200, 40), 120, tab, "Logout") {
@Override
public void click() {
ui.sess.close();
if(!XConfig.cl_render_on)
XConfig.cl_render_on = true;
}
};
new Label(new Coord(250, 190), tab, "SFX volume");
(new Scrollbar(new Coord(285, 85), 100, tab, 0, 100) {
{
val = max - XConfig.cl_sfx_volume;
}
@Override
public void changed() {
XConfig.cl_sfx_volume = max - val;
XMLConfigProvider.save();
double vol = (max-val)/100.;
Audio.setvolume(vol);
}
@Override
public Object tooltip(Coord c, boolean a) {
return Integer.toString(max - val);
}
@Override
public boolean mousewheel(Coord c, int amount) {
if(val+amount < min)
val = min;
else if(val+amount > max)
val = max;
else
val = val + amount;
changed();
return (true);
}
}).changed();
CheckBox checkb = new CheckBox(new Coord(20, 40), tab, "Toogle shadows") {
@Override
public void changed(boolean val) {
GameUI gui = getparent(GameUI.class);
if (gui != null) gui.setShadows(val);
}
};
if (gui != null) checkb.set(gui.togglesdw);
checkb = new CheckBox(new Coord(20, 80), tab, "Dump minimaps") {
@Override
public void changed(boolean val) {
XConfig.cl_dump_minimaps = val;
XMLConfigProvider.save();
}
};
checkb.set(XConfig.cl_dump_minimaps);
checkb = new CheckBox(new Coord(20, 120), tab, "New tempers") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_tempers = val;
GameUI gui = getparent(GameUI.class);
if (gui != null) gui.updateTempersToConfig();
XMLConfigProvider.save();
}
};
checkb.set(XConfig.cl_use_new_tempers);
new Label(new Coord(20, 160), tab, "Windows header align:");
final CheckBox[] aligns = new CheckBox[3];
aligns[0] = new CheckBox(new Coord(20, 170), tab, "Left") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_LEFT;
aligns[1].a = false;
aligns[2].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[1] = new CheckBox(new Coord(80, 170), tab, "Center") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_CENTER;
aligns[0].a = false;
aligns[2].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[2] = new CheckBox(new Coord(140, 170), tab, "Right") {
@Override
public void changed(boolean val) {
XConfig.cl_swindow_header_align = SWindow.HEADER_ALIGN_RIGHT;
aligns[0].a = false;
aligns[1].a = false;
GameUI ui = getparent(GameUI.class);
if (ui != null) ui.updateWindowStyle();
XMLConfigProvider.save();
}
};
aligns[XConfig.cl_swindow_header_align].a = true;
checkb = new CheckBox(new Coord(20, 210), tab, "Use Free Camera") {
@Override
public void changed(boolean val) {
XConfig.cl_use_free_cam = val;
XMLConfigProvider.save();
GameUI ui = getparent(GameUI.class);
if (ui != null && ui.map != null) ui.map.setupCamera();
}
};
checkb.set(XConfig.cl_use_free_cam);
checkb = new CheckBox(new Coord(20, 250), tab, "Use New Chat") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_chat = val;
XMLConfigProvider.save();
GameUI ui = getparent(GameUI.class);
if (ui.bdsChatB != null) {
if (XConfig.cl_use_new_chat) {
ui.bdsChatB.show();
} else {
ui.bdsChatB.hide();
}
}
}
};
checkb.set(XConfig.cl_use_new_chat);
checkb = new CheckBox(new Coord(120, 250), tab, "Use New Toolbars") {
@Override
public void changed(boolean val) {
XConfig.cl_use_new_toolbars = val;
XMLConfigProvider.save();
ToolbarsConfig.updateToolbars(parent.ui.root);
}
};
checkb.set(XConfig.cl_use_new_toolbars);
}
body.showtab(ftab);
}
|
diff --git a/src/com/pindroid/util/StringUtils.java b/src/com/pindroid/util/StringUtils.java
index 75235af..7a1f052 100644
--- a/src/com/pindroid/util/StringUtils.java
+++ b/src/com/pindroid/util/StringUtils.java
@@ -1,51 +1,51 @@
/*
* PinDroid - http://code.google.com/p/PinDroid/
*
* Copyright (C) 2010 Matt Schmidt
*
* PinDroid 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.
*
* PinDroid 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 PinDroid; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package com.pindroid.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
public static String capitalize(String s) {
if (s.length() == 0) return s;
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public static String getUrl(String s) {
String result = "";
- Pattern pattern = Pattern.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;()]*[-a-zA-Z0-9+&@#/%=~_|()]");
+ Pattern pattern = Pattern.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&@'#/%?=~_|!:,.;()]*[-a-zA-Z0-9+&@'#/%=~_|()]");
try{
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
result = s.substring(matcher.start(), matcher.end());
}
}
catch(Exception e){
result = "";
}
return result;
}
}
| true | true | public static String getUrl(String s) {
String result = "";
Pattern pattern = Pattern.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;()]*[-a-zA-Z0-9+&@#/%=~_|()]");
try{
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
result = s.substring(matcher.start(), matcher.end());
}
}
catch(Exception e){
result = "";
}
return result;
}
| public static String getUrl(String s) {
String result = "";
Pattern pattern = Pattern.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&@'#/%?=~_|!:,.;()]*[-a-zA-Z0-9+&@'#/%=~_|()]");
try{
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
result = s.substring(matcher.start(), matcher.end());
}
}
catch(Exception e){
result = "";
}
return result;
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index a521d67a..d5b58590 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1484 +1,1484 @@
/*
* 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.launcher2;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;
import android.os.Process;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import com.android.launcher.R;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
private int mBatchSize; // 0 is all apps at once
private int mAllAppsLoadDelay; // milliseconds between batches
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private Loader mLoader = new Loader();
private boolean mBeforeFirstLoad = true; // only access this from main thread
private WeakReference<Callbacks> mCallbacks;
private AllAppsList mAllAppsList;
private IconCache mIconCache;
private Bitmap mDefaultIcon;
public interface Callbacks {
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
public void bindAppsRemoved(ArrayList<ApplicationInfo> apps);
}
LauncherModel(LauncherApplication app, IconCache iconCache) {
mApp = app;
mAllAppsList = new AllAppsList(iconCache);
mIconCache = iconCache;
mDefaultIcon = Utilities.createIconBitmap(
app.getPackageManager().getDefaultActivityIcon(), app);
mAllAppsLoadDelay = app.getResources().getInteger(R.integer.config_allAppsBatchLoadDelay);
mBatchSize = app.getResources().getInteger(R.integer.config_allAppsBatchSize);
}
public Bitmap getFallbackIcon() {
return Bitmap.createBitmap(mDefaultIcon);
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
int cellX, int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsAdded(addedFinal);
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsUpdated(modifiedFinal);
}
});
}
if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsRemoved(removedFinal);
}
});
}
} else {
if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
}
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Whew! Hard work done.
synchronized (mLock) {
if (mIsLaunching) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAndBindAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
updateSavedIcon(context, info, c, iconIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
Uri uri = Uri.parse(c.getString(uriIndex));
// Make sure the live folder exists
final ProviderInfo providerInfo =
context.getPackageManager().resolveContentProvider(
uri.getAuthority(), 0);
if (providerInfo == null && !isSafeMode) {
itemsToRemove.add(id);
} else {
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
liveFolderInfo.uri = uri;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAndBindAllApps() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
synchronized (mLock) {
if (i == 0) {
// This needs to happen inside the same lock block as when we
// prepare the first batch for bindAllApplications. Otherwise
// the package changed receiver can come in and double-add
// (or miss one?).
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new ResolveInfo.DisplayNameComparator(packageManager));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache));
i++;
}
final boolean first = i <= batchSize;
+ final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
- final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
if (first) {
mBeforeFirstLoad = false;
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
info.title = resolveInfo.activityInfo.loadLabel(manager);
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
CellLayout.CellInfo cellInfo, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
return info;
}
private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean filtered = false;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
filtered = true;
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id),
context);
} catch (Exception e) {
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens either
// after the froyo OTA or when the app is updated with a new
// icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
| false | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsAdded(addedFinal);
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsUpdated(modifiedFinal);
}
});
}
if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsRemoved(removedFinal);
}
});
}
} else {
if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
}
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Whew! Hard work done.
synchronized (mLock) {
if (mIsLaunching) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAndBindAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
updateSavedIcon(context, info, c, iconIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
Uri uri = Uri.parse(c.getString(uriIndex));
// Make sure the live folder exists
final ProviderInfo providerInfo =
context.getPackageManager().resolveContentProvider(
uri.getAuthority(), 0);
if (providerInfo == null && !isSafeMode) {
itemsToRemove.add(id);
} else {
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
liveFolderInfo.uri = uri;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAndBindAllApps() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
synchronized (mLock) {
if (i == 0) {
// This needs to happen inside the same lock block as when we
// prepare the first batch for bindAllApplications. Otherwise
// the package changed receiver can come in and double-add
// (or miss one?).
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new ResolveInfo.DisplayNameComparator(packageManager));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache));
i++;
}
final boolean first = i <= batchSize;
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
if (first) {
mBeforeFirstLoad = false;
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
info.title = resolveInfo.activityInfo.loadLabel(manager);
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
CellLayout.CellInfo cellInfo, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
return info;
}
private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean filtered = false;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
filtered = true;
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id),
context);
} catch (Exception e) {
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens either
// after the froyo OTA or when the app is updated with a new
// icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsAdded(addedFinal);
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsUpdated(modifiedFinal);
}
});
}
if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindAppsRemoved(removedFinal);
}
});
}
} else {
if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String packages[] = intent.getStringArrayExtra(
Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (packages == null || packages.length == 0) {
return;
}
setAllAppsDirty();
setWorkspaceDirty();
startLoader(context, false);
}
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Whew! Hard work done.
synchronized (mLock) {
if (mIsLaunching) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAndBindAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
updateSavedIcon(context, info, c, iconIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
Uri uri = Uri.parse(c.getString(uriIndex));
// Make sure the live folder exists
final ProviderInfo providerInfo =
context.getPackageManager().resolveContentProvider(
uri.getAuthority(), 0);
if (providerInfo == null && !isSafeMode) {
itemsToRemove.add(id);
} else {
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
liveFolderInfo.uri = uri;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAndBindAllApps() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher (loadAndBindAllApps)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
synchronized (mLock) {
if (i == 0) {
// This needs to happen inside the same lock block as when we
// prepare the first batch for bindAllApplications. Otherwise
// the package changed receiver can come in and double-add
// (or miss one?).
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new ResolveInfo.DisplayNameComparator(packageManager));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
mBeforeFirstLoad = false;
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
info.title = resolveInfo.activityInfo.loadLabel(manager);
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
CellLayout.CellInfo cellInfo, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
return info;
}
private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean filtered = false;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
filtered = true;
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(resources.getDrawable(id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id),
context);
} catch (Exception e) {
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon = Utilities.createIconBitmap(
context.getResources().getDrawable(R.drawable.ic_launcher_folder),
context);
}
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens either
// after the froyo OTA or when the app is updated with a new
// icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
|
diff --git a/docdoku-server/docdoku-server-web/src/main/java/com/docdoku/server/rest/dto/TagDTO.java b/docdoku-server/docdoku-server-web/src/main/java/com/docdoku/server/rest/dto/TagDTO.java
index 67affa170..72d80c827 100644
--- a/docdoku-server/docdoku-server-web/src/main/java/com/docdoku/server/rest/dto/TagDTO.java
+++ b/docdoku-server/docdoku-server-web/src/main/java/com/docdoku/server/rest/dto/TagDTO.java
@@ -1,77 +1,78 @@
/*
* DocDoku, Professional Open Source
* Copyright 2006 - 2013 DocDoku SARL
*
* This file is part of DocDokuPLM.
*
* DocDokuPLM 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.
*
* DocDokuPLM 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 DocDokuPLM. If not, see <http://www.gnu.org/licenses/>.
*/
package com.docdoku.server.rest.dto;
import javax.xml.bind.annotation.XmlElement;
import java.io.Serializable;
/**
*
* @author Yassine Belouad
*/
public class TagDTO implements Serializable {
@XmlElement(nillable = true)
private String id;
@XmlElement(nillable = true)
private String label;
@XmlElement(nillable = true)
private String workspaceId;
public TagDTO(){
}
public TagDTO(String label){
this.label=label;
}
public TagDTO(String label, String workspaceId) {
+ this.id = label;
this.label = label;
this.workspaceId = workspaceId;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getWorkspaceId() {
return workspaceId;
}
public String getId() {
id= this.label;
return id;
}
public void setId(String id) {
this.id = id;
}
public void setWorkspaceId(String workspaceId) {
this.workspaceId = workspaceId;
}
}
| true | true | public TagDTO(String label, String workspaceId) {
this.label = label;
this.workspaceId = workspaceId;
}
| public TagDTO(String label, String workspaceId) {
this.id = label;
this.label = label;
this.workspaceId = workspaceId;
}
|
diff --git a/main/src/java/de/hunsicker/jalopy/printer/ParametersPrinter.java b/main/src/java/de/hunsicker/jalopy/printer/ParametersPrinter.java
index ca92b75..2891d65 100644
--- a/main/src/java/de/hunsicker/jalopy/printer/ParametersPrinter.java
+++ b/main/src/java/de/hunsicker/jalopy/printer/ParametersPrinter.java
@@ -1,1423 +1,1424 @@
/*
* Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package de.hunsicker.jalopy.printer;
import java.io.IOException;
import antlr.collections.AST;
import de.hunsicker.jalopy.language.JavaNode;
import de.hunsicker.jalopy.language.JavaNodeHelper;
import de.hunsicker.jalopy.language.antlr.JavaTokenTypes;
import de.hunsicker.jalopy.storage.ConventionDefaults;
import de.hunsicker.jalopy.storage.ConventionKeys;
/**
* Printer for parameter lists [<code>ELIST</code>, <code>PARAMETERS</code>].
*
* @author <a href="http://jalopy.sf.net/contact.html">Marco Hunsicker</a>
* @version $Revision$
*/
final class ParametersPrinter
extends AbstractPrinter
{
//~ Static variables/initializers ----------------------------------------------------
/** No alignment offset set. */
static final int OFFSET_NONE = -1;
/** The index of the first parameter in the list. */
private static final int FIRST_PARAM = 0;
/** Singleton. */
private static final Printer INSTANCE = new ParametersPrinter();
/** Always wrap/align all parameters. */
private static final int MODE_ALWAYS = 1;
/** Perform line wrapping/alignment only if necessary. */
private static final int MODE_AS_NEEDED = 2;
//~ Constructors ---------------------------------------------------------------------
/**
* Creates a new ParametersPrinter object.
*/
public ParametersPrinter()
{
}
//~ Methods --------------------------------------------------------------------------
/**
* Returns the sole instance of this class.
*
* @return the sole instance of this class.
*/
public static final Printer getInstance()
{
return INSTANCE;
}
/**
* {@inheritDoc}
*/
public void print(
AST node,
NodeWriter out)
throws IOException
{
int line = out.line;
boolean wrapped = false;
Marker marker = out.state.markers.add();
switch (node.getType())
{
// a method or ctor declaration
case JavaTokenTypes.PARAMETERS :
boolean newlineAfter =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_PARAMS_METHOD_DEF,
ConventionDefaults.LINE_WRAP_AFTER_PARAMS_METHOD_DEF);
/**
* @todo move the whole test into printImpl()?
*/
if (out.mode == NodeWriter.MODE_DEFAULT)
{
boolean align =
AbstractPrinter.settings.getBoolean(
ConventionKeys.ALIGN_PARAMS_METHOD_DEF,
ConventionDefaults.ALIGN_PARAMS_METHOD_DEF);
// determine if all parameters will be wrapped:
if (align)
{
// either wrapping is forced...
if (newlineAfter)
{
setAlignOffset(node, out);
}
else
{
AST expr = node.getFirstChild();
if (expr != null)
{
TestNodeWriter tester = out.testers.get();
PrinterFactory.create(expr, out).print(expr, tester);
int lineLength =
AbstractPrinter.settings.getInt(
ConventionKeys.LINE_LENGTH,
ConventionDefaults.LINE_LENGTH);
// ... or necessary
if ((out.column + tester.length) > lineLength)
{
setAlignOffset(node, out);
}
out.testers.release(tester);
}
}
}
}
wrapped =
out.state.parametersWrapped =
printImpl(
node, newlineAfter ? MODE_ALWAYS
: MODE_AS_NEEDED, JavaTokenTypes.PARAMETERS,
out);
out.state.paramOffset = OFFSET_NONE;
break;
// a method call or creator
case JavaTokenTypes.ELIST :
wrapped = printImpl(node, MODE_AS_NEEDED, JavaTokenTypes.ELIST, out);
break;
default :
throw new IllegalArgumentException("unexpected node type -- " + node);
}
// printImpl() returns 'false' if only one parameter was found, but we
// want to let the right parenthesis stand out if the parameter took
// more than one line to print anyway
if (out.line > line)
{
wrapped = true;
}
// wrap and align, if necessary
if (
wrapped
&& AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_BEFORE_RIGHT_PAREN,
ConventionDefaults.LINE_WRAP_BEFORE_RIGHT_PAREN))
{
if (!out.newline)
{
out.printNewline();
}
if (
AbstractPrinter.settings.getBoolean(
ConventionKeys.INDENT_DEEP, ConventionDefaults.INDENT_DEEP))
{
printIndentation(-1, out);
}
else
{
printIndentation(out);
}
}
out.state.markers.remove(marker,out);
}
/**
* Sets the offset to align parameters of method declarations.
*
* @param node PARAMETER node.
* @param out stream to write to.
*
* @throws IOException if an I/O exception occured.
*/
private void setAlignOffset(
AST node,
NodeWriter out)
throws IOException
{
int result = 0;
TestNodeWriter tester = out.testers.get();
for (AST param = node.getFirstChild(); param != null;
param = param.getNextSibling())
{
switch (param.getType())
{
case JavaTokenTypes.COMMA :
break;
default :
AST modifier = param.getFirstChild();
PrinterFactory.create(modifier, out).print(modifier, tester);
AST type = modifier.getNextSibling();
PrinterFactory.create(type, out).print(type, tester);
// +1 for the space between modifiers and name
int length = tester.length + 1;
if (length > result)
{
result = length;
}
tester.reset();
break;
}
}
out.testers.release(tester);
out.state.paramOffset = out.column + result;
}
/**
* Determines whether the given EXPR node denotes a concatenated expression (either a
* string concatenation or addititive expression using the + operator).
*
* @param node an EXPR node.
*
* @return <code>true</code> if the given node denotes a concatenated expression.
*
* @since 1.0b8
*/
// TODO private boolean isConcat(AST node)
// {
// for (AST child = node.getFirstChild(); child != null;
// child = child.getFirstChild())
// {
// switch (child.getType())
// {
// case JavaTokenTypes.PLUS :
// return true;
//
// default :
// return isConcat(child);
// }
// }
//
// return false;
// }
private AST getFirstStringConcat(AST node)
{
AST expr = node.getFirstChild();
switch (expr.getType())
{
case JavaTokenTypes.PLUS :
AST first = null;
SEARCH:
for (
AST next = expr.getFirstChild(); next != null;
next = next.getFirstChild())
{
switch (next.getType())
{
case JavaTokenTypes.PLUS :
break;
default :
first = next;
break SEARCH;
}
}
switch (first.getType())
{
case JavaTokenTypes.STRING_LITERAL :
return first;
}
break;
}
return null;
}
/**
* Returns the last (deepest nested) child of the given node.
*
* @param node an EXPR or PARAMETER_DEF node.
*
* @return the last child of the given node.
*
* @throws IllegalArgumentException DOCUMENT ME!
*
* @todo fully implement the method in AbstractPrinter.java and use that method
* @since 1.0b8
*/
// TODO private AST getLastChild(AST node)
// {
// AST result = null;
//
// switch (node.getType())
// {
// case JavaTokenTypes.EXPR :
// result = node.getFirstChild();
//
// for (AST child = result; child != null; child = child.getFirstChild())
// {
// result = child;
// }
//
// return result;
//
// case JavaTokenTypes.PARAMETER_DEF :
//
// for (
// AST child = node.getFirstChild(); child != null;
// child = child.getNextSibling())
// {
// result = child;
// }
//
// return result;
//
// default :
// throw new IllegalArgumentException("invalid type -- " + node);
// }
// }
/**
* Determines wether the given EXPR node denotes a single literal string.
*
* @param node an EXPR node.
*
* @return <code>true</code> if the given nodes denotes a single literal string.
*
* @since 1.0b8
*/
private boolean isSingleLiteral(AST node)
{
if ((node.getNextSibling() == null) && (node.getType() != JavaTokenTypes.PLUS))
{
switch (node.getFirstChild().getType())
{
case JavaTokenTypes.STRING_LITERAL :
return true;
}
}
return false;
}
/**
* Adjusts the aligment offset. Called from {@link #wrapFirst} if the first parameter
* was actually wrapped.
*
* @param column column offset before the newline was issued.
* @param out stream to write to.
*
* @since 1.0b9
*/
private void adjustAlignmentOffset(
int column,
NodeWriter out)
{
if (out.state.paramOffset != OFFSET_NONE)
{
out.state.paramOffset = out.state.paramOffset - column + out.column;
}
}
/**
* Indicates whether the given parameters node contains a METHOD_CALL node as a
* parameter.
*
* @param node a parameters node (either PARAMETERS or ELIST).
*
* @return <code>true</code> if the given parameters node does contain a METHOD_CALL
* node as a parameter.
*/
private boolean containsMethodCall(AST node)
{
for (AST child = node.getFirstChild(); child != null;
child = child.getNextSibling())
{
switch (child.getType())
{
case JavaTokenTypes.COMMA :
break;
default :
switch (child.getFirstChild().getType())
{
case JavaTokenTypes.METHOD_CALL :
case JavaTokenTypes.LITERAL_new :
return true;
}
break;
}
}
return false;
}
/**
* Prints the parameters of the given node.
*
* @param node parameter list.
* @param action action to perform.
* @param type the node type we print parameters for. Either PARAMETERS or ELIST
* @param out stream to write to.
*
* @return <code>true</code> if line wrap.
*
* @throws IOException if an I/O error occured.
*/
private boolean printImpl(
AST node,
int action,
int type,
NodeWriter out)
throws IOException
{
JavaNode parameter = (JavaNode) node.getFirstChild();
if (parameter == null)
{
// no parameters found, nothing to do
return false;
}
boolean wrapLines =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP, ConventionDefaults.LINE_WRAP)
&& (out.mode == NodeWriter.MODE_DEFAULT);
int lineLength =
AbstractPrinter.settings.getInt(
ConventionKeys.LINE_LENGTH, ConventionDefaults.LINE_LENGTH);
boolean indentDeep =
AbstractPrinter.settings.getBoolean(
ConventionKeys.INDENT_DEEP, ConventionDefaults.INDENT_DEEP);
int deepIndentSize =
AbstractPrinter.settings.getInt(
ConventionKeys.INDENT_SIZE_DEEP, ConventionDefaults.INDENT_SIZE_DEEP);
boolean alignMethodCall =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_PARAMS_METHOD_CALL,
ConventionDefaults.LINE_WRAP_AFTER_PARAMS_METHOD_CALL);
boolean alignMethodCallIfNested =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_PARAMS_METHOD_CALL_IF_NESTED,
ConventionDefaults.LINE_WRAP_AFTER_PARAMS_METHOD_CALL_IF_NESTED);
boolean spaceAfterComma =
AbstractPrinter.settings.getBoolean(
ConventionKeys.SPACE_AFTER_COMMA, ConventionDefaults.SPACE_AFTER_COMMA);
boolean preferWrapAfterLeftParen =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_LEFT_PAREN,
ConventionDefaults.LINE_WRAP_AFTER_LEFT_PAREN);
boolean wrapIfFirst =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_PARAMS_EXCEED,
ConventionDefaults.LINE_WRAP_PARAMS_EXCEED);
boolean result = false;
int paramIndex = 0;
boolean restoreAction = false;
int userAction = action;
boolean firstWrapped = false; // was the first parameter wrapped?
boolean[] data = shouldHaveSmallIndent(parameter,
action,
type,
out, spaceAfterComma, lineLength,alignMethodCall);
boolean smallIndent = data[0];
alignMethodCall = data[1];
if (out.mode == NodeWriter.MODE_DEFAULT)
{
out.state.paramList = true;
out.state.paramLevel++;
out.state.parenScope.addFirst(new ParenthesesScope(out.state.paramLevel));
}
while (parameter != null)
{
JavaNode next = (JavaNode) parameter.getNextSibling();
switch (parameter.getType())
{
case JavaTokenTypes.COMMA :
if (parameter.hasCommentsAfter())
{
out.print(COMMA, JavaTokenTypes.COMMA);
printCommentsAfter(
parameter, NodeWriter.NEWLINE_NO, action != MODE_ALWAYS, out);
}
else
{
out.print(COMMA, JavaTokenTypes.COMMA);
}
break;
default :
if (paramIndex == FIRST_PARAM && alignMethodCall){
if (smallIndent){
out.printNewline();
//add a new marker with an
// appropiate indent level
// on a new line
Marker lastMarker = out.state.markers.getLast();
// add only a 0 marker
// Add a new marker with 0 and indent
// the line was 0
Marker current=out.state.markers.add(
out.line,
0,true,out
);
}
}
//if (out.mode == NodeWriter.MODE_DEFAULT)
{
// overwrite the mode for method calls
if (
(type == JavaTokenTypes.ELIST)
&& (alignMethodCall
|| (alignMethodCallIfNested && containsMethodCall(node))))
{
if (restoreAction)
{
action = userAction;
}
switch (parameter.getFirstChild().getType())
{
case JavaTokenTypes.METHOD_CALL :
userAction = action;
action = MODE_ALWAYS;
restoreAction = true;
break;
default :
/**
* @todo use out.state.paramLevel?
*/
switch (out.state.markers.count)
{
case 0 :
case 1 : // first level parentheses restoreAction = false;
break;
default : // secondary, tertiary, ... parentheses
action = MODE_ALWAYS;
break;
}
}
}
switch (action)
{
case MODE_AS_NEEDED :
if (out.newline)
{
printIndentation(out);
if (
preferWrapAfterLeftParen
- && (paramIndex == FIRST_PARAM))
+ && (paramIndex == FIRST_PARAM)
+ && out.mode != NodeWriter.MODE_TEST )
{
TestNodeWriter tester = out.testers.get();
// determine the exact space all
// parameters would need
PrinterFactory.create(node, out).print(node, tester);
// +1 for the right parenthesis
if ((out.column + tester.length + 1) > lineLength)
{
firstWrapped = true;
}
out.testers.release(tester);
}
}
- else if (wrapLines)
+ else if (wrapLines && out.mode != NodeWriter.MODE_TEST )
{
TestNodeWriter tester = out.testers.get();
if (
preferWrapAfterLeftParen
&& (paramIndex == FIRST_PARAM))
{
// determine the exact space all
// parameters would need
PrinterFactory.create(node, out).print(node, tester);
// (+1 for the right parenthesis)
tester.length += 1;
}
else
{
// determine the exact space this
// parameter would need
PrinterFactory.create(parameter, out).print(
parameter, tester);
}
if (!preferWrapAfterLeftParen && (next != null))
{
if (spaceAfterComma)
{
tester.length += 2;
}
else
{
tester.length += 1;
}
}
// space exceeds the line length but we
// have to apply further checks
if ((out.column + tester.length) > lineLength)
{
// for the first parameter we need to determine
// whether we should print it directly after
// parenthesis or wrap and indent
if (paramIndex == FIRST_PARAM)
{
if (preferWrapAfterLeftParen)
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = result;
}
else if (
!indentDeep
&& !shouldWrapAtLowerLevel(
parameter.getFirstChild(), lineLength,
deepIndentSize, out))
{
if ((type == JavaTokenTypes.PARAMETERS))
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = result;
}
// for chained method calls prefer wrapping
// along the dots
else if (
!JavaNodeHelper.isChained(
((JavaNode) node)
.getPreviousSibling()))
{
if (isSingleLiteral(parameter))
{
/**
* @todo add StringBreaker
* feature
*/
result =
wrapFirst(
type, true, next == null,
out);
firstWrapped = result;
}
else
{
AST first =
getFirstStringConcat(
parameter);
if (first != null)
{
tester.reset();
PrinterFactory.create(first, out)
.print(
first, tester);
if (
(out.column
+ tester.length) > lineLength)
{
result =
wrapFirst(
type, true,
next == null, out);
firstWrapped = result;
}
else
{
result =
wrapFirst(
type, next == null,
out);
firstWrapped = result;
}
}
else if (
parameter.getFirstChild()
.getType() == JavaTokenTypes.STRING_LITERAL)
{
result =
wrapFirst(
type, next == null,
true, out);
firstWrapped = result;
}
else
{
result =
wrapFirst(
type, next == null,
out);
firstWrapped = result;
}
}
}
}
}
else // for successive params wrap/align
{
out.printNewline();
printIndentation(out);
result = true;
/*int indentLength = out.getIndentLength();
Marker m = out.state.markers.getLast();
int length = (m.column > indentLength)
? (m.column -
indentLength)
: m.column;
// line break only needed if no endline
// comment forced one
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
result = true;
}
else if (spaceAfterComma)
{
out.print(SPACE,
JavaTokenTypes.WS);
}*/
}
/*
else // force specified indentation
{
//int length = indentation * out.state.paramLevel;
int length = out.indentSize * out.state.paramLevel;
// line break only needed if no endline
// comment forced one
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
//out.print(out.getString(
// indentation * out.state.paramLevel),
// JavaTokenTypes.WS);
result = true;
}
else if (spaceAfterComma)
out.print(SPACE, JavaTokenTypes.WS);
}
}*/
}
else if (wrapIfFirst && firstWrapped)
{
/**
* @todo implement custom indentation
*/
int indentLength = out.getIndentLength();
Marker m = out.state.markers.getLast();
int length =
(m.column > indentLength)
? (m.column - indentLength)
: m.column;
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
result = true;
}
else if (spaceAfterComma)
{
out.print(SPACE, JavaTokenTypes.WS);
}
}
else if (
spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
out.testers.release(tester);
}
else if (spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
break;
case MODE_ALWAYS :
if (paramIndex != FIRST_PARAM)
{
if (!out.newline)
{
out.printNewline();
result = true;
}
printIndentation(out);
}
else
{
if (out.newline)
{
printIndentation(out);
firstWrapped = true;
}
else if (preferWrapAfterLeftParen || (!indentDeep))
{
if (next == null)
{
TestNodeWriter tester = out.testers.get();
PrinterFactory.create(parameter, out).print(
parameter, tester);
// +1 for the right parenthesis
if (
(out.column + tester.length + 1) > lineLength)
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = true;
}
out.testers.release(tester);
}
else
{
result =
wrapFirst(
type,
(preferWrapAfterLeftParen
|| !indentDeep), next == null, out);
firstWrapped = result;
}
}
else if (out.column > deepIndentSize)
{
result =
wrapFirst(
type, preferWrapAfterLeftParen,
next == null, out);
firstWrapped = result;
}
}
break;
}
}
/*
else if (spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
*/
PrinterFactory.create(parameter, out).print(parameter, out);
paramIndex++;
break;
}
parameter = next;
}
if (out.mode == NodeWriter.MODE_DEFAULT)
{
out.state.paramList = false;
out.state.paramLevel--;
out.state.parenScope.removeFirst();
}
return result;
}
/**
* Determines whether line wrapping should occur at a lower level (i.e. one of the
* children will be wrapped).
*
* @param node first child of an EXPR node (via <code>expr.getFirstChild()</code>) to
* determine line wrapping policy for.
* @param lineLength the maximum line length setting.
* @param deepIndent the deep indent setting.
* @param out stream to write to.
*
* @return <code>true</code> if line wrapping should be performed at a lower level.
*
* @throws IOException if an I/O error occured.
*/
private boolean shouldWrapAtLowerLevel(
AST node,
int lineLength,
int deepIndent,
NodeWriter out)
throws IOException
{
for (AST child = node; child != null; child = child.getNextSibling())
{
switch (child.getType())
{
case JavaTokenTypes.ELIST :
case JavaTokenTypes.QUESTION :
case JavaTokenTypes.PLUS :
AST first = child;
SEARCH:
for (
AST next = node.getFirstChild(); next != null;
next = next.getFirstChild())
{
switch (next.getType())
{
case JavaTokenTypes.PLUS :
break;
default :
first = next;
break SEARCH;
}
}
switch (first.getType())
{
case JavaTokenTypes.STRING_LITERAL :
TestNodeWriter tester = out.testers.get();
PrinterFactory.create(first, out).print(first, tester);
if ((out.column + tester.length) > lineLength)
{
out.testers.release(tester);
return false;
}
out.testers.release(tester);
break;
}
return true;
case JavaTokenTypes.METHOD_CALL :
{
AST name = child.getFirstChild();
if ((out.column < deepIndent) && JavaNodeHelper.isChained(name))
{
return true;
}
String text = JavaNodeHelper.getDottedName(name);
if ((out.column + text.length()) > lineLength)
{
return false;
}
AST elist = name.getNextSibling();
int paramNum = 0;
for (
AST param = elist.getFirstChild(); param != null;
param = param.getNextSibling())
{
paramNum++;
}
if (paramNum > 0)
{
return true;
}
return false;
}
case JavaTokenTypes.LITERAL_new :
{
AST name = child.getFirstChild();
if ((out.column + 4 + name.getText().length()) > lineLength)
{
return false;
}
for (AST c = child.getFirstChild(); c != null;
c = c.getNextSibling())
{
switch (c.getType())
{
case JavaTokenTypes.ARRAY_INIT :
return false;
case JavaTokenTypes.OBJBLOCK :
return true;
}
}
AST elist = name.getNextSibling();
int paramNum = 0;
for (
AST param = elist.getFirstChild(); param != null;
param = param.getNextSibling())
{
if (paramNum == 0)
{
;
}
else
{
return true;
}
}
return false;
}
/**
* @todo maybe this is debatable?
*/
case JavaTokenTypes.LAND :
case JavaTokenTypes.LOR :
case JavaTokenTypes.BAND :
case JavaTokenTypes.BOR :
case JavaTokenTypes.BXOR :
case JavaTokenTypes.BNOT :
case JavaTokenTypes.MINUS :
return true;
case JavaTokenTypes.LPAREN :
/**
* @todo this advancing stuff should no longer be necessary
*/
return shouldWrapAtLowerLevel(
PrinterHelper.advanceToFirstNonParen(child), deepIndent,
lineLength, out);
}
}
return false;
}
/**
* Prints a newline before the first parameter of a parameter list, if necessary.
*
* @param type the type of the parameter list. Either ELIST or PARAMETER.
* @param last the amount of whitespace that is to print before the parameter.
* @param out stream to write to.
*
* @return <code>true</code> if a newline was actually printed.
*
* @throws IOException DOCUMENT ME!
*/
private boolean wrapFirst(
int type,
boolean last,
NodeWriter out)
throws IOException
{
return wrapFirst(type, false, last, out);
}
/**
* Prints a newline before the first parameter of a parameter list.
*
* @param type the type of the parameter list. Either ELIST or PARAMETER.
* @param force if <code>true</code> a newline will be forced.
* @param last <code>true</code> indicates that this parameter is the last parameter
* of the list.
* @param out stream to write to.
*
* @return <code>true</code> if a newline was actually printed.
*
* @throws IOException DOCUMENT ME!
* @throws IllegalStateException DOCUMENT ME!
*/
private boolean wrapFirst(
int type,
boolean force,
boolean last,
NodeWriter out)
throws IOException
{
boolean result = false;
if (
!AbstractPrinter.settings.getBoolean(
ConventionKeys.INDENT_DEEP, ConventionDefaults.INDENT_DEEP) || !last)
{
switch (out.state.paramLevel)
{
case 0 :
if (!out.state.markers.isMarked())
{
throw new IllegalStateException(
"not inside parentheses and no marker found");
}
// parameters of the outmost parentheses are aligned relative
// to the current indentation level
case 1 :
{
int length = out.indentSize;
/*if (!force && (indentation == -1))
{
length += out.continuationIndentSize;
}*/
// only wrap if the new column offset would be smaller than
// the current one and is between a certain tolerance area
if (
force
|| (((length + out.getIndentLength()) < out.column)
&& (length > (out.column - out.indentSize))))
{
int column = out.column;
out.printNewline();
printIndentation(out);
result = true;
adjustAlignmentOffset(column, out);
}
out.state.markers.add();
break;
}
// level 2 or deeper
default :
{
Marker marker = out.state.markers.get(out.state.markers.count - 2);
int indentLength = out.getIndentLength();
int offset =
((marker.column > indentLength) ? (marker.column - indentLength)
: marker.column)
+ (out.indentSize);
/*if (!force && (indentation == -1))
{
offset += out.continuationIndentSize;
}*/
// only wrap if the new column offset would be smaller than
// the current one and is between a certain tolerance area
if (
((offset + indentLength) < out.column)
&& (((offset + indentLength) < (out.column - out.indentSize))
|| ((offset + indentLength) > (out.column + out.indentSize))))
{
int column = out.column;
out.printNewline();
printIndentation(out);
result = true;
adjustAlignmentOffset(column, out);
}
out.state.markers.add();
break;
}
}
}
/*}else
{
int column = out.column;
out.printNewline();
//out.print(out.getString(indentation * out.state.paramLevel), JavaTokenTypes.WS);
printIndentation(out);
result = true;
adjustAlignmentOffset(column, out);
}*/
return result;
}
private boolean[] shouldHaveSmallIndent(
JavaNode parameter,
int action,
int type,
NodeWriter out, boolean spaceAfterComma, int lineLength,boolean alignMethodCall)
throws IOException{
boolean results[] = new boolean[]{false,alignMethodCall};
int totalParameterWidth = 0;
int totalParameters = 0;
// Point paramsSizes[] = null;
boolean smallindent = false;
boolean debugmode=false;
JavaNode littleParam = null;
if (AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_PARAMS_HARD,
ConventionDefaults.LINE_WRAP_PARAMS_HARD)) {
if (debugmode)
System.out.println("**Scaning line "+out.line+","+out.column+","+totalParameterWidth+","+type);
// ignore method parameter calls for wrapping
// If we want we could change this but we need to adjust using
// setAlignOffset(node, out);
if (type!=JavaTokenTypes.PARAMETERS) {
TestNodeWriter paramTester = out.testers.get();
paramTester.reset(out,false);
//paramTester.column = paramTester.maxColumn = paramTester.length = out.column;
// determine the exact space all
// parameters would need
littleParam = parameter;
// Iterate through each parameter to get the length of the
// line
while(littleParam!=null){
PrinterFactory.create(littleParam, out).print(littleParam, paramTester);
if (spaceAfterComma && (totalParameters != FIRST_PARAM))
{
paramTester.print(SPACE, JavaTokenTypes.WS);
}
littleParam = (JavaNode) littleParam.getNextSibling();
if (paramTester.state.smallIndent) {
smallindent = true;
}
totalParameters ++;
// System.out.println("has indent is a "+paramTester.state.smallIndent+","+ totalParameters +"," + out.line+","+out.column);
}
// +1 for braces
totalParameterWidth = paramTester.maxColumn + 1;
if (debugmode)
System.out.println("initial result "+paramTester.line+","+paramTester.column+","+paramTester.maxColumn);
// new
// If doing a mall indent
// or we need to wrap
// or we have multiple lines
if (smallindent || totalParameterWidth > lineLength ||
paramTester.line>1) {
// Attempt to wrap parameters see if that was sucesful in
// reducing the size to prevent the smallindent
TestNodeWriter paramTester2 = out.testers.get();
// A new line has occured , we need to test to see
// if it would be more efficient for us to make
// the wrap or the child.
paramTester2.reset(out,false);
//paramTester2.indent();
if (debugmode)
System.out.println("***Choosing to perform second scan on line"+out.line+","+out.column);
littleParam = parameter;
// Iterate through each parameter to get the length of the
// line (This is a cheap and dirty alignment of method parameters call
// System.out.println("Scanning line "+out.line+","+out.column);
while(littleParam!=null){
PrinterFactory.create(littleParam, out).print(littleParam, paramTester2);
littleParam = (JavaNode) littleParam.getNextSibling();
//increment twice to ignore the commas
if (littleParam !=null) {
littleParam = (JavaNode) littleParam.getNextSibling();
if (littleParam !=null) {
// System.out.println("new line - "+paramTester2.line+","+littleParam+","+paramTester2.column);
paramTester2.printNewline();
printIndentation(paramTester2);
}
}
}
// Results
// Changed to +3 incase another wrap has occured at the correct
// position this will give a bit of flexibility
boolean pt1 = paramTester.maxColumn>lineLength+3;
if (debugmode)
System.out.println(pt1 + "Paramtesters 1,"+paramTester.line+","+paramTester.column+","+paramTester.maxColumn+":"+paramTester.state.smallIndent);
if (debugmode)
System.out.println("Paramtesters 2,"+paramTester2.line+","+paramTester2.column+","+paramTester2.maxColumn+":"+paramTester2.state.smallIndent);
// boolean pt2 = paramTester2.maxColumn>lineLength;
// Test if parameters in tester 1 exceed the line length
// or
// paramTester 1 is greater then line length
// or
// paramtester 2.state.smallindent is false
// and
// paramtester 1.state.smallindent is true
if (paramTester.line>=paramTester2.line || pt1 ||
(!paramTester2.state.smallIndent && paramTester.state.smallIndent))
//if (true)
{
if (debugmode)
System.out.println("Opting with 2");
out.testers.release(paramTester);
paramTester = paramTester2;
alignMethodCall=true;
}
else {
if (debugmode)
System.out.println("Opting with 1");
out.testers.release(paramTester2);
}
// Perform a small indent if tester wrapped small or
// if specified in options
smallindent = paramTester.state.smallIndent ||
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_PARAMS_DEEP,
ConventionDefaults.LINE_WRAP_PARAMS_DEEP);
if (!smallindent){
// Changed to +3 incase another wrap has occured at the correct
// position this will give a bit of flexibility
smallindent=paramTester.maxColumn>lineLength+3;
}
// || paramTester.line>1 if we want to break
// whenever a line is wrapped
if ((smallindent ) && !alignMethodCall){
alignMethodCall = true;
}
}
//end
// If we are using a new param tester we need to
// re initialize the total width
// +1 for braces
totalParameterWidth = paramTester.maxColumn + 1;
if (debugmode) {
System.out.println("Param tester status"+paramTester.line+","+paramTester.column);
}
out.testers.release(paramTester);
}
if (debugmode) {
System.out.println("FLAGS "+smallindent+","+alignMethodCall);
System.out.println("**Scanned line "+out.line+","+out.column+","+totalParameterWidth);
}
// Small indent state only applicable to TestNodeWriter's
if (out instanceof TestNodeWriter){
// Only change the state if the current state is not true
// On release of the node writers the state will be changed
if (!out.state.smallIndent){
out.state.smallIndent=smallindent;
}
}
else {
// Small indent state only applicable to tester
}
results[0] = smallindent;
results[1] = alignMethodCall;
}
return results;
}
}
| false | true | private boolean printImpl(
AST node,
int action,
int type,
NodeWriter out)
throws IOException
{
JavaNode parameter = (JavaNode) node.getFirstChild();
if (parameter == null)
{
// no parameters found, nothing to do
return false;
}
boolean wrapLines =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP, ConventionDefaults.LINE_WRAP)
&& (out.mode == NodeWriter.MODE_DEFAULT);
int lineLength =
AbstractPrinter.settings.getInt(
ConventionKeys.LINE_LENGTH, ConventionDefaults.LINE_LENGTH);
boolean indentDeep =
AbstractPrinter.settings.getBoolean(
ConventionKeys.INDENT_DEEP, ConventionDefaults.INDENT_DEEP);
int deepIndentSize =
AbstractPrinter.settings.getInt(
ConventionKeys.INDENT_SIZE_DEEP, ConventionDefaults.INDENT_SIZE_DEEP);
boolean alignMethodCall =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_PARAMS_METHOD_CALL,
ConventionDefaults.LINE_WRAP_AFTER_PARAMS_METHOD_CALL);
boolean alignMethodCallIfNested =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_PARAMS_METHOD_CALL_IF_NESTED,
ConventionDefaults.LINE_WRAP_AFTER_PARAMS_METHOD_CALL_IF_NESTED);
boolean spaceAfterComma =
AbstractPrinter.settings.getBoolean(
ConventionKeys.SPACE_AFTER_COMMA, ConventionDefaults.SPACE_AFTER_COMMA);
boolean preferWrapAfterLeftParen =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_LEFT_PAREN,
ConventionDefaults.LINE_WRAP_AFTER_LEFT_PAREN);
boolean wrapIfFirst =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_PARAMS_EXCEED,
ConventionDefaults.LINE_WRAP_PARAMS_EXCEED);
boolean result = false;
int paramIndex = 0;
boolean restoreAction = false;
int userAction = action;
boolean firstWrapped = false; // was the first parameter wrapped?
boolean[] data = shouldHaveSmallIndent(parameter,
action,
type,
out, spaceAfterComma, lineLength,alignMethodCall);
boolean smallIndent = data[0];
alignMethodCall = data[1];
if (out.mode == NodeWriter.MODE_DEFAULT)
{
out.state.paramList = true;
out.state.paramLevel++;
out.state.parenScope.addFirst(new ParenthesesScope(out.state.paramLevel));
}
while (parameter != null)
{
JavaNode next = (JavaNode) parameter.getNextSibling();
switch (parameter.getType())
{
case JavaTokenTypes.COMMA :
if (parameter.hasCommentsAfter())
{
out.print(COMMA, JavaTokenTypes.COMMA);
printCommentsAfter(
parameter, NodeWriter.NEWLINE_NO, action != MODE_ALWAYS, out);
}
else
{
out.print(COMMA, JavaTokenTypes.COMMA);
}
break;
default :
if (paramIndex == FIRST_PARAM && alignMethodCall){
if (smallIndent){
out.printNewline();
//add a new marker with an
// appropiate indent level
// on a new line
Marker lastMarker = out.state.markers.getLast();
// add only a 0 marker
// Add a new marker with 0 and indent
// the line was 0
Marker current=out.state.markers.add(
out.line,
0,true,out
);
}
}
//if (out.mode == NodeWriter.MODE_DEFAULT)
{
// overwrite the mode for method calls
if (
(type == JavaTokenTypes.ELIST)
&& (alignMethodCall
|| (alignMethodCallIfNested && containsMethodCall(node))))
{
if (restoreAction)
{
action = userAction;
}
switch (parameter.getFirstChild().getType())
{
case JavaTokenTypes.METHOD_CALL :
userAction = action;
action = MODE_ALWAYS;
restoreAction = true;
break;
default :
/**
* @todo use out.state.paramLevel?
*/
switch (out.state.markers.count)
{
case 0 :
case 1 : // first level parentheses restoreAction = false;
break;
default : // secondary, tertiary, ... parentheses
action = MODE_ALWAYS;
break;
}
}
}
switch (action)
{
case MODE_AS_NEEDED :
if (out.newline)
{
printIndentation(out);
if (
preferWrapAfterLeftParen
&& (paramIndex == FIRST_PARAM))
{
TestNodeWriter tester = out.testers.get();
// determine the exact space all
// parameters would need
PrinterFactory.create(node, out).print(node, tester);
// +1 for the right parenthesis
if ((out.column + tester.length + 1) > lineLength)
{
firstWrapped = true;
}
out.testers.release(tester);
}
}
else if (wrapLines)
{
TestNodeWriter tester = out.testers.get();
if (
preferWrapAfterLeftParen
&& (paramIndex == FIRST_PARAM))
{
// determine the exact space all
// parameters would need
PrinterFactory.create(node, out).print(node, tester);
// (+1 for the right parenthesis)
tester.length += 1;
}
else
{
// determine the exact space this
// parameter would need
PrinterFactory.create(parameter, out).print(
parameter, tester);
}
if (!preferWrapAfterLeftParen && (next != null))
{
if (spaceAfterComma)
{
tester.length += 2;
}
else
{
tester.length += 1;
}
}
// space exceeds the line length but we
// have to apply further checks
if ((out.column + tester.length) > lineLength)
{
// for the first parameter we need to determine
// whether we should print it directly after
// parenthesis or wrap and indent
if (paramIndex == FIRST_PARAM)
{
if (preferWrapAfterLeftParen)
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = result;
}
else if (
!indentDeep
&& !shouldWrapAtLowerLevel(
parameter.getFirstChild(), lineLength,
deepIndentSize, out))
{
if ((type == JavaTokenTypes.PARAMETERS))
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = result;
}
// for chained method calls prefer wrapping
// along the dots
else if (
!JavaNodeHelper.isChained(
((JavaNode) node)
.getPreviousSibling()))
{
if (isSingleLiteral(parameter))
{
/**
* @todo add StringBreaker
* feature
*/
result =
wrapFirst(
type, true, next == null,
out);
firstWrapped = result;
}
else
{
AST first =
getFirstStringConcat(
parameter);
if (first != null)
{
tester.reset();
PrinterFactory.create(first, out)
.print(
first, tester);
if (
(out.column
+ tester.length) > lineLength)
{
result =
wrapFirst(
type, true,
next == null, out);
firstWrapped = result;
}
else
{
result =
wrapFirst(
type, next == null,
out);
firstWrapped = result;
}
}
else if (
parameter.getFirstChild()
.getType() == JavaTokenTypes.STRING_LITERAL)
{
result =
wrapFirst(
type, next == null,
true, out);
firstWrapped = result;
}
else
{
result =
wrapFirst(
type, next == null,
out);
firstWrapped = result;
}
}
}
}
}
else // for successive params wrap/align
{
out.printNewline();
printIndentation(out);
result = true;
/*int indentLength = out.getIndentLength();
Marker m = out.state.markers.getLast();
int length = (m.column > indentLength)
? (m.column -
indentLength)
: m.column;
// line break only needed if no endline
// comment forced one
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
result = true;
}
else if (spaceAfterComma)
{
out.print(SPACE,
JavaTokenTypes.WS);
}*/
}
/*
else // force specified indentation
{
//int length = indentation * out.state.paramLevel;
int length = out.indentSize * out.state.paramLevel;
// line break only needed if no endline
// comment forced one
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
//out.print(out.getString(
// indentation * out.state.paramLevel),
// JavaTokenTypes.WS);
result = true;
}
else if (spaceAfterComma)
out.print(SPACE, JavaTokenTypes.WS);
}
}*/
}
else if (wrapIfFirst && firstWrapped)
{
/**
* @todo implement custom indentation
*/
int indentLength = out.getIndentLength();
Marker m = out.state.markers.getLast();
int length =
(m.column > indentLength)
? (m.column - indentLength)
: m.column;
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
result = true;
}
else if (spaceAfterComma)
{
out.print(SPACE, JavaTokenTypes.WS);
}
}
else if (
spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
out.testers.release(tester);
}
else if (spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
break;
case MODE_ALWAYS :
if (paramIndex != FIRST_PARAM)
{
if (!out.newline)
{
out.printNewline();
result = true;
}
printIndentation(out);
}
else
{
if (out.newline)
{
printIndentation(out);
firstWrapped = true;
}
else if (preferWrapAfterLeftParen || (!indentDeep))
{
if (next == null)
{
TestNodeWriter tester = out.testers.get();
PrinterFactory.create(parameter, out).print(
parameter, tester);
// +1 for the right parenthesis
if (
(out.column + tester.length + 1) > lineLength)
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = true;
}
out.testers.release(tester);
}
else
{
result =
wrapFirst(
type,
(preferWrapAfterLeftParen
|| !indentDeep), next == null, out);
firstWrapped = result;
}
}
else if (out.column > deepIndentSize)
{
result =
wrapFirst(
type, preferWrapAfterLeftParen,
next == null, out);
firstWrapped = result;
}
}
break;
}
}
/*
else if (spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
*/
PrinterFactory.create(parameter, out).print(parameter, out);
paramIndex++;
break;
}
parameter = next;
}
| private boolean printImpl(
AST node,
int action,
int type,
NodeWriter out)
throws IOException
{
JavaNode parameter = (JavaNode) node.getFirstChild();
if (parameter == null)
{
// no parameters found, nothing to do
return false;
}
boolean wrapLines =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP, ConventionDefaults.LINE_WRAP)
&& (out.mode == NodeWriter.MODE_DEFAULT);
int lineLength =
AbstractPrinter.settings.getInt(
ConventionKeys.LINE_LENGTH, ConventionDefaults.LINE_LENGTH);
boolean indentDeep =
AbstractPrinter.settings.getBoolean(
ConventionKeys.INDENT_DEEP, ConventionDefaults.INDENT_DEEP);
int deepIndentSize =
AbstractPrinter.settings.getInt(
ConventionKeys.INDENT_SIZE_DEEP, ConventionDefaults.INDENT_SIZE_DEEP);
boolean alignMethodCall =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_PARAMS_METHOD_CALL,
ConventionDefaults.LINE_WRAP_AFTER_PARAMS_METHOD_CALL);
boolean alignMethodCallIfNested =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_PARAMS_METHOD_CALL_IF_NESTED,
ConventionDefaults.LINE_WRAP_AFTER_PARAMS_METHOD_CALL_IF_NESTED);
boolean spaceAfterComma =
AbstractPrinter.settings.getBoolean(
ConventionKeys.SPACE_AFTER_COMMA, ConventionDefaults.SPACE_AFTER_COMMA);
boolean preferWrapAfterLeftParen =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_AFTER_LEFT_PAREN,
ConventionDefaults.LINE_WRAP_AFTER_LEFT_PAREN);
boolean wrapIfFirst =
AbstractPrinter.settings.getBoolean(
ConventionKeys.LINE_WRAP_PARAMS_EXCEED,
ConventionDefaults.LINE_WRAP_PARAMS_EXCEED);
boolean result = false;
int paramIndex = 0;
boolean restoreAction = false;
int userAction = action;
boolean firstWrapped = false; // was the first parameter wrapped?
boolean[] data = shouldHaveSmallIndent(parameter,
action,
type,
out, spaceAfterComma, lineLength,alignMethodCall);
boolean smallIndent = data[0];
alignMethodCall = data[1];
if (out.mode == NodeWriter.MODE_DEFAULT)
{
out.state.paramList = true;
out.state.paramLevel++;
out.state.parenScope.addFirst(new ParenthesesScope(out.state.paramLevel));
}
while (parameter != null)
{
JavaNode next = (JavaNode) parameter.getNextSibling();
switch (parameter.getType())
{
case JavaTokenTypes.COMMA :
if (parameter.hasCommentsAfter())
{
out.print(COMMA, JavaTokenTypes.COMMA);
printCommentsAfter(
parameter, NodeWriter.NEWLINE_NO, action != MODE_ALWAYS, out);
}
else
{
out.print(COMMA, JavaTokenTypes.COMMA);
}
break;
default :
if (paramIndex == FIRST_PARAM && alignMethodCall){
if (smallIndent){
out.printNewline();
//add a new marker with an
// appropiate indent level
// on a new line
Marker lastMarker = out.state.markers.getLast();
// add only a 0 marker
// Add a new marker with 0 and indent
// the line was 0
Marker current=out.state.markers.add(
out.line,
0,true,out
);
}
}
//if (out.mode == NodeWriter.MODE_DEFAULT)
{
// overwrite the mode for method calls
if (
(type == JavaTokenTypes.ELIST)
&& (alignMethodCall
|| (alignMethodCallIfNested && containsMethodCall(node))))
{
if (restoreAction)
{
action = userAction;
}
switch (parameter.getFirstChild().getType())
{
case JavaTokenTypes.METHOD_CALL :
userAction = action;
action = MODE_ALWAYS;
restoreAction = true;
break;
default :
/**
* @todo use out.state.paramLevel?
*/
switch (out.state.markers.count)
{
case 0 :
case 1 : // first level parentheses restoreAction = false;
break;
default : // secondary, tertiary, ... parentheses
action = MODE_ALWAYS;
break;
}
}
}
switch (action)
{
case MODE_AS_NEEDED :
if (out.newline)
{
printIndentation(out);
if (
preferWrapAfterLeftParen
&& (paramIndex == FIRST_PARAM)
&& out.mode != NodeWriter.MODE_TEST )
{
TestNodeWriter tester = out.testers.get();
// determine the exact space all
// parameters would need
PrinterFactory.create(node, out).print(node, tester);
// +1 for the right parenthesis
if ((out.column + tester.length + 1) > lineLength)
{
firstWrapped = true;
}
out.testers.release(tester);
}
}
else if (wrapLines && out.mode != NodeWriter.MODE_TEST )
{
TestNodeWriter tester = out.testers.get();
if (
preferWrapAfterLeftParen
&& (paramIndex == FIRST_PARAM))
{
// determine the exact space all
// parameters would need
PrinterFactory.create(node, out).print(node, tester);
// (+1 for the right parenthesis)
tester.length += 1;
}
else
{
// determine the exact space this
// parameter would need
PrinterFactory.create(parameter, out).print(
parameter, tester);
}
if (!preferWrapAfterLeftParen && (next != null))
{
if (spaceAfterComma)
{
tester.length += 2;
}
else
{
tester.length += 1;
}
}
// space exceeds the line length but we
// have to apply further checks
if ((out.column + tester.length) > lineLength)
{
// for the first parameter we need to determine
// whether we should print it directly after
// parenthesis or wrap and indent
if (paramIndex == FIRST_PARAM)
{
if (preferWrapAfterLeftParen)
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = result;
}
else if (
!indentDeep
&& !shouldWrapAtLowerLevel(
parameter.getFirstChild(), lineLength,
deepIndentSize, out))
{
if ((type == JavaTokenTypes.PARAMETERS))
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = result;
}
// for chained method calls prefer wrapping
// along the dots
else if (
!JavaNodeHelper.isChained(
((JavaNode) node)
.getPreviousSibling()))
{
if (isSingleLiteral(parameter))
{
/**
* @todo add StringBreaker
* feature
*/
result =
wrapFirst(
type, true, next == null,
out);
firstWrapped = result;
}
else
{
AST first =
getFirstStringConcat(
parameter);
if (first != null)
{
tester.reset();
PrinterFactory.create(first, out)
.print(
first, tester);
if (
(out.column
+ tester.length) > lineLength)
{
result =
wrapFirst(
type, true,
next == null, out);
firstWrapped = result;
}
else
{
result =
wrapFirst(
type, next == null,
out);
firstWrapped = result;
}
}
else if (
parameter.getFirstChild()
.getType() == JavaTokenTypes.STRING_LITERAL)
{
result =
wrapFirst(
type, next == null,
true, out);
firstWrapped = result;
}
else
{
result =
wrapFirst(
type, next == null,
out);
firstWrapped = result;
}
}
}
}
}
else // for successive params wrap/align
{
out.printNewline();
printIndentation(out);
result = true;
/*int indentLength = out.getIndentLength();
Marker m = out.state.markers.getLast();
int length = (m.column > indentLength)
? (m.column -
indentLength)
: m.column;
// line break only needed if no endline
// comment forced one
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
result = true;
}
else if (spaceAfterComma)
{
out.print(SPACE,
JavaTokenTypes.WS);
}*/
}
/*
else // force specified indentation
{
//int length = indentation * out.state.paramLevel;
int length = out.indentSize * out.state.paramLevel;
// line break only needed if no endline
// comment forced one
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
//out.print(out.getString(
// indentation * out.state.paramLevel),
// JavaTokenTypes.WS);
result = true;
}
else if (spaceAfterComma)
out.print(SPACE, JavaTokenTypes.WS);
}
}*/
}
else if (wrapIfFirst && firstWrapped)
{
/**
* @todo implement custom indentation
*/
int indentLength = out.getIndentLength();
Marker m = out.state.markers.getLast();
int length =
(m.column > indentLength)
? (m.column - indentLength)
: m.column;
if ((length + indentLength + 1) != out.column)
{
out.printNewline();
printIndentation(out);
result = true;
}
else if (spaceAfterComma)
{
out.print(SPACE, JavaTokenTypes.WS);
}
}
else if (
spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
out.testers.release(tester);
}
else if (spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
break;
case MODE_ALWAYS :
if (paramIndex != FIRST_PARAM)
{
if (!out.newline)
{
out.printNewline();
result = true;
}
printIndentation(out);
}
else
{
if (out.newline)
{
printIndentation(out);
firstWrapped = true;
}
else if (preferWrapAfterLeftParen || (!indentDeep))
{
if (next == null)
{
TestNodeWriter tester = out.testers.get();
PrinterFactory.create(parameter, out).print(
parameter, tester);
// +1 for the right parenthesis
if (
(out.column + tester.length + 1) > lineLength)
{
result =
wrapFirst(
type, true, next == null, out);
firstWrapped = true;
}
out.testers.release(tester);
}
else
{
result =
wrapFirst(
type,
(preferWrapAfterLeftParen
|| !indentDeep), next == null, out);
firstWrapped = result;
}
}
else if (out.column > deepIndentSize)
{
result =
wrapFirst(
type, preferWrapAfterLeftParen,
next == null, out);
firstWrapped = result;
}
}
break;
}
}
/*
else if (spaceAfterComma && (paramIndex != FIRST_PARAM))
{
out.print(SPACE, JavaTokenTypes.WS);
}
*/
PrinterFactory.create(parameter, out).print(parameter, out);
paramIndex++;
break;
}
parameter = next;
}
|
diff --git a/src/edu/mit/mel/locast/mobile/data/Sync.java b/src/edu/mit/mel/locast/mobile/data/Sync.java
index b62a06a..02eb705 100644
--- a/src/edu/mit/mel/locast/mobile/data/Sync.java
+++ b/src/edu/mit/mel/locast/mobile/data/Sync.java
@@ -1,576 +1,576 @@
package edu.mit.mel.locast.mobile.data;
/*
* Copyright (C) 2010 MIT Mobile Experience Lab
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpResponseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import edu.mit.mel.locast.mobile.MainActivity;
import edu.mit.mel.locast.mobile.R;
import edu.mit.mel.locast.mobile.net.AndroidNetworkClient;
import edu.mit.mel.locast.mobile.net.NetworkProtocolException;
import edu.mit.mel.locast.mobile.notifications.ProgressNotification;
/**
* A Simple Sync engine. Can do naive bi-directional sync with a server that exposes
* a last modified or created date and a unique ID via a JSON API.
*
* To use, simply extend JsonSyncableItem and create the sync map. This mapping tells
* the engine what JSON object properties sync to what local columns, as well
*
*
* @author stevep
*
*/
public class Sync extends Service implements OnSharedPreferenceChangeListener {
public final static String TAG = "LocastSync";
public final static String ACTION_CANCEL_SYNC = "edu.mit.mel.locast.mobile.ACTION_CANCEL_SYNC";
private final IBinder mBinder = new LocalBinder();
private AndroidNetworkClient nc;
private ContentResolver cr;
private Set<Uri> syncdItems;
protected final ConcurrentLinkedQueue<Uri> syncQueue = new ConcurrentLinkedQueue<Uri>();
private SyncTask currentSyncTask = null;
private static int NOTIFICATION_SYNC = 0;
@Override
public void onStart(Intent intent, int startId) {
if (intent != null){
if (Intent.ACTION_SYNC.equals(intent.getAction())){
startSync(intent.getData());
}else if (ACTION_CANCEL_SYNC.equals(intent.getAction())){
if(currentSyncTask != null){
currentSyncTask.cancel(true);
Toast.makeText(getApplicationContext(), "Sync cancelled.", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Does not appear to currently be syncing", Toast.LENGTH_LONG).show();
}
}
}else{
// restarted by system.
startSync();
}
}
@Override
public void onCreate() {
super.onCreate();
nc = AndroidNetworkClient.getInstance(getApplicationContext());
cr = getApplicationContext().getContentResolver();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// reload the network client.
nc = AndroidNetworkClient.getInstance(getApplicationContext());
}
private void sync(Uri toSync, SyncProgressNotifier syncProgress) throws SyncException, IOException {
JsonSyncableItem syncItem = null;
final String contentType = getApplicationContext().getContentResolver().getType(toSync);
if (!MediaProvider.canSync(toSync)){
throw new IllegalArgumentException("URI " + toSync + " is not syncable.");
}
if (MediaProvider.TYPE_COMMENT_DIR.equals(contentType)
|| MediaProvider.TYPE_COMMENT_ITEM.equals(contentType)){
syncItem = new Comment();
}else if (MediaProvider.TYPE_CAST_DIR.equals(contentType)
|| MediaProvider.TYPE_CAST_ITEM.equals(contentType)
|| MediaProvider.TYPE_PROJECT_CAST_DIR.equals(contentType)
|| MediaProvider.TYPE_PROJECT_CAST_ITEM.equals(contentType)){
syncItem = new Cast();
}else if (MediaProvider.TYPE_PROJECT_DIR.equals(contentType)
|| MediaProvider.TYPE_PROJECT_ITEM.equals(contentType)){
syncItem = new Project();
}else{
throw new RuntimeException("URI " + toSync + " is syncable, but don't know what type of object it is.");
}
sync(toSync, syncItem, syncProgress);
}
/**
* Sync the given URI to the server. Will compare dates and do a two-way sync.
* Does not yet handle the case where both server and and local are modified
* (collisions)
*
* @param toSync URI of the object to sync. Generally, this should be the dir URI
* @param sync A new object that extends JsonSyncableItem. This is needed for the JSON
* serialization routine in it, as well as the sync map.
* @throws IOException
*/
private void sync(Uri toSync, JsonSyncableItem sync, SyncProgressNotifier syncProgress) throws SyncException, IOException{
JSONArray remObjs;
syncdItems = new TreeSet<Uri>();
final String contentType = getApplicationContext().getContentResolver().getType(toSync);
final Cursor c = cr.query(toSync, sync.getFullProjection(), null, null, null);
syncProgress.addPendingTasks(c.getCount());
// Handle a list of items.
if (contentType.startsWith("vnd.android.cursor.dir")){
// load from the network first...
try {
remObjs = nc.getArray(MediaProvider.getPublicPath(cr, toSync));
// TODO figure out how to use getContentResolver().bulkInsert(url, values); for this:
syncProgress.addPendingTasks(remObjs.length());
for (int i = 0; i < remObjs.length(); i++){
final JSONObject jo = remObjs.getJSONObject(i);
syncItem(toSync, null, jo, sync, syncProgress);
syncProgress.completeTask();
}
} catch (final SyncException se){
throw se;
} catch (final Exception e1) {
String message = e1.getLocalizedMessage();
if (message == null){
message = "caused by " + e1.getClass().getCanonicalName();
}
final SyncException se = new SyncException("Sync error: " + message);
se.initCause(e1);
throw se;
}
}
// then load locally.
try {
Log.d(TAG, "have " + c.getCount() + " local items to sync");
for (c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){
try {
syncItem(toSync, c, null, sync, syncProgress);
syncProgress.completeTask();
}catch (final SyncItemDeletedException side){
Log.d(TAG, side.getLocalizedMessage() + " Deleting...");
cr.delete(side.getItem(), null, null);
//side.printStackTrace();
syncProgress.completeTask();
continue;
}
}
}finally{
c.close();
}
}
/**
* Given a live cursor pointing to a data item and/or a set of contentValues loaded from the network,
* attempt to sync.
* Either c or cvNet can be null, but not both.
*
* @param c A cursor pointing to the data item. Null is OK here.
* @param jsonObject JSON object for the item as loaded from the network. null is OK here.
* @param sync An empty JsonSyncableItem object.
* @return True if the item has been modified on either end.
* @throws IOException
*/
private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync, SyncProgressNotifier syncProgress) throws SyncException, IOException {
boolean modified = false;
boolean needToCloseCursor = false;
boolean toSyncIsIndex = false;
final SyncMap syncMap = sync.getSyncMap();
Uri locUri = null;
ContentValues cvNet = null;
final Context context = getApplicationContext();
final ContentResolver cr = context.getContentResolver();
if (jsonObject != null){
try {
cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap);
// XXX remove this when the API updates
Uri itemToGetPubPathOf = toSync;
if (itemToGetPubPathOf == null){
itemToGetPubPathOf = sync.getContentUri();
}
MediaProvider.translateIdToUri(context, cvNet, true, itemToGetPubPathOf);
}catch (final Exception e){
final SyncException se = new SyncException("Problem loading JSON object.");
se.initCause(e);
throw se;
}
}
final String contentType = cr.getType(toSync);
if (c != null) {
if (contentType.startsWith("vnd.android.cursor.dir")){
locUri = ContentUris.withAppendedId(toSync,
c.getLong(c.getColumnIndex(JsonSyncableItem._ID)));
toSyncIsIndex = true;
}else{
locUri = toSync;
}
// skip any items already sync'd
if (syncdItems.contains(locUri)) {
return false;
}
final int draftCol = c.getColumnIndex(TaggableItem._DRAFT);
if (draftCol != -1 && c.getInt(draftCol) != 0){
Log.d(TAG, locUri + " is marked a draft. Not syncing.");
return false;
}
syncMap.onPreSyncItem(cr, locUri, c);
}
// if (c != null){
// MediaProvider.dumpCursorToLog(c, sync.getFullProjection());
// }
// when the PUBLIC_URI is null, that means it's only local
final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1;
if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")){
// new content on the local side only. Gotta publish.
try {
jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap);
final String publicPath = MediaProvider.getPostPath(cr, locUri);
Log.d(TAG, "Posting "+locUri + " to " + publicPath);
// The response from a post to create a new item should be the newly created item,
// which contains the public ID that we need.
jsonObject = nc.postJson(publicPath, jsonObject);
final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
if (cr.update(locUri, cvUpdate, null, null) == 1){
// at this point, server and client should be in sync.
syncdItems.add(locUri);
Log.i(TAG, "Hooray! "+ locUri + " has been posted succesfully.");
}else{
Log.e(TAG, "update of "+locUri+" failed");
}
modified = true;
} catch (final Exception e) {
final SyncException se = new SyncException(getString(R.string.error_sync_no_post));
se.initCause(e);
throw se;
}
// only on the remote side, so pull it in.
}else if (c == null && cvNet != null) {
final String[] params = {cvNet.getAsString(JsonSyncableItem._PUBLIC_URI)};
c = cr.query(toSync,
sync.getFullProjection(),
JsonSyncableItem._PUBLIC_URI+"=?", params, null);
needToCloseCursor = true;
if (! c.moveToFirst()){
locUri = cr.insert(toSync, cvNet);
modified = true;
}else {
locUri = ContentUris.withAppendedId(toSync,
c.getLong(c.getColumnIndex(JsonSyncableItem._ID)));
syncMap.onPreSyncItem(cr, locUri, c);
}
}
// we've now found data on both sides, so sync them.
if (! modified && c != null){
final String publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI));
try {
if (cvNet == null){
try{
if (publicPath == null && toSyncIsIndex && ! MediaProvider.canSync(locUri)){
// At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems).
// If we can't sync individual items, it's possible that the index is paged or the item has been deleted.
Log.w(TAG, "Asked to sync "+locUri+" but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date.");
return false;
}else{
if (jsonObject == null){
jsonObject = nc.getObject(publicPath);
}
cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
}
}catch (final HttpResponseException hre){
if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND){
final SyncItemDeletedException side = new SyncItemDeletedException(locUri);
side.initCause(hre);
throw side;
}
}
}
if (cvNet == null){
- Log.e(TAG, "got null values from fromJSON() on item " + locUri +": " +jsonObject.toString());
+ Log.e(TAG, "got null values from fromJSON() on item " + locUri +": " +(jsonObject != null ? jsonObject.toString(): "<< no json object >>"));
return false;
}
final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE));
final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE)));
if (netLastModified.equals(locLastModified)){
// same! yay! We don't need to do anything.
Log.d("LocastSync", locUri + " doesn't need to sync.");
}else if (netLastModified.after(locLastModified)){
// remote is more up to date, update!
cr.update(locUri, cvNet, null, null);
Log.d("LocastSync", cvNet + " is newer than "+locUri);
modified = true;
}else if (netLastModified.before(locLastModified)){
// local is more up to date, propagate!
jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap));
Log.d("LocastSync", cvNet + " is older than "+locUri);
modified = true;
}
} catch (final JSONException e) {
final SyncException se = new SyncException("Item sync error for path "+publicPath+": invalid JSON.");
se.initCause(e);
throw se;
} catch (final NetworkProtocolException e) {
final SyncException se = new SyncException("Item sync error for path "+publicPath+": "+ e.getHttpResponseMessage());
se.initCause(e);
throw se;
}finally{
if (needToCloseCursor) {
c.close();
needToCloseCursor = false;
}
}
}
if (needToCloseCursor) {
c.close();
}
if (locUri == null) {
throw new RuntimeException("Never got a local URI for a sync'd item.");
}
syncMap.onPostSyncItem(context, locUri, jsonObject, modified);
syncdItems.add(locUri);
return modified;
}
public static void loadItemFromServer(Context context, String path, JsonSyncableItem sync) throws SyncException, IOException {
ContentValues cvNet;
final AndroidNetworkClient nc = AndroidNetworkClient.getInstance(context);
try {
cvNet = JsonSyncableItem.fromJSON(context, null, nc.getObject(path), sync.getSyncMap());
} catch (final JSONException e) {
final SyncException se = new SyncException("Item sync error for path "+path+": invalid JSON.");
se.initCause(e);
throw se;
} catch (final NetworkProtocolException e) {
final SyncException se = new SyncException("Item sync error for path "+path+": "+ e.getHttpResponseMessage());
se.initCause(e);
throw se;
}
context.getContentResolver().insert(sync.getContentUri(), cvNet);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
Sync getService(){
return Sync.this;
}
}
public void startSync(){
if (currentSyncTask == null || currentSyncTask.getStatus() == AsyncTask.Status.FINISHED){
currentSyncTask = new SyncTask();
currentSyncTask.execute();
}
}
public void startSync(Uri uri){
if (! syncQueue.contains(uri)){
syncQueue.add(uri);
Log.d(TAG, "enqueing " + uri + " to sync queue");
}else{
Log.d(TAG, "NOT enqueing " + uri + " to sync queue, as it's already present");
}
startSync();
}
private class SyncTask extends AsyncTask<Void, Void, Boolean> implements SyncProgressNotifier {
private Exception e;
private ProgressNotification notification;
private NotificationManager nm;
private Date startTime;
private int mTaskTotal = 0;
private int mTaskCompleted = 0;
private static final int
MSG_PROGRESS_ADD_TASKS = 0,
MSG_PROGRESS_COMPLETE_TASKS = 1;
// this is used, as publishProgress is not very good about garbage collector churn.
private final Handler mProgressHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case MSG_PROGRESS_ADD_TASKS:
mTaskTotal += msg.arg1;
break;
case MSG_PROGRESS_COMPLETE_TASKS:
mTaskCompleted += msg.arg1;
break;
}
updateProgressBars();
};
};
private void updateProgressBars(){
notification.setProgress(mTaskTotal, mTaskCompleted);
nm.notify(NOTIFICATION_SYNC, notification);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
startTime = new Date();
final Context context = getApplicationContext();
notification = new ProgressNotification(getApplicationContext(), R.drawable.stat_notify_sync);
notification.contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setProgress(0, 0);
notification.setTitle(getText(R.string.sync_notification));
nm = (NotificationManager) getApplication().getSystemService(NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_SYNC, notification);
}
@Override
protected Boolean doInBackground(Void... params) {
try {
while (!syncQueue.isEmpty()){
Log.d(TAG, syncQueue.size() + " items in the sync queue");
final Uri toSync = syncQueue.remove();
Sync.this.sync(toSync, this);
}
} catch (final SyncException e) {
e.printStackTrace();
this.e = e;
return false;
} catch (final IOException e) {
// TODO Auto-generated catch block
this.e = e;
e.printStackTrace();
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
if (result){
// only show a notification if the user has been waiting for a bit.
if ((new Date().getTime() - startTime.getTime()) > 10000){
Toast.makeText(getApplicationContext(), R.string.sync_success, Toast.LENGTH_LONG).show();
}
}else{
if (e instanceof SyncException){
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}else if (e instanceof IOException){
Toast.makeText(getApplicationContext(), R.string.error_sync, Toast.LENGTH_LONG).show();
}
}
nm.cancel(NOTIFICATION_SYNC);
}
public void addPendingTasks(int taskCount) {
mProgressHandler.obtainMessage(MSG_PROGRESS_ADD_TASKS, taskCount, 0).sendToTarget();
}
public void completeTask() {
mProgressHandler.obtainMessage(MSG_PROGRESS_COMPLETE_TASKS, 1, 0).sendToTarget();
}
}
public interface SyncProgressNotifier {
/**
* Mark an added task as completed.
*/
public void completeTask();
/**
* Adds a number of tasks to be completed.
* @param taskCount
*/
public void addPendingTasks(int taskCount);
}
}
| true | true | private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync, SyncProgressNotifier syncProgress) throws SyncException, IOException {
boolean modified = false;
boolean needToCloseCursor = false;
boolean toSyncIsIndex = false;
final SyncMap syncMap = sync.getSyncMap();
Uri locUri = null;
ContentValues cvNet = null;
final Context context = getApplicationContext();
final ContentResolver cr = context.getContentResolver();
if (jsonObject != null){
try {
cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap);
// XXX remove this when the API updates
Uri itemToGetPubPathOf = toSync;
if (itemToGetPubPathOf == null){
itemToGetPubPathOf = sync.getContentUri();
}
MediaProvider.translateIdToUri(context, cvNet, true, itemToGetPubPathOf);
}catch (final Exception e){
final SyncException se = new SyncException("Problem loading JSON object.");
se.initCause(e);
throw se;
}
}
final String contentType = cr.getType(toSync);
if (c != null) {
if (contentType.startsWith("vnd.android.cursor.dir")){
locUri = ContentUris.withAppendedId(toSync,
c.getLong(c.getColumnIndex(JsonSyncableItem._ID)));
toSyncIsIndex = true;
}else{
locUri = toSync;
}
// skip any items already sync'd
if (syncdItems.contains(locUri)) {
return false;
}
final int draftCol = c.getColumnIndex(TaggableItem._DRAFT);
if (draftCol != -1 && c.getInt(draftCol) != 0){
Log.d(TAG, locUri + " is marked a draft. Not syncing.");
return false;
}
syncMap.onPreSyncItem(cr, locUri, c);
}
// if (c != null){
// MediaProvider.dumpCursorToLog(c, sync.getFullProjection());
// }
// when the PUBLIC_URI is null, that means it's only local
final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1;
if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")){
// new content on the local side only. Gotta publish.
try {
jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap);
final String publicPath = MediaProvider.getPostPath(cr, locUri);
Log.d(TAG, "Posting "+locUri + " to " + publicPath);
// The response from a post to create a new item should be the newly created item,
// which contains the public ID that we need.
jsonObject = nc.postJson(publicPath, jsonObject);
final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
if (cr.update(locUri, cvUpdate, null, null) == 1){
// at this point, server and client should be in sync.
syncdItems.add(locUri);
Log.i(TAG, "Hooray! "+ locUri + " has been posted succesfully.");
}else{
Log.e(TAG, "update of "+locUri+" failed");
}
modified = true;
} catch (final Exception e) {
final SyncException se = new SyncException(getString(R.string.error_sync_no_post));
se.initCause(e);
throw se;
}
// only on the remote side, so pull it in.
}else if (c == null && cvNet != null) {
final String[] params = {cvNet.getAsString(JsonSyncableItem._PUBLIC_URI)};
c = cr.query(toSync,
sync.getFullProjection(),
JsonSyncableItem._PUBLIC_URI+"=?", params, null);
needToCloseCursor = true;
if (! c.moveToFirst()){
locUri = cr.insert(toSync, cvNet);
modified = true;
}else {
locUri = ContentUris.withAppendedId(toSync,
c.getLong(c.getColumnIndex(JsonSyncableItem._ID)));
syncMap.onPreSyncItem(cr, locUri, c);
}
}
// we've now found data on both sides, so sync them.
if (! modified && c != null){
final String publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI));
try {
if (cvNet == null){
try{
if (publicPath == null && toSyncIsIndex && ! MediaProvider.canSync(locUri)){
// At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems).
// If we can't sync individual items, it's possible that the index is paged or the item has been deleted.
Log.w(TAG, "Asked to sync "+locUri+" but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date.");
return false;
}else{
if (jsonObject == null){
jsonObject = nc.getObject(publicPath);
}
cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
}
}catch (final HttpResponseException hre){
if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND){
final SyncItemDeletedException side = new SyncItemDeletedException(locUri);
side.initCause(hre);
throw side;
}
}
}
if (cvNet == null){
Log.e(TAG, "got null values from fromJSON() on item " + locUri +": " +jsonObject.toString());
return false;
}
final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE));
final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE)));
if (netLastModified.equals(locLastModified)){
// same! yay! We don't need to do anything.
Log.d("LocastSync", locUri + " doesn't need to sync.");
}else if (netLastModified.after(locLastModified)){
// remote is more up to date, update!
cr.update(locUri, cvNet, null, null);
Log.d("LocastSync", cvNet + " is newer than "+locUri);
modified = true;
}else if (netLastModified.before(locLastModified)){
// local is more up to date, propagate!
jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap));
Log.d("LocastSync", cvNet + " is older than "+locUri);
modified = true;
}
} catch (final JSONException e) {
final SyncException se = new SyncException("Item sync error for path "+publicPath+": invalid JSON.");
se.initCause(e);
throw se;
} catch (final NetworkProtocolException e) {
final SyncException se = new SyncException("Item sync error for path "+publicPath+": "+ e.getHttpResponseMessage());
se.initCause(e);
throw se;
}finally{
if (needToCloseCursor) {
c.close();
needToCloseCursor = false;
}
}
}
if (needToCloseCursor) {
c.close();
}
if (locUri == null) {
throw new RuntimeException("Never got a local URI for a sync'd item.");
}
syncMap.onPostSyncItem(context, locUri, jsonObject, modified);
syncdItems.add(locUri);
return modified;
}
| private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync, SyncProgressNotifier syncProgress) throws SyncException, IOException {
boolean modified = false;
boolean needToCloseCursor = false;
boolean toSyncIsIndex = false;
final SyncMap syncMap = sync.getSyncMap();
Uri locUri = null;
ContentValues cvNet = null;
final Context context = getApplicationContext();
final ContentResolver cr = context.getContentResolver();
if (jsonObject != null){
try {
cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap);
// XXX remove this when the API updates
Uri itemToGetPubPathOf = toSync;
if (itemToGetPubPathOf == null){
itemToGetPubPathOf = sync.getContentUri();
}
MediaProvider.translateIdToUri(context, cvNet, true, itemToGetPubPathOf);
}catch (final Exception e){
final SyncException se = new SyncException("Problem loading JSON object.");
se.initCause(e);
throw se;
}
}
final String contentType = cr.getType(toSync);
if (c != null) {
if (contentType.startsWith("vnd.android.cursor.dir")){
locUri = ContentUris.withAppendedId(toSync,
c.getLong(c.getColumnIndex(JsonSyncableItem._ID)));
toSyncIsIndex = true;
}else{
locUri = toSync;
}
// skip any items already sync'd
if (syncdItems.contains(locUri)) {
return false;
}
final int draftCol = c.getColumnIndex(TaggableItem._DRAFT);
if (draftCol != -1 && c.getInt(draftCol) != 0){
Log.d(TAG, locUri + " is marked a draft. Not syncing.");
return false;
}
syncMap.onPreSyncItem(cr, locUri, c);
}
// if (c != null){
// MediaProvider.dumpCursorToLog(c, sync.getFullProjection());
// }
// when the PUBLIC_URI is null, that means it's only local
final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1;
if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")){
// new content on the local side only. Gotta publish.
try {
jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap);
final String publicPath = MediaProvider.getPostPath(cr, locUri);
Log.d(TAG, "Posting "+locUri + " to " + publicPath);
// The response from a post to create a new item should be the newly created item,
// which contains the public ID that we need.
jsonObject = nc.postJson(publicPath, jsonObject);
final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
if (cr.update(locUri, cvUpdate, null, null) == 1){
// at this point, server and client should be in sync.
syncdItems.add(locUri);
Log.i(TAG, "Hooray! "+ locUri + " has been posted succesfully.");
}else{
Log.e(TAG, "update of "+locUri+" failed");
}
modified = true;
} catch (final Exception e) {
final SyncException se = new SyncException(getString(R.string.error_sync_no_post));
se.initCause(e);
throw se;
}
// only on the remote side, so pull it in.
}else if (c == null && cvNet != null) {
final String[] params = {cvNet.getAsString(JsonSyncableItem._PUBLIC_URI)};
c = cr.query(toSync,
sync.getFullProjection(),
JsonSyncableItem._PUBLIC_URI+"=?", params, null);
needToCloseCursor = true;
if (! c.moveToFirst()){
locUri = cr.insert(toSync, cvNet);
modified = true;
}else {
locUri = ContentUris.withAppendedId(toSync,
c.getLong(c.getColumnIndex(JsonSyncableItem._ID)));
syncMap.onPreSyncItem(cr, locUri, c);
}
}
// we've now found data on both sides, so sync them.
if (! modified && c != null){
final String publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI));
try {
if (cvNet == null){
try{
if (publicPath == null && toSyncIsIndex && ! MediaProvider.canSync(locUri)){
// At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems).
// If we can't sync individual items, it's possible that the index is paged or the item has been deleted.
Log.w(TAG, "Asked to sync "+locUri+" but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date.");
return false;
}else{
if (jsonObject == null){
jsonObject = nc.getObject(publicPath);
}
cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap);
}
}catch (final HttpResponseException hre){
if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND){
final SyncItemDeletedException side = new SyncItemDeletedException(locUri);
side.initCause(hre);
throw side;
}
}
}
if (cvNet == null){
Log.e(TAG, "got null values from fromJSON() on item " + locUri +": " +(jsonObject != null ? jsonObject.toString(): "<< no json object >>"));
return false;
}
final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE));
final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE)));
if (netLastModified.equals(locLastModified)){
// same! yay! We don't need to do anything.
Log.d("LocastSync", locUri + " doesn't need to sync.");
}else if (netLastModified.after(locLastModified)){
// remote is more up to date, update!
cr.update(locUri, cvNet, null, null);
Log.d("LocastSync", cvNet + " is newer than "+locUri);
modified = true;
}else if (netLastModified.before(locLastModified)){
// local is more up to date, propagate!
jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap));
Log.d("LocastSync", cvNet + " is older than "+locUri);
modified = true;
}
} catch (final JSONException e) {
final SyncException se = new SyncException("Item sync error for path "+publicPath+": invalid JSON.");
se.initCause(e);
throw se;
} catch (final NetworkProtocolException e) {
final SyncException se = new SyncException("Item sync error for path "+publicPath+": "+ e.getHttpResponseMessage());
se.initCause(e);
throw se;
}finally{
if (needToCloseCursor) {
c.close();
needToCloseCursor = false;
}
}
}
if (needToCloseCursor) {
c.close();
}
if (locUri == null) {
throw new RuntimeException("Never got a local URI for a sync'd item.");
}
syncMap.onPostSyncItem(context, locUri, jsonObject, modified);
syncdItems.add(locUri);
return modified;
}
|
diff --git a/src/powercrystals/minefactoryreloaded/modhelpers/twilightforest/TwilightForestEggHandler.java b/src/powercrystals/minefactoryreloaded/modhelpers/twilightforest/TwilightForestEggHandler.java
index 5fc41259..b2266557 100644
--- a/src/powercrystals/minefactoryreloaded/modhelpers/twilightforest/TwilightForestEggHandler.java
+++ b/src/powercrystals/minefactoryreloaded/modhelpers/twilightforest/TwilightForestEggHandler.java
@@ -1,33 +1,33 @@
package powercrystals.minefactoryreloaded.modhelpers.twilightforest;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityEggInfo;
import net.minecraft.item.ItemStack;
import powercrystals.minefactoryreloaded.api.IMobEggHandler;
public class TwilightForestEggHandler implements IMobEggHandler
{
@SuppressWarnings("unchecked")
@Override
public EntityEggInfo getEgg(ItemStack safariNet)
{
try
{
Class<? extends Entity> entityClass = (Class<? extends Entity>)Class.forName(safariNet.getTagCompound().getString("_class"));
EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entityClass, true);
- if(er.getContainer() == TwilightForest.twilightForestContainer)
+ if(er.getContainer() != null && er.getContainer() == TwilightForest.twilightForestContainer)
{
return (EntityEggInfo)TwilightForest.entityEggs.get(er.getModEntityId());
}
return null;
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
}
}
| true | true | public EntityEggInfo getEgg(ItemStack safariNet)
{
try
{
Class<? extends Entity> entityClass = (Class<? extends Entity>)Class.forName(safariNet.getTagCompound().getString("_class"));
EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entityClass, true);
if(er.getContainer() == TwilightForest.twilightForestContainer)
{
return (EntityEggInfo)TwilightForest.entityEggs.get(er.getModEntityId());
}
return null;
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
}
| public EntityEggInfo getEgg(ItemStack safariNet)
{
try
{
Class<? extends Entity> entityClass = (Class<? extends Entity>)Class.forName(safariNet.getTagCompound().getString("_class"));
EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entityClass, true);
if(er.getContainer() != null && er.getContainer() == TwilightForest.twilightForestContainer)
{
return (EntityEggInfo)TwilightForest.entityEggs.get(er.getModEntityId());
}
return null;
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.